13bbbec1aSMichael Jones //===-- Implementation of strndup -----------------------------------------===// 23bbbec1aSMichael Jones // 33bbbec1aSMichael Jones // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 43bbbec1aSMichael Jones // See https://llvm.org/LICENSE.txt for license information. 53bbbec1aSMichael Jones // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 63bbbec1aSMichael Jones // 73bbbec1aSMichael Jones //===----------------------------------------------------------------------===// 83bbbec1aSMichael Jones 93bbbec1aSMichael Jones #include "src/string/strndup.h" 10*5ff3ff33SPetr Hosek #include "src/__support/macros/config.h" 111f578347SGuillaume Chatelet #include "src/string/memory_utils/inline_memcpy.h" 123bbbec1aSMichael Jones #include "src/string/string_utils.h" 133bbbec1aSMichael Jones 14c2f17bfbSSiva Chandra Reddy #include "src/__support/CPP/new.h" 153bbbec1aSMichael Jones #include "src/__support/common.h" 163bbbec1aSMichael Jones 173bbbec1aSMichael Jones #include <stddef.h> 183bbbec1aSMichael Jones 19*5ff3ff33SPetr Hosek namespace LIBC_NAMESPACE_DECL { 203bbbec1aSMichael Jones 213bbbec1aSMichael Jones LLVM_LIBC_FUNCTION(char *, strndup, (const char *src, size_t size)) { 223bbbec1aSMichael Jones if (src == nullptr) 233bbbec1aSMichael Jones return nullptr; 243bbbec1aSMichael Jones size_t len = internal::string_length(src); 253bbbec1aSMichael Jones if (len > size) 263bbbec1aSMichael Jones len = size; 27c2f17bfbSSiva Chandra Reddy AllocChecker ac; 28b5415f30SSiva Chandra Reddy char *dest = new (ac) char[len + 1]; 29c2f17bfbSSiva Chandra Reddy if (!ac) 303bbbec1aSMichael Jones return nullptr; 317b59fcb7SSiva Chandra Reddy inline_memcpy(dest, src, len + 1); 327b59fcb7SSiva Chandra Reddy dest[len] = '\0'; 337b59fcb7SSiva Chandra Reddy return dest; 343bbbec1aSMichael Jones } 353bbbec1aSMichael Jones 36*5ff3ff33SPetr Hosek } // namespace LIBC_NAMESPACE_DECL 37