Stroika Library 3.0d25
 
Loading...
Searching...
No Matches
StringBuilder.h
Go to the documentation of this file.
1/*
2 * Copyright(c) Sophist Solutions, Inc. 1990-2026. All rights reserved
3 */
4#ifndef _Stroika_Foundation_Characters_StringBuilder_h_
5#define _Stroika_Foundation_Characters_StringBuilder_h_ 1
6
7#include "Stroika/Foundation/StroikaPreComp.h"
8
12
13/**
14 * \file
15 *
16 * \note Code-Status: <a href="Code-Status.md#Beta">Beta</a>
17 *
18 * TODO:
19 * @todo Think about how to add support for STL manipulator/inserters like endl;
20 *
21 * @todo Consider adding (back) reserve/capacity methods, but be sure to document these are in units of
22 * BufferElementType not characters.
23 */
25 template <typename T>
26 String UnoverloadedToString (const T& t);
27}
28
30
31 namespace Private_ {
32 template <typename T>
33 concept IUnoverloadedToString_ = requires (T t) {
34 { UnoverloadedToString (t) } -> convertible_to<Characters::String>;
35 };
36 }
37
38 /**
39 * \brief rarely used directly - defaults generally fine
40 *
41 * BUF_CHAR_T of char32_t probably does better if definitely using a lot of wide unicode characters.
42 * BUF_CHAR_T of char8_t probably best for mostly ASCII text. Note - GetAt/SetAt very slow
43 * unless using char32_t.
44 *
45 * Maybe easy to support all at once.
46 */
47 template <IUNICODECanAlwaysConvertTo BUF_CHAR_T = char8_t, size_t INLINE_BUF_SIZE = 128>
49 /**
50 * Note that kInlineBufferSize is measured in 'buffer elements' - not (necessarily the same as) bytes or Characters.
51 */
52 static constexpr size_t kInlineBufferSize = INLINE_BUF_SIZE;
53
54 /**
55 */
56 using BufferElementType = BUF_CHAR_T;
57 };
58
59 /**
60 * \brief Similar to String, but intended to more efficiently construct a String. Mutable type (String is largely immutable).
61 *
62 * Has operator String() co can be used by value most places you can use a String.
63 *
64 * @see String
65 * @see .Net StringBuilder - http://msdn.microsoft.com/en-us/library/system.text.stringbuilder(v=vs.110).aspx
66 * @see Java StringBuilder - http://docs.oracle.com/javase/7/docs/api/java/lang/StringBuilder.html
67 *
68 * \note \em Thread-Safety <a href="Thread-Safety.md#C++-Standard-Thread-Safety">C++-Standard-Thread-Safety</a>
69 *
70 * \note pointless to ever create StringBuilder and not use, so [[nodiscard]] appropriate
71 */
72 template <typename OPTIONS = StringBuilder_Options<>>
73 class [[nodiscard]] StringBuilder {
74 public:
75 /**
76 */
77 using value_type = Character;
78
79 public:
80 static constexpr size_t kInlineBufferSize = OPTIONS::kInlineBufferSize;
81
82 public:
83 using BufferElementType = typename OPTIONS::BufferElementType;
85
86 public:
87 /**
88 */
89 StringBuilder () noexcept = default;
90 StringBuilder (const StringBuilder&) = default;
91 StringBuilder (const String& initialValue);
92 template <IUNICODECanUnambiguouslyConvertFrom CHAR_T>
93 StringBuilder (span<const CHAR_T> initialValue);
94
95 public:
96 nonvirtual StringBuilder& operator= (const StringBuilder& rhs) = default;
97 template <convertible_to<String> T>
98 nonvirtual StringBuilder& operator= (const T& rhs);
99
100 public:
101 /**
102 * Append the given argument characters to this buffer.
103 *
104 * argument characters can be given by
105 * o span<unicode (or narrow ASCII) characters>
106 * o const T* - nul-terminated array of unicode (or narrow ASCII) characters
107 * o basic_string<unicode (or narrow ASCII) characters>
108 * o basic_string_view<unicode (or narrow ASCII) characters>
109 * o String
110 * o Character
111 *
112 * This function appends as IF the argument was converted to a UNICODE string, and then
113 * appended.
114 */
115 template <IUNICODECanUnambiguouslyConvertFrom CHAR_T>
116 nonvirtual void Append (span<const CHAR_T> s);
117 template <IUNICODECanUnambiguouslyConvertFrom CHAR_T>
118 nonvirtual void Append (span<CHAR_T> s);
119 template <IUNICODECanUnambiguouslyConvertFrom CHAR_T>
120 nonvirtual void Append (const CHAR_T* s);
121 template <IStdBasicStringCompatibleCharacter CHAR_T>
122 nonvirtual void Append (const basic_string<CHAR_T>& s)
124 template <IStdBasicStringCompatibleCharacter CHAR_T>
125 nonvirtual void Append (const basic_string_view<CHAR_T>& s)
127 nonvirtual void Append (const String& s);
128 template <IUNICODECanUnambiguouslyConvertFrom CHAR_T>
129 nonvirtual void Append (CHAR_T c);
130
131 // clang-format off
132 public:
133 /**
134 * @aliases Append
135 */
136 template <typename APPEND_ARG_T>
137 nonvirtual auto operator+= (APPEND_ARG_T&& a)
138 -> StringBuilder& requires (requires (StringBuilder& s, APPEND_ARG_T&& a) { s.Append (forward<APPEND_ARG_T> (a)); })
139 #if qCompilerAndStdLib_template_Requires_templateDeclarationMatchesOutOfLine_Buggy
140 {
141 if constexpr (requires (StringBuilder& s, APPEND_ARG_T&& a) { s.Append (forward<APPEND_ARG_T> (a)); }) {
142 Append (forward<APPEND_ARG_T> (a));
143 }
144 else {
145 Append (Characters::UnoverloadedToString (forward<APPEND_ARG_T> (a)));
146 }
147 return *this;
148 }
149 #else
150 ;
151 #endif
152
153 public:
154 /**
155 * \brief same as str (): so a StringBuilder formats as its text, with _f and std::format alike
156 */
158 {
159 return this->str ();
160 }
161
162 public:
163 /**
164 * \brief Append a, if Append takes it (text, a character) - otherwise a as Characters::ToString writes it: a number,
165 * an enum by its name, a container, an optional, a filesystem::path, a type with a ToString () method
166 *
167 * @aliases Append if that would work, and otherwise alias for Append (ToString(arg)), if that would work;
168 *
169 * \par Example Usage
170 * \code
171 * StringBuilder sb;
172 * sb << "found "sv << 3 << " in "sv << Sequence<int>{1, 2, 3}; // sb.str () == "found 3 in [ 1, 2, 3 ]"
173 * \endcode
174 */
175 template <typename APPEND_ARG_T>
176 nonvirtual auto
177 operator<< (APPEND_ARG_T&& a)
178 -> StringBuilder& requires (Characters::Private_::IUnoverloadedToString_<APPEND_ARG_T> or requires (StringBuilder& s, APPEND_ARG_T&& a) { s.Append (forward<APPEND_ARG_T> (a)); })
179#if qCompilerAndStdLib_template_Requires_templateDeclarationMatchesOutOfLine_Buggy
180 {
181 if constexpr (requires (StringBuilder& s, APPEND_ARG_T&& a) { s.Append (forward<APPEND_ARG_T> (a)); }) {
182 Append (forward<APPEND_ARG_T> (a));
183 }
184 else {
185 Append (Characters::UnoverloadedToString (forward<APPEND_ARG_T> (a)));
186 }
187 return *this;
188 }
189#else
190 ;
191#endif
192 // clang-format on
193
194 public:
195 /**
196 */
197 nonvirtual void push_back (Character c);
198
199 public:
200 /**
201 * returns number of characters (not bytes, not including any possible NUL-terminator)
202 */
203 nonvirtual size_t size () const noexcept;
204
205 public:
206 /**
207 * Returns true if this is an empty string (aka iff size () == 0);
208 */
209 nonvirtual bool empty () const noexcept;
210
211 public:
212 /**
213 * \note - this can be very slow if OPTIONS::BufferElementType != char32_t (but if StringBuilder_Options<char32_t> its fast)
214 */
215 nonvirtual Character GetAt (size_t index) const noexcept;
216
217 public:
218 /**
219 * \note - this can be very slow if OPTIONS::BufferElementType != char32_t (but if StringBuilder_Options<char32_t> its fast)
220 */
221 nonvirtual void SetAt (Character item, size_t index) noexcept;
222
223 public:
224 /**
225 * \brief return (read-only) Character object
226 *
227 * @aliases GetAt (size_t i) const;
228 *
229 * \note this is very inefficient, unless using StringBuilder_Options<char32_t> - in which case its quite fast
230 */
231 nonvirtual const Character operator[] (size_t i) const noexcept;
232
233 public:
234 /**
235 * Mimic the String::InsertAt API, except modify in place.
236 */
237 template <Common::IAnyOf<char, Character, String, span<const Character>, span<Character>> T>
238 nonvirtual void InsertAt (T c, size_t at);
239
240 public:
241 /**
242 * Change the size of this object to sz = where sz must be <= size()
243 */
244 nonvirtual void ShrinkTo (size_t sz) noexcept;
245
246 public:
247 /**
248 * Only specifically specialized variants are supported. Convert String losslessly into a
249 * o String or
250 * o wstring
251 * o u8string
252 * o u16string
253 * o u32string
254 */
255 template <Common::IAnyOf<String, wstring, u8string, u16string, u32string> RESULT_T>
256 nonvirtual RESULT_T As () const;
257
258 public:
259 /*
260 * (mostly) explicit operator T () provides an alternative syntax to As<> - depending on user
261 * preference or context. Note - its important that this is explicit - to avoid
262 * creating overload problems.
263 */
264 nonvirtual /*explicit*/ operator String () const;
265 nonvirtual explicit operator wstring () const;
266 nonvirtual explicit operator u8string () const;
267 nonvirtual explicit operator u16string () const;
268 nonvirtual explicit operator u32string () const;
269
270 nonvirtual explicit operator span<const BufferElementType> () const;
271
272 public:
273 /**
274 */
275 nonvirtual void clear () noexcept;
276
277 public:
278 /**
279 * mimic wstringstream method
280 */
281 nonvirtual String str () const;
282
283 public:
284 /**
285 * \brief number of characters, not bytes or code-points
286 *
287 * @aliases size ()
288 */
289 nonvirtual size_t length () const noexcept;
290
291 public:
292 /**
293 * ONLY valid til the next non-const call to StringBuilder.
294 * See also GetData (to select a different charType).
295 */
296 nonvirtual span<BufferElementType> data ();
297 nonvirtual span<const BufferElementType> data () const;
298
299 public:
300 /**
301 * \brief access a span of data located inside the StringBuilder. Return internal pointer, or pointer internal to possiblyUsedBuffer
302 *
303 * \note Lifetime of resulting span is ONLY until the next change to the StackBuffer OR the StringBuilder.
304 * \note The pointer MIGHT refer to data inside the (possibly resized) StackBuffer, or be internal to the StringBuilder
305 *
306 * The point of this queer API is too allow accessing the internal data by pointer, but allow StringBuilder to change
307 * its internal representation (not necessarily matching the kind of string being requested).
308 *
309 * \note Caller should ignore the size of possiblyUsedBuffer; its for internal use inside of GetData() - and may not match the size
310 * of the resulting string/span. Note also, the span will not in general be NUL-terminated.
311 *
312 * \note Why use this function?
313 * You would think the point of StringBuilder was to - well - build a string - right? So why not use the str() API.
314 * Well, that allocates memory, which must be freed, and that is not cost free. For some short-lived strings, it CAN
315 * be cheaper to just peek at the constructed in memory stack based String already being produced in this StringBuilder.
316 *
317 * But this needs to be done in a way with data hiding (so we can change the internal representation of the StringBuilder class as needed)
318 * and with respect for the possibility that the string could be large (so break out of any small-string optimizations).
319 *
320 * Passing in a reference to the 'StackBuffer' class is a compromise among all these considerations. The only cost
321 * is initializing a pointer, and checking that pointer on destruction, if no memory allocation is needed.
322 *
323 * \par Example Usage:
324 * \code
325 * Memory::StackBuffer<wchar_t> probablyIgnoredBuf;
326 * span<const wchar_t> s = sb.GetData (&probablyIgnoredBuf);
327 * \endcode
328 *
329 * \code
330 * Memory::StackBuffer<wchar_t> probablyIgnoredBuf;
331 * out.Write (sb.GetData (&probablyIgnoredBuf));
332 * \endcode
333 */
335 nonvirtual span<const CHAR_T> GetData (Memory::StackBuffer<CHAR_T>* probablyIgnoredBuf) const
336 requires (not is_const_v<CHAR_T>);
337
338 public:
339 // @todo cleanup
340 bool operator== (const String& rhs) const;
341 bool operator== (const StringBuilder& rhs) const;
342
343 public:
344 // ape std::string API
345 // @todo cleanup
346 void erase (size_t from);
347 void erase (size_t from, size_t count);
348
349 public:
350 [[deprecated ("Since Stroika v3.0d1, use span{} argument")]] StringBuilder (const wchar_t* start, const wchar_t* end)
351 {
352 Append (span{start, end});
353 }
354 [[deprecated ("Since Stroika v3.0d1, use span{} argument")]] void Append (const char16_t* s, const char16_t* e)
355 {
356 Append (span{s, e});
357 }
358 [[deprecated ("Since Stroika v3.0d1, use span{} argument")]] void Append (const char32_t* s, const char32_t* e)
359 {
360 Append (span{s, e});
361 }
362 [[deprecated ("Since Stroika v3.0d1, use span{} argument")]] void Append (const wchar_t* s, const wchar_t* e)
363 {
364 Append (span{s, e});
365 }
366 [[deprecated ("Since Stroika v3.0d1, use span{} argument")]] void Append (const Character* s, const Character* e)
367 {
368 Append (span{s, e});
369 }
370 template <typename RESULT_T>
371 [[deprecated ("Since Stroika v3.0d2 - use As/0")]] void As (RESULT_T* into) const
372 requires (same_as<RESULT_T, String> or same_as<RESULT_T, wstring>)
373 {
374 RequireNotNull (into);
375 if constexpr (same_as<RESULT_T, String>) {
376 *into = str ();
377 }
378 if constexpr (same_as<RESULT_T, wstring>) {
379 *into = str ().template As<wstring> ();
380 }
381 }
382
383 private:
384 Stroika_ATTRIBUTE_NO_UNIQUE_ADDRESS_VCFORCE Debug::AssertExternallySynchronizedChecker fAssertExternallySynchronized_;
385
386 private:
387 Memory::InlineBuffer<BufferElementType, kInlineBufferSize> fData_{}; // not nul-terminated
388 };
389
390}
391
392/*
393 ********************************************************************************
394 ***************************** Implementation Details ***************************
395 ********************************************************************************
396 */
397#include "StringBuilder.inl"
398
399#endif /*_Stroika_Foundation_Characters_StringBuilder_h_*/
Similar to String, but intended to more efficiently construct a String. Mutable type (String is large...
Characters::String ToString() const
same as str (): so a StringBuilder formats as its text, with _f and std::format alike
nonvirtual void Append(span< const CHAR_T > s)
String is like std::u32string, except it is much easier to use, often much more space efficient,...
Definition String.h:201
UNICODE string can be always be converted into array of this type.
Definition Character.h:132
IUNICODECanUnambiguouslyConvertFrom is any 'character representation type' where array of them unambi...
Definition Character.h:179
String UnoverloadedToString(const T &t)
same as ToString()/1 - but without the potentially confusing multi-arg overloads (confused some templ...
Definition ToString.inl:435
rarely used directly - defaults generally fine