forked from DuffsDevice/tiny-utf8
-
Notifications
You must be signed in to change notification settings - Fork 1
/
tinyutf8.h
4406 lines (3891 loc) · 164 KB
/
tinyutf8.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
/**
* Copyright (c) 2019 Jakob Riedle (DuffsDevice)
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR 'AS IS' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef _TINY_UTF8_H_
#define _TINY_UTF8_H_
// Includes
#include <memory> // for std::unique_ptr
#include <cstring> // for std::memcpy, std::memmove
#include <string> // for std::string
#include <limits> // for std::numeric_limits
#include <functional> // for std::hash
#include <cstddef> // for ptrdiff_t, size_t and offsetof
#include <cstdint> // for uint8_t, uint16_t, uint32_t, std::uint_least16_t, std::uint_fast32_t
#include <initializer_list> // for std::initializer_list
#include <iosfwd> // for ostream/istream forward declarations
#ifdef _MSC_VER
#include <intrin.h> // for __lzcnt
#endif
//! Determine the mode of error handling
#if defined(__cpp_exceptions) && !defined(TINY_UTF8_NOEXCEPT) && !defined(TINY_UTF8_THROW)
#include <stdexcept> // for std::out_of_range
#define TINY_UTF8_THROW( LOCATION , FAILING_PREDICATE ) throw std::out_of_range( LOCATION ": " #FAILING_PREDICATE )
#else
#define TINY_UTF8_THROW( ... ) void()
#endif
namespace tiny_utf8_detail
{
// Used for tag dispatching in constructor
struct read_codepoints_tag{};
struct read_bytes_tag{};
//! Count leading zeros utility
#if defined(__GNUC__)
#ifndef TINY_UTF8_HAS_CLZ
#define TINY_UTF8_HAS_CLZ true
#endif
static inline unsigned int clz( unsigned int val ){ return __builtin_clz( val ); }
static inline unsigned int clz( unsigned long int val ){ return __builtin_clzl( val ); }
static inline unsigned int clz( char32_t val ){
return sizeof(char32_t) == sizeof(unsigned long int) ? __builtin_clzl( val ) : __builtin_clz( val );
}
#elif defined(_MSC_VER)
#ifndef TINY_UTF8_HAS_CLZ
#define TINY_UTF8_HAS_CLZ true
#endif
static inline unsigned int clz( uint16_t val ){ return __lzcnt16( val ); }
static inline unsigned int clz( uint32_t val ){ return __lzcnt( val ); }
#ifndef WIN32
static inline unsigned int clz( uint64_t val ){ return __lzcnt64(val); }
#endif // WIN32
static inline unsigned int clz( char32_t val ){ return __lzcnt( val ); }
#endif
//! Helper to detect little endian
class is_little_endian
{
constexpr static uint32_t u4 = 1;
constexpr static uint8_t u1 = (const uint8_t &) u4;
public:
constexpr static bool value = u1;
};
//! Helper to modify the last (address-wise) byte of a little endian value of type 'T'
template<typename T>
union last_byte
{
T number;
struct{
char dummy[sizeof(T)-1];
char last;
} bytes;
};
}
class utf8_string
{
public:
typedef std::size_t size_type;
typedef std::ptrdiff_t difference_type;
typedef char32_t value_type;
typedef value_type const_reference;
typedef std::uint_fast8_t width_type; // Data type capable of holding the number of code units in a code point
enum : size_type{ npos = (size_type)-1 };
private: //! Layout specifications
/*
* To determine, which layout is active, read either t_sso.data_len, or the last byte of t_non_sso.buffer_size:
* LSB == 0 => SSO
* LSB == 1 => NON-SSO
*/
// Layout used, if sso is inactive
struct NON_SSO
{
char* data; // Points to [ <data::char>... | '0'::char | <index::rle>... | <lut_indicator::size_type> ]
size_type data_len; // In bytes, excluding the trailing '\0'
size_type buffer_size; // Indicates the size of '::data' minus 'lut_width'
size_type string_len; // Shadows data_len on the last byte
};
// Layout used, if sso is active
struct SSO
{
char data[sizeof(NON_SSO)-1];
unsigned char data_len; // This field holds ( sizeof(SSO::data) - num_characters ) << 1
SSO( unsigned char data_len , char value ) :
data{ value }
, data_len( ( sizeof(SSO::data) - data_len ) << 1 )
{}
SSO( unsigned char data_len ) :
data_len( ( sizeof(SSO::data) - data_len ) << 1 )
{}
};
// Typedef for the lut indicator. Note: Don't change this, because else the buffer will not be a multiple of sizeof(size_type)
typedef size_type indicator_type;
private:
template<bool RangeCheck>
class utf8_codepoint_reference
{
private:
size_type t_index;
utf8_string* t_instance;
public:
//! Ctor
utf8_codepoint_reference( size_type index , utf8_string* instance ) :
t_index( index )
, t_instance( instance )
{}
//! Cast to wide char
operator value_type() const {
if( RangeCheck )
return static_cast<const utf8_string*>(t_instance)->at( t_index );
return static_cast<const utf8_string*>(t_instance)->at( t_index , std::nothrow );
}
//! Assignment operator
utf8_codepoint_reference& operator=( value_type cp ){
t_instance->replace( t_index , cp );
return *this;
}
};
template<bool RangeCheck>
class utf8_codepoint_raw_reference
{
private:
size_type t_raw_index;
utf8_string* t_instance;
public:
//! Ctor
utf8_codepoint_raw_reference( size_type raw_index , utf8_string* instance ) :
t_raw_index( raw_index )
, t_instance( instance )
{}
//! Cast to wide char
operator value_type() const {
if( RangeCheck )
return static_cast<const utf8_string*>(t_instance)->raw_at( t_raw_index );
return static_cast<const utf8_string*>(t_instance)->raw_at( t_raw_index , std::nothrow );
}
//! Assignment operator
utf8_codepoint_raw_reference& operator=( value_type cp ){
t_instance->raw_replace( t_raw_index , t_instance->get_index_bytes( t_raw_index ) , utf8_string( cp ) );
return *this;
}
};
class iterator_base
{
friend class utf8_string;
public:
typedef utf8_string::value_type value_type;
typedef utf8_string::difference_type difference_type;
typedef utf8_codepoint_raw_reference<false> reference;
typedef void* pointer;
typedef std::bidirectional_iterator_tag iterator_category;
bool operator==( const iterator_base& it ) const { return t_raw_index == it.t_raw_index; }
bool operator!=( const iterator_base& it ) const { return t_raw_index != it.t_raw_index; }
//! Ctor
iterator_base( difference_type raw_index , utf8_string* instance ) :
t_raw_index( raw_index )
, t_instance( instance )
{}
//! Default function
iterator_base() = default;
iterator_base( const iterator_base& ) = default;
iterator_base& operator=( const iterator_base& ) = default;
// Getter for the iterator index
difference_type get_index() const { return t_raw_index; }
utf8_string* get_instance() const { return t_instance; }
protected:
difference_type t_raw_index;
utf8_string* t_instance;
void advance( difference_type n ){
if( n > 0 )
do
increment();
while( --n > 0 );
else
while( n++ < 0 )
decrement();
}
void increment(){
t_raw_index += t_instance->get_index_bytes( t_raw_index );
}
void decrement(){
t_raw_index -= t_instance->get_index_pre_bytes( t_raw_index );
}
utf8_codepoint_raw_reference<false> get_reference() const {
return t_instance->raw_at( t_raw_index , std::nothrow );
}
value_type get_value() const {
return static_cast<const utf8_string*>(t_instance)->raw_at( t_raw_index );
}
};
public:
typedef utf8_codepoint_reference<false> reference;
struct iterator : iterator_base
{
//! Ctor
iterator( difference_type raw_index , utf8_string* instance ) :
iterator_base( raw_index , instance )
{}
//! Default Functions
iterator() = default;
iterator( const iterator& ) = default;
iterator& operator=( const iterator& ) = default;
//! Delete ctor from const iterator types
iterator( const struct const_iterator& ) = delete;
iterator( const struct const_reverse_iterator& ) = delete;
//! Increase the Iterator by one
iterator& operator++(){ // prefix ++iter
increment();
return *this;
}
iterator operator++( int ){ // postfix iter++
iterator tmp{ t_raw_index , t_instance };
increment();
return tmp;
}
//! Decrease the iterator by one
iterator& operator--(){ // prefix --iter
decrement();
return *this;
}
iterator operator--( int ){ // postfix iter--
iterator tmp{ t_raw_index , t_instance };
decrement();
return tmp;
}
//! Increase the Iterator n times
iterator operator+( difference_type n ) const {
iterator it{*this};
it.advance( n );
return it;
}
iterator& operator+=( difference_type n ){
advance( n );
return *this;
}
//! Decrease the Iterator n times
iterator operator-( difference_type n ) const {
iterator it{*this};
it.advance( -n );
return it;
}
iterator& operator-=( difference_type n ){
advance( -n );
return *this;
}
//! Returns the value of the code point behind the iterator
utf8_codepoint_raw_reference<false> operator*() const { return get_reference(); }
};
struct const_iterator : iterator
{
//! Ctor
const_iterator( difference_type raw_index , const utf8_string* instance ) :
iterator( raw_index , const_cast<utf8_string*>(instance) )
{}
//! Ctor from non const
const_iterator( const iterator& it ) :
iterator( it.get_index() , it.get_instance() )
{}
//! Default Functions
const_iterator() = default;
const_iterator( const const_iterator& ) = default;
const_iterator& operator=( const const_iterator& ) = default;
//! Returns the (raw) value behind the iterator
value_type operator*() const { return get_value(); }
};
struct reverse_iterator : iterator_base
{
//! Ctor
reverse_iterator( difference_type raw_index , utf8_string* instance ) :
iterator_base( raw_index , instance )
{}
//! Ctor from normal iterator
reverse_iterator( const iterator& it ) :
iterator_base( it.get_index() , it.get_instance() )
{}
//! Default Functions
reverse_iterator() = default;
reverse_iterator( const reverse_iterator& ) = default;
reverse_iterator& operator=( const reverse_iterator& ) = default;
//! Delete ctor from const iterator types
reverse_iterator( const const_iterator& ) = delete;
reverse_iterator( const struct const_reverse_iterator& ) = delete;
//! Increase the iterator by one
reverse_iterator& operator++(){ // prefix ++iter
decrement();
return *this;
}
reverse_iterator operator++( int ){ // postfix iter++
reverse_iterator tmp{ t_raw_index , t_instance };
decrement();
return tmp;
}
//! Decrease the Iterator by one
reverse_iterator& operator--(){ // prefix --iter
increment();
return *this;
}
reverse_iterator operator--( int ){ // postfix iter--
reverse_iterator tmp{ t_raw_index , t_instance };
increment();
return tmp;
}
//! Increase the Iterator n times
reverse_iterator operator+( difference_type n ) const {
reverse_iterator it{*this};
it.advance( -n );
return it;
}
reverse_iterator& operator+=( difference_type n ){
advance( -n );
return *this;
}
//! Decrease the Iterator n times
reverse_iterator operator-( difference_type n ) const {
reverse_iterator it{*this};
it.advance( n );
return it;
}
reverse_iterator& operator-=( difference_type n ){
advance( n );
return *this;
}
//! Returns the value of the code point behind the iterator
utf8_codepoint_raw_reference<false> operator*() const { return get_reference(); }
//! Get the underlying iterator instance
iterator base() const {
return iterator( t_raw_index , t_instance );
}
};
struct const_reverse_iterator : reverse_iterator
{
//! Ctor
const_reverse_iterator( difference_type raw_index , const utf8_string* instance ) :
reverse_iterator( raw_index , const_cast<utf8_string*>(instance) )
{}
//! Ctor from non const
const_reverse_iterator( const reverse_iterator& it ) :
reverse_iterator( it.get_index() , it.get_instance() )
{}
//! Ctor from normal iterator
const_reverse_iterator( const const_iterator& it ) :
reverse_iterator( it.get_index() , it.get_instance() )
{}
//! Default Functions
const_reverse_iterator() = default;
const_reverse_iterator( const const_reverse_iterator& ) = default;
const_reverse_iterator& operator=( const const_reverse_iterator& ) = default;
//! Returns the (raw) value behind the iterator
value_type operator*() const { return get_value(); }
//! Get the underlying iterator instance
const_iterator base() const {
return const_iterator( t_raw_index , t_instance );
}
};
private: //! Attributes
union{
SSO t_sso;
NON_SSO t_non_sso;
};
private: //! Static helper methods
//! Get the maximum number of bytes (excluding the trailing '\0') that can be stored within a utf8_string object
static constexpr inline size_type get_sso_capacity(){ return sizeof(SSO::data); }
//! Helpers for the constructors
template<size_type L>
using enable_if_small_string = typename std::enable_if<L<=get_sso_capacity(),bool>::type;
template<size_type L>
using enable_if_not_small_string = typename std::enable_if<get_sso_capacity()<L,bool>::type;
// Template to enable overloads, if the supplied type T is a character array without known bounds
template<typename T, typename CharType, typename DataType = bool>
using enable_if_ptr = typename std::enable_if<
std::is_pointer<typename std::remove_reference<T>::type>::value
&&
std::is_same<
CharType
, typename std::remove_cv<
typename std::remove_pointer<
typename std::remove_reference<T>::type
>::type
>::type
>::value
, DataType
>::type;
//! Check, if the lut is active using the lut base ptr
static inline bool is_lut_active( const char* lut_base_ptr ){ return *((const unsigned char*)lut_base_ptr) & 0x1; }
//! Rounds the supplied value to a multiple of sizeof(size_type)
static inline size_type round_up_to_align( size_type val ){
return ( val + sizeof(size_type) - 1 ) & ~( sizeof(size_type) - 1 );
}
//! Get the LUT base pointer from buffer and buffer size
static inline char* get_lut_base_ptr( char* buffer , size_type buffer_size ){ return buffer + buffer_size; }
static inline const char* get_lut_base_ptr( const char* buffer , size_type buffer_size ){ return buffer + buffer_size; }
//! Construct the lut mode indicator
static inline void set_lut_indiciator( char* lut_base_ptr , bool active , size_type lut_len = 0 ){
*(indicator_type*)lut_base_ptr = active ? ( lut_len << 1 ) | 0x1 : 0;
}
//! Copy lut indicator
static inline void copy_lut_indicator( char* dest , const char* source ){
*(indicator_type*)dest = *(indicator_type*)source;
}
//! Determine, whether we will use a 'uint8_t', 'uint16_t', 'uint32_t' or 'uint64_t'-based index table.
//! Returns the number of bytes of the destination data type
static inline width_type get_lut_width( size_type buffer_size );
//! Determine, whether or not a LUT is worth to set up. General case: worth below 25%. If LUT present <33,3%, otherwise <16,7%
static inline bool is_lut_worth( size_type pot_lut_len , size_type string_len , bool lut_present , bool biased = true ){
size_type threshold = biased ? ( lut_present ? string_len / 3u : string_len / 6u ) : string_len / 4u;
// Note pot_lut_len is supposed to underflow at '0'
return size_type( pot_lut_len - 1 ) < threshold;
}
//! Determine the needed buffer size and the needed lut width (excluding the trailling LUT indicator)
static inline size_type determine_main_buffer_size( size_type data_len , size_type lut_len , width_type* lut_width );
//! Determine the needed buffer size if the lut width is known (excluding the trailling LUT indicator)
static inline size_type determine_main_buffer_size( size_type data_len , size_type lut_len , width_type lut_width );
//! Determine the needed buffer size if the lut is empty (excluding the trailling LUT indicator)
static inline size_type determine_main_buffer_size( size_type data_len );
//! Same as above but this time including the LUT indicator
static inline size_type determine_total_buffer_size( size_type main_buffer_size ){
return main_buffer_size + sizeof(indicator_type); // Add the lut indicator
}
//! Get the nth index within a multibyte index table
static inline size_type get_lut( const char* iter , width_type lut_width ){
switch( lut_width ){
case sizeof(std::uint8_t): return *(const std::uint8_t*)iter;
case sizeof(std::uint16_t): return *(const std::uint16_t*)iter;
case sizeof(std::uint32_t): return *(const std::uint32_t*)iter;
}
return *(const std::uint64_t*)iter;
}
static inline void set_lut( char* iter , width_type lut_width , size_type value ){
switch( lut_width ){
case sizeof(std::uint8_t): *(std::uint8_t*)iter = value; break;
case sizeof(std::uint16_t): *(std::uint16_t*)iter = value; break;
case sizeof(std::uint32_t): *(std::uint32_t*)iter = value; break;
case sizeof(std::uint64_t): *(std::uint64_t*)iter = value; break;
}
}
//! Get the LUT size (given the lut is active!)
static inline size_type get_lut_len( const char* lut_base_ptr ){
return *(indicator_type*)lut_base_ptr >> 1;
}
/**
* Returns the number of code units (bytes) using the supplied first byte of a utf8 code point
*/
// Data left is the number of bytes left in the buffer INCLUDING this one
#if defined(TINY_UTF8_HAS_CLZ) && TINY_UTF8_HAS_CLZ == true
static inline width_type get_codepoint_bytes( char first_byte , size_type data_left )
{
if( first_byte ){
// Before counting the leading one's we need to shift the byte into the most significant part of the integer
size_type codepoint_bytes = tiny_utf8_detail::clz( ~((unsigned int)first_byte << (sizeof(unsigned int)-1)*8 ) );
// The test below would actually be ( codepoint_bytes <= data_left && codepoint_bytes ),
// but codepoint_bytes is unsigned and thus wraps around zero, which makes the following faster:
if( size_type( codepoint_bytes - 1 ) < size_type(data_left) )
return codepoint_bytes;
}
return 1;
}
#else
static width_type get_codepoint_bytes( char first_byte , size_type data_left ); // Defined in source file
#endif
/**
* Returns the number of code units (bytes) a code point will translate to in utf8
*/
static inline width_type get_codepoint_bytes( value_type cp )
{
#if defined(TINY_UTF8_HAS_CLZ) && TINY_UTF8_HAS_CLZ == true
if( !cp )
return 1;
static const width_type lut[32] = {
1 , 1 , 1 , 1 , 1 , 1 , 1 , 2 , 2 , 2 , 2 , 3 , 3 , 3 , 3 , 3
, 4 , 4 , 4 , 4 , 4 , 5 , 5 , 5 , 5 , 5 , 6 , 6 , 6 , 6 , 6 , 7
};
return lut[ 31 - tiny_utf8_detail::clz( cp ) ];
#else
if( cp <= 0x7F )
return 1;
else if( cp <= 0x7FF )
return 2;
else if( cp <= 0xFFFF )
return 3;
else if( cp <= 0x1FFFFF )
return 4;
else if( cp <= 0x3FFFFFF )
return 5;
else if( cp <= 0x7FFFFFFF )
return 6;
else
return 7;
#endif
}
//! Returns the number of bytes to expect before this one (including this one) that belong to this utf8 char
static width_type get_num_bytes_of_utf8_char_before( const char* data_start , size_type index );
//! Decodes a given input of rle utf8 data to a unicode code point, given the number of bytes it's made of
static inline value_type decode_utf8( const char* data , width_type num_bytes ){
value_type cp = (unsigned char)*data;
if( num_bytes > 1 ){
cp &= 0x7F >> num_bytes; // Mask out the header bits
for( width_type i = 1 ; i < num_bytes ; i++ )
cp = ( cp << 6 ) | ( (unsigned char)data[i] & 0x3F );
}
return cp;
}
/**
* Decodes a given input of rle utf8 data to a
* unicode code point and returns the number of bytes it used
*/
static inline width_type decode_utf8_and_len( const char* data , value_type& dest , size_type data_left ){
// See 'get_codepoint_bytes' for 'data_left'
width_type num_bytes = utf8_string::get_codepoint_bytes( *data , data_left );
dest = decode_utf8( data , num_bytes );
return num_bytes;
}
/**
* Encodes a given code point (expected to use 'cp_bytes') to a character
* buffer capable of holding that many bytes.
*/
inline static void encode_utf8( value_type cp , char* dest , width_type cp_bytes ){
switch( cp_bytes ){
case 7: dest[cp_bytes-6] = 0x80 | ((cp >> 30) & 0x3F); [[fallthrough]];
case 6: dest[cp_bytes-5] = 0x80 | ((cp >> 24) & 0x3F); [[fallthrough]];
case 5: dest[cp_bytes-4] = 0x80 | ((cp >> 18) & 0x3F); [[fallthrough]];
case 4: dest[cp_bytes-3] = 0x80 | ((cp >> 12) & 0x3F); [[fallthrough]];
case 3: dest[cp_bytes-2] = 0x80 | ((cp >> 6) & 0x3F); [[fallthrough]];
case 2: dest[cp_bytes-1] = 0x80 | ((cp >> 0) & 0x3F);
dest[0] = ( std::uint_least16_t(0xFF00uL) >> cp_bytes ) | ( cp >> ( 6 * cp_bytes - 6 ) );
break;
case 1: dest[0] = char(cp);
}
}
/**
* Encodes a given code point to a character buffer of at least 7 bytes
* and returns the number of bytes it used
*/
inline static width_type encode_utf8( value_type cp , char* dest ){
width_type width = get_codepoint_bytes( cp );
utf8_string::encode_utf8( cp , dest , width );
return width;
}
private: //! Non-static helper methods
//! Set the main buffer size (also disables SSO)
inline void set_non_sso_string_len( size_type string_len )
{
// Check, if NON_SSO is larger than its members, in which case it's not ambiguated by SSO::data_len
if( offsetof(SSO, data_len) > offsetof(NON_SSO, string_len) + sizeof(NON_SSO::string_len) - 1 ){
t_non_sso.string_len = string_len;
t_sso.data_len = 0x1; // Manually set flag to deactivate SSO
}
else if( tiny_utf8_detail::is_little_endian::value ){
tiny_utf8_detail::last_byte<size_type> lb;
lb.number = string_len;
lb.bytes.last <<= 1;
lb.bytes.last |= 0x1;
t_non_sso.string_len = lb.number;
}
else
t_non_sso.string_len = ( string_len << 1 ) | size_type(0x1);
}
//! Get buffer size, if SSO is disabled
inline size_type get_non_sso_string_len() const {
// Check, if NON_SSO is larger than its members, in which case it's not ambiguated by SSO::data_len
if( offsetof(SSO, data_len) > offsetof(NON_SSO, string_len) + sizeof(NON_SSO::string_len) - 1 )
return t_non_sso.string_len;
else if( tiny_utf8_detail::is_little_endian::value ){
tiny_utf8_detail::last_byte<size_type> lb;
lb.number = t_non_sso.string_len;
lb.bytes.last >>= 1;
return lb.number;
}
else
return t_non_sso.string_len >> 1;
}
//! Set the data length (also enables SSO)
inline void set_sso_data_len( unsigned char data_len = 0 ){
t_sso.data_len = ( sizeof(SSO::data) - data_len ) << 1;
}
//! Get the data length (when SSO is active)
inline size_type get_sso_data_len() const { return get_sso_capacity() - ( t_sso.data_len >> 1 ); }
//! Return a good guess of how many codepoints the currently allocated buffer can hold
size_type get_non_sso_capacity() const ;
//! Check, if sso is inactive (this operation doesn't require a negation and is faster)
inline bool sso_inactive() const { return t_sso.data_len & 0x1; }
// Helper for requires_unicode_sso that generates masks of the form 10000000 10000000...
template<typename T>
static constexpr T get_msb_mask( width_type bytes = sizeof(T) ){ return bytes ? ( T(1) << ( 8 * bytes - 1 ) ) | get_msb_mask<T>( bytes - 1 ) : T(0); }
//! Check, whether the string contains code points > 127
bool requires_unicode_sso() const ;
//! Get buffer
inline const char* get_buffer() const { return sso_inactive() ? t_non_sso.data : t_sso.data; }
inline char* get_buffer(){ return sso_inactive() ? t_non_sso.data : t_sso.data; }
//! Get buffer size (excluding the trailing LUT indicator)
inline size_type get_buffer_size() const {
return sso_inactive() ? t_non_sso.buffer_size : get_sso_capacity();
}
//! Returns an std::string with the UTF-8 BOM prepended
std::string cpp_str_bom() const ;
//! Constructs an utf8_string from a character literal
utf8_string( const char* str , size_type len , tiny_utf8_detail::read_codepoints_tag );
utf8_string( const char* str , size_type len , tiny_utf8_detail::read_bytes_tag );
public:
/**
* Default Ctor
*
* @note Creates an Instance of type utf8_string that is empty
*/
inline utf8_string() : t_sso( 0 , '\0' ) {}
/**
* Constructor taking an utf8 sequence and the maximum length to read from it (in number of codepoints)
*
* @note Creates an Instance of type utf8_string that holds the given utf8 sequence
* @param str The UTF-8 sequence to fill the utf8_string with
* @param len (Optional) The maximum number of codepoints to read from the sequence
*/
template<typename T>
inline utf8_string( T&& str , enable_if_ptr<T,char>* = {} ) :
utf8_string( str , utf8_string::npos , tiny_utf8_detail::read_codepoints_tag() )
{}
inline utf8_string( const char* str , size_type len ) :
utf8_string( str , len , tiny_utf8_detail::read_codepoints_tag() )
{}
/**
* Constructor taking an utf8 char literal
*
* @note Creates an Instance of type utf8_string that holds the given utf8 sequence
* @param str The UTF-8 literal to fill the utf8_string with
*/
template<size_type LITLEN>
inline utf8_string( const char (&str)[LITLEN] , enable_if_small_string<LITLEN> = {} ){
std::memcpy( t_sso.data , str , LITLEN );
if( str[LITLEN-1] ){
t_sso.data[LITLEN] = '\0';
set_sso_data_len( LITLEN );
}
else
set_sso_data_len( LITLEN - 1 );
}
template<size_type LITLEN>
inline utf8_string( const char (&str)[LITLEN] , enable_if_not_small_string<LITLEN> = {} ) :
utf8_string( str , LITLEN - ( str[LITLEN-1] ? 0 : 1 ) , tiny_utf8_detail::read_bytes_tag() )
{}
/**
* Constructor taking an std::string
*
* @note Creates an Instance of type utf8_string that holds the given data sequence
* @param str The byte data, that will be interpreted as UTF-8
*/
inline utf8_string( std::string str ) :
utf8_string( str.c_str() , str.length() , tiny_utf8_detail::read_bytes_tag() )
{}
/**
* Constructor that fills the string with a certain amount of codepoints
*
* @note Creates an Instance of type utf8_string that gets filled with 'n' codepoints
* @param n The number of codepoints generated
* @param cp The code point that the whole buffer will be set to
*/
utf8_string( size_type n , value_type cp );
/**
* Constructor that fills the string with the supplied codepoint
*
* @note Creates an Instance of type utf8_string that gets filled with 'n' codepoints
* @param n The number of codepoints generated
* @param cp The code point that the whole buffer will be set to
*/
explicit inline utf8_string( value_type cp ) : t_sso( cp = encode_utf8( cp , t_sso.data ) ) {
t_sso.data[cp] = '\0';
}
/**
* Constructor that fills the string with a certain amount of characters
*
* @note Creates an Instance of type utf8_string that gets filled with 'n' characters
* @param n The number of characters generated
* @param cp The characters that the whole buffer will be set to
*/
utf8_string( size_type n , char cp );
/**
* Constructs the string with a portion of the supplied string
*
* @param str The string that the constructed string shall be a substring of
* @param pos The code point position indicating the start of the string to be used for construction
* @param cp The number of code points to be taken from 'str'
*/
utf8_string( const utf8_string& str , size_type pos , size_type count = utf8_string::npos ) :
utf8_string( str.substr( pos , count ) )
{}
/**
* Constructs the string from the range of code points supplied. The resulting string will equal [first,last)
*
* @note The Range is expected to contain code points (rather than code units, i.e. bytes)
* @param first The start of the range to construct from
* @param last The end of the range
*/
template<typename InputIt>
utf8_string( InputIt first , InputIt last ) : t_sso( 0 ) {
while( first != last ) push_back( *first++ );
}
/**
* Copy Constructor that copies the supplied utf8_string to construct the string
*
* @note Creates an Instance of type utf8_string that has the exact same data as 'str'
* @param str The utf8_string to copy from
*/
utf8_string( const utf8_string& str )
{
// Copy data
std::memcpy( this , &str , sizeof(utf8_string) );
// Create a new buffer, if sso is not active
if( str.sso_inactive() ){
size_type total_buffer_size = utf8_string::determine_total_buffer_size( t_non_sso.buffer_size );
t_non_sso.data = new char[ total_buffer_size ];
std::memcpy( t_non_sso.data , str.t_non_sso.data , total_buffer_size );
}
}
/**
* Move Constructor that moves the supplied utf8_string content into the new utf8_string
*
* @note Creates an Instance of type utf8_string that takes all data from 'str'
* The supplied utf8_string is invalid afterwards and may not be used anymore
* @param str The utf8_string to move from
*/
inline utf8_string( utf8_string&& str ){
std::memcpy( this , &str , sizeof(utf8_string) ); // Copy data
str.set_sso_data_len(0); // Reset old string
}
/**
* Constructor taking a wide code point literal that will be copied to construct this utf8_string
*
* @note Creates an Instance of type utf8_string that holds the given codepoints
* The data itself will be first converted to UTF-8
* @param str The code point sequence to fill the utf8_string with
* @param len (Optional) The maximum number of codepoints to read from the sequence
*/
utf8_string( const value_type* str , size_type len );
template<typename T>
utf8_string( T&& str , enable_if_ptr<T,value_type>* = {} ) :
utf8_string( str , utf8_string::npos )
{}
template<size_type LITLEN>
inline utf8_string( const value_type (&str)[LITLEN] ) :
utf8_string( str , LITLEN - ( str[LITLEN-1] ? 0 : 1 ) )
{}
/**
* Constructor taking an initializer list of codepoints.
*
* @note The initializer list is expected to contain code points (rather than code units, i.e. bytes)
* @param ilist The initializer list with the contents to be applied to this string
*/
inline utf8_string( std::initializer_list<value_type> ilist ) :
utf8_string( ilist.begin() , ilist.end() )
{}
/**
* Destructor
*
* @note Destructs a utf8_string at the end of its lifetime releasing all held memory
*/
inline ~utf8_string(){
clear();
}
/**
* Copy Assignment operator that sets the utf8_string to a copy of the supplied one
*
* @note Assigns a copy of 'str' to this utf8_string deleting all data that previously was in there
* @param str The utf8_string to copy from
* @return A reference to the string now holding the data (*this)
*/
utf8_string& operator=( const utf8_string& str );
/**
* Move Assignment operator that moves all data out of the supplied and into this utf8_string
*
* @note Moves all data from 'str' into this utf8_string deleting all data that previously was in there
* The supplied utf8_string is invalid afterwards and may not be used anymore
* @param str The utf8_string to move from
* @return A reference to the string now holding the data (*this)
*/
inline utf8_string& operator=( utf8_string&& str ){
if( &str != this ){
clear(); // Reset old data
std::memcpy( (void*)this , &str , sizeof(utf8_string) ); // Copy data
str.set_sso_data_len(0); // Reset old string
}
return *this;
}
/**
* Swaps the contents of this utf8_string with the supplied one
*
* @note Swaps all data with the supplied utf8_string
* @param str The utf8_string to swap contents with
*/
inline void swap( utf8_string& str ){
if( &str != this ){
char tmp[sizeof(utf8_string)];
std::memcpy( &tmp , &str , sizeof(utf8_string) );
std::memcpy( (void*)&str , this , sizeof(utf8_string) );
std::memcpy( (void*)this , &tmp , sizeof(utf8_string) );
}
}
/**
* Clears the content of this utf8_string
*
* @note Resets the data to an empty string ("")
*/
inline void clear(){
if( sso_inactive() )
delete[] t_non_sso.data;
set_sso_data_len( 0 );
t_sso.data[0] = 0;
}
/**
* Returns the current capacity of this string. That is, the number of codepoints it can hold without reallocation
*
* @return The number of bytes currently allocated
*/
inline size_type capacity() const {
return sso_inactive() ? get_non_sso_capacity() : get_sso_capacity();
}
/**
* Requests the removal of unused capacity.
*/
void shrink_to_fit();
/**
* Returns the code point at the supplied index
*
* @param n The code point index of the code point to receive
* @return The code point at position 'n'
*/
inline value_type at( size_type n ) const {
return raw_at( get_num_bytes_from_start( n ) );
}
inline value_type at( size_type n , std::nothrow_t ) const {
return raw_at( get_num_bytes_from_start( n ) , std::nothrow );
}
inline utf8_codepoint_reference<true> at( size_type n ){
return utf8_codepoint_reference<true>( n , this );
}
inline utf8_codepoint_reference<false> at( size_type n , std::nothrow_t ){
return utf8_codepoint_reference<false>( n , this );
}
/**
* Returns the code point at the supplied byte position
*
* @note As this access is raw, that is not looking up for the actual byte position,
* it is very fast.