-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathstringbuilder.h
More file actions
1268 lines (1082 loc) · 51.8 KB
/
stringbuilder.h
File metadata and controls
1268 lines (1082 loc) · 51.8 KB
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
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
MIT License
Copyright (c) 2017-2020 Mariusz Łapiński <gmail:isameru>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
███████╗████████╗██████╗ ██╗███╗ ██╗ ██████╗ .██████╗ ██╗ ██╗██╗██╗ ██████╗ ███████╗██████╗
██╔════╝╚══██╔══╝██╔══██╗██║████╗ ██║██╔════╝ ██╔══██╗██║ ██║██║██║ ██╔══██╗██╔════╝██╔══██╗
███████╗ ██║ ██████╔╝██║██╔██╗ ██║██║ ███╗-:██████╔╝██║ ██║██║██║ ██║ ██║█████╗ ██████╔╝
╚════██║ ██║ ██╔══██╗██║██║╚██╗██║██║ ██║ ██╔══██╗██║ ██║██║██║ ██║ ██║██╔══╝ ██╔══██╗
███████║ ██║ ██║ ██║██║██║ ╚████║╚██████╔╝ .██████╔╝╚██████╔╝██║███████╗██████╔╝███████╗██║ ██║
╚══════╝ ╚═╝ ╚═╝ ╚═╝╚═╝╚═╝ ╚═══╝ ╚═════╝ ╚═════╝ ╚═════╝ ╚═╝╚══════╝╚═════╝ ╚══════╝╚═╝ ╚═╝
GitHub : https://github.com/Isameru/stringbuilder
Version : 1.1
Release Notes
:----------------
Version 1.1 (2020-03)
* C++11/C++14 support
* Fresh CMake files
* Doxygen, comments
Version 1.0 (2017)
* inplace_stringbuilder, stringbuilder, make_string, tests, benchmark
* Performance optimizations
* CMake, Travis, Appveyor
TODO
:-------
* Formatters (aligned column, float)
* More tests!
*/
#pragma once
#include <new>
#include <array>
#include <memory>
#include <string>
#include <numeric>
#include <utility>
#include <assert.h>
#include <type_traits>
#if defined(__has_include) && __has_include(<string_view>) && __cpp_lib_string_view
#include <string_view>
#define STRINGBUILDER_USES_STRING_VIEW true
#else
#define STRINGBUILDER_USES_STRING_VIEW false
#endif
#ifndef STRINGBUILDER_NAMESPACE
#define STRINGBUILDER_NAMESPACE sbldr
#endif
//#ifndef STRINGBUILDER_SIZE_T
//#define STRINGBUILDER_SIZE_T size_t
//#endif
#ifdef __GNUC__
#define STRINGBUILDER_LIKELY(x) __builtin_expect(!!(x), 1)
#define STRINGBUILDER_UNLIKELY(x) __builtin_expect(!!(x), 0)
#define STRINGBUILDER_NOINLINE __attribute__((noinline))
#else
#define STRINGBUILDER_LIKELY(x) (x)
#define STRINGBUILDER_UNLIKELY(x) (x)
#define STRINGBUILDER_NOINLINE __declspec(noinline)
#endif
#if defined(__has_include) && __has_include(<intrin.h>)
#include <intrin.h>
#endif
namespace STRINGBUILDER_NAMESPACE
{
namespace detail
{
inline void prefetchWrite(const void* p)
{
#if defined(__GNUC__)
__builtin_prefetch(p, 1);
#elif defined(_WIN32)
_mm_prefetch((const char*)p, _MM_HINT_T0);
#endif
}
}
template<size_t ExpectedSize, typename StringT>
struct sized_str_t
{
StringT str;
};
#ifdef __cpp_decltype_auto
template<size_t ExpectedSize, typename StringT>
auto sized_str(StringT&& str)
{
return sized_str_t<ExpectedSize, StringT>{ std::forward<StringT>(str) };
}
#endif
// Appender is an utility class for encoding various kinds of objects (integers) and their propagation to stringbuilder or inplace_stringbuilder.
//
// Unless there are suitable converters, make use of to_string() to stringify the object.
template<typename SB, typename T, typename Enable = void>
struct sb_appender {
void operator()(SB& sb, const T& v) const {
using namespace std;
sb.append(to_string(v));
}
};
template<typename SB, size_t ExpectedSize, typename StringT>
struct sb_appender<SB, sized_str_t<ExpectedSize, StringT>>
{
void operator()(SB& sb, const sized_str_t<ExpectedSize, StringT>& sizedStr) const
{
sb.append(sizedStr.str);
}
};
template<typename SB>
struct sb_appender<SB, const typename SB::char_type*>
{
void operator()(SB& sb, const typename SB::char_type* str) const
{
sb.append_c_str(str);
}
};
/// Compile-time switch which controls the behaiovr of inplace_stringbuilder upon buffer overflow.
///
enum class inplace_stringbuilder_overflow_polcy {
assert, // Debug: assertion failure | Release: like corrupt_memory
corrupt_memory, // Overwrite the memory beyond the buffer (not recommended)
early_exception, // Throw inplace_stringbuilder_early_overflow_error exception while the content remains unaltered
late_exception, // Throw inplace_stringbuilder_late_overflow_error expection after the content is filled up to the maximal capacity
protect // Fill up the content up to the maximal capacity, while the rest is ignored (clipped)
};
/// Exception raised whenever overflow occurs in an inplace_stringbuilder with overflow policy set to early_exception or later_exception.
///
struct inplace_stringbuilder_overflow_error : public std::overflow_error {
inplace_stringbuilder_overflow_error() :
std::overflow_error{ "inplace_stringbuilder overflow" }
{ }
};
/// Exception raised whenever overflow occurs in an inplace_stringbuilder with overflow policy set to early_exception.
///
struct inplace_stringbuilder_early_overflow_error : public inplace_stringbuilder_overflow_error {};
/// Exception raised whenever overflow occurs in an inplace_stringbuilder with overflow policy set to later_exception.
///
struct inplace_stringbuilder_late_overflow_error : public inplace_stringbuilder_overflow_error {};
/// Provides means for building size-delimited strings in-situ (without heap allocations).
/// Object of this class occupies fixed size (specified at compile-time) and allows appending portions of strings unless there is space available.
/// In debug mode appending ensures that the built string does not exceed the available space.
/// In release mode no such checks are made thus dangerous memory corruption may occur if used incorrectly.
///
template<
typename CharT,
size_t MaxSize,
bool Forward = true,
typename Traits = std::char_traits<CharT>,
inplace_stringbuilder_overflow_polcy OverflowPolicy = inplace_stringbuilder_overflow_polcy::assert
>
class basic_inplace_stringbuilder
{
static_assert(MaxSize > 0, "MaxSize must be greater than zero");
public:
using traits_type = Traits;
using char_type = CharT;
using value_type = char_type;
using size_type = size_t;
using difference_type = std::ptrdiff_t;
using reference = char_type&;
using const_reference = const char_type&;
using pointer = char_type*;
using const_pointer = const char_type*;
static constexpr bool forward = Forward;
static constexpr inplace_stringbuilder_overflow_polcy overflow_policy = OverflowPolicy;
/// Indicates whether the append*() function calls may throw.
/// This may happen upon character buffer overflow when the overflow policy is set to either early_exception or late_exception.
static constexpr bool append_may_not_throw = overflow_policy != inplace_stringbuilder_overflow_polcy::early_exception && overflow_policy != inplace_stringbuilder_overflow_polcy::late_exception;
/// Gets the number of characters appended to the buffer.
size_type size() const noexcept { return consumed; }
/// Gets the number of characters appended to the buffer.
size_type length() const noexcept { return size(); }
/// Gets the number of characters which can be safely appended to the buffer (before overflow happens).
size_type space_left() const noexcept { return MaxSize - consumed; }
/// Appends a single character to the buffer.
basic_inplace_stringbuilder& append(char_type ch)
//noexcept(append_may_not_throw)
{
assert(ch != '\0' && "Cannot append a null-termination character, as it may lead to undesirable effects");
switch (overflow_policy) {
case inplace_stringbuilder_overflow_polcy::assert:
assert(consumed < MaxSize);
break;
case inplace_stringbuilder_overflow_polcy::corrupt_memory:
break;
case inplace_stringbuilder_overflow_polcy::early_exception:
if (consumed >= MaxSize)
throw inplace_stringbuilder_early_overflow_error{};
break;
case inplace_stringbuilder_overflow_polcy::late_exception:
if (consumed >= MaxSize)
throw inplace_stringbuilder_late_overflow_error{};
break;
case inplace_stringbuilder_overflow_polcy::protect:
if (consumed >= MaxSize)
return *this;
break;
}
if (Forward) {
data_[consumed++] = ch;
}
else {
data_[MaxSize - (++consumed)] = ch;
}
return *this;
}
/// Appends the same character specified number of times.
basic_inplace_stringbuilder& append(size_type count, char_type ch)
//noexcept(append_may_not_throw)
{
assert(ch != '\0' && "Cannot append a null-termination character (\\0), as it may lead to undesirable effects");
bool throw_late_exception;
switch (overflow_policy) {
case inplace_stringbuilder_overflow_polcy::assert:
assert(consumed + count <= MaxSize);
break;
case inplace_stringbuilder_overflow_polcy::corrupt_memory:
break;
case inplace_stringbuilder_overflow_polcy::early_exception:
if (consumed + count > MaxSize)
throw inplace_stringbuilder_early_overflow_error{};
break;
case inplace_stringbuilder_overflow_polcy::late_exception: {
auto original_count = count;
count = std::min(space_left(), count);
throw_late_exception = (original_count != count);
break;
}
case inplace_stringbuilder_overflow_polcy::protect:
count = std::min(space_left(), count);
break;
}
if (Forward) {
while (count-- > 0) data_[consumed++] = ch;
}
else {
while (count-- > 0) data_[MaxSize - (++consumed)] = ch;
}
if (overflow_policy == inplace_stringbuilder_overflow_polcy::late_exception) {
if (throw_late_exception)
throw inplace_stringbuilder_late_overflow_error{};
}
return *this;
}
/// Appends a string literal, i.e. an array of characters without the last element, which is expected to be a trailing null-termination character.
template<size_type StrSizeWith0>
basic_inplace_stringbuilder& append(const char_type(&str)[StrSizeWith0])
//noexcept(append_may_not_throw)
{
assert(str[StrSizeWith0-1] == 0);
return append(str, StrSizeWith0-1);
}
/// Appends an array of characters.
template<size_type N>
basic_inplace_stringbuilder& append(const std::array<char_type, N>& arr)
//noexcept(append_may_not_throw)
{
return append(arr.data(), N);
}
/// Appends the specified number of characters of a given C-style string.
/// It is up to the user to ensure that the specified sized string is valid.
basic_inplace_stringbuilder& append(const char_type* str, size_type size)
//noexcept(append_may_not_throw)
{
bool throw_late_exception;
switch (overflow_policy) {
case inplace_stringbuilder_overflow_polcy::assert:
assert(consumed + size <= MaxSize);
break;
case inplace_stringbuilder_overflow_polcy::corrupt_memory:
break;
case inplace_stringbuilder_overflow_polcy::early_exception:
if (consumed + size > MaxSize)
throw inplace_stringbuilder_early_overflow_error{};
break;
case inplace_stringbuilder_overflow_polcy::late_exception: {
auto original_size = size;
size = std::min(space_left(), size);
throw_late_exception = (original_size != size);
break;
}
case inplace_stringbuilder_overflow_polcy::protect:
size = std::min(space_left(), size);
break;
}
if (Forward) {
Traits::copy(data_.data() + consumed, str, size);
}
else {
Traits::copy(data_.data() + MaxSize - size - consumed, str, size);
}
consumed += size;
if (overflow_policy == inplace_stringbuilder_overflow_polcy::late_exception) {
if (throw_late_exception)
throw inplace_stringbuilder_late_overflow_error{};
}
return *this;
}
/// Appends the specified number of characters of a given C-style string.
/// It is up to the user to ensure that the specified sized string is valid.
basic_inplace_stringbuilder& append_c_str(const char_type* str, size_type size)
//noexcept(append_may_not_throw)
{
return append(str, size);
}
/// Appends the null-terminated C-style string.
basic_inplace_stringbuilder& append_c_str(const char_type* str)
noexcept(append_may_not_throw)
{
return append(str, Traits::length(str));
}
/// Appends the null-terminated C-style string, copying the characters one-by-one.
/// This method may be slightly faster than append_c_str() for small strings (up to 4 characters), whose size is unknown a priori.
/// This is not a recommended approach, unless it proves to give a visible performance gain in your benchmark.
basic_inplace_stringbuilder& append_c_str_progressive(const char_type* str)
//noexcept(append_may_not_throw)
{
assert(Forward && "Progressive append is supported only in Forward mode");
while (*str != 0)
{
switch (overflow_policy) {
case inplace_stringbuilder_overflow_polcy::assert:
assert(consumed < MaxSize);
break;
case inplace_stringbuilder_overflow_polcy::corrupt_memory:
break;
case inplace_stringbuilder_overflow_polcy::early_exception:
// Progressive append cannot detect the overflow beforehand, so it works like late_exception.
if (consumed >= MaxSize)
throw inplace_stringbuilder_early_overflow_error{};
break;
case inplace_stringbuilder_overflow_polcy::late_exception:
if (consumed >= MaxSize)
throw inplace_stringbuilder_early_overflow_error{};
break;
case inplace_stringbuilder_overflow_polcy::protect:
if (consumed >= MaxSize)
return *this;
break;
}
data_[consumed++] = *(str++);
}
return *this;
}
/// Appends a string.
template<typename OtherTraits, typename OtherAlloc>
basic_inplace_stringbuilder& append(const std::basic_string<char_type, OtherTraits, OtherAlloc>& str)
//noexcept(append_may_not_throw)
{
return append(str.data(), str.size());
}
#if STRINGBUILDER_USES_STRING_VIEW
/// Appends a string view.
template<typename OtherTraits>
basic_inplace_stringbuilder& append(const std::basic_string_view<char_type, OtherTraits>& sv)
//noexcept(append_may_not_throw)
{
return append(sv.data(), sv.size());
}
#endif
/// Appends an in-place string builder.
template<size_type OtherMaxSize, bool OtherForward, typename OtherTraits>
basic_inplace_stringbuilder& append(const basic_inplace_stringbuilder<char_type, OtherMaxSize, OtherForward, OtherTraits>& sb)
//noexcept(append_may_not_throw)
{
return append_c_str(sb.data(), sb.size());
}
/// Appends an "any" object using a type-deduced formatter.
template<typename T>
basic_inplace_stringbuilder& append(const T& v)
{
sb_appender<basic_inplace_stringbuilder, T>{}(*this, v);
return *this;
}
/// Appends an "any" object using a type-deduced formatter.
template<typename AnyT>
basic_inplace_stringbuilder& operator<<(AnyT&& any)
{
return append(std::forward<AnyT>(any));
}
/// Appends multiple "any" objects using type-deduced formatters.
template<typename AnyT>
basic_inplace_stringbuilder& append_many(AnyT&& any)
{
return append(std::forward<AnyT>(any));
}
/// Appends multiple "any" objects using type-deduced formatters.
template<typename AnyT1, typename... AnyTX>
basic_inplace_stringbuilder& append_many(AnyT1&& any1, AnyTX&&... anyX)
{
return append(std::forward<AnyT1>(any1)).append_many(std::forward<AnyTX>(anyX)...);
}
/// Gets the pointer to the first character in the internal buffer.
/// The retrieved string is not null-terminated.
char_type* data() noexcept
{
return data_.data() + (Forward ? 0 : MaxSize - consumed);
}
/// Gets the const-pointer to the first character in the internal buffer.
/// The retrieved string is not null-terminated.
const char_type* data() const noexcept
{
return data_.data() + (Forward ? 0 : MaxSize - consumed);
}
/// Gets the pointer to the beginning of a null-terminated C-style string.
const char_type* c_str() const noexcept
{
// Placing '\0' at the end of string is a kind of lazy evaluation and is acceptable also for const objects.
const_cast<basic_inplace_stringbuilder*>(this)->placeNullTerminator();
return data();
}
/// Creates and returns a string object containing a copy of all appended characters.
std::basic_string<char_type> str() const
{
assert(consumed <= MaxSize);
const auto b = data_.cbegin();
if /*constexpr*/ (Forward) {
return { b, b + consumed };
}
else {
return { b + MaxSize - consumed, b + MaxSize };
}
}
#if STRINGBUILDER_USES_STRING_VIEW
/// Returns a string_view spanning over all appended characters.
/// The retrieved string is not null-terminated.
std::basic_string_view<char_type, traits_type> str_view() const noexcept
{
return { data(), size() };
}
#endif
/// Prints the content to the output stream.
template<typename OtherCharTraitsT>
friend std::basic_ostream<char_type, OtherCharTraitsT>& operator<<(
std::basic_ostream<char_type, OtherCharTraitsT>& out,
const basic_inplace_stringbuilder<char_type, MaxSize, forward, traits_type, overflow_policy>& sb)
{
return out.write(sb.data(), static_cast<std::streamsize>(sb.size()));
}
private:
/// Puts a null-termination character ('\0') after the last appended character.
void placeNullTerminator() const noexcept
{
assert(consumed <= MaxSize);
const_cast<char_type&>(data_[Forward ? consumed : MaxSize]) = '\0';
}
private:
/// Number of characters appended to the buffer.
size_type consumed = 0;
/// In-situ internal character buffer.
std::array<char_type, MaxSize + 1> data_; // Last character is reserved for '\0'.
};
namespace detail
{
// The following code is based on Empty Base Optimization Helper (ebo_helper) explained in this talk:
// https://youtu.be/hHQS-Q7aMzg?t=3039 [code::dive 2016 conference – Mateusz Pusz – std::shared_ptr/T/]
// This technique achieves what [[no_unique_address]] attribute (available since C++20) does.
//
template<typename OrigAlloc, bool UseEbo =
#if __cpp_lib_is_final
!std::is_final<OrigAlloc>::value&& std::is_empty<OrigAlloc>::value
#else
false
#endif
>
struct raw_alloc_provider;
template<typename OrigAlloc>
struct raw_alloc_provider<OrigAlloc, true> :
private std::allocator_traits<OrigAlloc>::template rebind_alloc<uint8_t>
{
using AllocRebound = typename std::allocator_traits<OrigAlloc>::template rebind_alloc<uint8_t>;
template<typename OtherAlloc> constexpr explicit raw_alloc_provider(OtherAlloc&& otherAlloc) : AllocRebound{ std::forward<AllocRebound>(otherAlloc) } {}
AllocRebound& get_rebound_allocator() { return *this; }
OrigAlloc get_original_allocator() const { return OrigAlloc{ *this }; }
};
template<typename OrigAlloc>
struct raw_alloc_provider<OrigAlloc, false>
{
using AllocRebound = typename std::allocator_traits<OrigAlloc>::template rebind_alloc<uint8_t>;
template<typename OtherAlloc> constexpr explicit raw_alloc_provider(OtherAlloc&& otherAlloc) : alloc_rebound{ std::forward<AllocRebound>(otherAlloc) } {}
AllocRebound& get_rebound_allocator() { return alloc_rebound; }
OrigAlloc get_original_allocator() const { return OrigAlloc{ alloc_rebound }; }
private:
mutable AllocRebound alloc_rebound;
};
template<typename CharT>
struct Chunk;
template<typename CharT>
struct ChunkHeader
{
Chunk<CharT>* next;
size_t consumed;
size_t reserved;
};
template<typename CharT>
struct Chunk : public ChunkHeader<CharT>
{
CharT data[1]; // In practice there are ChunkHeader::reserved of characters in this array.
Chunk(size_t reserve) : ChunkHeader<CharT>{nullptr, size_t{0}, reserve} { }
};
template<typename CharT, int DataLength>
struct ChunkInPlace : public ChunkHeader<CharT>
{
std::array<CharT, DataLength> data;
ChunkInPlace() : ChunkHeader<CharT>{nullptr, 0, DataLength} { }
};
template<typename CharT>
struct ChunkInPlace<CharT, 0> : public ChunkHeader<CharT>
{
ChunkInPlace() : ChunkHeader<CharT>{nullptr, 0, 0} { }
};
}
/// Provides means for efficient construction of strings.
/// Object of this class occupies fixed size (specified at compile-time) and allows appending portions of strings.
/// If the available space gets exhausted, new chunks of memory are allocated on the heap.
///
template<typename Char,
size_t InPlaceSize,
typename Traits,
typename AllocOrig>
class basic_stringbuilder : private detail::raw_alloc_provider<AllocOrig>
{
using AllocProvider = detail::raw_alloc_provider<AllocOrig>;
using Alloc = typename AllocProvider::AllocRebound;
using AllocTraits = std::allocator_traits<Alloc>;
public:
using traits_type = Traits;
using char_type = Char;
using value_type = char_type;
using allocator_type = AllocOrig;
using size_type = size_t;
using difference_type = std::ptrdiff_t;
using reference = char_type&;
using const_reference = const char_type&;
using pointer = char_type*;
using const_pointer = const char_type*;
static constexpr size_t inplace_size = InPlaceSize;
private:
using Chunk = detail::Chunk<char_type>;
using ChunkHeader = detail::ChunkHeader<char_type>;
template<int N> using ChunkInPlace = detail::ChunkInPlace<char_type, N>;
public:
/// Recreates and returns the allocator originally passed to stringbuilder object during construction (it is kept internally in a rebound form).
AllocOrig get_allocator() const noexcept { return AllocProvider::get_original_allocator(); }
template<typename AllocOther = Alloc>
basic_stringbuilder(AllocOther&& allocOther = AllocOther{}) noexcept : AllocProvider{std::forward<AllocOther>(allocOther)} {}
basic_stringbuilder(const basic_stringbuilder&) = delete;
basic_stringbuilder(basic_stringbuilder&& other) noexcept :
AllocProvider{other.get_allocator()},
headChunkInPlace{other.headChunkInPlace},
tailChunk{other.tailChunk}
{
other.headChunkInPlace.next = nullptr;
}
~basic_stringbuilder()
{
Chunk* nextChunk = headChunk()->next;
for (auto chunk = nextChunk; chunk != nullptr; chunk = nextChunk)
{
nextChunk = chunk->next;
//AllocTraits::destroy...?
AllocTraits::deallocate(AllocProvider::get_rebound_allocator(), reinterpret_cast<typename AllocTraits::pointer>(chunk), sizeof(ChunkHeader) + chunk->reserved);
}
}
/// Gets the number of characters appended to the buffer.
size_type size() const noexcept
{
size_type size = 0;
const auto* chunk = headChunk();
do {
size += chunk->consumed;
chunk = chunk->next;
} while (chunk != nullptr);
return size;
}
/// Gets the number of characters appended to the buffer.
size_type length() const noexcept { return size(); }
void reserve(size_type size)
{
for (Chunk* chunk = tailChunk; size > chunk->reserved - chunk->consumed; chunk = chunk->next)
{
size -= chunk->reserved - chunk->consumed;
assert(size > 0);
if (chunk->next == nullptr) {
chunk->next = allocChunk(size);
}
}
}
/// Appends a single character to the buffer.
basic_stringbuilder& append(char_type ch)
{
assert(ch != '\0');
claimOne() = ch;
return *this;
}
/// Appends the same character specified number of times.
basic_stringbuilder& append(size_type count, char_type ch)
{
assert(ch != '\0');
for (auto left = count; left > 0;) {
const auto claimed = claim(1, left);
for (size_type i = 0; i < claimed.second; ++i) {
claimed.first[i] = ch;
}
left -= claimed.second;
}
return *this;
}
/// Appends a string literal, i.e. an array of characters without the last element, which is expected to be a trailing null-termination character.
template<size_type StrSizeWith0>
basic_stringbuilder& append(const char_type(&str)[StrSizeWith0])
{
assert(str[StrSizeWith0-1] == 0);
return append(str, StrSizeWith0-1);
}
/// Appends an array of characters.
template<size_type N>
basic_stringbuilder& append(const std::array<char_type, N>& arr)
{
return append(arr.data(), N);
}
/// Appends the specified number of characters of a given C-style string.
/// It is up to the user to ensure that the specified sized string is valid.
basic_stringbuilder& append(const char_type* str, size_type size)
{
Traits::copy(claim(size), str, size);
return *this;
}
/// Appends the specified number of characters of a given C-style string.
/// It is up to the user to ensure that the specified sized string is valid.
basic_stringbuilder& append_c_str(const char_type* str, size_type size)
{
return append(str, size);
}
/// Appends the null-terminated C-style string.
template<bool Prefetch = false>
basic_stringbuilder& append_c_str(const char_type* str)
{
if (Prefetch) detail::prefetchWrite(&tailChunk->data[tailChunk->consumed]);
return append(str, Traits::length(str));
}
/// Appends the null-terminated C-style string, copying the characters one-by-one.
/// This method may be slightly faster than append_c_str() for small strings (up to 4 characters), whose size is unknown a priori.
/// This is not a recommended approach, unless it proves to give a visible performance gain in your benchmark.
basic_stringbuilder& append_c_str_progressive(const char_type* str)
{
while (true) {
auto claimed = claim(1, 64);
auto dst = claimed.first;
const auto dstEnd = dst + claimed.second;
while (dst < dstEnd) {
if (*str == 0) {
reclaim(dstEnd - dst);
return *this;
}
*(dst++) = *(str++);
}
}
assert(false);
return *this;
}
/// Appends a string.
template<typename OtherTraits, typename OtherAlloc>
basic_stringbuilder& append(const std::basic_string<char_type, OtherTraits, OtherAlloc>& str)
{
return append(str.data(), str.size());
}
#if STRINGBUILDER_USES_STRING_VIEW
/// Appends a string view.
template<typename OtherTraits>
basic_stringbuilder& append(const std::basic_string_view<char_type, OtherTraits>& sv)
{
return append(sv.data(), sv.size());
}
#endif
/// Appends an in-place string builder.
template<size_type OtherMaxSize, bool OtherForward, typename OtherTraits>
basic_stringbuilder& append(const basic_inplace_stringbuilder<char_type, OtherMaxSize, OtherForward, OtherTraits>& sb)
{
return append(sb.data(), sb.size());
}
/// Appends a string builder.
template<size_type OtherInPlaceSize, typename OtherTraits, typename OtherAlloc>
basic_stringbuilder& append(const basic_stringbuilder<char_type, OtherInPlaceSize, OtherTraits, OtherAlloc>& sb)
{
size_type size = sb.size();
reserve(size);
const Chunk* chunk = sb.headChunk();
while (size > 0) {
assert(chunk != nullptr);
const size_type toCopy = std::min(size, chunk->consumed);
append(chunk->data, toCopy);
size -= toCopy;
chunk = chunk->next;
}
return *this;
}
/// Appends an "any" object using a type-deduced formatter.
template<typename T>
basic_stringbuilder& append(const T& v)
{
sb_appender<basic_stringbuilder, T>{}(*this, v);
return *this;
}
/// Appends an "any" object using a type-deduced formatter.
template<typename AnyT>
basic_stringbuilder& operator<<(AnyT&& any)
{
return append(std::forward<AnyT>(any));
}
/// Appends multiple "any" objects using type-deduced formatters.
template<typename AnyT>
basic_stringbuilder& append_many(AnyT&& any)
{
return append(std::forward<AnyT>(any));
}
/// Appends multiple "any" objects using type-deduced formatters.
template<typename AnyT1, typename... AnyTX>
basic_stringbuilder& append_many(AnyT1&& any1, AnyTX&&... anyX)
{
return append(std::forward<AnyT1>(any1)).append_many(std::forward<AnyTX>(anyX)...);
}
/// Creates and returns a string object containing a copy of all appended characters.
std::basic_string<char_type> str() const
{
const auto size0 = size();
auto str = std::basic_string<char_type>{};
str.reserve(size0);
for (const Chunk* chunk = headChunk(); chunk != nullptr; chunk = chunk->next)
{
str.append(chunk->data, chunk->consumed);
}
return str;
}
/// Checks whether the contained (valid) characters form a linear buffer in memory.
bool is_linear() const
{
const auto* chunk = headChunk();
bool has_data = chunk->consumed > 0;
while (chunk->next) {
chunk = chunk->next;
if (chunk->consumed > 0) {
if (has_data)
return false;
has_data = true;
}
}
return true;
}
#if STRINGBUILDER_USES_STRING_VIEW
/// Returns a string_view spanning over all appended characters.
/// The retrieved string is not null-terminated.
std::basic_string_view<char_type> str_view() const
{
assert(is_linear());
const auto* chunk = headChunk();
while (chunk->consumed == 0) {
chunk = chunk->next;
assert(chunk != nullptr);
}
return { chunk->data, chunk->consumed };
}
#endif
/// Prints the content to the output stream.
/// There may be multiple writes to ostream.
template<typename OtherCharTraitsT>
friend std::basic_ostream<char_type, OtherCharTraitsT>& operator<<(
std::basic_ostream<char_type, OtherCharTraitsT>& out,
const basic_stringbuilder<char_type, inplace_size, traits_type, allocator_type>& sb)
{
for (const Chunk* chunk = sb.headChunk(); chunk != nullptr; chunk = chunk->next)
{
out.write(chunk->data, static_cast<std::streamsize>(chunk->consumed));
}
return out;
}
private:
Chunk* headChunk() noexcept { return reinterpret_cast<Chunk*>(&headChunkInPlace); }
const Chunk* headChunk() const noexcept { return reinterpret_cast<const Chunk*>(&headChunkInPlace); }
char_type* claim(size_type exact)
{
if (STRINGBUILDER_UNLIKELY(tailChunk->reserved - tailChunk->consumed < exact))
prepareSpace(exact);
char_type* const claimedChars = &tailChunk->data[tailChunk->consumed];
tailChunk->consumed += exact;
return claimedChars;
}
std::pair<char_type*, size_type> claim(size_type minimum, size_type maximum)
{
assert(maximum >= minimum);
assert(tailChunk->reserved >= tailChunk->consumed);
if (STRINGBUILDER_UNLIKELY(tailChunk->reserved - tailChunk->consumed < minimum))
prepareSpace(minimum, maximum);
assert(tailChunk->reserved >= tailChunk->consumed);
assert(minimum <= tailChunk->reserved - tailChunk->consumed);
const size_type claimedSize = std::min(maximum, tailChunk->reserved - tailChunk->consumed);
const auto claimed = std::make_pair(&tailChunk->data[tailChunk->consumed], claimedSize);
tailChunk->consumed += claimedSize;
return claimed;
}
Char& claimOne()
{
if (STRINGBUILDER_UNLIKELY(tailChunk->reserved - tailChunk->consumed < 1))
prepareSpace(1);
return tailChunk->data[tailChunk->consumed++];
}
void reclaim(size_t exact)
{
assert(tailChunk->consumed >= exact);
tailChunk->consumed -= exact;
}
STRINGBUILDER_NOINLINE void prepareSpace(size_type minimum)
{
if (tailChunk->next == nullptr) {
tailChunk->next = allocChunk(minimum);
tailChunk = tailChunk->next;
}
else {
while (true) {
tailChunk = tailChunk->next;
assert(tailChunk->consumed == 0);
if (tailChunk->reserved >= minimum)
return;
if (tailChunk->next == nullptr)
tailChunk->next = allocChunk(minimum);
}
}
}
STRINGBUILDER_NOINLINE void prepareSpace(size_type minimum, size_type maximum)
{
if (tailChunk->next == nullptr) {
tailChunk->next = allocChunk(maximum);
tailChunk = tailChunk->next;
}
else
{
while (true) {
tailChunk = tailChunk->next;
assert(tailChunk->consumed == 0);
if (tailChunk->reserved >= minimum)
return;
if (tailChunk->next == nullptr)
tailChunk->next = allocChunk(maximum);
}
}
}
size_type determineNextChunkSize(size_type minimum) const noexcept { return std::max(2 * tailChunk->reserved, minimum); }
constexpr static size_type l1DataCacheLineSize = 64; //std::hardware_destructive_interference_size;
constexpr static size_type roundToL1DataCacheLine(size_type size) noexcept
{
return ((l1DataCacheLineSize - 1) + size) / l1DataCacheLineSize * l1DataCacheLineSize;
}
Chunk* allocChunk(size_type minimum)
{
assert(minimum > 0);
const auto chunkTotalSize = roundToL1DataCacheLine(determineNextChunkSize(minimum) + sizeof(ChunkHeader));
auto* rawChunk = AllocTraits::allocate(AllocProvider::get_rebound_allocator(), chunkTotalSize, tailChunk);
auto* chunk = reinterpret_cast<Chunk*>(rawChunk);