-
Notifications
You must be signed in to change notification settings - Fork 25
/
Copy pathSIMDString.h
2366 lines (1965 loc) · 82.5 KB
/
SIMDString.h
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
#pragma once
/*
MIT License
Copyright (c) 2022 Morgan McGuire and Zander Majercik
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.
*/
#define USE_SSE_MEMCPY 1
#include <string>
#include <stdint.h>
#include <assert.h>
#include <algorithm>
#include <cstring>
#include <iterator>
#include <cstddef>
#include <limits>
#include <ios>
#include <iostream>
#include <string_view>
#include <initializer_list>
#include <errno.h>
#if defined(USE_SSE_MEMCPY) && USE_SSE_MEMCPY
# if defined(__i386__) || defined(_M_IX86) || defined(__x86_64__) || defined(_M_X64)
# define SSE_x64
# include <immintrin.h>
typedef __m128i u64x2_t;
# elif defined(__ARM_NEON) || defined(__arm__) || defined(_M_ARM)
# include <arm_neon.h>
typedef uint64x2_t u64x2_t;
# endif
#endif
#if defined(USE_G3D_ALLOCATOR) || (G3D_ALLOCATOR == 1)
# include <G3D-base/System.h>
#endif
#ifdef G3D_System_h
#define TEMPLATE template<size_t INTERNAL_SIZE = 64, class Allocator = G3D::g3d_allocator<char>>
#else
#define TEMPLATE template<size_t INTERNAL_SIZE = 64, class Allocator = ::std::allocator<char>>
#endif
bool inConstSegment(const char* c);
constexpr size_t SSO_ALIGNMENT = 16;
/**
\brief Very fast string class that follows the std::string/std::basic_string interface.
- Recognizes constant segment strings and avoids copying them
- Stores small strings internally to avoid heap allocation
- Uses SSE instructions to copy internal strings
- Uses the G3D free-list/block allocator when heap allocation is required
INTERNAL_SIZE is in bytes. It should be chosen to be a multiple of 16.
*/
TEMPLATE
class
/** This inline storage is used when strings are small */
alignas(SSO_ALIGNMENT)
SIMDString {
public:
typedef char value_type;
typedef std::char_traits<value_type> traits_type;
typedef value_type& reference;
typedef const value_type& const_reference;
typedef value_type* pointer;
typedef const value_type* const_pointer;
typedef ptrdiff_t difference_type;
typedef size_t size_type;
// We use custom iterators for this function, because otherwise
// SIMDString(char*, 0) is ambiguously overloaded
template<typename StrType>
class Const_Iterator {
public:
using iterator_category = std::random_access_iterator_tag;
using value_type = typename StrType::value_type;
using reference = const value_type&;
using pointer = typename StrType::const_pointer;
using difference_type = typename StrType::difference_type;
private:
pointer m_ptr;
public:
Const_Iterator() : m_ptr(nullptr) {}
Const_Iterator(pointer ptr) : m_ptr(ptr) {}
Const_Iterator(const Const_Iterator& i) : m_ptr(i.m_ptr) {}
inline reference operator*() const { return *m_ptr; }
inline pointer operator->() const { std::pointer_traits<pointer>::pointer_to(**this); }
inline reference operator[](difference_type rhs) { return m_ptr[rhs]; }
inline Const_Iterator& operator+=(difference_type rhs) {m_ptr += rhs; return *this;}
inline Const_Iterator& operator++() { m_ptr++; return *this; }
inline Const_Iterator operator++(int) { Const_Iterator tmp (*this); ++m_ptr; return tmp; }
inline Const_Iterator& operator-=(difference_type rhs) {m_ptr -= rhs; return *this;}
inline Const_Iterator& operator--() { m_ptr--; return *this; }
inline Const_Iterator operator--(int) { Const_Iterator tmp(*this); --(*this); return tmp; }
inline difference_type operator-(const Const_Iterator& rhs) const {return m_ptr - rhs.m_ptr;}
inline Const_Iterator operator-(difference_type rhs) const { Const_Iterator tmp (*this); return tmp -= rhs; }
inline Const_Iterator operator+(difference_type rhs) const { Const_Iterator tmp (*this); return tmp += rhs; }
friend inline Const_Iterator operator+(difference_type lhs, Const_Iterator<StrType> rhs){ return rhs += lhs; }
inline bool operator== (const Const_Iterator& rhs) const { return m_ptr == rhs.m_ptr; };
inline bool operator!= (const Const_Iterator& rhs) const { return m_ptr != rhs.m_ptr; };
inline bool operator< (const Const_Iterator& rhs) const { return m_ptr < rhs.m_ptr; };
inline bool operator<= (const Const_Iterator& rhs) const { return m_ptr <= rhs.m_ptr; };
inline bool operator> (const Const_Iterator& rhs) const { return m_ptr > rhs.m_ptr; };
inline bool operator>= (const Const_Iterator& rhs) const { return m_ptr >= rhs.m_ptr; };
};
template<typename StrType>
class Iterator: public Const_Iterator<StrType> {
public:
using super = Const_Iterator<StrType>;
using iterator_category = std::random_access_iterator_tag;
using value_type = typename StrType::value_type;
using reference = value_type&;
using pointer = typename StrType::pointer;
using difference_type = typename StrType::difference_type;
using super::super;
inline reference operator*() { return const_cast<reference>(super::operator*()); }
inline pointer operator->() { std::pointer_traits<pointer>::pointer_to(**this); }
inline reference operator[](difference_type diff) { return const_cast<reference>(super::operator[](diff)); }
inline Iterator& operator+=(difference_type rhs) { super::operator+=(rhs); return *this; }
inline Iterator& operator++() { super::operator++(); return *this; }
inline Iterator operator++(int) { Iterator tmp (*this); super::operator++(); return tmp; }
inline Iterator& operator-=(difference_type rhs) { super::operator-=(rhs); return *this; }
inline Iterator& operator--() { super::operator--(); return *this; }
inline Iterator operator--(int) { Iterator tmp(*this); super::operator--(); return tmp; }
using super::operator-;
inline Iterator operator-(difference_type rhs) const { Iterator tmp (*this); return tmp -= rhs; }
inline Iterator operator+(difference_type rhs) const { Iterator tmp (*this); return tmp += rhs; }
friend inline Iterator operator+(difference_type lhs, Iterator<StrType> rhs){ return rhs += lhs; }
using super::operator==;
using super::operator!=;
using super::operator<=;
using super::operator>=;
using super::operator<;
using super::operator>;
};
typedef Const_Iterator<SIMDString> const_iterator;
typedef Iterator<SIMDString> iterator;
typedef std::reverse_iterator<const_iterator> const_reverse_iterator;
typedef std::reverse_iterator<iterator> reverse_iterator;
protected:
// Throw compile time error if INTERNAL_SIZE is not a multiple of SSO_ALIGNMENT
static_assert(INTERNAL_SIZE % SSO_ALIGNMENT == 0, "SIMDString Internal Size must be a multiple of 16");
// Using a union to save space. m_buffer and m_ptr are never used at the same time.
union {
// This is intentionally char, as it is bytes
char m_buffer[INTERNAL_SIZE];
pointer m_ptr;
};
/** Bytes to but not including '\0' */
size_type m_length = 0;
// Uses the empty-base optimization trick from the standard library: http://www.cantrip.org/emptyopt.html,
// which unfortunately requires slightly obfuscating the code by sticking the
// m_allocated member into the data property, which we try to minimize the visibility
// of using the m_allocated macro.
mutable struct _AllocHider : public Allocator {
_AllocHider() { }
_AllocHider(size_t allocated) : m_allocated(allocated) { }
size_t m_allocated = INTERNAL_SIZE;
} m_allocator;
/** Total size of data() including '\0', or 0 if data() is in a const segment. This is actually
* implemented in the m_allocator.m_allocated property in practice.
*
* There are 3 modes you can be in:
* 1. In the constant data segment: m_allocated = 0 (inConst() = true)
* 2. In the buffer inline data structure: m_allocated = INTERNAL_SIZE (inBuffer() = true)
* 3. In the heap: m_allocated is the size of the allocated data. This will
* never be less than INTERNAL_SIZE (inHeap() = true) */
# define m_allocatedSize m_allocator.m_allocated
constexpr inline bool inConst() const {
return !m_allocatedSize;
}
constexpr inline bool inHeap() const {
return m_allocatedSize > INTERNAL_SIZE;
}
constexpr inline bool inBuffer() const {
return !(m_allocatedSize - INTERNAL_SIZE);
}
/** Requires 128-bit alignment */
constexpr inline static void swapBuffer(void* buf1, void* buf2) {
# if USE_SSE_MEMCPY
// Can assume that INTERNAL_SIZE % SSO_ALIGNMENT == 0 because of the static assertion on line 201
u64x2_t* d = reinterpret_cast<u64x2_t*>(buf1);
u64x2_t* s = reinterpret_cast<u64x2_t*>(buf2);
u64x2_t tmp;
unsigned int i = (unsigned int) (INTERNAL_SIZE / SSO_ALIGNMENT);
assert(i);
while(i--) {
# ifdef SSE_x64
tmp = _mm_stream_load_si128(d + i);
d[i] = _mm_load_si128(s + i);
s[i] = _mm_load_si128(&tmp);
# else
tmp = d[i];
d[i] = s[i];
s[i] = tmp;
# endif
}
# else
char tmp[INTERNAL_SIZE];
::memcpy(tmp, buf1, INTERNAL_SIZE);
::memcpy(buf1, buf2, INTERNAL_SIZE);
::memcpy(buf2, tmp, INTERNAL_SIZE);
# endif
}
/** Requires 128-bit alignment */
constexpr inline static void memcpyBuffer(void* dst, const void* src, size_t count = INTERNAL_SIZE) {
# if USE_SSE_MEMCPY
// Can assume that INTERNAL_SIZE % SSO_ALIGNMENT == 0 because of the static assertion on line 201
u64x2_t* d = reinterpret_cast<u64x2_t*>(dst);
#ifdef SSE_x64
const u64x2_t* s = reinterpret_cast<const u64x2_t*>(src);
#else
const uint64_t* s = reinterpret_cast<const uint64_t*>(src);
#endif
size_t i = count / SSO_ALIGNMENT;
assert(i);
while (i--) {
# ifdef SSE_x64
d[i] = _mm_stream_load_si128(s + i);
# else
d[i] = vld1q_u64(s + (2 * i));
# endif
}
# else
::memcpy(dst, src, count);
# endif
}
constexpr inline pointer alloc(size_t b) {
if (b <= INTERNAL_SIZE) {
return m_buffer;
} else {
m_ptr = m_allocator.allocate(b);
return m_ptr;
}
}
constexpr void free(void* p, size_t oldSize) const {
m_allocator.deallocate(static_cast<pointer>(p), oldSize);
}
/** Choose the number of bytes to allocate to hold a string of length L
* Note: Calling functions are expected to +1 for the null terminator */
constexpr inline static size_t chooseAllocationSize(size_t requestedSize) {
// Avoid allocating more than internal size unless required, but always allocate at least the internal size
return (requestedSize <= INTERNAL_SIZE) ? INTERNAL_SIZE : std::max((size_t)(2 * requestedSize + 1), (size_t)(2 * INTERNAL_SIZE + 1));
}
constexpr pointer prepareToMutate() {
if (inConst()) {
pointer const old = m_ptr;
m_allocatedSize = chooseAllocationSize(m_length + 1);
// can call alloc and assign directly to m_buffer or m_ptr
// because we know the old pointer points to const data
pointer dataPtr = (pointer) alloc(m_allocatedSize);
::memcpy(dataPtr, old, m_length + 1);
return dataPtr;
}
return data();
}
/** Ensure enough bytes are allocated to hold a string of length newSize
* and copies the old string over
* Note: Calling functions are expected to +1 for the null terminator */
constexpr pointer ensureAllocation(size_t newSize) {
if (m_allocatedSize < newSize) {
const bool wasInHeap = inHeap();
pointer const old = data();
const size_type oldSize = m_allocatedSize;
m_allocatedSize = chooseAllocationSize(newSize);
pointer newPtr = m_buffer;
if (inBuffer()){
::memcpy(newPtr, old, m_length);
} else {
// do not set m_ptr directly because old data could be in m_buffer
newPtr = m_allocator.allocate(m_allocatedSize);
::memcpy(newPtr, old, m_length);
m_ptr = newPtr;
}
if (wasInHeap) free(old, oldSize);
return newPtr;
}
return data();
}
/** Create a gap in the data for insert/replace.
* Re-allocates if necessary
* Note: Calling functions are expected to +1 for the null terminator */
constexpr pointer createGap(size_type newSize, size_type count, size_type count2, size_type pos) {
if (((m_allocatedSize < newSize) && !(inBuffer() && (newSize < INTERNAL_SIZE))) || inConst()) {
// Allocate a new string and copy over first n values
const bool wasInHeap = inHeap();
pointer const old = data();
const size_type oldSize = m_allocatedSize;
m_allocatedSize = chooseAllocationSize(newSize);
pointer newPtr = m_buffer;
if (inBuffer()) {
// copy [old, old + pos) to [newPtr, newPtr + pos)
::memcpy(newPtr, old, pos);
// copy [old + pos + count, old + m_length) to [newPtr + pos + count2, newPtr + newSize)
::memcpy(newPtr + pos + count2, old + pos + count, m_length - pos - count + 1);
} else {
newPtr = m_allocator.allocate(m_allocatedSize);
// copy [old, old + pos) to [newPtr, newPtr + pos)
::memcpy(newPtr, old, pos);
// copy [old + pos + count, old + m_length) to [newPtr + pos + count2, newPtr + newSize)
::memcpy(newPtr + pos + count2, old + pos + count, m_length - pos - count + 1);
m_ptr = newPtr;
}
if (wasInHeap) { free(old, oldSize); }
return newPtr;
} else {
// move [data() + pos + count, data() + m_length) to [data() + pos + count2, data() + newSize)
pointer const dataPtr = data();
memmove(dataPtr + pos + count2, dataPtr + pos + count, m_length - pos - count + 1);
return dataPtr;
}
}
constexpr inline void maybeDeallocate() {
if (inHeap()) {
// Free previously allocated data
free(m_ptr, m_allocatedSize);
m_allocatedSize = INTERNAL_SIZE;
}
}
/** Ensure enough bytes are allocated to hold a string of length newSize.
* Note: Calling functions are expected to +1 for the null terminator */
constexpr inline pointer maybeReallocate(size_t newSize) {
// Don't waste an allocation if the memory already allocated is large enough to hold the new data
if (m_allocatedSize && m_allocatedSize >= newSize) {
return data();
}
// free the old data, if applicable
if (inHeap()) {
// Free previously allocated data
free(m_ptr, m_allocatedSize);
}
// allocate memory
m_allocatedSize = chooseAllocationSize(newSize);
return alloc(m_allocatedSize);
}
// primary template handles types that have no nested ::iterator_category:
template<class InputIter, class = void>
static inline constexpr bool is_iterator = false;
// specialization recognizes types that have a nested ::iterator_category
// void_t is part of c++17 and up
#if (__cplusplus < 201703L) && !defined(_MSC_VER)
template<class InputIter>
static constexpr bool is_iterator<InputIter, std::__void_t<typename std::iterator_traits<InputIter>::iterator_category>> = true;
#else
template<class InputIter>
static constexpr bool is_iterator<InputIter, std::void_t<typename std::iterator_traits<InputIter>::iterator_category>> = true;
#endif
#define ITERATOR_TRAITS template<typename InputIter, std::enable_if_t<is_iterator<InputIter>, int> = 0>
// Construct for input iterators, which do not implement operator-
ITERATOR_TRAITS
inline void m_construct(InputIter first, InputIter last, std::input_iterator_tag t) {
m_length = 0;
// first allocate to buffer
m_allocatedSize = INTERNAL_SIZE;
while (first != last && m_length < m_allocatedSize) {
m_buffer[m_length++] = *first++;
}
// too large for buffer -> allocate to heap
ensureAllocation(m_length + 1);
while (first != last){
// we can use m_ptr here because we know we've maxxed out buffer space
m_ptr[m_length++] = *first++;
if (m_length == m_allocatedSize){
// chooseAllocation will allocate 2x the requested amount
ensureAllocation(m_length + 1);
}
}
data()[m_length] = '\0';
}
// Construct for all other iterators (forward, random access, const char*, etc.)
ITERATOR_TRAITS
inline void m_construct(InputIter first, InputIter last, std::forward_iterator_tag t) {
m_length = last - first;
// Allocate more than needed for fast append
m_allocatedSize = chooseAllocationSize(m_length + 1);
if (inBuffer()){
::memcpy(m_buffer, &*first, last - first);
m_buffer[m_length] = '\0';
} else {
m_ptr = m_allocator.allocate(m_allocatedSize);
::memcpy(m_ptr, &*first, last - first);
m_ptr[m_length] = '\0';
}
}
// Assign for input iterators, which do not implement operator-
ITERATOR_TRAITS
constexpr SIMDString& m_assign(InputIter first, InputIter last, std::input_iterator_tag t) {
m_length = 0;
// Allocate to buffer first if existing string is inConst
if (inConst()){
m_allocatedSize = INTERNAL_SIZE;
}
// don't need to allocate because either the string already has heap allocation or
// we're allocating to the buffer
pointer dataPtr = data();
while (first != last){
dataPtr[m_length++] = *first++;
if (m_length == m_allocatedSize){
// chooseAllocation will allocate 2x the requested amount
dataPtr = ensureAllocation(m_length + 1);
}
}
dataPtr[m_length] = '\0';
return *this;
}
// Assign for all other iterators (forward, random access, const char*, etc.)
ITERATOR_TRAITS
constexpr SIMDString& m_assign(InputIter first, InputIter last, std::forward_iterator_tag t){
m_length = last - first;
//allocate memory if necessary.
pointer dataPtr = maybeReallocate(m_length + 1);
// Clone the other value, putting it in the internal storage if possible
::memcpy(dataPtr, &*first, last - first);
dataPtr[m_length] = '\0';
return *this;
}
public:
static constexpr size_type npos = size_type(-1);
SIMDString(std::nullptr_t): m_length(0), m_allocator(INTERNAL_SIZE) {
m_buffer[0] = '\0';
}
/** Creates a zero-length string */
constexpr inline SIMDString(): m_length(0), m_allocator(INTERNAL_SIZE) {
m_buffer[0] = '\0';
}
/** \param count Copy this many characters. */
constexpr SIMDString(size_type count, value_type c) : m_length(count) {
// Allocate more than needed for fast append
m_allocatedSize = chooseAllocationSize(m_length + 1);
if (inBuffer()){
::memset((void*) m_buffer, c, m_length);
m_buffer[m_length] = '\0';
} else {
m_ptr = m_allocator.allocate(m_allocatedSize);
::memset((void*) m_ptr, c, m_length);
m_ptr[m_length] = '\0';
}
}
explicit constexpr inline SIMDString(const value_type c): m_length(1), m_allocator(INTERNAL_SIZE) {
m_buffer[0] = c;
m_buffer[1] = '\0';
}
constexpr SIMDString(const SIMDString& str, size_type pos = 0) {
m_length = str.m_length - pos;
if (str.inConst()) {
// Share this const_seg value
m_ptr = str.m_ptr + pos;
m_allocatedSize = 0;
} else {
m_allocatedSize = chooseAllocationSize(m_length + 1);
// Clone the value, putting it in the internal storage if possible
// memcpyBuffer assumes SSE so this needs to be aligned to SSO_ALIGNMENT
// Since INTERNAL_SIZE is a multiple of 2, the compiler will optimize `% SSO_ALIGNMENT` to `& (SSO_ALIGNMENT - 1)`
if (inBuffer() && str.inBuffer() && !(pos % SSO_ALIGNMENT)) {
memcpyBuffer(m_buffer, str.m_buffer + pos, INTERNAL_SIZE - pos);
} else {
pointer dataPtr = (pointer) alloc(m_allocatedSize);
// + 1 is for the '\0'
::memcpy(dataPtr, str.data() + pos, m_length + 1);
}
}
}
constexpr SIMDString(const SIMDString& str, size_type pos, size_type count) {
// cannot point to const string
m_length = (count == npos || pos + count >= str.size()) ? str.size() - pos : count;
m_allocatedSize = chooseAllocationSize(m_length + 1);
if (inBuffer() && str.inBuffer() && !(pos % SSO_ALIGNMENT)) {
memcpyBuffer(m_buffer, str.m_buffer + pos, INTERNAL_SIZE - pos);
m_buffer[m_length] = '\0';
} else {
pointer dataPtr = (pointer) alloc(m_allocatedSize);
// + 1 is for the '\0'
::memcpy(dataPtr, str.data() + pos, m_length + 1);
dataPtr[m_length] = '\0';
}
}
constexpr SIMDString(const_pointer s) : m_length(::strlen(s)) {
if (inConstSegment(s)) {
m_ptr = const_cast<pointer>(s);
m_allocatedSize = 0;
} else {
// Allocate more than needed for fast append
m_allocatedSize = chooseAllocationSize(m_length + 1);
pointer dataPtr = (pointer) alloc(m_allocatedSize);
::memcpy(dataPtr, s, m_length + 1);
}
}
/** \param count Copy this many characters. The result is always copied because it is unsafe to
check past the end of s for a null terminator.*/
constexpr SIMDString(const_pointer s, size_type count) : m_length(count) {
// Allocate more than needed for fast append
m_allocatedSize = chooseAllocationSize(m_length + 1);
pointer const dataPtr = (pointer) alloc(m_allocatedSize);
::memcpy(dataPtr, s, m_length);
dataPtr[m_length] = '\0';
}
constexpr SIMDString(const_pointer s, size_type pos, size_type count)
: m_length(count)
{
// Allocate more than needed for fast append
m_allocatedSize = chooseAllocationSize(m_length + 1);
pointer const dataPtr = (pointer) alloc(m_allocatedSize);
::memcpy(dataPtr, s + pos, m_length);
dataPtr[m_length] = '\0';
}
constexpr SIMDString(SIMDString&& str) noexcept: m_length(0), m_allocator(INTERNAL_SIZE) {
swap(str);
}
// These aren't passed by reference because this was the signature on basic_string
// https://en.cppreference.com/w/cpp/string/basic_string/basic_string
ITERATOR_TRAITS
constexpr SIMDString(InputIter first, InputIter last) {
typedef typename std::iterator_traits<InputIter>::iterator_category tag;
m_construct(first, last, tag());
}
// explicit to prevent auto casting
explicit constexpr SIMDString(const std::string& str, size_type pos = 0, size_type count = npos) {
m_length = (count == npos || pos + count >= str.size()) ? str.size() - pos : count;
// Allocate more than needed for fast append
m_allocatedSize = chooseAllocationSize(m_length + 1);
pointer const dataPtr = (pointer) alloc(m_allocatedSize);
::memcpy(dataPtr, str.data() + pos, m_length);
dataPtr[m_length] = '\0';
}
constexpr SIMDString(std::initializer_list<value_type> ilist) : m_length(ilist.size()) {
// The initializer list points to a list of const elements
// They can't be moved and they're not null terminated
m_allocatedSize = chooseAllocationSize(m_length + 1);
pointer const dataPtr = (pointer) alloc(m_allocatedSize);
::memcpy(dataPtr, ilist.begin(), m_length);
dataPtr[m_length] = '\0';
}
explicit constexpr SIMDString(const std::string_view& sv, size_type pos = 0) : m_length(sv.size() - pos) {
if (inConstSegment(sv.data() + pos) && sv.data()[pos + m_length] == '\0') {
m_ptr = const_cast<pointer>(sv.data() + pos);
m_allocatedSize = 0;
} else {
// Allocate more than needed for fast append
m_allocatedSize = chooseAllocationSize(m_length + 1);
pointer const dataPtr = (pointer) alloc(m_allocatedSize);
::memcpy(dataPtr, sv.data() + pos, m_length);
dataPtr[m_length] = '\0';
}
}
constexpr SIMDString(const std::string_view& sv, size_type pos, size_type count) {
m_length = (count == npos || pos + count >= sv.size()) ? sv.size() - pos : count;
// Allocate more than needed for fast append
m_allocatedSize = chooseAllocationSize(m_length + 1);
pointer const dataPtr = (pointer) alloc(m_allocatedSize);
::memcpy(dataPtr, sv.data() + pos, m_length);
dataPtr[m_length] = '\0';
}
~SIMDString() {
if (inHeap()) {
// Note that this calls the method, not ::free
free(m_ptr, m_allocatedSize);
}
}
constexpr SIMDString& operator=(const SIMDString& str) {
if (&str == this) {
return *this;
} else if (str.inConst()) { // Constant storage
maybeDeallocate();
// Share this const_seg value
m_ptr = str.m_ptr;
m_length = str.m_length;
m_allocatedSize = str.m_allocatedSize;
} else { // Buffer and heap storage
m_length = str.m_length;
// free and/or allocate memory if necessary.
pointer dataPtr = maybeReallocate(m_length + 1);
// Clone the other value, putting it in the internal storage if possible
if (inBuffer() && str.inBuffer()) {
memcpyBuffer(dataPtr, str.m_buffer);
} else {
::memcpy(dataPtr, str.data(), m_length + 1);
}
}
return *this;
}
constexpr SIMDString& operator=(SIMDString&& str) noexcept {
swap(str);
str.clear();
return *this;
}
constexpr SIMDString& operator=(const_pointer s) {
m_length = ::strlen(s);
if (inConstSegment(s)) {
maybeDeallocate();
// Share this const_seg value
m_ptr = const_cast<pointer>(s);
m_allocatedSize = 0;
} else {
// free and/or allocate memory if necessary.
pointer const dataPtr = maybeReallocate(m_length + 1);
// Clone the other value, putting it in the internal storage if possible
::memcpy(dataPtr, s, m_length + 1);
}
return *this;
}
constexpr SIMDString& operator=(const std::string& str) {
m_length = str.length();
// free and/or allocate memory if necessary.
pointer const dataPtr = maybeReallocate(m_length + 1);
// Clone the other value, putting it in the internal storage if possible
::memcpy(dataPtr, str.data(), m_length + 1);
return *this;
}
constexpr SIMDString& operator=(const std::string&& str)
{
m_length = str.length();
// free and/or allocate memory if necessary.
pointer const dataPtr = maybeReallocate(m_length + 1);
// Clone the other value, putting it in the internal storage if possible
::memcpy(dataPtr, str.data(), m_length + 1);
return *this;
}
constexpr SIMDString& operator=(const value_type c) {
maybeDeallocate();
m_length = 1;
m_allocatedSize = INTERNAL_SIZE;
m_buffer[0] = c;
m_buffer[1] = '\0';
return *this;
}
constexpr SIMDString& operator=(std::initializer_list<value_type> ilist) {
m_length = ilist.size();
// free and/or allocate memory if necessary.
pointer const dataPtr = maybeReallocate(m_length + 1);
// Clone the other value, putting it in the internal storage if possible
::memcpy(dataPtr, ilist.begin(), m_length);
dataPtr[m_length] = '\0';
return *this;
}
constexpr SIMDString& operator=(const std::string_view& sv) {
m_length = sv.size();
// free and/or allocate memory if necessary.
pointer const dataPtr = maybeReallocate(m_length + 1);
// Clone the other value, putting it in the internal storage if possible
::memcpy(dataPtr, sv.data(), m_length);
dataPtr[m_length] = '\0';
return *this;
}
constexpr SIMDString& assign(const SIMDString& str, size_type pos = 0, size_type count = npos) {
size_type copy_len = (count == npos || pos + count >= str.size()) ? str.size() - pos : count;
if (pos == 0 && copy_len == str.size()) {
return (*this) = str;
}
// Constant storage and can use the same null terminator
if (str.inConst() && pos + copy_len == str.size()) {
maybeDeallocate();
// Share this const_seg value
m_ptr = str.m_ptr + pos;
m_length = copy_len;
m_allocatedSize = str.m_allocatedSize;
} else { // Buffer and heap storage or a substring
m_length = copy_len;
// free and/or allocate memory if necessary.
pointer const dataPtr = maybeReallocate(m_length + 1);
// Clone the other value, putting it in the internal storage if possible
// memcpyBuffer assumes SSE this needs be aligned to SSO_ALIGNMENT
// Since INTERNAL_SIZE is a multiple of 2, the compiler will optimize `% SSO_ALIGNMENT` to `& (SSO_ALIGNMENT - 1)`
if (inBuffer() && str.inBuffer() && !(pos % SSO_ALIGNMENT)) {
// can copy over entire buffer because the string gets null terminated anyway
memcpyBuffer(dataPtr, str.m_buffer + pos, INTERNAL_SIZE - pos);
} else {
::memcpy(dataPtr, str.data() + pos, m_length);
}
dataPtr[m_length] = '\0';
}
return *this;
}
constexpr SIMDString& assign(const_pointer s, size_type count) {
m_length = count;
// free and/or allocate memory if necessary.
pointer const dataPtr = maybeReallocate(m_length + 1);
// Clone the other value, putting it in the internal storage if possible
::memcpy(dataPtr, s, m_length);
dataPtr[m_length] = '\0';
return *this;
}
constexpr SIMDString& assign(const_pointer s) {
return (*this = s);
}
constexpr SIMDString& assign(size_type count, const value_type c) {
m_length = count;
// free and/or allocate memory if necessary.
pointer const dataPtr = maybeReallocate(m_length + 1);
// Clone the other value, putting it in the internal storage if possible
::memset(dataPtr, c, m_length);
dataPtr[m_length] = '\0';
return *this;
}
constexpr SIMDString& assign(const SIMDString&& str) {
return (*this) = str;
}
ITERATOR_TRAITS
constexpr SIMDString& assign(InputIter first, InputIter last)
{
typedef typename std::iterator_traits<InputIter>::iterator_category tag;
return m_assign(first, last, tag());
}
constexpr SIMDString& assign(std::initializer_list<value_type> ilist) {
return (*this) = ilist;
}
constexpr SIMDString& assign(const std::string_view& sv) {
return (*this) = sv;
}
constexpr SIMDString& assign(const std::string_view& sv, size_type pos, size_type count) {
if (pos == 0 && count == sv.size()) {
return (*this = sv);
}
m_length = (count == npos || pos + count >= sv.size()) ? sv.size() - pos : count;
// free and/or allocate memory if necessary.
pointer const dataPtr = maybeReallocate(m_length + 1);
// Clone the other value, putting it in the internal storage if possible
::memcpy(dataPtr, sv.data(), m_length);
dataPtr[m_length] = '\0';
return *this;
}
constexpr Allocator get_allocator() {
return m_allocator;
}
// access
constexpr const_pointer c_str() const noexcept{
return data();
}
/**
* data: https://github.com/llvm-mirror/libcxx/blob/78d6a7767ed57b50122a161b91f59f19c9bd0d19/include/string#L1242
* __get_pointer: https://github.com/llvm-mirror/libcxx/blob/78d6a7767ed57b50122a161b91f59f19c9bd0d19/include/string#L1513
*/
constexpr const_pointer data() const noexcept {
return inBuffer() ? m_buffer : m_ptr;
}
constexpr pointer data() noexcept {
return inBuffer() ? m_buffer : m_ptr;
}
constexpr const_reference operator[](size_type x) const {
assert(x < m_length && x >= 0); // "Index out of bounds");
return data()[x];
}
constexpr reference operator[](size_type x) {
assert(x < m_length && x >= 0); // "Index out of bounds");
prepareToMutate();
return data()[x];
}
constexpr const_reference at(size_type x) const {
assert(x < m_length&& x >= 0); // "Index out of bounds");
return data()[x];
}
constexpr reference at(size_type x) {
assert(x < m_length&& x >= 0); // "Index out of bounds");
prepareToMutate();
return data()[x];
}
constexpr const_reference front() const {
const_pointer dataPtr = data();
assert(dataPtr); // "Empty string"
return dataPtr[0];
}
constexpr reference front() {
assert(data()); // "Empty string"
prepareToMutate();
// call data again because it's a mutated string
return data()[0];
}
constexpr const_reference back() const {
const_pointer dataPtr = data();
assert(dataPtr); // "Empty string"
return dataPtr[m_length - 1];
}
constexpr reference back() {
assert(data()); // "Empty string"
prepareToMutate();
// call data again because it's a mutated string
return data()[m_length - 1];
}
explicit constexpr inline operator std::basic_string_view<value_type>() {
return std::string_view(data(), m_length);
}
// iterators
constexpr iterator begin() {
prepareToMutate();
return iterator(data());
}
constexpr iterator end() {
prepareToMutate();
return iterator(data() + m_length);
}
constexpr const_iterator begin() const {
return const_iterator(data());
}
constexpr const_iterator end() const {
return const_iterator(data() + m_length);
}
constexpr const_iterator cbegin() const {
return const_iterator(data());
}
constexpr const_iterator cend() const {
return const_iterator(data() + m_length);
}
// std::reverse_iterator in cpp2017 or older don't have constexpr constructors
// thus these functions can't be constexpr for now
reverse_iterator rbegin() {
prepareToMutate();
return reverse_iterator(data() + m_length);
}
reverse_iterator rend() {
prepareToMutate();
return reverse_iterator(data());
}
const_reverse_iterator rbegin() const {
return const_reverse_iterator(data() + m_length);
}
const_reverse_iterator rend() const {
return const_reverse_iterator(data());
}
const_reverse_iterator crbegin() const
{
return const_reverse_iterator(data() + m_length);
}
const_reverse_iterator crend() const {
return const_reverse_iterator(data());
}
constexpr size_type size() const {
return m_length;
}
constexpr size_type length() const {
return m_length;
}
constexpr size_type capacity() const {
if (inBuffer()) {
return INTERNAL_SIZE;
} else if (inConst()) {
return m_length;
} else {
return m_allocatedSize; // 0 when isConst() is true
}
}
constexpr size_type max_size() const {
return size_type(-1);
}