-
Notifications
You must be signed in to change notification settings - Fork 14
Expand file tree
/
Copy pathstringhelpers.h
More file actions
2447 lines (2276 loc) · 102 KB
/
stringhelpers.h
File metadata and controls
2447 lines (2276 loc) · 102 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* version 0.9.5
* general string-helper functions
* Note: currently, most up to date Version is in live!
*
* only depends on g++:
* -std=c++17 std:: standard headers
* on esyslog (from VDR)
* on "to_chars10.h"
*
* no other dependencies, so it can be easily included in any other header
*
*
*/
#ifndef __STRINGHELPERS_H
#define __STRINGHELPERS_H
#if !defined test_stringhelpers
#include "vdr/tools.h"
#endif
#include "to_chars10.h"
#include <cstdarg>
#include <string>
#include <string_view>
#include <string.h>
#include <regex>
#include <vector>
#include <set>
#include <array>
#include <algorithm>
#include <fcntl.h>
#include <unistd.h>
#include <sys/stat.h>
#include <locale>
#include <iostream>
#include <chrono>
// =========================================================
// =========================================================
// Chapter 0: **************************************
// methods for char *s, make sure that s==NULL is just an empty string
// =========================================================
// =========================================================
inline std::string charPointerToString(const char *s) {
return s?s:std::string();
}
inline std::string charPointerToString(const unsigned char *s) {
return s?reinterpret_cast<const char *>(s):std::string();
}
// challenge:
// method with importing parameter std::string_view called with const char * = nullptr
// undefined behavior, as std::string_view(nullptr) is undefined. In later c++ standard, it is even an abort
// solution:
// a) be very careful, check const char * for nullptr before calling a method with std::string_view as import parameter
// or:
// b) replace all std::string_view with cSv
// very small performance impact if such a method if called with cSv
// this will convert nullptr to empty cSv if called with const char *
// 2nd advantage of cSv: substr(pos) if pos > length: no dump, just an empty cSv as result
class cSv: public std::string_view {
public:
typedef typename std::string_view::size_type size_type;
typedef typename std::string_view::const_iterator const_iterator;
static const size_type npos = std::string_view::npos;
cSv(): std::string_view() {}
template<size_type N> cSv(const char (&s)[N]): std::string_view(s, N-1) {
// std::cout << "cSv const char (&s)[N] " << s << "\n";
}
template<typename T, std::enable_if_t<std::is_same_v<T, const char*>, bool> = true>
cSv(T s): std::string_view(charPointerToStringView(s)) {
// std::cout << "cSv const char *s " << (s?s:"nullptr") << "\n";
}
template<typename T, std::enable_if_t<std::is_same_v<T, char*>, bool> = true>
cSv(T s): std::string_view(charPointerToStringView(s)) {
// std::cout << "cSv char *s " << (s?s:"nullptr") << "\n";
}
cSv(const unsigned char *s): std::string_view(charPointerToStringView(reinterpret_cast<const char *>(s))) {}
cSv(const char *s, size_type l): std::string_view(s, l) {}
cSv(const unsigned char *s, size_type l): std::string_view(reinterpret_cast<const char *>(s), l) {}
cSv(std::string_view sv): std::string_view(sv) {}
cSv(const std::string &s): std::string_view(s) {}
cSv substr(size_type pos) const { return (length() > pos)?cSv(data() + pos, length() - pos):cSv(); }
cSv substr(size_type pos, size_type count) const { return (length() > pos)?cSv(data() + pos, std::min(length() - pos, count) ):cSv(); }
size_type find2(char ch, size_type pos = 0) const { // as find, but return length() if ch is not found
for (; pos < length() && (*this)[pos] != ch; ++pos);
return pos;
}
private:
static std::string_view charPointerToStringView(const char *s) {
return s?std::string_view(s, strlen(s)):std::string_view();
}
};
// =========================================================
// cStr: similar to cSv, but support c_str()
// never returns null pointer!
// always return pointer to zero terminated char array
// =========================================================
class cStr {
public:
cStr() {}
cStr(const char *s) { if (s) m_s = s; }
cStr(const unsigned char *s) { if (s) m_s = reinterpret_cast<const char *>(s); }
cStr(const std::string &s): m_s(s.c_str()) {}
operator const char *() const { return m_s; }
const char *c_str() const { return m_s; }
char *data() { return (char *)m_s; }
size_t length() const { return strlen(m_s); }
operator cSv() const { return cSv(m_s, strlen(m_s)); }
const char *begin() const { return m_s; }
const char *cbegin() const { return m_s; }
const char *end() const { return m_s + strlen(m_s); }
const char *cend() const { return m_s + strlen(m_s); }
private:
const char *m_s = "";
};
// ===============================================================
// === Proxy Iterators
// ===============================================================
/*
* These iterators are not iterators of own containers, but more like views
* to containers:
* we do not change data, but prepare existing data.
* e.g. display wint_t codepoints of an utf8 string
* Consequence:
* a) these are proxy iterators, dereference returns a value (and not a reference)
* -> LegacyInputIterator, even if we also provide operator--()
* -> most iterators are std::bidirectional_iterator (since c++20)
* -> std::reverse_iterator does not work, we provide const_reverse_iterator
* -> const_: all iterator names start with const, as it is not possible
* to change the content of the underlying container
*
* b) the iterators know their own end. To test for end in loops,
* you can compare with a "sentinel":
*
* for (const_..._iterator it("123"); it != iterator_end(); ++it) {
* auto value = *it;
* do something;
* }
* to support ranged for loops, for each const_..._iterator class IT we provide:
* template<class IT> IT begin(const IT &it) { return it; }
* template<class IT> iterator_end end (const IT &it) { return iterator_end(); }
* so you can also write:
*
* for (auto value: const_..._iterator it("123")) {
* do something;
* }
* Some pre-c++20 methods need an end iterator with the same class as the iterator itself
* To support this, the default constructor of each const_..._iterator class creates an end iterator.
* So you can e.g. write:
*
* std::set<int> int_set(const_..._iterator(...), const_..._iterator() );
*
* to initialize int_set with the elements of const_..._iterator(...)
*
* See also:
* https://stackoverflow.com/questions/51046897/what-could-be-a-least-bad-implementation-for-an-iterator-over-a-proxied-contai
* std::bidirectional_iterator (since c++20), see https://en.cppreference.com/w/cpp/iterator/bidirectional_iterator
*
* stashing iterators are still not std::bidirectional_iterator, as they violate:
* Pointers and references obtained from a forward iterator into a range remain valid while the range exists.
* -> use proxy iterators (returning a value) and
* not stashing iterators (returning a reference to an object in the iterator)
*/
class iterator_begin {};
class iterator_end {};
class iterator_empty {};
enum class iterator_pos {
none = 0,
begin = 1,
end = 2
};
// ===============================================================
// === reverse iterator ==============
// creates a proxy iterator (dereference returns the value)
// the iterator class IT must provide:
// operator--()
// operator++()
// operator==(IT other)
// operator!=(IT other)
// operator==(iterator_begin other)
// operator!=(iterator_begin other)
// IT::value_type operator*()
// the empty constructor () returns an "empty" iterator which is
// equal to both, the begin iterator AND the end iterator
//
// provides a generic constructor forwarding the arguments to the constructor of IT
//
// ===============================================================
template<class IT> class const_reverse_iterator {
IT m_it;
public:
using iterator_category = std::input_iterator_tag;
using value_type = typename IT::value_type;
using difference_type = typename IT::difference_type;
using pointer = typename IT::pointer;
using reference = typename IT::reference;
// explicit copy constructor to avoid that the generic constructor is used for that
constexpr const_reverse_iterator(const const_reverse_iterator &rit): m_it(rit.m_it) {}
constexpr const_reverse_iterator( const_reverse_iterator &rit): const_reverse_iterator(const_cast<const const_reverse_iterator&>(rit)) {}
// ==== constructor for the end iterator ======================================
constexpr explicit const_reverse_iterator(): m_it(iterator_begin()) { }
// generic constructor, forward arguments to underlying iterator
template<typename... Args>
constexpr explicit const_reverse_iterator(Args&&... args): m_it(std::forward<Args>(args)...) {}
const_reverse_iterator& operator++() { --m_it; return *this; }
const_reverse_iterator operator++(int) { auto tmp = *this; --m_it; return tmp; }
const_reverse_iterator& operator--() { ++m_it; return *this; }
const_reverse_iterator operator--(int) { auto tmp = *this; ++m_it; return tmp; }
// compare
bool operator==(const_reverse_iterator other) const { return m_it == other.m_it; }
bool operator!=(const_reverse_iterator other) const { return m_it != other.m_it; }
bool operator==(iterator_end other) const { return m_it == iterator_begin(); }
bool operator!=(iterator_end other) const { return m_it != iterator_begin(); }
typename IT::value_type operator*() const {
IT tmp = m_it;
return *--tmp;
}
constexpr IT base() const { return m_it; }
IT val_base() const {
// must only be called if the iterator is dereferencable!
// return the underlying it at the position we also dereference
IT tmp = m_it;
return --tmp;
}
};
template<class IT> const_reverse_iterator<IT> begin(const const_reverse_iterator<IT> &rit) { return rit; }
template<class IT> iterator_end end (const const_reverse_iterator<IT> &rit) { return iterator_end(); }
// =========================================================
// =========================================================
// Chapter 1: utf8 utilities
// =========================================================
// =========================================================
inline int utf8CodepointIsValid(const char *p) {
// p must be zero terminated
// In case of invalid UTF8, return 0
// otherwise, return number of characters for this UTF codepoint
static const uint8_t LEN[] = {2,2,2,2,3,3,4,0};
int len = ((unsigned char)*p >= 0xC0) * LEN[(*p >> 3) & 7] + ((unsigned char)*p < 128);
for (int k=1; k < len; k++) if ((p[k] & 0xC0) != 0x80) return 0;
return len;
}
inline int utf8CodepointIsValid(cSv sv, cSv::size_type pos) {
// In case of invalid UTF8, return 0
// otherwise, return number of characters for this utf8 codepoint
static const uint8_t LEN[] = {2,2,2,2,3,3,4,0};
int len = ((unsigned char)sv[pos] >= 0xC0) * LEN[(sv[pos] >> 3) & 7] + ((unsigned char)sv[pos] < 128);
if (len + pos > sv.length()) return 0;
for (cSv::size_type k= pos + 1; k < pos + len; k++) if ((sv[k] & 0xC0) != 0x80) return 0;
return len;
}
// =================================================
// Chapter 1.1: utf8 iterators
// =================================================
/*
* const_simple_utf8_iterator: simple forward iterator for utf8
* note: this iterator does not really implement standard iterator requirements:
* ++it does nothing: *it also increments
* example:
* for (const_simple_utf8_iterator it(cSv("abüXßs")); it != iterator_end(); ) {
* wint_t value = *it;
* ... (do something with value)
* }
* example 2: (with a very small performance penalty to example 1)
* for (wint_t value: const_simple_utf8_iterator("2sßöw") ) { ... }
*/
template<class C_IT>
class const_simple_utf8_iterator {
public:
// begin & end
constexpr explicit const_simple_utf8_iterator(C_IT it, C_IT it_end): m_it_next(it), m_it_end(it_end) { }
constexpr explicit const_simple_utf8_iterator(cSv s): m_it_next(s.cbegin()), m_it_end(s.cend()) { }
constexpr explicit const_simple_utf8_iterator(iterator_end d, cSv s): m_it_next(s.cend()), m_it_end(s.cend()) { }
// class C can be any container with value type char
// We need to use reference &s to avoid string copies resulting in only temporary valid pointers
template<class C>
constexpr explicit const_simple_utf8_iterator(C &s): m_it_next(s.cbegin()), m_it_end(s.cend()) { }
template<class C>
constexpr explicit const_simple_utf8_iterator(iterator_end d, C &s): m_it_next(s.cend()), m_it_end(s.cend()) { }
// end iterator if iterator_end cannot be used
// we assume that the default constructed iterator != any other iterator
constexpr explicit const_simple_utf8_iterator(): m_it_next(C_IT()), m_it_end(C_IT()) { }
C_IT pos() const { return m_it_next; }
bool not_end() const { return m_it_next != m_it_end; } // see operator!=(iterator_end other)
wint_t operator*() { return get_value_and_forward(); }
// compare
bool operator==(const_simple_utf8_iterator other) const {
return ((*this == iterator_end()) & (other == iterator_end())) |
(m_it_next == other.m_it_next);
}
bool operator!=(const_simple_utf8_iterator other) const { return !(*this == other); }
bool operator==(iterator_end other) const { return m_it_next == m_it_end; }
bool operator!=(iterator_end other) const { return m_it_next != m_it_end; }
const_simple_utf8_iterator& operator++() { return *this;} // does nothing, operator* increments
protected:
C_IT m_it_next; // the * operator takes the value from this pos, and increases this pos
const C_IT m_it_end;
inline static const uint8_t LEN[] = {2,2,2,2,3,3,4,0};
wint_t get_value_and_forward() {
// In case of invalid UTF8, return '?'
char current_char = *m_it_next;
++m_it_next;
if ((unsigned char)current_char < 128) return current_char; // optimize for ascii chars
static const uint8_t FF_MSK[] = {0xFF >>0, 0xFF >>0, 0xFF >>3, 0xFF >>4, 0xFF >>5};
int len = ((current_char & 0xC0) == 0xC0) * LEN[(current_char >> 3) & 7];
if (len == 0) return '?'; // utf8 start byte must start with 11xx xxxx, 1111 1xxx is not defined
wint_t val = current_char & FF_MSK[len];
for (int k = 1; k < len; ++k, ++m_it_next) {
if (m_it_next == m_it_end) return '?';
current_char = *m_it_next;
if ((current_char & 0xC0) != 0x80) return '?';
val = (val << 6) | (current_char & 0x3F);
}
return val;
}
};
template<class C> const_simple_utf8_iterator(C c1) -> const_simple_utf8_iterator<typename C::const_iterator>;
template<class C> const_simple_utf8_iterator(iterator_end d, C c1) -> const_simple_utf8_iterator<typename C::const_iterator>;
template<class C_IT>
const_simple_utf8_iterator<C_IT> begin(const const_simple_utf8_iterator<C_IT> &it) { return it; }
template<class C_IT>
iterator_end end(const const_simple_utf8_iterator<C_IT> &it) { return iterator_end(); } // to support ranged for loops
// for (wint_t value: const_simple_utf8_iterator("2sßöw") ) { ... }
/*
auto&& range__ = const_simple_utf-8_iterator("abc");
auto begin__ = range__.begin();
auto end__ = range__.end();
for ( ; begin__ != end__ ; ++begin) {
item-declaration = *begin__;
....
}
*/
template<class C_IT>
class const_utf8_iterator: public const_simple_utf8_iterator<C_IT> {
// this is an std::bidirectional_iterator (since c++20), see https://en.cppreference.com/w/cpp/iterator/bidirectional_iterator
// it does not satisfy the LegacyBidirectionalIterator requirements, as dereference returns a value and not an lvalue
// still satisfies the LegacyInputIterator -> using iterator_category = std::input_iterator_tag;
const C_IT m_it_begin;
C_IT m_it;
wint_t m_value;
iterator_pos m_pos = iterator_pos::none;
public:
using iterator_category = std::input_iterator_tag;
using value_type = wint_t;
using difference_type = std::ptrdiff_t;
using pointer = wint_t*;
using reference = wint_t;
// explicit copy constructor, to avoid that a template is used for that
constexpr const_utf8_iterator(const const_utf8_iterator &it):
const_simple_utf8_iterator<C_IT>(it.m_it_next, it.m_it_end),
m_it_begin(it.m_it_begin), m_it(it.m_it), m_pos(it.m_pos) {}
constexpr const_utf8_iterator( const_utf8_iterator &it):
const_utf8_iterator(const_cast<const const_utf8_iterator &>(it)) {}
// ==== constructors for the begin iterator =======================================
// begin & end
constexpr explicit const_utf8_iterator(C_IT it, C_IT it_end): const_simple_utf8_iterator<C_IT>(it, it_end), m_it_begin(it), m_it(it) {
if (it == it_end) m_pos = (iterator_pos)((int)iterator_pos::begin | (int)iterator_pos::end);
else m_pos = iterator_pos::begin;
}
constexpr explicit const_utf8_iterator(iterator_end d, C_IT it, C_IT it_end): const_simple_utf8_iterator<C_IT>(it_end, it_end), m_it_begin(it), m_it(it_end) {
if (it == it_end) m_pos = (iterator_pos)((int)iterator_pos::begin | (int)iterator_pos::end);
else m_pos = iterator_pos::end;
}
constexpr explicit const_utf8_iterator(cSv s): const_utf8_iterator(s.begin(), s.end()) {}
constexpr explicit const_utf8_iterator(iterator_end d, cSv s): const_utf8_iterator(d, s.begin(), s.end()) {}
// We need to use reference &s to avoid string copies resulting in only temporary valid pointers
template<class C>
constexpr explicit const_utf8_iterator(C &s): const_utf8_iterator(s.begin(), s.end()) {}
template<class C>
constexpr explicit const_utf8_iterator(iterator_end d, C &s): const_utf8_iterator(d, s.begin(), s.end()) {}
// ==== constructor for the end iterator ======================================
constexpr explicit const_utf8_iterator(): const_utf8_iterator(C_IT(), C_IT() ) {
m_pos = iterator_pos::end;
}
// ==== constructor for the begin iterator ====================================
constexpr explicit const_utf8_iterator(iterator_begin d): const_utf8_iterator() {
m_pos = iterator_pos::begin;
}
// ==== constructor for the empty list (begin and end iterator) ===============
constexpr explicit const_utf8_iterator(iterator_empty d): const_utf8_iterator() {
m_pos = (iterator_pos)((int)iterator_pos::begin | (int)iterator_pos::end);
}
// position (counting chars, not utf codepoints!)
size_t pos() const { return std::distance(m_it_begin, m_it); }
// change position of iterator
void move_to_begin() {
m_it = const_simple_utf8_iterator<C_IT>::m_it_next = m_it_begin;
m_pos = iterator_pos::begin;
}
void move_to_end() {
m_it = const_simple_utf8_iterator<C_IT>::m_it_next = const_simple_utf8_iterator<C_IT>::m_it_end;
m_pos = iterator_pos::end;
}
const_utf8_iterator& operator++() {
if (m_it == const_simple_utf8_iterator<C_IT>::m_it_next) const_simple_utf8_iterator<C_IT>::get_value_and_forward();
m_it = const_simple_utf8_iterator<C_IT>::m_it_next;
if (m_it == const_simple_utf8_iterator<C_IT>::m_it_end) m_pos = iterator_pos::end;
else m_pos = iterator_pos::none;
return *this;
}
const_utf8_iterator operator++(int) { auto tmp = *this; ++*this; return tmp; }
const_utf8_iterator& operator--() {
move_one_back(); // moves m_it
const_simple_utf8_iterator<C_IT>::m_it_next = m_it;
if (m_it == m_it_begin) m_pos = iterator_pos::begin;
else m_pos = iterator_pos::none;
return *this;
}
const_utf8_iterator operator--(int) { auto tmp = *this; --*this; return tmp; }
// compare
bool operator==(const_utf8_iterator other) const {
return ((*this == iterator_begin()) & (other == iterator_begin())) |
((*this == iterator_end()) & (other == iterator_end())) |
(m_it == other.m_it);
}
bool operator!=(const_utf8_iterator other) const { return !(*this == other); }
bool operator==(iterator_begin other) const { return (int)m_pos & (int)iterator_pos::begin; }
bool operator!=(iterator_begin other) const { return !(*this == other); }
bool operator==(iterator_end other) const { return (int)m_pos & (int)iterator_pos::end; }
bool operator!=(iterator_end other) const { return !(*this == other); }
wint_t operator*() {
if (m_it == const_simple_utf8_iterator<C_IT>::m_it_next) m_value = const_simple_utf8_iterator<C_IT>::get_value_and_forward();
return m_value;
}
private:
void move_one_back() {
// see also https://stackoverflow.com/questions/22257486/iterate-backwards-through-a-utf8-multibyte-string
while (m_it != m_it_begin) {
--m_it;
if ((*m_it & 0xC0) != 0x80) return;
// (s[i] & 0xC0) == 0x80 is true if bit 6 is clear and bit 7 is set
}
}
};
template<class C> const_utf8_iterator(C c1) -> const_utf8_iterator<typename C::const_iterator>;
template<class C> const_utf8_iterator(iterator_end d, C c1) -> const_utf8_iterator<typename C::const_iterator>;
template<class C_IT>
const_utf8_iterator<C_IT> begin(const const_utf8_iterator<C_IT> &it) { return it; }
// class const_reverse_utf8_iterator ========================
template<class C_IT>
class const_reverse_utf8_iterator: public const_reverse_iterator<const_utf8_iterator<C_IT>> {
public:
// Generic constructor to create a new reverse iterator, forwarding the arguments to the underlying classes
explicit const_reverse_utf8_iterator(): const_reverse_iterator<const_utf8_iterator<C_IT>>() {} // end iterator
template<typename... Args> explicit const_reverse_utf8_iterator(Args&&... args):
const_reverse_iterator<const_utf8_iterator<C_IT>>(iterator_end(), std::forward<Args>(args)...) {}
// But: It must not be used with const_reverse_utf8_iterator itself.
// To prevent this, we use explicit.
// Still not good enough for const_reverse_utf8_iterator<const char*> et1(at1);
// Also, const_reverse_utf8_iterator(const_reverse_utf8_iterator& rit) = default; is not sufficient for that
// So we need explicit constructors:
constexpr const_reverse_utf8_iterator(const const_reverse_utf8_iterator& rit):
const_reverse_iterator<const_utf8_iterator<C_IT>>(static_cast<const const_reverse_iterator<const_utf8_iterator<C_IT>>&>(rit)){}
constexpr const_reverse_utf8_iterator(const_reverse_utf8_iterator& rit): const_reverse_utf8_iterator(const_cast<const const_reverse_utf8_iterator&>(rit)) {}
};
template<class C> const_reverse_utf8_iterator(C c1) -> const_reverse_utf8_iterator<typename C::const_iterator>;
template<class T, class U> // T,U have iterators with char value type
inline int compare_utf8_lower_case(T ls, U rs) {
// compare utf8 strings case-insensitive
const_simple_utf8_iterator i_ls(ls);
const_simple_utf8_iterator i_rs(rs);
while (i_ls.not_end() && i_rs.not_end() ) {
wint_t ls_lc = *i_ls;
wint_t rs_lc = *i_rs;
if (ls_lc == rs_lc) continue;
ls_lc = std::towlower(ls_lc);
rs_lc = std::towlower(rs_lc);
if (ls_lc == rs_lc) continue;
if (ls_lc > rs_lc) return 1;
return -1;
}
if (i_ls.not_end() ) return 1;
if (i_rs.not_end() ) return -1;
return 0;
}
template<class I>
inline wint_t next_non_punct(const_simple_utf8_iterator<I> &it) {
while (it.not_end() ) {
wint_t value = *it;
if (!iswpunct(value) ) return value;
}
return 0;
}
template<class I>
inline wint_t next_non_punct(wint_t val, const_simple_utf8_iterator<I> &it) {
if (!iswpunct(val) ) return val;
while (it.not_end() ) {
wint_t value = *it;
if (!iswpunct(value) ) return value;
}
return 0;
}
template<class T, class U> // T,U have iterators with char value type
inline int compare_utf8_lower_case_ignore_punct(T ls, U rs, int *num_equal_chars = nullptr) {
// compare utf8 strings case-insensitive and ignore punctuation characters
// num_equal_chars has no measurable performance impact
// num_equal_chars will be one to high if the compare result is 0 and both end with a punctuation character
const_simple_utf8_iterator i_ls(ls);
const_simple_utf8_iterator i_rs(rs);
int i_num_equal_chars = 0;
while (i_ls.not_end() && i_rs.not_end()) {
++i_num_equal_chars;
wint_t ls_lc = *i_ls;
wint_t rs_lc = *i_rs;
if (ls_lc == rs_lc) continue;
ls_lc = next_non_punct(ls_lc, i_ls);
rs_lc = next_non_punct(rs_lc, i_rs);
if (ls_lc == rs_lc) continue;
ls_lc = std::towlower(ls_lc);
rs_lc = std::towlower(rs_lc);
if (ls_lc == rs_lc) continue;
if (num_equal_chars) *num_equal_chars += i_num_equal_chars-1;
if (ls_lc > rs_lc) return 1;
return -1;
}
if (num_equal_chars) *num_equal_chars += i_num_equal_chars;
wint_t ls_value = next_non_punct(i_ls);
wint_t rs_value = next_non_punct(i_rs);
if (ls_value) return 1;
if (rs_value) return -1;
return 0;
}
inline void stringAppendUtfCodepoint(std::string &target, unsigned int codepoint) {
if (codepoint <= 0x7F){
target.push_back( (char) (codepoint) );
return;
}
if (codepoint <= 0x07FF) {
target.push_back( (char) (0xC0 | (codepoint >> 6 ) ) );
target.push_back( (char) (0x80 | (codepoint & 0x3F)) );
return;
}
if (codepoint <= 0xFFFF) {
target.push_back( (char) (0xE0 | ( codepoint >> 12)) );
target.push_back( (char) (0x80 | ((codepoint >> 6) & 0x3F)) );
target.push_back( (char) (0x80 | ( codepoint & 0x3F)) );
return;
}
target.push_back( (char) (0xF0 | ((codepoint >> 18) & 0x07)) );
target.push_back( (char) (0x80 | ((codepoint >> 12) & 0x3F)) );
target.push_back( (char) (0x80 | ((codepoint >> 6) & 0x3F)) );
target.push_back( (char) (0x80 | ( codepoint & 0x3F)) );
return;
}
inline void utf8_sanitize_string(std::string &s) {
// check s for any invalid utf8. If found, replace with ?
bool error_reported = false;
for (char *p = s.data(); *p; ++p) {
if ((unsigned char)*p < 128) continue; // optimization for strings where many chars are < 128
int len = utf8CodepointIsValid(p);
if (len == 0) {
if (!error_reported) {
dsyslog(PLUGIN_NAME_I18N ": WARNING, invalid utf8 in string %s", s.c_str());
error_reported = true;
}
*p = '?';
} else {
p += len - 1;
}
}
}
inline bool is_equal_utf8_sanitized_string(cSv s, const char *other) {
// return true if s == other
// invalid utf8 in other is replaced with '?' before the comparison
// other must be zero terminated
if (!other) return s.empty();
auto len = strlen(other);
if (s.length() != len) return false;
if (memcmp(s.data(), other, len) == 0) return true;
for (cSv::size_type pos = 0; pos < len; ++pos) {
if (s[pos] == other[pos]) continue;
if (s[pos] != '?') return false;
if (utf8CodepointIsValid(other+pos) != 0) return false;
}
return true;
}
inline wint_t Utf8ToUtf32(const char *p, int len) {
// assumes, that uft8 validity checks have already been done. len must be provided. call utf8CodepointIsValid first
static const uint8_t FF_MSK[] = {0xFF >>0, 0xFF >>0, 0xFF >>3, 0xFF >>4, 0xFF >>5, 0xFF >>0, 0xFF >>0, 0xFF >>0};
wint_t val = *p & FF_MSK[len];
for (int i = 1; i < len; i++) val = (val << 6) | (p[i] & 0x3F);
return val;
}
inline wint_t getNextUtfCodepoint(const char *&p) {
// p must be zero terminated
// get next codepoint, and increment p
// 0 is returned at end of string, and p will point to the end of the string (0)
if(!p || !*p) return 0;
int l = utf8CodepointIsValid(p);
if( l == 0 ) { p++; return '?'; }
wint_t result = Utf8ToUtf32(p, l);
p += l;
return result;
}
// =========================================================
// =========================================================
// Chapter 3: Parse char* / string_view / string
// =========================================================
// =========================================================
// =========================================================
// whitespace ==============================================
// =========================================================
inline cSv trim(cSv s) {
// remove all ASCII <= 32 from left and right,
// this is whitespace and special characters
cSv::size_type left = 0;
for (; left < s.length() && (unsigned char)s[left] < 33; ++left);
cSv::size_type right = s.length();
for (; right > left && (unsigned char)s[right-1] < 33; --right);
return s.substr(left, right-left);
}
inline cSv remove_trailing_whitespace(cSv sv) {
// return a string_view with trailing whitespace from sv removed
for (cSv::size_type i = sv.length(); i > 0; ) {
--i;
if ((unsigned char)sv[i] > 32) return sv.substr(0, i+1); // non whitespace found at i -> length i+1 !!!
}
return cSv();
}
inline cSv remove_leading_whitespace(cSv s) {
// return a string_view with leading whitespace from sv removed
// for performance:
// avoid changing sv: cSv &sv is much slower than cSv sv
cSv::size_type left = 0;
for (; left < s.length() && (unsigned char)s[left] < 33; ++left);
return s.substr(left);
}
inline void trim_string(std::string &s) {
// remove all ASCII <= 32 from left and right,
// this is whitespace and special characters
std::string::size_type left = 0;
for (; left < s.length() && (unsigned char)s[left] < 33; ++left);
s.erase(0, left);
cSv::size_type right = s.length();
for (; right > 0 && (unsigned char)s[right-1] < 33; --right);
s.erase(right);
}
// =========================================================
// parse string_view for int
// =========================================================
template<class T> inline T parse_int_check_error(cSv sv, cSv::size_type start, cSv::size_type end, T val, T returnOnError, const char *context) {
// check for severe error (no digit available)
if (start == end) {
// severe error, no data (no digit)
if (context)
esyslog(PLUGIN_NAME_I18N ": ERROR, cannot convert \"%.*s\" to int/bool, context %s", (int)sv.length(), sv.data(), context);
return returnOnError;
}
if (context) {
// check for other errors -> any non-whitespace after number?
if (remove_trailing_whitespace(sv).length() != end)
isyslog(PLUGIN_NAME_I18N ": WARNING, trailing characters after conversion from \"%.*s\" to int/bool, context %s", (int)sv.length(), sv.data(), context);
}
return val;
}
template<class T> inline T parse_int_overflow(cSv sv, T returnOnError, const char *context) {
if (context)
esyslog(PLUGIN_NAME_I18N ": ERROR, integer overflow converting \"%.*s\" to int/bool, context %s", (int)sv.length(), sv.data(), context);
return returnOnError;
}
template<class T> inline T parse_unsigned_internal(cSv sv, T returnOnError = T(), const char *context = nullptr) {
// T can also be a signed data type
// But: result will always be >=0, except in case of error and returnOnError < 0
static const T limit_10 = std::numeric_limits<T>::max() / 10;
T val = 0;
cSv::size_type start = 0;
for (; start < sv.length() && std::isdigit(sv[start]); ++start) {
if (val > limit_10) return parse_int_overflow<T>(sv, returnOnError, context);
val *= 10;
T addval = sv[start]-'0';
if (val > std::numeric_limits<T>::max() - addval) return parse_int_overflow<T>(sv, returnOnError, context);
val += addval;
}
return parse_int_check_error<T>(sv, 0, start, val, returnOnError, context);
}
template<class T> inline T parse_neg_internal(cSv sv, T returnOnError = T(), const char *context = nullptr) {
// sv[0] == '-' must be correct, this is not checked!!
// T must be signed, a negative value will be returned
static const T limit_10 = std::numeric_limits<T>::min() / 10;
T val = 0;
cSv::size_type start = 1;
for (; start < sv.length() && std::isdigit(sv[start]); ++start) {
if (val < limit_10) return parse_int_overflow<T>(sv, returnOnError, context);
val *= 10;
T addval = sv[start]-'0';
if (val < std::numeric_limits<T>::min() + addval) return parse_int_overflow<T>(sv, returnOnError, context);
val -= addval;
}
return parse_int_check_error<T>(sv, 1, start, val, returnOnError, context);
}
template<class T> inline T parse_int(cSv sv) {
if (sv.empty() ) return 0;
if (!std::isdigit(sv[0]) && sv[0] != '-') {
sv = remove_leading_whitespace(sv);
if (sv.empty() ) return 0;
}
if (sv[0] != '-') return parse_unsigned_internal<T>(sv);
return -parse_unsigned_internal<T>(sv.substr(1));
}
template<class T> inline T parse_unsigned(cSv sv) {
if (sv.empty() ) return 0;
if (!std::isdigit(sv[0])) sv = remove_leading_whitespace(sv);
return parse_unsigned_internal<T>(sv);
}
namespace stringhelpers_internal {
inline static const signed char hex_values[256] = {
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, -1, -1, -1, -1, -1, -1,
-1, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
};
}
template<class T> inline T parse_hex(cSv sv, size_t *num_digits = 0) {
T value = 0;
const unsigned char *data = reinterpret_cast<const unsigned char *>(sv.data());
const unsigned char *data_e = data + sv.length();
for (; data < data_e; ++data) {
signed char val = stringhelpers_internal::hex_values[*data];
if (val == -1) break;
value = value*16 + val;
}
if (num_digits) *num_digits = data - reinterpret_cast<const unsigned char *>(sv.data());
return value;
}
// =========================================================
// split string at delimiter in two parts
// =========================================================
inline bool splitString(cSv str, cSv delim, size_t minLength, cSv &first, cSv &second) {
// true if delim is part of str, and length of first & second >= minLength
for (std::size_t found = str.find(delim); found != std::string::npos; found = str.find(delim, found + 1)) {
cSv first_guess = remove_trailing_whitespace(str.substr(0, found));
if (first_guess.length() >= minLength) {
// we found the first part. Is the second part long enough?
cSv second_guess = remove_leading_whitespace(str.substr(found + delim.length()));
if (second_guess.length() < minLength) return false; // nothing found
first = first_guess;
second = second_guess;
return true;
}
}
return false; // nothing found
}
inline cSv SecondPart(cSv str, cSv delim, size_t minLength) {
// return second part of split string if delim is part of str, and length of first & second >= minLength
// otherwise, return ""
cSv first, second;
if (splitString(str, delim, minLength, first, second)) return second;
else return cSv();
}
inline cSv SecondPart(cSv str, cSv delim) {
// if delim is not in str, return ""
// Otherwise, return part of str after first occurrence of delim
// remove leading blanks from result
size_t found = str.find(delim);
if (found == std::string::npos) return cSv();
std::size_t ssnd;
for(ssnd = found + delim.length(); ssnd < str.length() && str[ssnd] == ' '; ssnd++);
return str.substr(ssnd);
}
// =========================================================
// =========================================================
// Chapter 4: convert data to cSv:
// cToSv classes, with buffer containing text representation of data
// =========================================================
// =========================================================
// =========================================================
// integer and hex
// =========================================================
namespace stringhelpers_internal {
// ====================================================
// numChars(T i), for signed & unsigned integers
// return number of chars needed to print i
// for neg. integers: including the - sign
// ====================================================
static const int numChars_guess[] = {
0, 0, 0, 0, 1, 1, 1, 2, 2, 2,
3, 3, 3, 3, 4, 4, 4, 5, 5, 5,
6, 6, 6, 6, 7, 7, 7, 8, 8, 8,
9, 9, 9,
9, 10, 10, 10, 11, 11, 11,
12, 12, 12, 12, 13, 13, 13,
14, 14, 14, 15, 15, 15, 15,
16, 16, 16, 17, 17, 17,
18, 18, 18, 18, 19
};
// i > 0 is pre-requisite for all usedBinDigits methods. !!! not checked in usedBinDigits !!!!!
inline int usedBinDigits(unsigned char i) {
return 8*sizeof(unsigned int)-__builtin_clz((unsigned int)i);
}
inline int usedBinDigits(unsigned short int i) {
return 8*sizeof(unsigned int)-__builtin_clz((unsigned int)i);
}
inline int usedBinDigits(unsigned int i) {
// if we write:
// return 4*sizeof(unsigned long long int)-__builtin_clzll(0x80000000 | ((unsigned long long int)i << 32));
// this also works for i == 0. But, no performance improvement. So keep it simple
return 8*sizeof(unsigned int)-__builtin_clz(i);
}
inline int usedBinDigits(unsigned long int i) {
return 8*sizeof(unsigned long int)-__builtin_clzl(i);
}
inline int usedBinDigits(unsigned long long int i) {
return 8*sizeof(unsigned long long int)-__builtin_clzll(i);
}
template<typename T, std::enable_if_t<std::is_unsigned_v<T>, bool> = true>
inline int numChars_internal(T i) {
// calculate the number of decimal digits from the binary digits
// i > 0 !!! not checked here !!!!!
int digits = numChars_guess[usedBinDigits(i)];
return digits + (i > to_chars10_internal::max_int[digits]);
}
template<typename T, std::enable_if_t<std::is_unsigned_v<T>, bool> = true>
inline int numChars(T i) {
return i?numChars_internal(i):1;
}
template<typename T, std::enable_if_t<std::is_signed_v<T>, bool> = true>
inline int numChars(T i) {
typedef std::make_unsigned_t<T> TU;
if (i > 0) return numChars_internal(static_cast<TU>(i));
if (i < 0) return numChars_internal(~(static_cast<TU>(i)) + static_cast<TU>(1)) + 1;
return 1;
}
// ==== itoaN ===================================================================
// itoaN: Template for fixed number of characters, left fill with 0
// note: i must fit in N digits, this is not checked!
template<size_t N, typename T, std::enable_if_t<std::is_unsigned_v<T> && N == 0, bool> = true>
inline char* itoaN(char *b, T i) { return b; }
template<size_t N, typename T, std::enable_if_t<std::is_unsigned_v<T> && N == 1, bool> = true>
inline char* itoaN(char *b, T i) {
*b = i + '0';
return b+N;
}
template<size_t N, typename T, std::enable_if_t<std::is_unsigned_v<T> && N == 2, bool> = true>
inline char* itoaN(char *b, T i) {
memcpy(b, to_chars10_internal::digits_100 + (i << 1), 2);
return b+N;
}
// max uint16_t 65535
template<size_t N, typename T, std::enable_if_t<std::is_unsigned_v<T> && (N == 3 || N == 4), bool> = true>
inline char* itoaN(char *b, T i) {
uint16_t q = (static_cast<uint32_t>(i) * 5243U) >> 19; // q = i/100; i < 43699
b = itoaN<N-2>(b, q);
memcpy(b, to_chars10_internal::digits_100 + ((static_cast<uint16_t>(i) - q*100) << 1), 2);
return b+2;
}
// max uint32_t 4294967295, sizeof(uint32_t) == 4
template<size_t N, typename T, std::enable_if_t<std::is_unsigned_v<T> && N >= 5 && (N <= 9 || sizeof(T) <= 4), bool> = true>
inline char* itoaN(char *b, T i) {
for (int j = N-2; j > 0; j-=2) {
uint32_t q = static_cast<uint32_t>(i)/100;
memcpy(b+j, to_chars10_internal::digits_100 + ((static_cast<uint32_t>(i) - q*100) << 1), 2);
i = q;
}
itoaN<2-N%2>(b, i);
return b+N;
}
// for uint64_t, sizeof(uint64_t) == 8
template<size_t N, typename T, std::enable_if_t<std::is_unsigned_v<T> && N >= 10 && N != 18 && sizeof(T) >= 5, bool> = true>
inline char* itoaN(char *b, T i) {
T q = i/100000000;
b = itoaN<N-8>(b, q);
return itoaN<8>(b, static_cast<uint32_t>(i - q*100000000));
}
template<size_t N, typename T, std::enable_if_t<std::is_unsigned_v<T> && N == 18 && sizeof(T) >= 5, bool> = true>
inline char* itoaN(char *b, T i) {
T q = i/1000000000;
b = itoaN<N-9>(b, static_cast<uint32_t>(q));
return itoaN<9>(b, static_cast<uint32_t>(i - q*1000000000));
}
// ==== powN ===============================
template<uint8_t N>
inline typename std::enable_if_t<N == 0, uint64_t> powN() { return 1; }
template<uint8_t N>
inline typename std::enable_if_t<N <= 19 && N >= 1, uint64_t> powN() {
// return 10^N
return powN<N-1>() * 10;
}
// ==== itoa_min_width =====================
template<size_t N, typename T, std::enable_if_t<std::is_integral_v<T> && N == 0, bool> = true>
inline char* itoa_min_width(char *b, T i) {
return to_chars10_internal::itoa(b, i);
}
template<size_t N, typename T, std::enable_if_t<std::is_unsigned_v<T> && N >= 1 && N <= 19, bool> = true>
inline char* itoa_min_width(char *b, T i) {
if (i < powN<N>() ) return itoaN<N, T>(b, i);
T q = i/powN<N>();
b = to_chars10_internal::itoa(b, q);
return itoaN<N, T>(b, i - q*powN<N>() );
}
template<size_t N, typename T, std::enable_if_t<std::is_unsigned_v<T> && N >= 20, bool> = true>
inline char* itoa_min_width(char *b, T i) {
// i < 10^20 is always true
memset(b, '0', N-20);
b += N-20;
return itoaN<20, T>(b, i);
}
template<size_t N, typename T, std::enable_if_t<std::is_signed_v<T> && N >= 1, bool> = true>
inline char* itoa_min_width(char *b, T i) {
typedef std::make_unsigned_t<T> TU;
if (i >= 0) return itoa_min_width<N, TU>(b, (TU)i);
*b = '-';
return itoa_min_width<N-1, TU>(b + 1, ~(TU(i)) + (TU)1);
}
// ==== addCharsHex ========================
template<typename T, std::enable_if_t<std::is_unsigned_v<T>, bool> = true>
inline T addCharsHex(char *buffer, size_t num_chars, T value) {