1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
|
/*
* libfud
* Copyright 2024 Dominick Allen
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef FUD_STRING_HPP
#define FUD_STRING_HPP
#include "fud_allocator.hpp"
#include "fud_assert.hpp"
#include "fud_c_string.hpp"
#include "fud_option.hpp"
#include "fud_result.hpp"
#include "fud_status.hpp"
#include "fud_string_view.hpp"
#include "fud_utf8.hpp"
#include <climits>
#include <cstddef>
static_assert(CHAR_BIT == 8);
/** @file */
namespace fud {
struct DrainResult {
size_t bytesWritten;
FudStatus status;
};
/** \brief The maximum length of a string using the small string optimization
* buffer. */
constexpr size_t SSO_BUF_LENGTH = 15;
/** \brief The size of the small string optimization buffer, to include space
* for the null terminator. */
constexpr size_t SSO_BUF_SIZE = SSO_BUF_LENGTH + 1;
class String;
/** \brief A result containing a valid @String or the @FudStatus error
* encountered during its creation. */
using StringResult = Result<String, FudStatus>;
/** \brief A null terminated, growable, array of utf8 code points, with a custom
* allocator. */
class String {
public:
/** \brief Create a string from a C String.
*
* \param [in] cString a pointer to a C string to populate the String.
*
* \returns String on success.
* \returns NullPointer if cString is null.
* \returns ArgumentInvalid if the length of cString is greater than or
* equal to SSIZE_MAX.
* \returns FudStatus::AllocFailure if the allocator fails.
*/
static StringResult makeFromCString(const char* cString);
/** \brief Create a string from a C String, specifying the allocator.
*
* \param [in] cString a pointer to a C string to populate the String.
* \param [in] allocator the allocator the string will use.
*
* \returns String on success.
* \returns NullPointer if cString or allocator is null.
* \returns ArgumentInvalid if the length of cString is greater than or
* equal to SSIZE_MAX.
* \returns FudStatus::AllocFailure if the allocator fails.
*/
static StringResult makeFromCString(const char* cString, Allocator* allocator);
/** \brief Create a string from concatenating multiple C Strings.
*
* This function uses the default globalFudAllocator.
*
* \tparam CStrings a parameter pack of types convertible to const char*.
* \param [in] cStrings pointers to C strings to concatenate into a single String.
*
* \returns String on success.
* \returns NullPointer if cString or allocator is null.
* \returns ArgumentInvalid if the length of cString is greater than or
* equal to SSIZE_MAX.
* \returns FudStatus::AllocFailure if the allocator fails.
*/
template <typename... CStrings>
static StringResult makeFromCStrings(CStrings... cStrings)
{
return makeFromCStringsAlloc(&globalFudAllocator, cStrings...);
}
/** \brief Create a string from concatenating multiple C Strings.
*
* \tparam CStrings a parameter pack of types convertible to const char*.
* \param [in] cStrings pointers to C strings to concatenate into a single String.
* \param [in] allocator the allocator the string will use.
*
* \returns String on success.
* \returns NullPointer if cString or allocator is null.
* \returns ArgumentInvalid if the length of cString is greater than or
* equal to SSIZE_MAX.
* \returns FudStatus::AllocFailure if the allocator fails.
*/
template <typename... CStrings>
static StringResult makeFromCStringsAlloc(Allocator* allocator, CStrings... cStrings)
{
if (allocator == nullptr) {
return StringResult::error(FudStatus::NullPointer);
}
if (!String::allocatorValid(allocator)) {
return StringResult::error(FudStatus::ArgumentInvalid);
}
size_t totalLength = 0;
Array<size_t, sizeof...(cStrings)> lengths{};
Array<const char*, sizeof...(cStrings)> strPointers{};
size_t index = 0;
for (const auto* cStringItem : {cStrings...}) {
const char* cString = nullptr;
if constexpr (std::is_same_v<decltype(cStringItem), const char*>) {
cString = cStringItem;
} else if constexpr (std::is_same_v<decltype(cStringItem), const utf8*>) {
cString = reinterpret_cast<const char*>(cStringItem);
} else {
static_assert(!std::is_same_v<decltype(cStringItem), const char*>);
}
strPointers[index] = cString;
auto lengthResult = cStringLength(cString);
if (lengthResult < 0 || lengthResult >= SSIZE_MAX) {
return StringResult::error(FudStatus::ArgumentInvalid);
}
auto stringLength = static_cast<size_t>(lengthResult);
if (SIZE_MAX - totalLength < stringLength) {
return StringResult::error(FudStatus::Failure);
}
totalLength += stringLength;
lengths[index] = stringLength;
index++;
}
String output{};
output.m_length = totalLength;
output.m_allocator = allocator;
if (output.m_length >= output.m_capacity) {
output.m_capacity = output.m_length + 1;
/* Avoid using compiler expansions in headers */
auto dataResult = output.allocator()->allocate(output.m_capacity);
if (dataResult.isError()) {
return StringResult::error(dataResult.getError());
}
output.m_data = static_cast<utf8*>(dataResult.getOkay());
}
auto* data = output.dataMut();
size_t cumulativeLength = 0;
for (size_t idx = 0; idx < strPointers.size(); ++idx) {
const auto* cString = strPointers[idx];
auto copyStatus = copyMem(
data + cumulativeLength,
output.m_capacity - cumulativeLength,
cString,
lengths[idx]);
fudAssert(copyStatus == FudStatus::Success);
cumulativeLength += lengths[idx];
}
auto terminateStatus = output.nullTerminate();
fudAssert(terminateStatus == FudStatus::Success);
return StringResult::okay(std::move(output));
}
String() noexcept = default;
String(const String& rhs) = delete;
String(String&& rhs) noexcept;
~String();
String& operator=(const String& rhs) = delete;
String& operator=(String&& rhs) noexcept;
static StringResult from(const String& rhs);
static StringResult from(StringView view, Allocator* allocator = &globalFudAllocator);
FudStatus copy(const String& rhs);
/** \brief The raw length of the string's data, excluding the null terminator. */
[[nodiscard]] constexpr size_t length() const
{
return m_length;
}
/** \brief Indicates if no characters are present in the string's data. */
[[nodiscard]] constexpr bool empty() const
{
return m_length == 0;
}
/** \brief The total size of the string's data, including the null terminator. */
[[nodiscard]] constexpr size_t size() const
{
return m_length + 1;
}
/** \brief The current capacity of the string, excluding the reserved slot
* for the null terminator. */
[[nodiscard]] constexpr size_t capacity() const
{
fudAssert(m_capacity > 0);
return m_capacity - 1;
}
/** \brief The underlying data, guaranteed to have c string representation. */
[[nodiscard]] constexpr const utf8* data() const
{
return isLarge() ? m_data : m_buffer.data();
}
/** \brief The underlying data as an explicit c string. */
[[nodiscard]] inline const char* c_str() const
{
return reinterpret_cast<const char*>(data());
}
[[nodiscard]] bool utf8Valid() const;
FudStatus reserve(size_t newCapacity);
[[nodiscard]] Option<utf8> back();
[[nodiscard]] constexpr size_t remainingLength() const
{
if (m_length >= m_capacity) {
return 0;
}
return m_capacity - 1U - m_length;
}
[[nodiscard]] inline StringView asView() const
{
return StringView(*this);
}
FudStatus pushBack(char letter);
FudStatus pushBack(utf8 letter);
FudStatus pushBack(const FudUtf8& letter);
Option<utf8> pop();
FudStatus append(const char* source);
FudStatus append(const String& source);
FudStatus append(StringView source);
DrainResult drain(const char* source);
DrainResult drain(const String& source);
DrainResult drain(StringView source);
[[nodiscard]] StringResult catenate(const String& rhs) const;
[[nodiscard]] StringResult catenate(const char* rhs) const;
[[nodiscard]] bool compare(const String& rhs) const;
FudStatus clear();
const utf8* begin() const;
const utf8* end() const;
private:
static constexpr uint8_t capacityMask = 0x07;
[[nodiscard]] static bool allocatorValid(Allocator* allocator)
{
return ((reinterpret_cast<uintptr_t>(allocator) & capacityMask) == 0);
}
[[nodiscard]] bool nullTerminated() const;
[[nodiscard]] bool valid() const;
FudStatus nullTerminate();
Allocator* allocator() const
{
constexpr uintptr_t ALLOCATOR_MASK = ~static_cast<uintptr_t>(capacityMask);
const auto allocptr = reinterpret_cast<uintptr_t>(m_allocator);
return reinterpret_cast<Allocator*>(allocptr & ALLOCATOR_MASK);
}
/** \brief The underlying data, guaranteed to have c string
* representation. */
[[nodiscard]] constexpr utf8* dataMut()
{
return isLarge() ? m_data : m_buffer.data();
}
void cleanup();
FudStatus resize(size_t newCapacity);
void setLength(size_t newLength)
{
m_length = newLength;
}
/** \brief The allocator used to get storage for characters when the string
* is large. */
Allocator* m_allocator{&globalFudAllocator};
using BufType = Array<utf8, SSO_BUF_SIZE>;
union {
/** \brief The storage for string characters when using SSO. */
BufType m_buffer{BufType::constFill(0)};
/** \brief The storage for string characters when the string is
* large. */
utf8* m_data;
};
/** \brief The length of the string excluding the null terminator. */
size_t m_length{0};
/** \brief The capacity of the string, including the null terminator. */
size_t m_capacity{SSO_BUF_SIZE};
/** \brief Whether or not the string must use its allocator for storage. */
[[nodiscard]] constexpr bool isLarge() const
{
return m_capacity > SSO_BUF_SIZE;
}
};
} // namespace fud
#endif
|