1db8a88feSMichael Jones //===-- Implementation of memccpy ----------------------------------------===//
2db8a88feSMichael Jones //
3db8a88feSMichael Jones // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4db8a88feSMichael Jones // See https://llvm.org/LICENSE.txt for license information.
5db8a88feSMichael Jones // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6db8a88feSMichael Jones //
7db8a88feSMichael Jones //===----------------------------------------------------------------------===//
8db8a88feSMichael Jones 
9db8a88feSMichael Jones #include "src/string/memccpy.h"
10db8a88feSMichael Jones 
11db8a88feSMichael Jones #include "src/__support/common.h"
12db8a88feSMichael Jones #include <stddef.h> // For size_t.
13db8a88feSMichael Jones 
14db8a88feSMichael Jones namespace __llvm_libc {
15db8a88feSMichael Jones 
16db8a88feSMichael Jones LLVM_LIBC_FUNCTION(void *, memccpy,
17db8a88feSMichael Jones                    (void *__restrict dest, const void *__restrict src, int c,
18db8a88feSMichael Jones                     size_t count)) {
19db8a88feSMichael Jones   unsigned char end = static_cast<unsigned char>(c);
20*1c92911eSMichael Jones   const unsigned char *uc_src = static_cast<const unsigned char *>(src);
21*1c92911eSMichael Jones   unsigned char *uc_dest = static_cast<unsigned char *>(dest);
22db8a88feSMichael Jones   size_t i = 0;
23db8a88feSMichael Jones   // Copy up until end is found.
24*1c92911eSMichael Jones   for (; i < count && uc_src[i] != end; ++i)
25*1c92911eSMichael Jones     uc_dest[i] = uc_src[i];
26db8a88feSMichael Jones   // if i < count, then end must have been found, so copy end into dest and
27db8a88feSMichael Jones   // return the byte after.
28db8a88feSMichael Jones   if (i < count) {
29*1c92911eSMichael Jones     uc_dest[i] = uc_src[i];
30*1c92911eSMichael Jones     return uc_dest + i + 1;
31db8a88feSMichael Jones   }
32db8a88feSMichael Jones   return nullptr;
33db8a88feSMichael Jones }
34db8a88feSMichael Jones 
35db8a88feSMichael Jones } // namespace __llvm_libc
36