1 //===-- Standalone implementation of a char vector --------------*- C++ -*-===//
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
7 //===----------------------------------------------------------------------===//
9 #ifndef LLVM_LIBC_SRC_SUPPORT_CHARVECTOR_H
10 #define LLVM_LIBC_SRC_SUPPORT_CHARVECTOR_H
12 #include "src/__support/common.h"
15 #include <stdlib.h> // For allocation.
17 namespace __llvm_libc
{
19 // This is very simple alternate of the std::string class. There is no
20 // bounds check performed in any of the methods. The callers are expected to
21 // do the checks before invoking the methods.
23 // This class will be extended as needed in future.
26 static constexpr size_t INIT_BUFF_SIZE
= 64;
27 char local_buffer
[INIT_BUFF_SIZE
];
28 char *cur_str
= local_buffer
;
29 size_t cur_buff_size
= INIT_BUFF_SIZE
;
33 CharVector() = default;
34 LIBC_INLINE
~CharVector() {
35 if (cur_str
!= local_buffer
)
39 // append returns true on success and false on allocation failure.
40 LIBC_INLINE
bool append(char new_char
) {
41 // Subtract 1 for index starting at 0 and another for the null terminator.
42 if (index
>= cur_buff_size
- 2) {
43 // If the new character would cause the string to be longer than the
44 // buffer's size, attempt to allocate a new buffer.
45 cur_buff_size
= cur_buff_size
* 2;
46 if (cur_str
== local_buffer
) {
48 new_str
= reinterpret_cast<char *>(malloc(cur_buff_size
));
49 if (new_str
== NULL
) {
52 // TODO: replace with inline memcpy
53 for (size_t i
= 0; i
< index
; ++i
)
54 new_str
[i
] = cur_str
[i
];
57 cur_str
= reinterpret_cast<char *>(realloc(cur_str
, cur_buff_size
));
58 if (cur_str
== NULL
) {
63 cur_str
[index
] = new_char
;
68 LIBC_INLINE
char *c_str() {
69 cur_str
[index
] = '\0';
73 LIBC_INLINE
size_t length() { return index
; }
76 } // namespace __llvm_libc
78 #endif // LLVM_LIBC_SRC_SUPPORT_CHARVECTOR_H