1 //===-- Allocating string utils ---------------------------------*- C++ -*-===// 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 #ifndef LLVM_LIBC_SRC_STRING_ALLOCATING_STRING_UTILS_H 10 #define LLVM_LIBC_SRC_STRING_ALLOCATING_STRING_UTILS_H 11 12 #include "src/__support/CPP/new.h" 13 #include "src/__support/CPP/optional.h" 14 #include "src/__support/macros/config.h" 15 #include "src/string/memory_utils/inline_memcpy.h" 16 #include "src/string/string_utils.h" 17 18 #include <stddef.h> // For size_t 19 20 namespace LIBC_NAMESPACE_DECL { 21 namespace internal { 22 strdup(const char * src)23LIBC_INLINE cpp::optional<char *> strdup(const char *src) { 24 if (src == nullptr) 25 return cpp::nullopt; 26 size_t len = string_length(src) + 1; 27 AllocChecker ac; 28 char *newstr = new (ac) char[len]; 29 if (!ac) 30 return cpp::nullopt; 31 inline_memcpy(newstr, src, len); 32 return newstr; 33 } 34 35 } // namespace internal 36 } // namespace LIBC_NAMESPACE_DECL 37 38 #endif // LLVM_LIBC_SRC_STRING_ALLOCATING_STRING_UTILS_H 39