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