xref: /llvm-project/libc/src/string/allocating_string_utils.h (revision ab07fd9ffa3a76a4608ee7ac884960c982972d8c)
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/__support/macros/config.h"
15 #include "src/string/memory_utils/memcpy_implementations.h" // For string_length
16 #include "src/string/string_utils.h"
17 
18 #include <stddef.h> // For size_t
19 
20 namespace __llvm_libc {
21 namespace internal {
22 
23 LIBC_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 __llvm_libc
37 
38 #endif
39