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