1//===-- Implementation of strndup -----------------------------------------===//
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/strndup.h"
10#include "src/__support/macros/config.h"
11#include "src/string/memory_utils/inline_memcpy.h"
12#include "src/string/string_utils.h"
13
14#include "src/__support/CPP/new.h"
15#include "src/__support/common.h"
16
17#include <stddef.h>
18
19namespace LIBC_NAMESPACE_DECL {
20
21LLVM_LIBC_FUNCTION(char *, strndup, (const char *src, size_t size)) {
22 if (src == nullptr)
23 return nullptr;
24 size_t len = internal::string_length(src);
25 if (len > size)
26 len = size;
27 AllocChecker ac;
28 char *dest = new (ac) char[len + 1];
29 if (!ac)
30 return nullptr;
31 inline_memcpy(dest, src, len + 1);
32 dest[len] = '\0';
33 return dest;
34}
35
36} // namespace LIBC_NAMESPACE_DECL
37

source code of libc/src/string/strndup.cpp