-
Notifications
You must be signed in to change notification settings - Fork 3
/
tinyutf8.h
4975 lines (4438 loc) · 200 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) 2015-2020 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 <algorithm> // for std::min, std::max
#include <type_traits> // for std::is_*
#include <cstddef> // for std::size_t and offsetof
#include <cstdint> // for std::uint8_t, std::uint16_t, std::uint32_t, std::uint_least16_t, std::uint_fast32_t
#include <initializer_list> // for std::initializer_list
#include <iosfwd> // for std::ostream and std::istream forward declarations
#ifdef _MSC_VER
#include <intrin.h> // for _BitScanReverse, _BitScanReverse64
#endif
//! Determine the mode of error handling
#ifndef TINY_UTF8_THROW
#if defined(__cpp_exceptions) && !defined(TINY_UTF8_NOEXCEPT)
#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
#endif
//! Determine the way to inform about fallthrough behavior
#if __cplusplus >= 201700L
#define TINY_UTF8_FALLTHROUGH [[fallthrough]];
#elif defined(__clang__)
// Clang does not warn about implicit fallthrough
#define TINY_UTF8_FALLTHROUGH
#elif defined(__GNUC__) && __GNUG__ > 6
#define TINY_UTF8_FALLTHROUGH [[gnu::fallthrough]];
#else
#define TINY_UTF8_FALLTHROUGH /* fall through */
#endif
//! Remove Warnings, since it is wrong for all cases in this file
#if defined(__clang__)
#pragma clang diagnostic push
// #pragma clang diagnostic ignored "-Wmaybe-uninitialized" // Clang is missing it. See https://bugs.llvm.org/show_bug.cgi?id=24979
#elif defined(__GNUC__)
#pragma GCC diagnostic push
#elif defined(_MSC_VER)
#pragma warning(push)
#pragma warning(disable:4701) // Maybe unitialized
#pragma warning(disable:4702) // Unreachable code after call to TINY_UTF8_THROW()
#pragma warning(disable:4703) // Maybe unitialized
#pragma warning(disable:26819) // Implicit Fallthrough
#endif
//! Create macro that yields its arguments, if C++17 or later is present (used for "if constexpr")
#if __cplusplus >= 201700L
#define TINY_UTF8_CPP17( ... ) __VA_ARGS__
#else
#define TINY_UTF8_CPP17( ... )
#endif
//! Determine noexcept specifications
#if defined(TINY_UTF8_NOEXCEPT)
#undef TINY_UTF8_NOEXCEPT
#define TINY_UTF8_NOEXCEPT true
#elif !defined(__cpp_exceptions)
#define TINY_UTF8_NOEXCEPT true
#else
#define TINY_UTF8_NOEXCEPT false
#endif
//! Want global declarations?
#ifdef TINY_UTF8_GLOBAL_NAMESPACE
inline
#endif
namespace tiny_utf8
{
// Forward Declaration
template<
typename ValueType = char32_t
, typename DataType = char
, typename Allocator = std::allocator<char>
>
class basic_string;
//! Typedef of string (data type: char)
using string = basic_string<char32_t, char>;
//! Typedef of u8string (data type char8_t)
#if __cplusplus > 201703L
#if defined(__cpp_char8_t)
using u8string = basic_string<char32_t, char8_t>;
#else
using u8string = utf8_string;
#endif
#endif
//! Typedef of utf8_string (data type: char)
using utf8_string = basic_string<char32_t, char>; // For backwards compatibility
//! Implementation Detail
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 value ) noexcept { return (unsigned int)__builtin_clz( value ); }
static inline unsigned int clz( unsigned long int value ) noexcept { return (unsigned int)__builtin_clzl( value ); }
static inline unsigned int clz( char32_t value ) noexcept {
return sizeof(char32_t) == sizeof(unsigned long int) ? (unsigned int)__builtin_clzl( value ) : (unsigned int)__builtin_clz( value );
}
#elif defined(_MSC_VER)
#ifndef TINY_UTF8_HAS_CLZ
#define TINY_UTF8_HAS_CLZ true
#endif
template<typename T>
static inline unsigned int lzcnt( T value ) noexcept {
unsigned long value_log2;
#if !defined( WIN32 ) && !defined( _WIN32 ) && !defined( __WIN32__ )
_BitScanReverse64( &value_log2 , value );
#else
_BitScanReverse( &value_log2 , value );
#endif
return sizeof(T) * 8 - value_log2 - 1;
}
static inline unsigned int clz( std::uint16_t value ) noexcept { return lzcnt( value ); }
static inline unsigned int clz( std::uint32_t value ) noexcept { return lzcnt( value ); }
#ifndef WIN32
static inline unsigned int clz( std::uint64_t value ) noexcept { return lzcnt( value ); }
#endif // WIN32
static inline unsigned int clz( char32_t value ) noexcept { return lzcnt( value ); }
#endif
//! Helper to detect little endian
class is_little_endian
{
constexpr static std::uint32_t u4 = 1;
constexpr static std::uint8_t u1 = (const std::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, std::size_t = sizeof(T)>
union last_byte
{
T number;
struct{
char dummy[sizeof(T)-1];
char last;
} bytes;
};
template<typename T>
union last_byte<T, 1>
{
T number;
struct{
char last;
} bytes;
};
//! strlen for different character types
template<typename T>
inline std::size_t strlen( const T* str ){ std::size_t len = 0u; while( *str++ ) ++len; return len; }
template<> inline std::size_t strlen<char>( const char* str ){ return std::strlen( str ); }
}
template<typename Container, bool RangeCheck>
struct codepoint_reference
{
typename Container::size_type t_index;
Container* t_instance;
public:
//! Ctor
codepoint_reference( typename Container::size_type index , Container* instance ) noexcept :
t_index( index )
, t_instance( instance )
{}
//! Cast to wide char
operator typename Container::value_type() const noexcept( TINY_UTF8_NOEXCEPT || RangeCheck == false ) {
if TINY_UTF8_CPP17(constexpr) ( RangeCheck )
return static_cast<const Container*>(t_instance)->at( t_index );
else
return static_cast<const Container*>(t_instance)->at( t_index , std::nothrow );
}
//! Dereference operator to act as pointer type
codepoint_reference& operator*() const noexcept { return *this; }
//! Assignment operator
codepoint_reference& operator=( typename Container::value_type cp ) noexcept(TINY_UTF8_NOEXCEPT) {
t_instance->replace( t_index , cp );
return *this;
}
};
template<typename Container, bool RangeCheck>
struct raw_codepoint_reference
{
typename Container::size_type t_raw_index;
Container* t_instance;
public:
//! Ctors
raw_codepoint_reference( typename Container::size_type raw_index , Container* instance ) noexcept :
t_raw_index( raw_index )
, t_instance( instance )
{}
template<bool RC>
explicit raw_codepoint_reference( const codepoint_reference<Container, RC>& reference ) noexcept :
t_raw_index( reference.t_instance->get_num_bytes_from_start( reference.t_index ) )
, t_instance( reference.t_instance )
{}
//! Cast to wide char
operator typename Container::value_type() const noexcept( TINY_UTF8_NOEXCEPT || RangeCheck == false ) {
if TINY_UTF8_CPP17(constexpr) ( RangeCheck )
return static_cast<const Container*>(t_instance)->raw_at( t_raw_index );
else
return static_cast<const Container*>(t_instance)->raw_at( t_raw_index , std::nothrow );
}
//! Dereference operator to act as pointer type
raw_codepoint_reference& operator*() const noexcept { return *this; }
//! Cast to normal (non-raw) code point reference
template<bool RC>
explicit operator codepoint_reference<Container, RC>() const noexcept { return { t_instance->get_num_codepoints( 0 , t_raw_index ) , t_instance }; }
//! Assignment operator
raw_codepoint_reference& operator=( typename Container::value_type cp ) noexcept {
t_instance->raw_replace( t_raw_index , t_instance->get_index_bytes( t_raw_index ) , Container( cp ) );
return *this;
}
};
template<typename Container>
struct iterator_base
{
template<typename, typename, typename>
friend class basic_string;
public:
typedef typename Container::value_type value_type;
typedef typename Container::difference_type difference_type;
typedef raw_codepoint_reference<Container, false> reference;
typedef void* pointer;
typedef std::bidirectional_iterator_tag iterator_category;
bool operator==( const iterator_base& it ) const noexcept { return t_raw_index == it.t_raw_index; }
bool operator!=( const iterator_base& it ) const noexcept { return t_raw_index != it.t_raw_index; }
//! Ctor
iterator_base( difference_type raw_index , Container* instance ) noexcept :
t_raw_index( raw_index )
, t_instance( instance )
{}
//! Default function
iterator_base() noexcept = default;
iterator_base( const iterator_base& ) noexcept = default;
iterator_base& operator=( const iterator_base& ) noexcept = default;
// Getter for the iterator index
difference_type get_index() const noexcept { return t_raw_index; }
Container* get_instance() const noexcept { return t_instance; }
protected:
difference_type t_raw_index;
Container* t_instance = nullptr;
protected:
//! Advance the iterator n times (negative values allowed!)
void advance( difference_type n ) noexcept {
if( n > 0 )
do
increment();
while( --n > 0 );
else
while( n++ < 0 )
decrement();
}
//! Move the iterator one codepoint ahead
void increment() noexcept { t_raw_index += t_instance->get_index_bytes( t_raw_index ); }
//! Move the iterator one codepoint backwards
void decrement() noexcept { t_raw_index -= t_instance->get_index_pre_bytes( t_raw_index ); }
//! Get a reference to the codepoint the iterator points to
reference get_reference() const noexcept { return t_instance->raw_at( t_raw_index , std::nothrow ); }
//! Get the value that the iterator points to
value_type get_value() const noexcept { return static_cast<const Container*>(t_instance)->raw_at( t_raw_index ); }
//! Get the index of the codepoint the iterator points to
difference_type get_raw_index() const noexcept { return t_raw_index; }
};
template<typename Container> struct iterator;
template<typename Container> struct const_iterator;
template<typename Container> struct reverse_iterator;
template<typename Container> struct const_reverse_iterator;
template<typename Container>
struct iterator : iterator_base<Container>
{
//! Ctor
iterator( typename iterator_base<Container>::difference_type raw_index , Container* instance ) noexcept :
iterator_base<Container>( raw_index , instance )
{}
//! Default Functions
iterator() noexcept = default;
iterator( const iterator& ) noexcept = default;
iterator& operator=( const iterator& ) noexcept = default;
//! Delete ctor from const iterator types
iterator( const const_iterator<Container>& ) = delete;
iterator( const const_reverse_iterator<Container>& ) = delete;
//! Increase the Iterator by one
iterator& operator++() noexcept { // prefix ++iter
this->increment();
return *this;
}
iterator operator++( int ) noexcept { // postfix iter++
iterator tmp{ this->t_raw_index , this->t_instance };
this->increment();
return tmp;
}
//! Decrease the iterator by one
iterator& operator--() noexcept { // prefix --iter
this->decrement();
return *this;
}
iterator operator--( int ) noexcept { // postfix iter--
iterator tmp{ this->t_raw_index , this->t_instance };
this->decrement();
return tmp;
}
//! Increase the Iterator n times
iterator operator+( typename iterator_base<Container>::difference_type n ) const noexcept {
iterator it{*this};
it.advance( n );
return it;
}
iterator& operator+=( typename iterator_base<Container>::difference_type n ) noexcept {
this->advance( n );
return *this;
}
//! Decrease the Iterator n times
iterator operator-( typename iterator_base<Container>::difference_type n ) const noexcept {
iterator it{*this};
it.advance( -n );
return it;
}
iterator& operator-=( typename iterator_base<Container>::difference_type n ) noexcept {
this->advance( -n );
return *this;
}
//! Returns the value of the code point behind the iterator
typename iterator::reference operator*() const noexcept { return this->get_reference(); }
};
template<typename Container>
struct const_iterator : iterator<Container>
{
//! Ctor
const_iterator( typename iterator_base<Container>::difference_type raw_index , const Container* instance ) noexcept :
iterator<Container>( raw_index , const_cast<Container*>(instance) )
{}
//! Ctor from non const
const_iterator( const iterator<Container>& it ) noexcept :
iterator<Container>( it.get_index() , it.get_instance() )
{}
//! Default Functions
const_iterator() noexcept = default;
const_iterator( const const_iterator& ) noexcept = default;
const_iterator& operator=( const const_iterator& ) noexcept = default;
//! Returns the (raw) value behind the iterator
typename iterator<Container>::value_type operator*() const noexcept { return this->get_value(); }
};
template<typename Container>
struct reverse_iterator : iterator_base<Container>
{
//! Ctor
reverse_iterator( typename iterator_base<Container>::difference_type raw_index , Container* instance ) noexcept :
iterator_base<Container>( raw_index , instance )
{}
//! Ctor from normal iterator
reverse_iterator( const iterator<Container>& it ) noexcept :
iterator_base<Container>( it.get_index() , it.get_instance() )
{}
//! Default Functions
reverse_iterator() noexcept = default;
reverse_iterator( const reverse_iterator& ) noexcept = default;
reverse_iterator& operator=( const reverse_iterator& ) noexcept = default;
//! Delete ctor from const iterator types
reverse_iterator( const const_iterator<Container>& ) = delete;
reverse_iterator( const const_reverse_iterator<Container>& ) = delete;
//! Increase the iterator by one
reverse_iterator& operator++() noexcept { // prefix ++iter
this->decrement();
return *this;
}
reverse_iterator operator++( int ) noexcept { // postfix iter++
reverse_iterator tmp{ this->t_raw_index , this->t_instance };
this->decrement();
return tmp;
}
//! Decrease the Iterator by one
reverse_iterator& operator--() noexcept { // prefix --iter
this->increment();
return *this;
}
reverse_iterator operator--( int ) noexcept { // postfix iter--
reverse_iterator tmp{ this->t_raw_index , this->t_instance };
this->increment();
return tmp;
}
//! Increase the Iterator n times
reverse_iterator operator+( typename iterator_base<Container>::difference_type n ) const noexcept {
reverse_iterator it{*this};
it.advance( -n );
return it;
}
reverse_iterator& operator+=( typename iterator_base<Container>::difference_type n ) noexcept {
this->advance( -n );
return *this;
}
//! Decrease the Iterator n times
reverse_iterator operator-( typename iterator_base<Container>::difference_type n ) const noexcept {
reverse_iterator it{*this};
it.advance( n );
return it;
}
reverse_iterator& operator-=( typename iterator_base<Container>::difference_type n ) noexcept {
this->advance( n );
return *this;
}
//! Returns the value of the code point behind the iterator
typename iterator<Container>::reference operator*() const noexcept { return this->get_reference(); }
//! Get the underlying iterator instance
iterator<Container> base() const noexcept { return { this->t_raw_index , this->t_instance }; }
};
template<typename Container>
struct const_reverse_iterator : reverse_iterator<Container>
{
//! Ctor
const_reverse_iterator( typename iterator_base<Container>::difference_type raw_index , const Container* instance ) noexcept :
reverse_iterator<Container>( raw_index , const_cast<Container*>(instance) )
{}
//! Ctor from non const
const_reverse_iterator( const reverse_iterator<Container>& it ) noexcept :
reverse_iterator<Container>( it.get_index() , it.get_instance() )
{}
//! Ctor from normal iterator
const_reverse_iterator( const const_iterator<Container>& it ) noexcept :
reverse_iterator<Container>( it.get_index() , it.get_instance() )
{}
//! Default Functions
const_reverse_iterator() noexcept = default;
const_reverse_iterator( const const_reverse_iterator& ) noexcept = default;
const_reverse_iterator& operator=( const const_reverse_iterator& ) noexcept = default;
//! Returns the (raw) value behind the iterator
typename iterator<Container>::value_type operator*() const noexcept { return this->get_value(); }
//! Get the underlying iterator instance
const_iterator<Container> base() const noexcept { return { this->t_raw_index , this->t_instance }; }
};
//! Compare two iterators
template<typename Container>
static inline bool operator>( const const_iterator<Container>& lhs , const const_iterator<Container>& rhs ) noexcept {
return lhs.get_index() > rhs.get_index();
}
template<typename Container>
static inline bool operator>( const const_reverse_iterator<Container>& lhs , const const_reverse_iterator<Container>& rhs ) noexcept {
return lhs.get_index() < rhs.get_index();
}
template<typename Container>
static inline bool operator>=( const const_iterator<Container>& lhs , const const_iterator<Container>& rhs ) noexcept {
return lhs.get_index() >= rhs.get_index();
}
template<typename Container>
static inline bool operator>=( const const_reverse_iterator<Container>& lhs , const const_reverse_iterator<Container>& rhs ) noexcept {
return lhs.get_index() <= rhs.get_index();
}
template<typename Container>
static inline bool operator<( const const_iterator<Container>& lhs , const const_iterator<Container>& rhs ) noexcept {
return lhs.get_index() < rhs.get_index();
}
template<typename Container>
static inline bool operator<( const const_reverse_iterator<Container>& lhs , const const_reverse_iterator<Container>& rhs ) noexcept {
return lhs.get_index() > rhs.get_index();
}
template<typename Container>
static inline bool operator<=( const const_iterator<Container>& lhs , const const_iterator<Container>& rhs ) noexcept {
return lhs.get_index() <= rhs.get_index();
}
template<typename Container>
static inline bool operator<=( const const_reverse_iterator<Container>& lhs , const const_reverse_iterator<Container>& rhs ) noexcept {
return lhs.get_index() >= rhs.get_index();
}
//! Iterator difference computation functions (difference is in terms of codepoints)
template<typename Container>
typename iterator<Container>::difference_type operator-( const iterator<Container>& lhs , const iterator<Container>& rhs ) noexcept {
typename iterator<Container>::difference_type minIndex = std::min( lhs.get_index() , rhs.get_index() );
typename iterator<Container>::difference_type max_index = std::max( lhs.get_index() , rhs.get_index() );
typename iterator<Container>::difference_type num_codepoints = lhs.get_instance()->get_num_codepoints( minIndex , max_index - minIndex );
return max_index == lhs.get_index() ? num_codepoints : -num_codepoints;
}
template<typename Container>
typename reverse_iterator<Container>::difference_type operator-( const reverse_iterator<Container>& lhs , const reverse_iterator<Container>& rhs ) noexcept {
typename reverse_iterator<Container>::difference_type minIndex = std::min( lhs.get_index() , rhs.get_index() );
typename reverse_iterator<Container>::difference_type max_index = std::max( lhs.get_index() , rhs.get_index() );
typename reverse_iterator<Container>::difference_type num_codepoints = lhs.get_instance()->get_num_codepoints( minIndex , max_index - minIndex );
return max_index == rhs.get_index() ? num_codepoints : -num_codepoints;
}
// Base class for basic_string
template<
typename ValueType
, typename DataType
, typename Allocator
>
class basic_string : private Allocator
{
public:
typedef DataType data_type;
typedef typename std::allocator_traits<Allocator>::size_type size_type;
typedef typename std::allocator_traits<Allocator>::difference_type difference_type;
typedef ValueType value_type;
typedef codepoint_reference<basic_string, false> reference;
typedef codepoint_reference<basic_string, true> checked_reference;
typedef raw_codepoint_reference<basic_string, false> raw_reference;
typedef raw_codepoint_reference<basic_string, true> raw_checked_reference;
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
typedef tiny_utf8::iterator<basic_string> iterator;
typedef tiny_utf8::const_iterator<basic_string> const_iterator;
typedef tiny_utf8::reverse_iterator<basic_string> reverse_iterator;
typedef tiny_utf8::const_reverse_iterator<basic_string> const_reverse_iterator;
typedef Allocator allocator_type;
typedef size_type indicator_type; // Typedef for the lut indicator. Note: Don't change this, because else the buffer will not be a multiple of sizeof(size_type)
enum : size_type{ npos = (size_type)-1 };
protected: //! 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
{
data_type* 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
{
enum : size_type{ size = sizeof(NON_SSO)-1 };
data_type data[size];
unsigned char data_len; // This field holds ( size - num_characters ) << 1
SSO( data_type value ) noexcept :
data{ value , '\0' }
, data_len( (unsigned char)( size - 1u ) << 1 )
{}
SSO( size_type data_len ) noexcept :
// Note: No initialization of .data (important for the constructor of basic_string(value_type)...)
data_len( (unsigned char)( ( size - data_len ) << 1 ) )
{
data[data_len] = '\0'; // Add delimiter to actual data
}
SSO() noexcept :
data{ '\0' }
, data_len( (unsigned char)( size - 0 ) << 1 )
{}
};
protected: //! Attributes
union{
SSO t_sso;
NON_SSO t_non_sso;
};
protected: //! Static helper methods
//! Get the maximum number of bytes (excluding the trailing '\0') that can be stored within a basic_string object
static constexpr inline size_type get_sso_capacity() noexcept { return SSO::size; }
//! SFINAE helpers for constructors
template<size_type L>
using enable_if_small_string = typename std::enable_if<( L <= SSO::size ), bool>::type;
template<size_type L>
using enable_if_not_small_string = typename std::enable_if<( L > SSO::size ), 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 data_type* lut_base_ptr ) noexcept { 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 ) noexcept {
return ( val + sizeof(size_type) - 1 ) & ~( sizeof(size_type) - 1 );
}
//! Get the LUT base pointer from buffer and buffer size
static inline data_type* get_lut_base_ptr( data_type* buffer , size_type buffer_size ) noexcept { return buffer + buffer_size; }
static inline const data_type* get_lut_base_ptr( const data_type* buffer , size_type buffer_size ) noexcept { return buffer + buffer_size; }
//! Construct the lut mode indicator
static inline void set_lut_indiciator( data_type* lut_base_ptr , bool active , size_type lut_len = 0 ) noexcept {
*(indicator_type*)lut_base_ptr = active ? ( lut_len << 1 ) | 0x1 : 0;
}
//! Copy lut indicator
static inline void copy_lut_indicator( data_type* dest , const data_type* source ) noexcept {
*(indicator_type*)dest = *(indicator_type*)source;
}
//! Determine, whether we will use a 'std::uint8_t', 'std::uint16_t', 'std::uint32_t' or 'std::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 ) noexcept {
return buffer_size <= (size_type)std::numeric_limits<std::uint8_t>::max() + 1
? sizeof(std::uint8_t)
: buffer_size <= (size_type)std::numeric_limits<std::uint16_t>::max() + 1
? sizeof(std::uint16_t)
: buffer_size <= (size_type)std::numeric_limits<std::uint32_t>::max() + 1
? sizeof(std::uint32_t)
: sizeof(std::uint64_t)
;
}
//! 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 ) noexcept {
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 ) noexcept {
size_type width_guess = get_lut_width( ++data_len ); // Don't forget, we need a terminating '\0', distinct from the lut indicator
data_len += lut_len * width_guess; // Add the estimated number of bytes from the lut
data_len += lut_len * ( ( *lut_width = get_lut_width( data_len ) ) - width_guess ); // Adjust the added bytes from the lut
return round_up_to_align( data_len ); // Make the buffer size_type-aligned
}
//! 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 ) noexcept {
return round_up_to_align( data_len + 1 + lut_len * lut_width ); // Compute the size_type-aligned buffer size
}
//! 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 ) noexcept {
return round_up_to_align( data_len + 1 ); // Make the buffer size_type-aligned
}
//! Same as above but this time including the LUT indicator
static inline size_type determine_total_buffer_size( size_type main_buffer_size ) noexcept {
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 data_type* iter , width_type lut_width ) noexcept {
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 (size_type)*(const std::uint64_t*)iter;
}
static inline void set_lut( data_type* iter , width_type lut_width , size_type value ) noexcept {
switch( lut_width ){
case sizeof(std::uint8_t): *(std::uint8_t*)iter = (std::uint8_t)value; break;
case sizeof(std::uint16_t): *(std::uint16_t*)iter = (std::uint16_t)value; break;
case sizeof(std::uint32_t): *(std::uint32_t*)iter = (std::uint32_t)value; break;
case sizeof(std::uint64_t): *(std::uint64_t*)iter = (std::uint64_t)value; break;
}
}
//! Get the LUT size (given the lut is active!)
static inline size_type get_lut_len( const data_type* lut_base_ptr ) noexcept {
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( data_type first_byte , size_type data_left ) noexcept
{
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 (width_type)codepoint_bytes;
}
return 1;
}
#else
static width_type get_codepoint_bytes( data_type first_byte , size_type data_left ) noexcept ; // 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 ) noexcept
{
#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 data_type* data_start , size_type index ) noexcept ;
//! 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 data_type* data , width_type num_bytes ) noexcept {
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 data_type* data , value_type& dest , size_type data_left ) noexcept {
// See 'get_codepoint_bytes' for 'data_left'
width_type num_bytes = basic_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 , data_type* dest , width_type cp_bytes ) noexcept {
switch( cp_bytes ){
case 7: dest[cp_bytes-6] = 0x80 | ((cp >> 30) & 0x3F); TINY_UTF8_FALLTHROUGH
case 6: dest[cp_bytes-5] = 0x80 | ((cp >> 24) & 0x3F); TINY_UTF8_FALLTHROUGH
case 5: dest[cp_bytes-4] = 0x80 | ((cp >> 18) & 0x3F); TINY_UTF8_FALLTHROUGH
case 4: dest[cp_bytes-3] = 0x80 | ((cp >> 12) & 0x3F); TINY_UTF8_FALLTHROUGH
case 3: dest[cp_bytes-2] = 0x80 | ((cp >> 6) & 0x3F); TINY_UTF8_FALLTHROUGH
case 2: dest[cp_bytes-1] = 0x80 | ((cp >> 0) & 0x3F);
dest[0] = (unsigned char)( ( std::uint_least16_t(0xFF00uL) >> cp_bytes ) | ( cp >> ( 6 * cp_bytes - 6 ) ) );
break;
case 1:
dest[0] = (unsigned char)cp;
break;
}
}
/**
* 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 , data_type* dest ) noexcept {
width_type width = get_codepoint_bytes( cp );
basic_string::encode_utf8( cp , dest , width );
return width;
}
protected: //! Non-static helper methods
//! Set the main buffer size (also disables SSO)
inline void set_non_sso_string_len( size_type string_len ) noexcept
{
// Check, if NON_SSO is larger than its members, in which case it's not ambiguated by SSO::data_len
if TINY_UTF8_CPP17(constexpr) ( 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_CPP17(constexpr) ( 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 noexcept {
// 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 ) noexcept {
t_sso.data_len = (unsigned char)( SSO::size - data_len ) << 1;
}
//! Get the data length (when SSO is active)
inline size_type get_sso_data_len() const noexcept { 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 noexcept ;
//! Check, if sso is inactive (this operation doesn't require a negation and is faster)
inline bool sso_inactive() const noexcept { 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) ) noexcept { 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 noexcept ;
//! Get buffer
inline const data_type* get_buffer() const noexcept { return sso_inactive() ? t_non_sso.data : t_sso.data; }
inline data_type* get_buffer() noexcept { 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 noexcept {
return sso_inactive() ? t_non_sso.buffer_size : get_sso_capacity();
}
//! Returns an std::string with the UTF-8 BOM prepended
std::basic_string<data_type> cpp_str_bom() const noexcept ;
//! Allocates size_type-aligned storage (make sure, total_buffer_size is a multiple of sizeof(size_type)!)
inline data_type* allocate( size_type total_buffer_size ) const noexcept {
using appropriate_allocator = typename std::allocator_traits<Allocator>::template rebind_alloc<size_type>;
appropriate_allocator casted_allocator = (const Allocator&)*this;
return reinterpret_cast<data_type*>(
std::allocator_traits<appropriate_allocator>::allocate(
casted_allocator
, total_buffer_size / sizeof(size_type) * sizeof(data_type)
)
);
}
//! Allocates size_type-aligned storage (make sure, buffer_size is a multiple of sizeof(size_type)!)
inline void deallocate( data_type* buffer , size_type buffer_size ) const noexcept {
using appropriate_allocator = typename std::allocator_traits<Allocator>::template rebind_alloc<size_type>;
appropriate_allocator casted_allocator = (const Allocator&)*this;
std::allocator_traits<appropriate_allocator>::deallocate(
casted_allocator
, reinterpret_cast<size_type*>( buffer )
, basic_string::determine_total_buffer_size( buffer_size ) / sizeof(size_type) * sizeof(data_type)
);
}
//! Constructs an basic_string from a character literal
basic_string( const data_type* str , size_type pos , size_type count , size_type data_left , const allocator_type& alloc , tiny_utf8_detail::read_codepoints_tag ) noexcept(TINY_UTF8_NOEXCEPT) ;
basic_string( const data_type* str , size_type count , const allocator_type& alloc , tiny_utf8_detail::read_bytes_tag ) noexcept(TINY_UTF8_NOEXCEPT) ;
public:
/**
* Default Ctor
*
* @note Creates an Instance of type basic_string that is empty
*/
basic_string()
noexcept(TINY_UTF8_NOEXCEPT && std::is_nothrow_default_constructible<Allocator>())
: Allocator()
, t_sso()
{}
/**
* Ctor taking an alloc
*
* @note Creates an Instance of type basic_string that is empty
*/
explicit basic_string( const allocator_type& alloc )
noexcept(TINY_UTF8_NOEXCEPT && std::is_nothrow_copy_constructible<Allocator>())
: Allocator( alloc )