simstr 2.1.4
Yet another strings library
 
Загрузка...
Поиск...
Не найдено
sstring.h
1/*
2* ver. 2.1.4
3 * (c) Проект "SimStr", Александр Орефков orefkov@gmail.com
4 * Классы для работы со строками
5* (c) Project "SimStr", Aleksandr Orefkov orefkov@gmail.com
6* Classes for working with strings
7 */
8
19#pragma once
20
21#ifndef __has_declspec_attribute
22#define __has_declspec_attribute(x) 0
23#endif
24const bool isWindowsOs = // NOLINT
25#ifdef _WIN32
26 true
27#else
28 false
29#endif
30 ;
31
32#ifdef SIMSTR_IN_SHARED
33 #if defined(_MSC_VER) || (defined(__clang__) && __has_declspec_attribute(dllexport))
34 #ifdef SIMSTR_EXPORT
35 #define SIMSTR_API __declspec(dllexport)
36 #else
37 #define SIMSTR_API __declspec(dllimport)
38 #endif
39 #elif (defined(__GNUC__) || defined(__GNUG__)) && defined(SIMSTR_EXPORT)
40 #define SIMSTR_API __attribute__((visibility("default")))
41 #else
42 #define SIMSTR_API
43 #endif
44#else
45 #define SIMSTR_API
46#endif
47
48#define IN_FULL_SIMSTR
49#include "strexpr.h"
50
51#include <format>
52#include <unordered_map>
53#include <atomic>
54#include <memory>
55#include <string.h>
56#include <iostream>
57#include <cmath>
58
59#ifdef _WIN32
60#include <stdio.h>
61#endif
62
63#ifdef _MSC_VER
64// warning C4201 : nonstandard extension used : nameless struct / union
65#pragma warning(disable : 4201)
66#endif
67
68namespace simstr {
69
70template<typename T>
71struct unicode_traits {}; // NOLINT
72
73template<>
74struct unicode_traits<u8s> {
75 // Эти операции с utf-8 могут изменить длину строки
76 // Поэтому их специализации отличаются
77 // В функцию помимо текста и адреса буфера для записи передается размер буфера
78 // Возвращает длину получающейся строки.
79 // Если получающеюся строка не влезает в отведенный буфер, указатели устанавливаются на последние
80 // обработанные символы, для повторного возобновления работы,
81 // а для оставшихся символов считается нужный размер буфера.
82 // These utf-8 operations can change the length of the string
83 // Therefore their specializations are different
84 // In addition to the text and address of the buffer for writing, the buffer size is passed to the function
85 // Returns the length of the resulting string.
86 // If the resulting string does not fit into the allocated buffer, pointers are set to the last
87 // processed characters to resume work again,
88 // and for the remaining characters the required buffer size is calculated.
89 static SIMSTR_API size_t upper(const u8s*& src, size_t len, u8s*& dest, size_t lenBuf);
90 static SIMSTR_API size_t lower(const u8s*& src, size_t len, u8s*& dest, size_t lenBuf);
91 static SIMSTR_API size_t upper_len(const u8s* src, size_t len);
92 static SIMSTR_API size_t lower_len(const u8s* src, size_t len);
93
94 static SIMSTR_API int compareiu(const u8s* text1, size_t len1, const u8s* text2, size_t len2);
95
96 static SIMSTR_API size_t hashia(const u8s* src, size_t l);
97 static SIMSTR_API size_t hashiu(const u8s* src, size_t l);
98};
99
100template<>
101struct unicode_traits<u16s> {
102 static SIMSTR_API void upper(const u16s* src, size_t len, u16s* dest);
103 static SIMSTR_API void lower(const u16s* src, size_t len, u16s* dest);
104
105 static SIMSTR_API int compareiu(const u16s* text1, size_t len1, const u16s* text2, size_t len2);
106 static SIMSTR_API size_t hashia(const u16s* src, size_t l);
107 static SIMSTR_API size_t hashiu(const u16s* src, size_t l);
108};
109
110template<>
111struct unicode_traits<u32s> {
112 static SIMSTR_API void upper(const u32s* src, size_t len, u32s* dest);
113 static SIMSTR_API void lower(const u32s* src, size_t len, u32s* dest);
114
115 static SIMSTR_API int compareiu(const u32s* text1, size_t len1, const u32s* text2, size_t len2);
116 static SIMSTR_API size_t hashia(const u32s* src, size_t s);
117 static SIMSTR_API size_t hashiu(const u32s* src, size_t s);
118};
119
120template<>
121struct unicode_traits<wchar_t> {
122 static void upper(const wchar_t* src, size_t len, wchar_t* dest) {
123 unicode_traits<wchar_type>::upper(to_w(src), len, to_w(dest));
124 }
125 static void lower(const wchar_t* src, size_t len, wchar_t* dest) {
126 unicode_traits<wchar_type>::lower(to_w(src), len, to_w(dest));
127 }
128
129 static int compareiu(const wchar_t* text1, size_t len1, const wchar_t* text2, size_t len2) {
130 return unicode_traits<wchar_type>::compareiu(to_w(text1), len1, to_w(text2), len2);
131 }
132 static size_t hashia(const wchar_t* src, size_t s) {
133 return unicode_traits<wchar_type>::hashia(to_w(src), s);
134 }
135 static size_t hashiu(const wchar_t* src, size_t s) {
136 return unicode_traits<wchar_type>::hashiu(to_w(src), s);
137 }
138};
139
140template<>
141struct unicode_traits<char8_t> {
142 static size_t upper(const ubs*& src, size_t lenStr, ubs*& dest, size_t lenBuf) {
143 return unicode_traits<char>::upper((const u8s*&)src, lenStr, (u8s*&)dest, lenBuf);
144 }
145 static size_t lower(const ubs*& src, size_t len, ubs*& dest, size_t lenBuf) {
146 return unicode_traits<char>::lower((const u8s*&)src, len, (u8s*&)dest, lenBuf);
147 }
148 static size_t upper_len(const ubs* src, size_t len) {
149 return unicode_traits<char>::upper_len((const u8s*)src, len);
150 }
151 static size_t lower_len(const ubs* src, size_t len) {
152 return unicode_traits<char>::lower_len((const u8s*)src, len);
153 }
154
155 static int compareiu(const char8_t* text1, size_t len1, const char8_t* text2, size_t len2) {
156 return unicode_traits<char>::compareiu((const char*)text1, len1, (const char*)text2, len2);
157 }
158 static size_t hashia(const char8_t* src, size_t s) {
159 return unicode_traits<char>::hashia((const char*)src, s);
160 }
161 static size_t hashiu(const char8_t* src, size_t s) {
162 return unicode_traits<char>::hashiu((const char*)src, s);
163 }
164};
165
166#if defined(_MSC_VER) && _MSC_VER <= 1933
167template<typename K, typename... Args>
168using FmtString = std::_Basic_format_string<K, std::type_identity_t<Args>...>;
169#elif __clang_major__ >= 15 || _MSC_VER > 1933 || __GNUC__ >= 13
170template<typename K, typename... Args>
171using FmtString = std::basic_format_string<K, std::type_identity_t<Args>...>;
172#else
173template<typename K, typename... Args>
174using FmtString = std::basic_string_view<K>;
175#endif
176
177template<typename K>
178SIMSTR_API std::optional<double> impl_to_double(const K* start, const K* end);
179
192template<typename K, typename StrRef, typename Impl, bool Mutable>
193class str_algs : public str_src_algs<K, StrRef, Impl, Mutable> {
194 constexpr const Impl& d() const noexcept {
195 return *static_cast<const Impl*>(this);
196 }
197 constexpr size_t _len() const noexcept {
198 return d().length();
199 }
200 constexpr const K* _str() const noexcept {
201 return d().symbols();
202 }
203 constexpr bool _is_empty() const noexcept {
204 return d().is_empty();
205 }
206
207public:
208 using symb_type = K;
209 using str_piece = StrRef;
210 using traits = ch_traits<K>;
211 using uni = unicode_traits<K>;
212 using uns_type = std::make_unsigned_t<K>;
213 using my_type = Impl;
214 using base = str_src_algs<K, StrRef, Impl, Mutable>;
215 str_algs() = default;
216
217 int compare_iu(const K* text, size_t len) const noexcept { // NOLINT
218 if (!len)
219 return _is_empty() ? 0 : 1;
220 return uni::compareiu(_str(), _len(), text, len);
221 }
230 int compare_iu(str_piece text) const noexcept { // NOLINT
231 return compare_iu(text.symbols(), text.length());
232 }
233
241 bool equal_iu(str_piece text) const noexcept { // NOLINT
242 return text.length() == _len() && compare_iu(text.symbols(), text.length()) == 0;
243 }
244
252 bool less_iu(str_piece text) const noexcept { // NOLINT
253 return compare_iu(text.symbols(), text.length()) < 0;
254 }
255 // Начинается ли эта строка с указанной подстроки без учета unicode регистра
256 // Does this string begin with the specified substring, insensitive to unicode case
257 bool starts_with_iu(const K* prefix, size_t len) const noexcept {
258 return _len() >= len && 0 == uni::compareiu(_str(), len, prefix, len);
259 }
266 bool starts_with_iu(str_piece prefix) const noexcept {
267 return starts_with_iu(prefix.symbols(), prefix.length());
268 }
269 // Заканчивается ли строка указанной подстрокой без учета регистра UNICODE
270 // Whether the string ends with the specified substring, case insensitive UNICODE
271 constexpr bool ends_with_iu(const K* suffix, size_t len) const noexcept {
272 size_t myLen = _len();
273 return myLen >= len && 0 == uni::compareiu(_str() + myLen - len, len, suffix, len);
274 }
281 constexpr bool ends_with_iu(str_piece suffix) const noexcept {
282 return ends_with_iu(suffix.symbols(), suffix.length());
283 }
284
292 template<typename R = my_type>
293 R upperred() const {
294 return R::upperred_from(d());
295 }
296
304 template<typename R = my_type>
305 R lowered() const {
306 return R::lowered_from(d());
307 }
308
314 template<bool SkipWS = true, bool AllowPlus = true>
315 std::optional<double> to_double() const noexcept {
316 size_t len = _len();
317 const K* ptr = _str();
318 if constexpr (SkipWS) {
319 while (len && uns_type(*ptr) <= ' ') {
320 len--;
321 ptr++;
322 }
323 }
324 if constexpr (AllowPlus) {
325 if (len && *ptr == K('+')) {
326 ptr++;
327 len--;
328 }
329 }
330 if (!len) {
331 return {};
332 }
333 #ifdef __linux__
334 if constexpr(sizeof(K) == 1 && requires {std::from_chars(std::declval<const K*>(), std::declval<const K*>(), std::declval<double&>()); }) {
335 double d{};
336 if (std::from_chars((const K*)ptr, (const K*)ptr + len, d).ec == std::errc{}) {
337 return d;
338 }
339 return {};
340 }
341 #endif
342 if constexpr (sizeof(K) == 1) {
343 return impl_to_double((const char*)ptr, (const char*)ptr + len);
344 } else if constexpr (sizeof(K) == 2) {
345 return impl_to_double((const char16_t*)ptr, (const char16_t*)ptr + len);
346 } else {
347 return impl_to_double((const char32_t*)ptr, (const char32_t*)ptr + len);
348 }
349 }
350
356 void as_number(double& t) const {
357 auto res = to_double();
358 t = res ? *res : std::nan("0");
359 }
360
372 template<ToIntNumber T>
373 constexpr void as_number(T& t) const {
375 }
376
388 template<typename R = str_piece>
389 constexpr std::optional<R> strip_prefix_iu(str_piece prefix) const {
390 if (starts_with_iu(prefix)) {
391 return R{d().tail(prefix.length())};
392 }
393 return {};
394 }
395
407 template<typename R = str_piece>
408 constexpr std::optional<R> strip_suffix_iu(str_piece suffix) const {
409 if (ends_with_iu(suffix)) {
410 return R{d().slice(0, from_end{suffix.length()})};
411 }
412 return {};
413 }
414
426 template<typename R = str_piece>
427 constexpr R trimmed_prefix_iu(str_piece prefix, size_t max_count = 0) const {
428 str_piece res = d();
429 while(res.starts_with_iu(prefix)) {
430 res = res.tail(prefix.length());
431 if (--max_count == 0) {
432 break;
433 }
434 }
435 return res;
436 }
437
449 template<typename R = str_piece>
450 constexpr R trimmed_suffix_iu(str_piece suffix) const {
451 str_piece res = d();
452 while(res.ends_with_iu(suffix)) {
453 res = res.slice(0, from_end(suffix.length()));
454 }
455 return res;
456 }
457};
458
459/*
460* Базовая структура с информацией о строке.
461* Это структура для не владеющих строк.
462* Так как здесь только один базовый класс, MSVC компилятор автоматом применяет empty base optimization,
463* в результате размер класса не увеличивается
464* Basic structure with string information.
465* This is the structure for non-owning strings.
466* Since there is only one base class, the MSVC compiler automatically applies empty base optimization,
467* as a result the class size does not increase
468*/
469
480template<typename K>
481struct simple_str : str_algs<K, simple_str<K>, simple_str<K>, false> {
482 using symb_type = K;
483 using my_type = simple_str<K>;
484
485 const symb_type* str;
486 size_t len;
487
488 constexpr simple_str() = default;
489
490 constexpr simple_str(str_src<K> src) : str(src.str), len(src.len){}
491
496 template<typename T, size_t N = const_lit_for<K, T>::Count>
497 constexpr simple_str(T&& v) noexcept : str((const K*)v), len(N - 1) {}
502 constexpr simple_str(const K* p, size_t l) noexcept : str(p), len(l) {}
507 template<typename A>
508 constexpr simple_str(const std::basic_string<K, std::char_traits<K>, A>& s) noexcept : str(s.data()), len(s.length()) {}
513 constexpr simple_str(const std::basic_string_view<K, std::char_traits<K>>& s) noexcept : str(s.data()), len(s.length()) {}
518 constexpr size_t length() const noexcept {
519 return len;
520 }
521
525 constexpr const symb_type* symbols() const noexcept {
526 return str;
527 }
528
532 constexpr bool is_empty() const noexcept {
533 return len == 0;
534 }
535
541 constexpr bool is_same(simple_str<K> other) const noexcept {
542 return str == other.str && len == other.len;
543 }
544
550 constexpr bool is_part_of(simple_str<K> other) const noexcept {
551 return str >= other.str && str + len <= other.str + other.len;
552 }
553
561 constexpr K operator[](size_t idx) const {
562 return str[idx];
563 }
564
572 constexpr my_type& remove_prefix(size_t delta) {
573 str += delta;
574 len -= delta;
575 return *this;
576 }
577
585 constexpr my_type& remove_suffix(size_t delta) {
586 len -= delta;
587 return *this;
588 }
589};
590
591template<typename K>
592struct simple_str_selector {
593 using type = simple_str<K>;
594};
595
616template<typename K>
617struct simple_str_nt : simple_str<K>, null_terminated<K, simple_str_nt<K>> {
618 using symb_type = K;
619 using my_type = simple_str_nt<K>;
620 using base = simple_str<K>;
621
622 constexpr static const K empty_string[1] = {0};
623
624 simple_str_nt() = default;
641 template<typename T> requires is_one_of_type<std::remove_cvref_t<T>, const K*, K*>::value
642 constexpr explicit simple_str_nt(T&& p) noexcept {
643 base::len = p ? static_cast<size_t>(base::traits::length(p)) : 0;
644 base::str = base::len ? p : empty_string;
645 }
646
650 template<typename T, size_t N = const_lit_for<K, T>::Count>
651 constexpr simple_str_nt(T&& v) noexcept : base(std::forward<T>(v)) {}
652
657 constexpr simple_str_nt(const K* p, size_t l) noexcept : base(p, l) {}
658
659 template<StrType<K> T>
660 constexpr simple_str_nt(T&& t) {
661 base::str = t.symbols();
662 base::len = t.length();
663 }
668 template<typename A>
669 constexpr simple_str_nt(const std::basic_string<K, std::char_traits<K>, A>& s) noexcept : base(s) {}
670
671 static const my_type empty_str;
680 constexpr my_type to_nts(size_t from) {
681 if (from > base::len) {
682 from = base::len;
683 }
684 return {base::str + from, base::len - from};
685 }
686};
687
688template<typename K>
689inline const simple_str_nt<K> simple_str_nt<K>::empty_str{simple_str_nt<K>::empty_string, 0};
690
691template<typename K>
692using Splitter = SplitterBase<K, simple_str<K>>;
693
694using ssa = simple_str<u8s>;
695using ssb = simple_str<ubs>;
696using ssw = simple_str<wchar_t>;
697using ssu = simple_str<u16s>;
698using ssuu = simple_str<u32s>;
699using stra = simple_str_nt<u8s>;
700using strb = simple_str_nt<ubs>;
701using strw = simple_str_nt<wchar_t>;
702using stru = simple_str_nt<u16s>;
703using struu = simple_str_nt<u32s>;
704
705template<typename Src, typename Dest>
706struct utf_convert_selector;
707
708template<typename Src>
709struct utf_convert_selector<Src, Src> {
710 static size_t need_len(const Src* src, size_t srcLen) {
711 return srcLen;
712 }
713 static size_t convert(const Src* src, size_t srcLen, Src* dest) {
714 ch_traits<Src>::copy(dest, src, srcLen + 1);
715 return srcLen;
716 }
717};
718
719template<>
720struct utf_convert_selector<u8s, u16s> {
721 static SIMSTR_API size_t need_len(const u8s* src, size_t srcLen);
722 static SIMSTR_API size_t convert(const u8s* src, size_t srcLen, u16s* dest);
723};
724
725template<>
726struct utf_convert_selector<u8s, u32s> {
727 static SIMSTR_API size_t need_len(const u8s* src, size_t srcLen);
728 static SIMSTR_API size_t convert(const u8s* src, size_t srcLen, u32s* dest);
729};
730
731template<>
732struct utf_convert_selector<u16s, u8s> {
733 static SIMSTR_API size_t need_len(const u16s* src, size_t srcLen);
734 static SIMSTR_API size_t convert(const u16s* src, size_t srcLen, u8s* dest);
735};
736
737template<>
738struct utf_convert_selector<u16s, u32s> {
739 static SIMSTR_API size_t need_len(const u16s* src, size_t srcLen);
740 static SIMSTR_API size_t convert(const u16s* src, size_t srcLen, u32s* dest);
741};
742
743template<>
744struct utf_convert_selector<u32s, u8s> {
745 static SIMSTR_API size_t need_len(const u32s* src, size_t srcLen);
746 static SIMSTR_API size_t convert(const u32s* src, size_t srcLen, u8s* dest);
747};
748
749template<>
750struct utf_convert_selector<u32s, u16s> {
751 static SIMSTR_API size_t need_len(const u32s* src, size_t srcLen);
752 static SIMSTR_API size_t convert(const u32s* src, size_t srcLen, u16s* dest);
753};
754
769template<typename K, typename Impl>
770class from_utf_convertible {
771protected:
772 from_utf_convertible() = default;
773 using my_type = Impl;
774 /*
775 Эти методы должен реализовать класс-наследник.
776 вызывается только при создании объекта
777 init(size_t size)
778 */
779 template<typename O>
780 requires(!std::is_same_v<O, K>)
781 void init_from_utf_convertible(simple_str<O> init) {
782 using from_t = to_base_char_t<O>;
783 using to_t = to_base_char_t<K>;
784
785 using worker = utf_convert_selector<from_t, to_t>;
786 Impl* d = static_cast<Impl*>(this);
787 size_t len = init.length();
788 if (!len)
789 d->create_empty();
790 else {
791 size_t need = worker::need_len((const from_t*)init.symbols(), len);
792 K* str = d->init(need);
793 str[need] = 0;
794 worker::convert((const from_t*)init.symbols(), len, (to_t*)str);
795 }
796 }
797};
798
816template<is_one_of_char_v From>
817struct to_utf {
818 simple_str<From> from_;
819 template<StrSource S>
820 to_utf(S&& from) : from_(std::forward<S>(from)){};
821};
822
823template<StrSource S>
825
834template<typename From, typename To> requires (!std::is_same_v<From, To>)
835struct expr_utf : expr_to_std_string<expr_utf<From, To>> {
836 using symb_type = To;
837 using from_t = to_base_char_t<From>;
838 using to_t = to_base_char_t<To>;
839 using worker = utf_convert_selector<from_t, to_t>;
840
841 simple_str<From> source_;
842
843 constexpr expr_utf(simple_str<From> source) : source_(source){}
844
845 constexpr expr_utf(const to_utf<From>& source) : source_(source.from_){}
846
847 size_t length() const noexcept {
848 return worker::need_len((const from_t*)source_.symbols(), source_.length());
849 }
850 To* place(To* ptr) const noexcept {
851 return ptr + worker::convert((const from_t*)source_.symbols(), source_.length(), (to_t*)ptr);
852 }
853};
854
855template<typename K, is_one_of_char_v From>
856struct convert_to_strexpr<K, to_utf<From>> {
857 using type = expr_utf<From, K>;
858};
859
872template<typename To, typename From> requires (!std::is_same_v<From, To>)
874 return {from};
875}
876
877template<is_one_of_char_v K, bool upper>
878struct expr_change_case : expr_to_std_string<expr_change_case<K, upper>>{
879 using symb_type = K;
880
881 str_src<K> src_;
882 mutable size_t len_{};
883
884 template<StrSource S>
885 expr_change_case(S&& s) : src_(std::forward<S>(s)){}
886
887 constexpr size_t length() const noexcept {
888 if constexpr (sizeof(K) > 1) {
889 return src_.length();
890 } else {
891 if constexpr (upper) {
892 len_ = unicode_traits<K>::upper_len(src_.str, src_.len);
893 } else {
894 len_ = unicode_traits<K>::lower_len(src_.str, src_.len);
895 }
896 return len_;
897 }
898 }
899 constexpr K* place(K* ptr) const noexcept {
900 if constexpr (sizeof(K) > 1) {
901 if constexpr (upper) {
902 unicode_traits<K>::upper(src_.str, src_.len, ptr);
903 } else {
904 unicode_traits<K>::lower(src_.str, src_.len, ptr);
905 }
906 return ptr + src_.len;
907 } else {
908 const K* src = src_.str;
909 if constexpr (upper) {
910 unicode_traits<K>::upper(src, src_.len, ptr, len_);
911 } else {
912 unicode_traits<K>::lower(src, src_.len, ptr, len_);
913 }
914 return ptr;
915 }
916 }
917};
918
933template<is_one_of_char_v K>
934struct e_upper : expr_change_case<K, true> {
935 using base = expr_change_case<K, true>;
936 using base::base;
937};
938
939template<StrSource S>
941
956template<is_one_of_char_v K>
957struct e_lower : expr_change_case<K, false> {
958 using base = expr_change_case<K, false>;
959 using base::base;
960};
961
962template<StrSource S>
964
969template<typename A, typename K>
970concept storable_str = requires {
971 A::is_str_storable == true;
972 std::is_same_v<typename A::symb_type, K>;
973};
974
979template<typename A, typename K>
980concept mutable_str = storable_str<A, K> && requires { A::is_str_mutable == true; };
981
986template<typename A, typename K>
988
1025template<typename K, typename Impl, typename Allocator>
1026class str_storable : protected Allocator {
1027public:
1028 using my_type = Impl;
1029 using traits = ch_traits<K>;
1030 using allocator_t = Allocator;
1031 using s_str = simple_str<K>;
1032 using s_str_nt = simple_str_nt<K>;
1033
1034protected:
1039 constexpr allocator_t& allocator() {
1040 return *static_cast<Allocator*>(this);
1041 }
1042 constexpr const allocator_t& allocator() const {
1043 return *static_cast<const Allocator*>(this);
1044 }
1045
1046 using uni = unicode_traits<K>;
1047
1048 constexpr Impl& d() noexcept {
1049 return *static_cast<Impl*>(this);
1050 }
1051 constexpr const Impl& d() const noexcept {
1052 return *static_cast<const Impl*>(this);
1053 }
1054
1061 template<typename... Args>
1062 explicit constexpr str_storable(Args&&... args) : Allocator(std::forward<Args>(args)...) {}
1063
1070 constexpr void init_from_str_other(s_str other) {
1071 if (other.length()) {
1072 K* ptr = d().init(other.length());
1073 traits::copy(ptr, other.symbols(), other.length());
1074 ptr[other.length()] = 0;
1075 } else
1076 d().create_empty();
1077 }
1078
1086 constexpr void init_str_repeat(size_t repeat, s_str pattern) {
1087 size_t l = pattern.length(), allLen = l * repeat;
1088 if (allLen) {
1089 K* ptr = d().init(allLen);
1090 for (size_t i = 0; i < repeat; i++) {
1091 traits::copy(ptr, pattern.symbols(), l);
1092 ptr += l;
1093 }
1094 *ptr = 0;
1095 } else
1096 d().create_empty();
1097 }
1098
1106 constexpr void init_symb_repeat(size_t count, K pad) {
1107 if (count) {
1108 K* str = d().init(count);
1109 traits::assign(str, count, pad);
1110 str[count] = 0;
1111 } else
1112 d().create_empty();
1113 }
1114
1126 template<StrExprForType<K> A>
1127 constexpr void init_str_expr(const A& expr) {
1128 size_t len = expr.length();
1129 if (len)
1130 *expr.place((typename A::symb_type*)d().init(len)) = 0;
1131 else
1132 d().create_empty();
1133 }
1134
1148 template<StrType<K> From>
1149 void init_replaced(const From& f, s_str pattern, s_str repl, size_t offset = 0, size_t maxCount = 0) {
1150 auto findes = f.find_all(pattern, offset, maxCount);
1151 if (!findes.size()) {
1152 new (this) my_type{f};
1153 return;
1154 }
1155 size_t srcLen = f.length();
1156 size_t newSize = srcLen + static_cast<ptrdiff_t>(repl.len - pattern.len) * findes.size();
1157
1158 if (!newSize) {
1159 new (this) my_type{};
1160 return;
1161 }
1162
1163 K* ptr = d().init(newSize);
1164 const K* src = f.symbols();
1165 size_t from = 0;
1166 for (const auto& s: findes) {
1167 size_t copyLen = s - from;
1168 if (copyLen) {
1169 traits::copy(ptr, src + from, copyLen);
1170 ptr += copyLen;
1171 }
1172 if (repl.len) {
1173 traits::copy(ptr, repl.str, repl.len);
1174 ptr += repl.len;
1175 }
1176 from = s + pattern.len;
1177 }
1178 srcLen -= from;
1179 if (srcLen) {
1180 traits::copy(ptr, src + from, srcLen);
1181 ptr += srcLen;
1182 }
1183 *ptr = 0;
1184 }
1185
1186public:
1187
1188 inline static constexpr bool is_str_storable = true;
1195 constexpr operator const K*() const noexcept {
1196 return d().symbols();
1197 }
1198
1206 constexpr s_str_nt to_nts(size_t from = 0) const {
1207 size_t len = d().length();
1208 if (from >= len) {
1209 from = len;
1210 }
1211 return {d().symbols() + from, len - from};
1212 }
1213
1219 constexpr operator s_str_nt() const {
1220 return {d().symbols(), d().length()};
1221 }
1222
1260 template<typename T, typename... Args>
1261 requires std::is_constructible_v<allocator_t, Args...>
1262 static my_type join(const T& strings, s_str delimiter, bool tail = false, bool skip_empty = false, Args&&... args) {
1263 my_type result(std::forward<Args>(args)...);
1264 if (strings.size()) {
1265 if (strings.size() == 1 && (!delimiter.length() || !tail)) {
1266 result = strings.front();
1267 } else {
1268 size_t commonLen = 0;
1269 for (const auto& t: strings) {
1270 size_t len = t.length();
1271 if (len > 0 || !skip_empty) {
1272 if (commonLen > 0) {
1273 commonLen += delimiter.len;
1274 }
1275 commonLen += len;
1276 }
1277 }
1278 commonLen += (tail && delimiter.len > 0 && (commonLen > 0 || (!skip_empty && strings.size() > 0))? delimiter.len : 0);
1279 if (commonLen) {
1280 K* ptr = result.init(commonLen);
1281 K* write = ptr;
1282 for (const auto& t: strings) {
1283 size_t copyLen = t.length();
1284 if (delimiter.len > 0 && write != ptr && (copyLen || !skip_empty)) {
1285 ch_traits<K>::copy(write, delimiter.str, delimiter.len);
1286 write += delimiter.len;
1287 }
1288 ch_traits<K>::copy(write, t.symbols(), copyLen);
1289 write += copyLen;
1290 }
1291 if (delimiter.len > 0 && tail && (write != ptr || (!skip_empty && strings.size() > 0))) {
1292 ch_traits<K>::copy(write, delimiter.str, delimiter.len);
1293 write += delimiter.len;
1294 }
1295 *write = 0;
1296 } else {
1297 result.create_empty();
1298 }
1299 }
1300 }
1301 return result;
1302 }
1303
1311 template<StrType<K> From, typename... Args>
1312 requires std::is_constructible_v<allocator_t, Args...>
1313 static my_type upperred_only_ascii_from(const From& f, Args&&... args) {
1314 return my_type{e_ascii_upper<K>{f}, std::forward<Args>(args)...};
1315 }
1316
1324 template<StrType<K> From, typename... Args>
1325 requires std::is_constructible_v<allocator_t, Args...>
1326 static my_type lowered_only_ascii_from(const From& f, Args&&... args) {
1327 return my_type{e_ascii_lower<K>{f}, std::forward<Args>(args)...};
1328 }
1329
1341 template<StrType<K> From, typename... Args>
1342 requires std::is_constructible_v<allocator_t, Args...>
1343 static my_type upperred_from(const From& f, Args&&... args) {
1344 return my_type{e_upper<K>{f}, std::forward<Args>(args)...};
1345 }
1346
1358 template<StrType<K> From, typename... Args>
1359 requires std::is_constructible_v<allocator_t, Args...>
1360 static my_type lowered_from(const From& f, Args&&... args) {
1361 return my_type{e_lower<K>{f}, std::forward<Args>(args)...};
1362 }
1363
1379 template<StrType<K> From, typename... Args>
1380 requires std::is_constructible_v<allocator_t, Args...>
1381 static my_type replaced_from(const From& f, s_str pattern, s_str repl, size_t offset = 0, size_t maxCount = 0, Args&&... args) {
1382 return my_type{f, pattern, repl, offset, maxCount, std::forward<Args>(args)...};
1383 }
1384};
1385
1390template<typename A>
1391concept AllocatableNoSized = requires(A& a, size_t size, void* void_ptr) {
1392 { a.allocate(size) } -> std::same_as<void*>;
1393 { a.deallocate(void_ptr) } noexcept -> std::same_as<void>;
1394};
1395
1400template<typename A>
1401concept AllocatableSized = requires(A& a, size_t size, void* void_ptr) {
1402 { a.allocate(size) } -> std::same_as<void*>;
1403 { a.deallocate(void_ptr, size) } noexcept -> std::same_as<void>;
1404};
1405
1410template<typename A>
1412
1413struct printf_selector {
1414 template<typename K, typename... T> requires (is_one_of_std_char_v<K>)
1415 static int snprintf(K* buffer, size_t count, const K* format, T&&... args) {
1416 if constexpr (sizeof(K) == 1) {
1417 #ifndef _WIN32
1418 return std::snprintf(to_one_of_std_char(buffer), count, to_one_of_std_char(format), std::forward<T>(args)...);
1419 #else
1420 // Поддерживает позиционные параметры
1421 // Supports positional parameters
1422 return _sprintf_p(to_one_of_std_char(buffer), count, to_one_of_std_char(format), args...);
1423 #endif
1424 } else {
1425 #ifndef _WIN32
1426 return std::swprintf(to_one_of_std_char(buffer), count, to_one_of_std_char(format), args...);
1427 #else
1428 // Поддерживает позиционные параметры
1429 // Supports positional parameters
1430 return _swprintf_p(to_one_of_std_char(buffer), count, to_one_of_std_char(format), args...);
1431 #endif
1432 }
1433 }
1434 template<typename K> requires (is_one_of_std_char_v<K>)
1435 static int vsnprintf(K* buffer, size_t count, const K* format, va_list args) {
1436 if constexpr (std::is_same_v<K, u8s>) {
1437 #ifndef _WIN32
1438 return std::vsnprintf(buffer, count, format, args);
1439 #else
1440 // Поддерживает позиционные параметры
1441 // Supports positional parameters
1442 return _vsprintf_p(buffer, count, format, args);
1443 #endif
1444 } else {
1445 #ifndef _WIN32
1446 return std::vswprintf(to_one_of_std_char(buffer), count, to_one_of_std_char(format), args);
1447 #else
1448 // Поддерживает позиционные параметры
1449 // Supports positional parameters
1450 return _vswprintf_p(buffer, count, format, args);
1451 #endif
1452 }
1453 }
1454};
1455
1456inline size_t grow2(size_t ret, size_t currentCapacity) {
1457 return ret <= currentCapacity ? ret : ret * 2;
1458}
1459
1498template<typename K, typename Impl>
1500public:
1501 using my_type = Impl;
1502
1503private:
1504 Impl& d() {
1505 return *static_cast<Impl*>(this);
1506 }
1507 const Impl& d() const {
1508 return *static_cast<const Impl*>(this);
1509 }
1510 size_t _len() const noexcept {
1511 return d().length();
1512 }
1513 const K* _str() const noexcept {
1514 return d().symbols();
1515 }
1516 using str_piece = simple_str<K>;
1517 using symb_type = K;
1518 using traits = ch_traits<K>;
1519 using uni = unicode_traits<K>;
1520 using uns_type = std::make_unsigned_t<K>;
1521
1522 template<typename Op>
1523 Impl& make_trim_op(const Op& op) {
1524 str_piece me = d(), pos = op(me);
1525 if (me.length() != pos.length()) {
1526 if (me.symbols() != pos.symbols())
1527 traits::move(const_cast<K*>(me.symbols()), pos.symbols(), pos.length());
1528 d().set_size(pos.length());
1529 }
1530 return d();
1531 }
1532
1533 template<auto Op>
1534 Impl& commonChangeCase() {
1535 size_t len = _len();
1536 if (len)
1537 Op(_str(), len, str());
1538 return d();
1539 }
1540 // GCC до сих пор не позволяет делать внутри класса полную специализацию вложенного класса,
1541 // только частичную. Поэтому добавим неиспользуемый параметр шаблона.
1542 // GCC still does not allow full specialization of a nested class within a class,
1543 // only partial. Resources additive unused parameter template.
1544 template<typename T, bool Dummy = true>
1545 struct CaseTraits {
1546 static Impl& upper(Impl& obj) {
1547 return obj.template commonChangeCase<unicode_traits<K>::upper>();
1548 }
1549 static Impl& lower(Impl& obj) {
1550 return obj.template commonChangeCase<unicode_traits<K>::lower>();
1551 }
1552 };
1553
1554 template<auto Op>
1555 Impl& utf8CaseChange() {
1556 // Для utf-8 такая операция может изменить длину строки, поэтому для них делаем разные специализации
1557 // For utf-8, such an operation can change the length of the string, so we make different specializations for them
1558 size_t len = _len();
1559 if (len) {
1560 u8s* writePos = str();
1561 const u8s *startData = writePos, *readPos = writePos;
1562 size_t newLen = Op(readPos, len, writePos, len);
1563 if (newLen < len) {
1564 // Строка просто укоротилась
1565 // The string was simply shortened
1566 d().set_size(newLen);
1567 } else if (newLen > len) {
1568 // Строка не влезла в буфер.
1569 // The string did not fit into the buffer.
1570 size_t readed = static_cast<size_t>(readPos - startData);
1571 size_t writed = static_cast<size_t>(writePos - startData);
1572 d().set_size(newLen);
1573 startData = str(); // при изменении размера могло изменится | may change when resizing
1574 readPos = startData + readed;
1575 writePos = const_cast<u8s*>(startData) + writed;
1576 Op(readPos, len - readed, writePos, newLen - writed);
1577 }
1578 }
1579 return d();
1580 }
1581 template<bool Dummy>
1582 struct CaseTraits<u8s, Dummy> {
1583 static Impl& upper(Impl& obj) {
1584 return obj.template utf8CaseChange<unicode_traits<u8s>::upper>();
1585 }
1586 static Impl& lower(Impl& obj) {
1587 return obj.template utf8CaseChange<unicode_traits<u8s>::lower>();
1588 }
1589 };
1590
1591 template<TrimSides S, bool withSpaces, typename T, size_t N = const_lit_for<K, T>::Count>
1592 Impl& makeTrim(T&& pattern) {
1593 return make_trim_op(trim_operator<S, K, N - 1, withSpaces>{pattern});
1594 }
1595
1596 template<TrimSides S, bool withSpaces>
1597 Impl& makeTrim(str_piece pattern) {
1598 return make_trim_op(trim_operator<S, K, 0, withSpaces>{{pattern}});
1599 }
1600
1601public:
1608 K* str() noexcept {
1609 return d().str();
1610 }
1611
1617 explicit operator K*() noexcept {
1618 return str();
1619 }
1620
1626 Impl& trim() {
1627 return make_trim_op(SimpleTrim<TrimSides::TrimAll, K>{});
1628 }
1629
1635 Impl& trim_left() {
1636 return make_trim_op(SimpleTrim<TrimSides::TrimLeft, K>{});
1637 }
1638
1644 Impl& trim_right() {
1645 return make_trim_op(SimpleTrim<TrimSides::TrimRight, K>{});
1646 }
1647
1655 template<typename T, size_t N = const_lit_for<K, T>::Count>
1656 requires is_const_pattern<N>
1657 Impl& trim(T&& pattern) {
1658 return makeTrim<TrimSides::TrimAll, false>(pattern);
1659 }
1660
1668 template<typename T, size_t N = const_lit_for<K, T>::Count>
1669 requires is_const_pattern<N>
1670 Impl& trim_left(T&& pattern) {
1671 return makeTrim<TrimSides::TrimLeft, false>(pattern);
1672 }
1673
1681 template<typename T, size_t N = const_lit_for<K, T>::Count>
1682 requires is_const_pattern<N>
1683 Impl& trim_right(T&& pattern) {
1684 return makeTrim<TrimSides::TrimRight, false>(pattern);
1685 }
1686
1694 template<typename T, size_t N = const_lit_for<K, T>::Count>
1695 requires is_const_pattern<N>
1696 Impl& trim_with_spaces(T&& pattern) {
1697 return makeTrim<TrimSides::TrimAll, true>(pattern);
1698 }
1699
1707 template<typename T, size_t N = const_lit_for<K, T>::Count>
1708 requires is_const_pattern<N>
1709 Impl& trim_left_with_spaces(T&& pattern) {
1710 return makeTrim<TrimSides::TrimLeft, true>(pattern);
1711 }
1712
1720 template<typename T, size_t N = const_lit_for<K, T>::Count>
1721 requires is_const_pattern<N>
1722 Impl& trim_right_with_wpaces(T&& pattern) {
1723 return makeTrim<TrimSides::TrimRight, true>(pattern);
1724 }
1725
1733 Impl& trim(str_piece pattern) {
1734 return pattern.length() ? makeTrim<TrimSides::TrimAll, false>(pattern) : d();
1735 }
1736
1744 Impl& trim_left(str_piece pattern) {
1745 return pattern.length() ? makeTrim<TrimSides::TrimLeft, false>(pattern) : d();
1746 }
1747
1755 Impl& trim_right(str_piece pattern) {
1756 return pattern.length() ? makeTrim<TrimSides::TrimRight, false>(pattern) : d();
1757 }
1758
1766 Impl& trim_with_spaces(str_piece pattern) {
1767 return makeTrim<TrimSides::TrimAll, true>(pattern);
1768 }
1769
1777 Impl& trim_left_with_spaces(str_piece pattern) {
1778 return makeTrim<TrimSides::TrimLeft, true>(pattern);
1779 }
1780
1788 Impl& trim_right_with_spaces(str_piece pattern) {
1789 return makeTrim<TrimSides::TrimRight, true>(pattern);
1790 }
1791
1798 K* ptr = str();
1799 for (size_t i = 0, l = _len(); i < l; i++, ptr++) {
1800 K s = *ptr;
1801 if (isAsciiLower(s))
1802 *ptr = s & ~0x20;
1803 }
1804 return d();
1805 }
1806
1813 K* ptr = str();
1814 for (size_t i = 0, l = _len(); i < l; i++, ptr++) {
1815 K s = *ptr;
1816 if (isAsciiUpper(s))
1817 *ptr = s | 0x20;
1818 }
1819 return d();
1820 }
1821
1831 Impl& upper() {
1832 // Для utf-8 такая операция может изменить длину строки, поэтому для них делаем разные специализации
1833 // For utf-8, such an operation can change the length of the string, so we make different specializations for them
1834 return CaseTraits<K>::upper(d());
1835 }
1836
1846 Impl& lower() {
1847 // Для utf-8 такая операция может изменить длину строки, поэтому для них делаем разные специализации
1848 // For utf-8, such an operation can change the length of the string, so we make different specializations for them
1849 return CaseTraits<K>::lower(d());
1850 }
1851
1852private:
1853 template<typename T>
1854 Impl& changeImpl(size_t from, size_t len, T expr) {
1855 size_t myLen = _len();
1856 if (from > myLen) {
1857 from = myLen;
1858 }
1859 if (from + len > myLen) {
1860 len = myLen - from;
1861 }
1862 K* buffer = str();
1863 size_t otherLen = expr.length();
1864 if (len == otherLen) {
1865 expr.place(buffer + from);
1866 } else {
1867 size_t tailLen = myLen - from - len;
1868 if (len > otherLen) {
1869 expr.place(buffer + from);
1870 traits::move(buffer + from + otherLen, buffer + from + len, tailLen);
1871 d().set_size(myLen - (len - otherLen));
1872 } else {
1873 buffer = d().set_size(myLen + otherLen - len);
1874 traits::move(buffer + from + otherLen, buffer + from + len, tailLen);
1875 expr.place(buffer + from);
1876 }
1877 }
1878 return d();
1879 }
1880
1881 template<typename T>
1882 Impl& appendImpl(T expr) {
1883 if (size_t len = expr.length(); len) {
1884 size_t size = _len();
1885 expr.place(d().set_size(size + len) + size);
1886 }
1887 return d();
1888 }
1889
1890 template<typename T>
1891 Impl& appendFromImpl(size_t pos, T expr) {
1892 if (pos > _len())
1893 pos = _len();
1894 if (size_t len = expr.length())
1895 expr.place(d().set_size(pos + len) + pos);
1896 else
1897 d().set_size(pos);
1898 return d();
1899 }
1900
1901public:
1902 inline static constexpr bool is_str_mutable = true;
1911 Impl& append(str_piece other) {
1912 return appendImpl<str_piece>(other);
1913 }
1914
1922 template<StrExprForType<K> A>
1923 Impl& append(const A& expr) {
1924 return appendImpl<const A&>(expr);
1925 }
1926
1934 Impl& operator+=(str_piece other) {
1935 return appendImpl<str_piece>(other);
1936 }
1937
1945 template<StrExprForType<K> A>
1946 Impl& operator+=(const A& expr) {
1947 return appendImpl<const A&>(expr);
1948 }
1949
1963 Impl& append_in(size_t pos, str_piece other) {
1964 return appendFromImpl<str_piece>(pos, other);
1965 }
1966
1980 template<StrExprForType<K> A>
1981 Impl& append_in(size_t pos, const A& expr) {
1982 return appendFromImpl<const A&>(pos, expr);
1983 }
1984
1996 Impl& change(size_t from, size_t len, str_piece other) {
1997 return changeImpl<str_piece>(from, len, other);
1998 }
1999
2011 template<StrExprForType<K> A>
2012 Impl& change(size_t from, size_t len, const A& expr) {
2013 return changeImpl<const A&>(from, len, expr);
2014 }
2015
2025 Impl& insert(size_t to, str_piece other) {
2026 return changeImpl<str_piece>(to, 0, other);
2027 }
2028
2038 template<StrExprForType<K> A>
2039 Impl& insert(size_t to, const A& expr) {
2040 return changeImpl<const A&>(to, 0, expr);
2041 }
2042
2052 Impl& remove(size_t from, size_t len) {
2053 return changeImpl<const empty_expr<K>&>(from, len, {});
2054 }
2055
2063 Impl& prepend(str_piece other) {
2064 return changeImpl<str_piece>(0, 0, other);
2065 }
2066
2074 template<StrExprForType<K> A>
2075 Impl& prepend(const A& expr) {
2076 return changeImpl<const A&>(0, 0, expr);
2077 }
2078
2092 Impl& replace(str_piece pattern, str_piece repl, size_t offset = 0, size_t maxCount = 0) {
2093 offset = d().find(pattern, offset);
2094 if (offset == str::npos) {
2095 return d();
2096 }
2097 if (!maxCount)
2098 maxCount--;
2099 size_t replLength = repl.length(), patternLength = pattern.length();
2100
2101 if (patternLength == replLength) {
2102 // Заменяем inplace на подстроку такой же длины
2103 // Replace inplace with a substring of the same length
2104 K* ptr = str();
2105 while (maxCount--) {
2106 traits::copy(ptr + offset, repl.symbols(), replLength);
2107 offset = d().find(pattern, offset + replLength);// replLength == patternLength
2108 if (offset == str::npos)
2109 break;
2110 }
2111 } else if (patternLength > replLength) {
2112 // Заменяем на более короткий кусок, длина текста уменьшится, идём слева направо
2113 // Replace with a shorter piece, the length of the text will decrease, go from left to right
2114 K* ptr = str();
2115 traits::copy(ptr + offset, repl.symbols(), replLength);
2116 size_t posWrite = offset + replLength;
2117 offset += patternLength;
2118
2119 while (--maxCount) {
2120 size_t idx = d().find(pattern, offset);
2121 if (idx == str::npos)
2122 break;
2123 size_t lenOfPiece = idx - offset;
2124 traits::move(ptr + posWrite, ptr + offset, lenOfPiece);
2125 posWrite += lenOfPiece;
2126 traits::copy(ptr + posWrite, repl.symbols(), replLength);
2127 posWrite += replLength;
2128 offset = idx + patternLength;
2129 }
2130 size_t tailLen = _len() - offset;
2131 traits::move(ptr + posWrite, ptr + offset, tailLen);
2132 d().set_size(posWrite + tailLen);
2133 } else {
2134 struct replace_grow_helper {
2135 replace_grow_helper(my_type& src, str_piece p, str_piece r, size_t mc, size_t d)
2136 : source(src), pattern(p), repl(r), maxCount(mc), delta(d) {}
2137 my_type& source;
2138 const str_piece pattern;
2139 const str_piece repl;
2140 size_t maxCount;
2141 const size_t delta;
2142 size_t all_delta{};
2143 K* reserve_for_copy{};
2144 size_t end_of_piece{};
2145 size_t total_length{};
2146
2147 void replace(size_t offset) {
2148 size_t found[16] = {offset};
2149 maxCount--;
2150 offset += pattern.length();
2151 all_delta += delta;
2152 size_t idx = 1;
2153 for (; idx < std::size(found) && maxCount > 0; idx++, maxCount--) {
2154 found[idx] = source.find(pattern, offset);
2155 if (found[idx] == str::npos) {
2156 break;
2157 }
2158 offset = found[idx] + pattern.length();
2159 all_delta += delta;
2160 }
2161 if (idx == std::size(found) && maxCount > 0 && (offset = source.find(pattern, offset)) != str::npos) {
2162 replace(offset); // здесь произойдут замены в оставшемся хвосте | replacements will be made here in the remaining tail
2163 }
2164 // Теперь делаем свои замены
2165 // Now we make our replacements
2166 if (!reserve_for_copy) {
2167 // Только начинаем
2168 // Just getting started
2169 end_of_piece = source.length();
2170 total_length = end_of_piece + all_delta;
2171 reserve_for_copy = source.alloc_for_copy(total_length);
2172 }
2173 K* dst_start = reserve_for_copy;
2174 const K* src_start = source.symbols();
2175 while(idx-- > 0) {
2176 size_t pos = found[idx] + pattern.length();
2177 size_t lenOfPiece = end_of_piece - pos;
2178 ch_traits<K>::move(dst_start + pos + all_delta, src_start + pos, lenOfPiece);
2179 ch_traits<K>::copy(dst_start + pos + all_delta - repl.length(), repl.symbols(), repl.length());
2180 all_delta -= delta;
2181 end_of_piece = found[idx];
2182 }
2183 if (!all_delta && reserve_for_copy != src_start) {
2184 ch_traits<K>::copy(dst_start, src_start, found[0]);
2185 }
2186 }
2187 } helper(d(), pattern, repl, maxCount, repl.length() - pattern.length());
2188 helper.replace(offset);
2189 d().set_from_copy(helper.reserve_for_copy, helper.total_length);
2190 }
2191 return d();
2192 }
2193
2209 template<StrType<K> From>
2210 Impl& replace_from(const From& f, str_piece pattern, str_piece repl, size_t offset = 0, size_t maxCount = 0) {
2211 if (pattern.length() >= repl.length()) {
2212 K* dst = d().reserve_no_preserve(f.length());
2213 const K* src = f.symbols();
2214 size_t delta = 0;
2215 if (maxCount == 0) {
2216 maxCount--;
2217 }
2218 size_t src_length = f.length(), start = 0;
2219 while (maxCount--) {
2220 offset = f.find(pattern, offset);
2221 if (offset == str::npos) {
2222 break;
2223 }
2224 size_t piece_len = offset - start;
2225 if (piece_len) {
2226 ch_traits<K>::copy(dst, src + start, piece_len);
2227 dst += piece_len;
2228 }
2229 if (repl.length()) {
2230 ch_traits<K>::copy(dst, repl.symbols(), repl.length());
2231 dst += repl.length();
2232 }
2233 delta += pattern.length() - repl.length();
2234 offset += pattern.length();
2235 start = offset;
2236 }
2237 if (start < src_length) {
2238 ch_traits<K>::copy(dst, src + start, src_length - start);
2239 }
2240 d().set_size(src_length - delta);
2241 } else {
2242 d() = f;
2243 replace(pattern, repl, offset, maxCount);
2244 }
2245 return d();
2246 }
2247
2271 template<typename Op>
2272 Impl& fill(size_t from, const Op& fillFunction) {
2273 size_t size = _len();
2274 if (from > size)
2275 from = size;
2276 size_t capacity = d().capacity();
2277 K* ptr = str();
2278 capacity -= from;
2279 for (;;) {
2280 size_t needSize = static_cast<size_t>(fillFunction(ptr + from, capacity));
2281 if (capacity >= needSize) {
2282 d().set_size(from + needSize);
2283 break;
2284 }
2285 ptr = from == 0 ? d().reserve_no_preserve(needSize) : d().set_size(from + needSize);
2286 capacity = d().capacity() - from;
2287 }
2288 return d();
2289 }
2290
2298 template<typename Op>
2299 requires std::is_invocable_v<Op, K*, size_t>
2300 Impl& operator<<(const Op& fillFunction) {
2301 return fill(0, fillFunction);
2302 }
2303
2311 template<typename Op>
2312 requires std::is_invocable_v<Op, K*, size_t>
2313 Impl& operator<<=(const Op& fillFunction) {
2314 return fill(_len(), fillFunction);
2315 }
2316
2324 template<typename Op>
2325 requires std::is_invocable_v<Op, my_type&>
2326 Impl& operator<<(const Op& fillFunction) {
2327 fillFunction(d());
2328 return d();
2329 }
2330
2344 template<typename... T> requires (is_one_of_std_char_v<K>)
2345 Impl& printf_from(size_t from, const K* format, T&&... args) {
2346 size_t size = _len();
2347 if (from > size)
2348 from = size;
2349 size_t capacity = d().capacity();
2350 K* ptr = str();
2351 capacity -= from;
2352
2353 int result = 0;
2354 // Тут грязный хак для u8s и wide_char. u8s версия snprintf сразу возвращает размер нужного буфера, если он мал
2355 // а swprintf - возвращает -1. Под windows оба варианта xxx_p - тоже возвращают -1.
2356 // Поэтому для них надо тупо увеличивать буфер наугад, пока не подойдет
2357 // Here's a dirty hack for u8s and wide_char. u8s version of snprintf immediately returns the size of the required buffer if it is small
2358 // and swprintf returns -1. Under Windows, both options xxx_p also return -1.
2359 // Therefore, for them you need to stupidly increase the buffer at random until it fits
2360 if constexpr (sizeof(K) == 1 && !isWindowsOs) {
2361 result = printf_selector::snprintf(ptr + from, capacity + 1, format, std::forward<T>(args)...);
2362 if (result > (int)capacity) {
2363 ptr = from == 0 ? d().reserve_no_preserve(result) : d().set_size(from + result);
2364 result = printf_selector::snprintf(ptr + from, result + 1, format, std::forward<T>(args)...);
2365 }
2366 } else {
2367 for (;;) {
2368 result = printf_selector::snprintf(ptr + from, capacity + 1, format, std::forward<T>(args)...);
2369 if (result < 0) {
2370 // Не хватило буфера или ошибка конвертации.
2371 // Попробуем увеличить буфер в два раза
2372 // Not enough buffer or conversion error.
2373 // Let's try to double the buffer
2374 capacity *= 2;
2375 ptr = from == 0 ? d().reserve_no_preserve(capacity) : d().set_size(from + capacity);
2376 } else
2377 break;
2378 }
2379 }
2380 if (result < 0)
2381 d().set_size(static_cast<size_t>(traits::length(_str())));
2382 else
2383 d().set_size(from + result);
2384 return d();
2385 }
2386
2398 template<typename... T> requires (is_one_of_std_char_v<K>)
2399 Impl& printf(const K* format, T&&... args) {
2400 return printf_from(0, format, std::forward<T>(args)...);
2401 }
2402
2414 template<typename... T> requires (is_one_of_std_char_v<K>)
2415 Impl& append_printf(const K* format, T&&... args) {
2416 return printf_from(_len(), format, std::forward<T>(args)...);
2417 }
2418
2419 struct writer {
2420 my_type* store;
2421 K* ptr;
2422 const K* end;
2423 size_t max_write;
2424 size_t writed = 0;
2425 inline static K pad;
2426 K& operator*() const {
2427 return *ptr;
2428 }
2429 writer& operator++() {
2430 if (writed < max_write) {
2431 ++ptr;
2432 if (ptr == end) {
2433 size_t l = ptr - store->begin();
2434 store->set_size(l);
2435 ptr = store->set_size(l + std::min(l / 2, size_t(8192))) + l;
2436 end = store->end();
2437 }
2438 } else {
2439 ptr = &pad;
2440 }
2441 return *this;
2442 }
2443 writer operator++(int) {
2444 auto ret = *this;
2445 operator++();
2446 return ret;
2447 }
2448
2449 writer(my_type& s, K* p, K* e, size_t ml) : store(&s), ptr(p), end(e), max_write(ml) {}
2450 writer() = default;
2451 writer(const writer&) = delete;
2452 writer& operator=(const writer&) noexcept = delete;
2453 writer(writer&&) noexcept = default;
2454 writer& operator=(writer&&) noexcept = default;
2455 using difference_type = int;
2456 };
2457 using fmt_type = to_std_char_t<K>;
2472 template<typename... T> requires (is_one_of_std_char_v<K>)
2473 Impl& format_from(size_t from, const FmtString<fmt_type, T...>& format, T&&... args) {
2474 size_t size = _len();
2475 if (from > size)
2476 from = size;
2477 size_t capacity = d().capacity();
2478 K* ptr = str();
2479
2480 auto result = std::format_to(writer{d(), ptr + from, ptr + capacity, size_t(-1)},
2481 std::forward<decltype(format)>(format), std::forward<T>(args)...);
2482 d().set_size(result.ptr - _str());
2483 return d();
2484 }
2485
2501 template<typename... T> requires (is_one_of_std_char_v<K>)
2502 Impl& vformat_from(size_t from, size_t max_write, str_piece format, T&&... args) {
2503 size_t size = _len();
2504 if (from > size)
2505 from = size;
2506 size_t capacity = d().capacity();
2507 K* ptr = str();
2508
2509 if constexpr (std::is_same_v<K, u8s>) {
2510 auto result = std::vformat_to(
2511 writer{d(), ptr + from, ptr + capacity, max_write},
2512 std::basic_string_view<K>{format.symbols(), format.length()},
2513 std::make_format_args(args...));
2514 d().set_size(result.ptr - _str());
2515 } else {
2516 auto result = std::vformat_to(
2517 writer{d(), to_one_of_std_char(ptr + from), ptr + capacity, max_write},
2518 std::basic_string_view<wchar_t>{to_one_of_std_char(format.symbols()), format.length()},
2519 std::make_wformat_args(std::forward<T>(args)...));
2520 d().set_size(result.ptr - _str());
2521 }
2522 return d();
2523 }
2524
2536 template<typename... T> requires (is_one_of_std_char_v<K>)
2537 Impl& format(const FmtString<fmt_type, T...>& pattern, T&&... args) {
2538 return format_from(0, pattern, std::forward<T>(args)...);
2539 }
2540
2552 template<typename... T> requires (is_one_of_std_char_v<K>)
2553 Impl& append_formatted(const FmtString<fmt_type, T...>& format, T&&... args) {
2554 return format_from(_len(), format, std::forward<T>(args)...);
2555 }
2556
2568 template<typename... T> requires (is_one_of_std_char_v<K>)
2569 Impl& vformat(str_piece format, T&&... args) {
2570 return vformat_from(0, -1, format, std::forward<T>(args)...);
2571 }
2572
2584 template<typename... T> requires (is_one_of_std_char_v<K>)
2585 Impl& append_vformatted(str_piece format, T&&... args) {
2586 return vformat_from(_len(), -1, format, std::forward<T>(args)...);
2587 }
2588
2602 template<typename... T> requires (is_one_of_std_char_v<K>)
2603 Impl& vformat_n(size_t max_write, str_piece format, T&&... args) {
2604 return vformat_from(0, max_write, format, std::forward<T>(args)...);
2605 }
2606
2620 template<typename... T> requires (is_one_of_std_char_v<K>)
2621 Impl& append_vformatted_n(size_t max_write, str_piece format, T&&... args) {
2622 return vformat_from(_len(), max_write, format, std::forward<T>(args)...);
2623 }
2624
2634 template<typename Op, typename... Args>
2635 Impl& with(const Op& fillFunction, Args&&... args) {
2636 fillFunction(d(), std::forward<Args>(args)...);
2637 return d();
2638 }
2639};
2640
2641template<typename K>
2642struct SharedStringData {
2643 std::atomic_size_t ref_; // Счетчик ссылок | Reference count
2644 inline static constexpr size_t mask = (size_t(-1)) >> 1, check = ~mask;
2645
2646 SharedStringData() {
2647 ref_ = 1;
2648 }
2649 SharedStringData(size_t capacity) {
2650 ref_ = 1 | check;
2651 reinterpret_cast<size_t*>(this)[-1] = (capacity + 1) * sizeof(K) + sizeof(*this) + sizeof(size_t);
2652 }
2653 K* str() const {
2654 return (K*)(this + 1);
2655 }
2656 void incr() {
2657 ref_.fetch_add(1, std::memory_order_relaxed);
2658 }
2659 void decr(AllocatableNoSized auto& allocator) {
2660 size_t val = ref_.fetch_sub(1, std::memory_order_relaxed);
2661 if (val == 1) {
2662 allocator.deallocate(this);
2663 }
2664 }
2665 void decr(AllocatableSized auto& allocator, size_t len) {
2666 size_t val = ref_.fetch_sub(1, std::memory_order_relaxed);
2667 if ((val & mask) == 1) {
2668 if (val & check) {
2669 // Это блок от перемещённой lstring, перед ним записан размер выделенной памяти.
2670 // This is a block from the moved lstring, the size of the allocated memory is written in front of it.
2671 size_t* ptr = reinterpret_cast<size_t*>(this);
2672 ptr--;
2673 allocator.deallocate(ptr, *ptr);
2674 } else {
2675 allocator.deallocate(this, (len + 1) * sizeof(K) + sizeof(*this));
2676 }
2677 }
2678 }
2679 static SharedStringData* create(size_t l, Allocatable auto& allocator) {
2680 size_t size = sizeof(SharedStringData) + (l + 1) * sizeof(K);
2681 return new (allocator.allocate(size)) SharedStringData();
2682 }
2683 static SharedStringData* from_str(const K* p) {
2684 return (SharedStringData*)p - 1;
2685 }
2686 K* place(K* p, size_t len) {
2687 ch_traits<K>::copy(p, str(), len);
2688 return p + len;
2689 }
2690};
2691
2692// Дефолтный аллокатор для строк, может работать статически
2693// Default allocator for strings, can work statically
2694class string_common_allocator {
2695public:
2696 void* allocate(size_t bytes) {
2697 return ::operator new(bytes);
2698 }
2699 void deallocate(void* address) noexcept {
2700 ::operator delete(address);
2701 }
2702};
2703
2704string_common_allocator default_string_allocator_selector(...);
2705// Если вы хотите задать свой дефолтный аллокатор для строк, перед включение sstring.h
2706// объявите функцию
2707// ваш_тип_аллокатора default_string_allocator_selector(int);
2708// If you want to set your default allocator for strings, before including sstring.h
2709// declare a function
2710// your_allocator_type default_string_allocator_selector(int);
2711using allocator_string = decltype(default_string_allocator_selector(int(0)));
2712
2713template<typename K, Allocatable Allocator>
2714class sstring;
2715
2716/*
2717* Так как у класса несколько базовых классов, MSVC не применяет автоматом empty base optimization,
2718* и без явного указания - вставит в начало класса пустые байты, сдвинув поле size на 4-8 байта.
2719* Укажем ему явно.
2720* Since a class has several base classes, MSVC does not automatically apply empty base optimization,
2721* and without explicit indication - will insert empty bytes at the beginning of the class, shifting the size field by 4-8 bytes.
2722* Let's tell him explicitly.
2723*/
2724
2745template<typename K, size_t N, bool forShared = false, Allocatable Allocator = allocator_string>
2746class decl_empty_bases lstring :
2747 public str_algs<K, simple_str<K>, lstring<K, N, forShared, Allocator>, true>,
2748 public str_mutable<K, lstring<K, N, forShared, Allocator>>,
2749 public str_storable<K, lstring<K, N, forShared, Allocator>, Allocator>,
2750 public null_terminated<K, lstring<K, N, forShared, Allocator>>,
2751 public from_utf_convertible<K, lstring<K, N, forShared, Allocator>> {
2752public:
2753 using symb_type = K;
2755 using allocator_t = Allocator;
2756
2757 enum : size_t {
2759 LocalCapacity = N | (sizeof(void*) / sizeof(K) - 1),
2760 };
2761
2762protected:
2763 enum : size_t {
2764 extra = forShared ? sizeof(SharedStringData<K>) + (AllocatableSized<Allocator> ? sizeof(size_t) : 0) : 0,
2765 };
2766
2767 using base_algs = str_algs<K, simple_str<K>, my_type, true>;
2768 using base_storable = str_storable<K, my_type, Allocator>;
2769 using base_mutable = str_mutable<K, my_type>;
2770 using base_utf = from_utf_convertible<K, my_type>;
2771 using traits = ch_traits<K>;
2772 using s_str = base_storable::s_str;
2773
2774 friend base_storable;
2775 friend base_mutable;
2776 friend base_utf;
2777 friend class sstring<K, Allocator>;
2778
2779 K* data_;
2780 size_t size_;
2781
2782 union {
2783 size_t capacity_;
2784 K local_[LocalCapacity + 1];
2785 };
2786
2787 constexpr void create_empty() {
2788 data_ = local_;
2789 size_ = 0;
2790 local_[0] = 0;
2791 }
2792 constexpr static size_t calc_capacity(size_t s) {
2793 const int al = alignof(std::max_align_t) < 16 ? 16 : alignof(std::max_align_t);
2794 size_t real_need = (s + 1) * sizeof(K) + extra;
2795 size_t aligned_alloced = (real_need + al - 1) / al * al;
2796 return (aligned_alloced - extra) / sizeof(K) - 1;
2797 }
2798
2799 constexpr K* init(size_t s) {
2800 size_t need_cap = s;
2801 if (need_cap > LocalCapacity) {
2802 need_cap = calc_capacity(s);
2803 data_ = alloc_place(need_cap);
2804 capacity_ = need_cap;
2805 } else {
2806 data_ = local_;
2807 }
2808 size_ = s;
2809 return str();
2810 }
2811 // Методы для себя | Methods for yourself
2812 constexpr bool is_alloced() const noexcept {
2813 return data_ != local_;
2814 }
2815
2816 constexpr void dealloc() {
2817 if (is_alloced()) {
2818 if constexpr (AllocatableNoSized<Allocator>) {
2819 base_storable::allocator().deallocate(to_real_address(data_));
2820 } else {
2821 base_storable::allocator().deallocate(to_real_address(data_), (capacity_ + 1) * sizeof(K) + extra);
2822 }
2823 data_ = local_;
2824 }
2825 }
2826
2827 constexpr static K* to_real_address(void* ptr) {
2828 return reinterpret_cast<K*>(reinterpret_cast<u8s*>(ptr) - extra);
2829 }
2830 constexpr static K* from_real_address(void* ptr) {
2831 return reinterpret_cast<K*>(reinterpret_cast<u8s*>(ptr) + extra);
2832 }
2833
2834 constexpr K* alloc_place(size_t newSize) {
2835 return from_real_address(base_storable::allocator().allocate((newSize + 1) * sizeof(K) + extra));
2836 }
2837 // Вызывается при replace, когда меняют на более длинную замену
2838 // Called on replace when changing to a longer replacement
2839 constexpr K* alloc_for_copy(size_t newSize) {
2840 if (capacity() >= newSize) {
2841 // Замена войдёт в текущий буфер
2842 // Replacement will go into the current buffer
2843 return data_;
2844 }
2845 return alloc_place(calc_capacity(newSize));
2846 }
2847 // Вызывается после replace, когда меняли на более длинную замену, могли скопировать в новый буфер
2848 // Called after replace, when they changed to a longer replacement, they could have copied it to a new buffer
2849 constexpr void set_from_copy(K* ptr, size_t newSize) {
2850 if (ptr != data_) {
2851 // Да, копировали в новый буфер
2852 // Yes, copied to a new buffer
2853 dealloc();
2854 data_ = ptr;
2855 capacity_ = calc_capacity(newSize);
2856 }
2857 size_ = newSize;
2858 data_[newSize] = 0;
2859 }
2860 constexpr void copy_from_another(K* buf, const K* src, size_t size) {
2861 // Реальный размер буфера всегда кратен sizeof(void*), поэтому копируя по sizeof(void*) байтов, мы не выйдем за пределы буфера
2862 // The actual buffer size is always a multiple of sizeof(void*), so by copying sizeof(void*) bytes at a time, we won't go beyond the buffer's limits.
2863 size_t need_copy_bytes = (size + 1) * sizeof(K);
2864 size_t cnt = (need_copy_bytes + sizeof(void*) - 1) / sizeof(void*) * sizeof(void*);
2865 traits::copy(buf, src, cnt / sizeof(K));
2866 }
2867public:
2874 template<typename... Args>
2875 requires (std::is_constructible_v<allocator_t, Args...> && sizeof...(Args) > 0)
2876 constexpr lstring(Args&&... args) noexcept(std::is_nothrow_constructible_v<allocator_t, Args...>)
2877 : base_storable(std::forward<Args>(args)...) {
2878 create_empty();
2879 }
2880
2889 template<typename... Args>
2890 requires std::is_constructible_v<allocator_t, Args...>
2891 constexpr lstring(s_str other, Args&&... args) : base_storable(std::forward<Args>(args)...) {
2893 }
2894
2904 template<typename... Args>
2905 requires std::is_constructible_v<allocator_t, Args...>
2906 constexpr lstring(size_t repeat, s_str pattern, Args&&... args) : base_storable(std::forward<Args>(args)...) {
2907 base_storable::init_str_repeat(repeat, pattern);
2908 }
2909
2919 template<typename... Args>
2920 requires std::is_constructible_v<allocator_t, Args...>
2921 constexpr lstring(size_t count, K pad, Args&&... args) : base_storable(std::forward<Args>(args)...) {
2923 }
2924
2938 template<typename... Args>
2939 requires std::is_constructible_v<allocator_t, Args...>
2940 constexpr lstring(const StrExprForType<K> auto& expr, Args&&... args) : base_storable(std::forward<Args>(args)...) {
2942 }
2943
2959 template<StrType<K> From, typename... Args>
2960 requires std::is_constructible_v<allocator_t, Args...>
2961 constexpr lstring(const From& f, s_str pattern, s_str repl, size_t offset = 0, size_t maxCount = 0, Args&&... args)
2962 : base_storable(std::forward<Args>(args)...) {
2963 base_storable::init_replaced(f, pattern, repl, offset, maxCount);
2964 }
2965
2966 constexpr lstring() {
2967 create_empty();
2968 }
2969
2970 constexpr ~lstring() {
2971 dealloc();
2972 }
2973
2980 constexpr lstring(const my_type& other) : base_storable(other.allocator()) {
2981 struct copy{uint64_t p[2];};
2982 constexpr size_t short_str = sizeof(copy) / sizeof(K);
2983 if constexpr (LocalCapacity >= short_str - 1) {
2984 if (other.size_ < short_str) {
2985 data_ = local_;
2986 size_ = other.size_;
2987 *(copy*)local_ = *(const copy*)other.local_;
2988 return;
2989 }
2990 }
2991 if (size_t size = other.size_) {
2992 copy_from_another(init(size), other.symbols(), size);
2993 } else {
2994 create_empty();
2995 }
2996 }
2997
3005 template<typename... Args>
3006 requires(sizeof...(Args) > 0 && std::is_convertible_v<allocator_t, Args...>)
3007 constexpr lstring(const my_type& other, Args&&... args) : base_storable(std::forward<Args>(args)...) {
3008 if (other.size_) {
3009 copy_from_another(init(other.size_), other.symbols(), other.size_);
3010 } else {
3011 create_empty();
3012 }
3013 }
3014
3022 template<typename T, size_t I = const_lit_for<K, T>::Count, typename... Args>
3023 requires std::is_constructible_v<allocator_t, Args...>
3024 constexpr lstring(T&& value, Args&&... args) : base_storable(std::forward<Args>(args)...) {
3025 if constexpr (I > 1) {
3026 K* ptr = init(I - 1);
3027 traits::copy(ptr, (const K*)value, I - 1);
3028 ptr[I - 1] = K{};
3029 } else {
3030 create_empty();
3031 }
3032 }
3033
3039 constexpr lstring(my_type&& other) noexcept : base_storable(std::move(other.allocator())) {
3040 if (other.size_) {
3041 size_ = other.size_;
3042 if (other.is_alloced()) {
3043 data_ = other.data_;
3044 other.data_ = other.local_;
3045 capacity_ = other.capacity_;
3046 } else {
3047 data_ = local_;
3048 copy_from_another(data_, other.local_, size_);
3049 }
3050 other.size_ = 0;
3051 other.local_[0] = 0;
3052 } else {
3053 create_empty();
3054 }
3055 }
3056
3064 template<typename Op, typename... Args>
3065 requires(std::is_constructible_v<Allocator, Args...> && (std::is_invocable_v<Op, my_type&> || std::is_invocable_v<Op, K*, size_t>))
3066 lstring(const Op& op, Args&&... args) : base_storable(std::forward<Args>(args)...) {
3067 create_empty();
3068 this->operator<<(op);
3069 }
3070 template<typename O>
3071 requires(!std::is_same_v<O, K>)
3072 lstring(simple_str<O> init) {
3073 this->init_from_utf_convertible(init);
3074 }
3075
3076 template<typename O, typename I, bool M>
3077 requires(!std::is_same_v<O, K>)
3078 lstring(const str_algs<O, simple_str<O>, I, M>& init) {
3079 this->init_from_utf_convertible(init.to_str());
3080 }
3081
3082 // copy and swap для присваиваний здесь не очень применимо, так как для строк с большим локальным буфером лишняя копия даже перемещением будет дорого стоить
3083 // Поэтому реализуем копирующее и перемещающее присваивание отдельно
3084 // copy and swap for assignments is not very applicable here, since for strings with a large local buffer, an extra copy, even by moving, will be expensive
3085 // Therefore, we implement the copy and move assignment separately
3086
3095 my_type& operator=(const my_type& other) {
3096 // Так как между этими объектами не может быть косвенной зависимости, достаточно проверить только на равенство
3097 // Since there cannot be an indirect dependency between these objects, it is enough to check only for equality
3098 if (&other != this) {
3099 traits::copy(reserve_no_preserve(other.size_), other.data_, other.size_ + 1);
3100 size_ = other.size_;
3101 }
3102 return *this;
3103 }
3104
3112 my_type& operator=(my_type&& other) noexcept {
3113 // Так как между этими объектами не может быть косвенной зависимости, достаточно проверить только на равенство
3114 // Since there cannot be an indirect dependency between these objects, it is enough to check only for equality
3115 if (&other != this) {
3116 dealloc();
3117 if (other.is_alloced()) {
3118 data_ = other.data_;
3119 capacity_ = other.capacity_;
3120 } else {
3121 traits::copy(data_, other.local_, other.size_ + 1);
3122 }
3123 base_storable::allocator() = std::move(other.allocator());
3124 size_ = other.size_;
3125 other.create_empty();
3126 }
3127 return *this;
3128 }
3129
3130 my_type& assign(const K* other, size_t len) {
3131 if (len) {
3132 bool isIntersect = other >= data_ && other + len <= data_ + size_;
3133 if (isIntersect) {
3134 // Особый случай, нам пытаются присвоить кусок нашей же строки.
3135 // Просто переместим текст в буфере, и установим новый размер
3136 // A special case, they are trying to assign us a piece of our own string.
3137 // Just move the text in the buffer and set a new size
3138 if (other > data_) {
3139 traits::move(data_, other, len);
3140 }
3141 } else {
3142 traits::copy(reserve_no_preserve(len), other, len);
3143 }
3144 }
3145 size_ = len;
3146 data_[size_] = 0;
3147 return *this;
3148 }
3157 my_type& operator=(simple_str<K> other) {
3158 return assign(other.str, other.len);
3159 }
3160
3168 template<typename T, size_t S = const_lit_for<K, T>::Count>
3169 my_type& operator=(T&& other) {
3170 return assign((const K*)other, S - 1);
3171 }
3172
3182 my_type& operator=(const StrExprForType<K> auto& expr) {
3183 size_t newLen = expr.length();
3184 if (newLen) {
3185 expr.place(reserve_no_preserve(newLen));
3186 }
3187 size_ = newLen;
3188 data_[size_] = 0;
3189 return *this;
3190 }
3191
3192 constexpr size_t length() const noexcept {
3193 return size_;
3194 }
3195
3196 constexpr const K* symbols() const noexcept {
3197 return data_;
3198 }
3199
3200 constexpr K* str() noexcept {
3201 return data_;
3202 }
3203
3204 constexpr bool is_empty() const noexcept {
3205 return size_ == 0;
3206 }
3207
3208 constexpr bool empty() const noexcept {
3209 return size_ == 0;
3210 }
3211
3212 constexpr size_t capacity() const noexcept {
3213 return is_alloced() ? capacity_ : LocalCapacity;
3214 }
3215
3227 constexpr K* reserve_no_preserve(size_t newSize) {
3228 if (newSize > capacity()) {
3229 newSize = calc_capacity(newSize);
3230 K* newData = alloc_place(newSize);
3231 dealloc();
3232 data_ = newData;
3233 capacity_ = newSize;
3234 }
3235 return data_;
3236 }
3237
3249 constexpr K* reserve(size_t newSize) {
3250 if (newSize > capacity()) {
3251 newSize = calc_capacity(newSize);
3252 K* newData = alloc_place(newSize);
3253 traits::copy(newData, data_, size_);
3254 dealloc();
3255 data_ = newData;
3256 capacity_ = newSize;
3257 }
3258 return data_;
3259 }
3260
3272 constexpr K* set_size(size_t newSize) {
3273 size_t cap = capacity();
3274 if (newSize > cap) {
3275 size_t needPlace = newSize;
3276 if (needPlace < (cap + 1) * 2) {
3277 needPlace = (cap + 1) * 2 - 1;
3278 }
3279 reserve(needPlace);
3280 }
3281 size_ = newSize;
3282 data_[newSize] = 0;
3283 return data_;
3284 }
3285
3289 constexpr bool is_local() const noexcept {
3290 return !is_alloced();
3291 }
3292
3298 constexpr void define_size() {
3299 size_t cap = capacity();
3300 for (size_t i = 0; i < cap; i++) {
3301 if (data_[i] == 0) {
3302 size_ = i;
3303 return;
3304 }
3305 }
3306 size_ = cap;
3307 data_[size_] = 0;
3308 }
3309
3315 constexpr void shrink_to_fit() {
3316 size_t need_capacity = calc_capacity(size_);
3317 if (is_alloced() && capacity_ > need_capacity) {
3318 K* newData = size_ <= LocalCapacity ? local_ : alloc_place(need_capacity);
3319 traits::copy(newData, data_, size_ + 1);
3320 dealloc();
3321 data_ = newData;
3322
3323 if (size_ > LocalCapacity) {
3324 capacity_ = need_capacity;
3325 }
3326 }
3327 }
3328
3329 constexpr void clear() {
3330 set_size(0);
3331 }
3332
3333 constexpr void reset() {
3334 dealloc();
3335 local_[0] = 0;
3336 size_ = 0;
3337 }
3338};
3339
3340template<size_t N = 15>
3341using lstringa = lstring<u8s, N>;
3342template<size_t N = 15>
3343using lstringb = lstring<ubs, N>;
3344template<size_t N = 15>
3345using lstringw = lstring<wchar_t, N>;
3346template<size_t N = 15>
3347using lstringu = lstring<u16s, N>;
3348template<size_t N = 15>
3349using lstringuu = lstring<u32s, N>;
3350
3351template<size_t N = 15>
3352using lstringsa = lstring<u8s, N, true>;
3353template<size_t N = 15>
3354using lstringsb = lstring<ubs, N, true>;
3355template<size_t N = 15>
3356using lstringsw = lstring<wchar_t, N, true>;
3357template<size_t N = 15>
3358using lstringsu = lstring<u16s, N, true>;
3359template<size_t N = 15>
3360using lstringsuu = lstring<u32s, N, true>;
3361
3362
3363template<typename T, typename K = typename const_lit<T>::symb_type>
3364auto getLiteralType(T&&) {
3365 return K{};
3366};
3367
3368template<size_t Arch, size_t L>
3369inline constexpr const size_t _local_count = 0;
3370
3371template<>
3372inline constexpr const size_t _local_count<8, 1> = 23;
3373template<>
3374inline constexpr const size_t _local_count<8, 2> = 15;
3375template<>
3376inline constexpr const size_t _local_count<8, 4> = 7;
3377template<>
3378inline constexpr const size_t _local_count<4, 1> = 15;
3379template<>
3380inline constexpr const size_t _local_count<4, 2> = 11;
3381template<>
3382inline constexpr const size_t _local_count<4, 4> = 5;
3383
3384template<typename T>
3385constexpr const size_t local_count = _local_count<sizeof(size_t), sizeof(T)>;
3386
3439template<typename K, Allocatable Allocator = allocator_string>
3440class decl_empty_bases sstring :
3441 public str_algs<K, simple_str<K>, sstring<K, Allocator>, false>,
3442 public str_storable<K, sstring<K, Allocator>, Allocator>,
3443 public null_terminated<K, sstring<K, Allocator>>,
3444 public from_utf_convertible<K, sstring<K, Allocator>> {
3445public:
3446 using symb_type = K;
3447 using uns_type = std::make_unsigned_t<K>;
3448 using my_type = sstring<K, Allocator>;
3449 using allocator_t = Allocator;
3450
3451 enum { LocalCount = local_count<K> };
3452
3453protected:
3454 using base_algs = str_algs<K, simple_str<K>, my_type, false>;
3455 using base_storable = str_storable<K, my_type, Allocator>;
3456 using base_utf = from_utf_convertible<K, my_type>;
3457 using traits = ch_traits<K>;
3458 using uni = unicode_traits<K>;
3459 using s_str = base_storable::s_str;
3460
3461 friend base_storable;
3462 friend base_utf;
3463
3464 enum Types { Local, Constant, Shared };
3465
3466 union {
3467 // Когда у нас короткая строка, она лежит в самом объекте, а в localRemain
3468 // пишется, сколько символов ещё можно вписать. Когда строка занимает всё
3469 // возможное место, то localRemain становится 0, type в этом случае тоже 0,
3470 // и в итоге после символов строки получается 0, как и надо!
3471 // When we have a short string, it lies in the object itself, and in localRemain
3472 // writes how many more characters can be entered. When a string takes up everything
3473 // possible location, then localRemain becomes 0, type in this case is also 0,
3474 // and as a result, after the characters of the string we get 0, as it should!
3475 struct {
3476 K buf_[LocalCount]; // Локальный буфер строки | Local string buffer
3477 uns_type localRemain_ : sizeof(uns_type) * CHAR_BIT - 2;
3478 uns_type type_ : 2;
3479 };
3480 struct {
3481 union {
3482 // Указатель на конcтантную строку | Pointer to a constant string
3483 const K* cstr_;
3484 // Указатель на строку, перед которой лежит SharedStringData
3485 // Pointer to the string preceded by SharedStringData
3486 const K* sstr_;
3487 };
3488 size_t bigLen_; // Длина не локальной строки | Non-local string length
3489 };
3490 };
3491
3492 constexpr void create_empty() {
3493 type_ = Local;
3494 localRemain_ = LocalCount;
3495 buf_[0] = 0;
3496 }
3497 constexpr K* init(size_t s) {
3498 if (s > LocalCount) {
3499 type_ = Shared;
3500 localRemain_ = 0;
3501 bigLen_ = s;
3502 sstr_ = SharedStringData<K>::create(s, base_storable::allocator())->str();
3503 return (K*)sstr_;
3504 } else {
3505 type_ = Local;
3506 localRemain_ = LocalCount - s;
3507 return buf_;
3508 }
3509 }
3510
3511 void dealloc() {
3512 if (type_ == Shared) {
3513 if constexpr (AllocatableNoSized<Allocator>) {
3514 SharedStringData<K>::from_str(sstr_)->decr(base_storable::allocator());
3515 } else {
3516 SharedStringData<K>::from_str(sstr_)->decr(base_storable::allocator(), bigLen_);
3517 }
3518 }
3519 }
3520public:
3521
3522 sstring() {
3523 create_empty();
3524 }
3525
3532 template<typename... Args>
3533 requires (std::is_constructible_v<allocator_t, Args...> && sizeof...(Args) > 0)
3534 sstring(Args&&... args) noexcept(std::is_nothrow_constructible_v<allocator_t, Args...>)
3535 : base_storable(std::forward<Args>(args)...) {
3536 create_empty();
3537 }
3538
3547 template<typename... Args>
3548 requires std::is_constructible_v<allocator_t, Args...>
3549 sstring(s_str other, Args&&... args) : base_storable(std::forward<Args>(args)...) {
3551 }
3552
3562 template<typename... Args>
3563 requires std::is_constructible_v<allocator_t, Args...>
3564 sstring(size_t repeat, s_str pattern, Args&&... args) : base_storable(std::forward<Args>(args)...) {
3565 base_storable::init_str_repeat(repeat, pattern);
3566 }
3567
3577 template<typename... Args>
3578 requires std::is_constructible_v<allocator_t, Args...>
3579 sstring(size_t count, K pad, Args&&... args) : base_storable(std::forward<Args>(args)...) {
3581 }
3582
3596 template<typename... Args>
3597 requires std::is_constructible_v<allocator_t, Args...>
3598 constexpr sstring(const StrExprForType<K> auto& expr, Args&&... args) : base_storable(std::forward<Args>(args)...) {
3600 }
3601
3617 template<StrType<K> From, typename... Args>
3618 requires std::is_constructible_v<allocator_t, Args...>
3619 sstring(const From& f, s_str pattern, s_str repl, size_t offset = 0, size_t maxCount = 0, Args&&... args)
3620 : base_storable(std::forward<Args>(args)...) {
3621 base_storable::init_replaced(f, pattern, repl, offset, maxCount);
3622 }
3623
3624 static const sstring<K> empty_str;
3626 constexpr ~sstring() {
3627 dealloc();
3628 }
3629
3635 constexpr sstring(const my_type& other) noexcept : base_storable(other.allocator()) {
3636 memcpy(buf_, other.buf_, sizeof(buf_) + sizeof(K));
3637 if (type_ == Shared)
3638 SharedStringData<K>::from_str(sstr_)->incr();
3639 }
3640
3646 constexpr sstring(my_type&& other) noexcept : base_storable(std::move(other.allocator())) {
3647 memcpy(buf_, other.buf_, sizeof(buf_) + sizeof(K));
3648 other.create_empty();
3649 }
3650
3661 template<size_t N>
3662 constexpr sstring(lstring<K, N, true, Allocator>&& src) : base_storable(std::move(src.allocator())) {
3663 size_t size = src.length();
3664 if (size) {
3665 if (src.is_alloced()) {
3666 // Там динамический буфер, выделенный с запасом для SharedStringData и size_t.
3667 // There is a dynamic buffer allocated with a reserve for SharedStringData and size_t.
3668 K* str = src.str();
3669 if (size > LocalCount) {
3670 // Просто присвоим его себе.
3671 // Let's just assign it to ourselves.
3672 sstr_ = str;
3673 bigLen_ = size;
3674 type_ = Shared;
3675 localRemain_ = 0;
3676 if constexpr (AllocatableNoSized<Allocator>) {
3677 new (SharedStringData<K>::from_str(str)) SharedStringData<K>;
3678 } else {
3679 new (SharedStringData<K>::from_str(str)) SharedStringData<K>(src.capacity_);
3680 }
3681 } else {
3682 // Скопируем локально
3683 // Copy locally
3684 type_ = Local;
3685 localRemain_ = LocalCount - size;
3686 traits::copy(buf_, str, size + 1);
3687 // Освободим тот буфер, у локальной строки буфер не разделяется с другими
3688 // Let's free that buffer; a local string's buffer is not shared with others
3689 src.dealloc();
3690 }
3691 } else {
3692 // Копируем из локального буфера
3693 // Copy from local buffer
3694 K* str = init(src.size_);
3695 traits::copy(str, src.symbols(), size + 1);
3696 }
3697 src.create_empty();
3698 } else
3699 create_empty();
3700 }
3701
3712 template<typename T, size_t N = const_lit_for<K, T>::Count, typename... Args>
3713 requires std::is_constructible_v<allocator_t, Args...>
3714 sstring(T&& s, Args&&... args) : base_storable(std::forward<Args>(args)...) {
3715 type_ = Constant;
3716 localRemain_ = 0;
3717 cstr_ = (const K*)s;
3718 bigLen_ = N - 1;
3719 }
3720
3726 template<typename O> requires(!std::is_same_v<O, K>)
3728 this->init_from_utf_convertible(init);
3729 }
3730
3731 template<typename O, typename I, bool M> requires(!std::is_same_v<O, K>)
3732 sstring(const str_algs<O, simple_str<O>, I, M>& init) {
3733 this->init_from_utf_convertible(init.to_str());
3734 }
3735
3736 constexpr void swap(my_type&& other) noexcept {
3737 char buf[sizeof(buf_) + sizeof(K)];
3738 memcpy(buf, buf_, sizeof(buf));
3739 memcpy(buf_, other.buf_, sizeof(buf));
3740 memcpy(other.buf_, buf, sizeof(buf));
3741
3742 std::swap(base_storable::allocator(), other.allocator());
3743 }
3752 constexpr my_type& operator=(my_type other) noexcept {
3753 swap(std::move(other));
3754 return *this;
3755 }
3756
3764 constexpr my_type& operator=(simple_str<K> other) {
3765 return operator=(my_type{other, base_storable::allocator()});
3766 }
3767
3775 template<typename T, size_t N = const_lit_for<K, T>::Count>
3776 constexpr my_type& operator=(T&& other) {
3777 return operator=(my_type{std::forward<T>(other), base_storable::allocator()});
3778 }
3779
3787 template<size_t N, bool forShared, typename A>
3788 constexpr my_type& operator=(const lstring<K, N, forShared, A>& other) {
3789 return operator=(my_type{other.to_str(), base_storable::allocator()});
3790 }
3791
3799 template<size_t N>
3800 constexpr my_type& operator=(lstring<K, N, true, Allocator>&& other) {
3801 return operator=(my_type{std::move(other)});
3802 }
3803
3813 constexpr my_type& operator=(const StrExprForType<K> auto& expr) {
3814 return operator=(my_type{expr, base_storable::allocator()});
3815 }
3816
3822 constexpr my_type& make_empty() noexcept {
3823 dealloc();
3824 create_empty();
3825 return *this;
3826 }
3827
3828 constexpr const K* symbols() const noexcept {
3829 return type_ == Local ? buf_ : cstr_;
3830 }
3831
3832 constexpr size_t length() const noexcept {
3833 return type_ == Local ? LocalCount - localRemain_ : bigLen_;
3834 }
3835
3836 constexpr bool is_empty() const noexcept {
3837 return length() == 0;
3838 }
3839
3840 constexpr bool empty() const noexcept {
3841 return is_empty();
3842 }
3843
3855 template<typename... T>
3856 static my_type printf(const K* pattern, T&&... args) {
3857 return my_type{lstring<K, 256, true>{}.printf(pattern, std::forward<T>(args)...)};
3858 }
3859
3869 template<typename... T>
3870 static my_type format(const FmtString<to_std_char_t<K>, T...>& fmtString, T&&... args) {
3871 return my_type{lstring<K, 256, true, Allocator>{}.format(fmtString, std::forward<T>(args)...)};
3872 }
3873
3883 template<typename... T>
3884 static my_type vformat(simple_str<K> fmtString, T&&... args) {
3885 return my_type{lstring<K, 256, true, Allocator>{}.vformat(fmtString, std::forward<T>(args)...)};
3886 }
3887};
3888
3889template<typename K, Allocatable Allocator>
3890inline const sstring<K> sstring<K, Allocator>::empty_str{};
3891
3892struct no_alloc{};
3893
3894template<typename K, size_t N>
3895class decl_empty_bases cestring :
3896 public str_algs<K, simple_str<K>, cestring<K, N>, true>,
3897 public str_storable<K, cestring<K, N>, no_alloc>,
3898 public null_terminated<K, lstring<K, N>>
3899 //, public from_utf_convertible<K, lstring<K, N, forShared, Allocator>>
3900{
3901public:
3902 using symb_type = K;
3903 using my_type = cestring<K, N>;
3904
3905 enum : size_t {
3907 LocalCapacity = N | (sizeof(void*) / sizeof(K) - 1),
3908 };
3909
3910protected:
3911
3912 using base_algs = str_algs<K, simple_str<K>, my_type, true>;
3913 using base_storable = str_storable<K, my_type, no_alloc>;
3914 //using base_utf = from_utf_convertible<K, my_type>;
3915 using traits = ch_traits<K>;
3916 using s_str = base_storable::s_str;
3917
3918 friend base_storable;
3919 //friend base_utf;
3920 const K* cstr_{};
3921 size_t size_{};
3922 bool is_cstr_{};
3923 K local_[LocalCapacity + 1]{};
3924
3925 constexpr void create_empty() {
3926 is_cstr_ = false;
3927 size_ = 0;
3928 local_[0] = 0;
3929 }
3930
3931 constexpr K* init(size_t s) {
3932 size_ = s;
3933 if (size_ > LocalCapacity) {
3934 throw std::bad_alloc{};
3935 }
3936 is_cstr_ = false;
3937 return local_;
3938 }
3939public:
3941 constexpr size_t length() const noexcept {
3942 return size_;
3943 }
3945 constexpr const K* symbols() const noexcept {
3946 return is_cstr_ ? cstr_ : local_;
3947 }
3949 constexpr bool is_empty() const noexcept {
3950 return size_ == 0;
3951 }
3953 constexpr bool empty() const noexcept {
3954 return size_ == 0;
3955 }
3957 constexpr size_t capacity() const noexcept {
3958 return LocalCapacity;
3959 }
3964 constexpr cestring() noexcept = default;
3965
3972 constexpr cestring(s_str other) : base_storable() {
3973 base_storable::init_from_str_other(other);
3974 }
3983 constexpr cestring(size_t repeat, s_str pattern) : base_storable() {
3984 base_storable::init_str_repeat(repeat, pattern);
3985 }
3994 constexpr cestring(size_t count, K pad) : base_storable() {
3995 base_storable::init_symb_repeat(count, pad);
3996 }
4009 constexpr cestring(const StrExprForType<K> auto& expr) : base_storable() {
4010 base_storable::init_str_expr(expr);
4011 }
4026 template<StrType<K> From>
4027 constexpr cestring(const From& f, s_str pattern, s_str repl, size_t offset = 0, size_t maxCount = 0)
4028 : base_storable() {
4029 base_storable::init_replaced(f, pattern, repl, offset, maxCount);
4030 }
4031
4033 constexpr ~cestring() {}
4034
4043 template<typename T, size_t M = const_lit_for<K, T>::Count>
4044 constexpr cestring(T&& s) : base_storable(), cstr_((const K*)s), size_(M - 1), is_cstr_(true), local_{0} {}
4045};
4046
4047template<typename K>
4048consteval simple_str_nt<K> select_str(simple_str_nt<u8s> s8, simple_str_nt<ubs> sb, simple_str_nt<uws> sw, simple_str_nt<u16s> s16, simple_str_nt<u32s> s32) {
4049 if constexpr (std::is_same_v<K, u8s>)
4050 return s8;
4051 if constexpr (std::is_same_v<K, ubs>)
4052 return sb;
4053 if constexpr (std::is_same_v<K, uws>)
4054 return sw;
4055 if constexpr (std::is_same_v<K, u16s>)
4056 return s16;
4057 if constexpr (std::is_same_v<K, u32s>)
4058 return s32;
4059}
4060
4061#define uni_string(K, p) select_str<K>(p, u8##p, L##p, u##p, U##p)
4062
4063template<typename K, template<typename C> typename H>
4064struct StoreType {
4065 simple_str<K> str;
4066 size_t hash;
4067 char node[sizeof(sstring<K>)];
4068
4069 const simple_str_nt<K>& to_nt() const noexcept {
4070 return static_cast<const simple_str_nt<K>&>(str);
4071 }
4072 const sstring<K>& to_str() const noexcept {
4073 return *reinterpret_cast<const sstring<K>*>(node);
4074 }
4075 bool operator==(const StoreType& other) const {
4076 return hash == other.hash && typename H<K>::eql{}(*this, other);
4077 }
4078};
4079
4080template<bool Wide>
4081struct fnv_const {
4082 static inline constexpr size_t basis = static_cast<size_t>(14695981039346656037ULL);
4083 static inline constexpr size_t prime = static_cast<size_t>(1099511628211ULL);
4084};
4085
4086template<>
4087struct fnv_const<false> {
4088 static inline constexpr size_t basis = static_cast<size_t>(2166136261U);
4089 static inline constexpr size_t prime = static_cast<size_t>(16777619U);
4090};
4091
4092using fnv = fnv_const<sizeof(size_t) == 8>;
4093
4094template<typename K>
4095inline constexpr size_t fnv_hash(const K* ptr, size_t l) {
4096 size_t h = fnv::basis;
4097 for (size_t i = 0; i < l; i++) {
4098 h = (h ^ (std::make_unsigned_t<K>)ptr[i]) * fnv::prime;
4099 }
4100 return h;
4101};
4102
4103template<typename K>
4104inline constexpr size_t fnv_hash_ia(const K* ptr, size_t l) {
4105 size_t h = fnv::basis;
4106 for (size_t i = 0; i < l; i++) {
4107 std::make_unsigned_t<K> s = (std::make_unsigned_t<K>)ptr[i];
4108 h = (h ^ (s >= 'A' && s <= 'Z' ? s | 0x20 : s)) * fnv::prime;
4109 }
4110 return h;
4111};
4112
4113template<typename T, typename K = typename const_lit<T>::symb_type, size_t N = const_lit<T>::Count>
4114inline constexpr size_t fnv_hash(T&& value) {
4115 size_t h = fnv::basis;
4116 for (size_t i = 0; i < N - 1; i++) {
4117 h = (h ^ (std::make_unsigned_t<K>)value[i]) * fnv::prime;
4118 }
4119 return h;
4120};
4121
4122template<typename T, typename K = typename const_lit<T>::symb_type, size_t N = const_lit<T>::Count>
4123inline constexpr size_t fnv_hash_ia(T&& value) {
4124 size_t h = fnv::basis;
4125 for (size_t i = 0; i < N - 1; i++) {
4126 std::make_unsigned_t<K> s = (std::make_unsigned_t<K>)value[i];
4127 h = (h ^ (s >= 'A' && s <= 'Z' ? s | 0x20 : s)) * fnv::prime;
4128 }
4129 return h;
4130};
4131
4132template<typename K>
4133inline consteval size_t fnv_hash_compile(const K* ptr, size_t l) {
4134 return fnv_hash(ptr, l);
4135};
4136
4137template<typename K>
4138inline consteval size_t fnv_hash_ia_compile(const K* ptr, size_t l) {
4139 return fnv_hash_ia(ptr, l);
4140};
4141
4142template<typename K>
4143struct str_exact;
4144
4145static_assert(std::is_trivially_copyable_v<StoreType<u8s, str_exact>>, "Store type must be trivially copyable");
4146
4147
4148template<typename K, typename V>
4149std::allocator<std::pair<K, V>> default_hashstrmap_allocator_selector(...);
4150// Если вы хотите задать свой дефолтный аллокатор для hashStrmap, перед включение sstring.h
4151// объявите функцию
4152// template<typename K, typename V>
4153// ваш_тип_аллокатора default_hashstrmap_allocator_selector(int);
4154// If you want to set your default allocator for hashStrMap, before including sstring.h
4155// declare a function
4156// template<typename K, typename V>
4157// your_allocator_type default_hashstrmap_allocator_selector(int);
4158template<typename K, template<typename C> typename H, typename V>
4159using allocator_hashstrmap = decltype(default_hashstrmap_allocator_selector<const StoreType<K, H>, V>(int(0)));
4160
4255template<typename K, typename T, template<typename C> typename HE = str_exact, typename A = allocator_hashstrmap<K, HE, T>>
4256class hashStrMap : public std::unordered_map<StoreType<K, HE>, T, typename HE<K>::hash, typename HE<K>::eql, A> {
4257protected:
4258 using InStore = StoreType<K, HE>;
4259
4260public:
4261 using hasher = typename HE<K>::hash;
4262 using comparator = typename HE<K>::eql;
4263 using my_type = hashStrMap<K, T, HE, A>;
4264 using hash_t = std::unordered_map<StoreType<K, HE>, T, hasher, comparator, A>;
4265
4266 hashStrMap() = default;
4267 hashStrMap(const my_type& other) : hash_t(other) {
4268 for (const auto& [k, v] : *this) {
4269 InStore& stored = const_cast<InStore&>(k);
4270 sstring<K> tmp = *(sstring<K>*)stored.node;
4271 new (stored.node) sstring<K>(std::move(tmp));
4272 stored.str.str = stored.to_str().symbols();
4273 }
4274 }
4275 ~hashStrMap() {
4276 for (auto& k: *this)
4277 ((sstring<K>*)k.first.node)->~sstring();
4278 }
4279
4280 hashStrMap(my_type&& o) = default;
4281
4282 my_type& operator=(const my_type& other) {
4283 hash_t::operator=(other);
4284 for (const auto& [k, v] : *this) {
4285 InStore& stored = const_cast<InStore&>(k);
4286 sstring<K> tmp = *(sstring<K>*)stored.node;
4287 new (stored.node) sstring<K>(std::move(tmp));
4288 stored.str.str = stored.to_str().symbols();
4289 }
4290 return *this;
4291 };
4292 my_type& operator=(my_type&&) = default;
4293
4294 hashStrMap(std::initializer_list<std::pair<const InStore, T>>&& init) {
4295 for (const auto& e: init)
4296 emplace(e.first, e.second);
4297 }
4298
4299 using init_str = std::initializer_list<std::pair<const sstring<K>, T>>;
4300
4301 hashStrMap(init_str&& init) {
4302 for (const auto& e: init)
4303 emplace(e.first, e.second);
4304 }
4305
4306 // При входе хэш должен быть уже посчитан
4307 // When entering, the hash must already be calculated
4308 template<typename... ValArgs>
4309 requires(std::is_constructible_v<T, ValArgs...>)
4310 auto try_emplace(const InStore& key, ValArgs&&... args) {
4311 auto it = hash_t::try_emplace(key, std::forward<ValArgs>(args)...);
4312 if (it.second) {
4313 InStore& stored = const_cast<InStore&>(it.first->first);
4314 new (stored.node) sstring<K>(key.str);
4315 stored.str.str = stored.to_str().symbols();
4316 }
4317 return it;
4318 }
4319
4320 static InStore toStoreType(simple_str<K> key) {
4321 return {key, hasher{}(key)};
4322 }
4323
4324 template<typename Key, typename... ValArgs>
4325 requires(std::is_convertible_v<Key, simple_str<K>> && std::is_constructible_v<T, ValArgs...>)
4326 auto try_emplace(Key&& key, ValArgs&&... args) {
4327 auto it = hash_t::try_emplace(toStoreType(key), std::forward<ValArgs>(args)...);
4328 if (it.second) {
4329 InStore& stored = const_cast<InStore&>(it.first->first);
4330 new (stored.node) sstring<K>(std::forward<Key>(key));
4331 stored.str.str = stored.to_str().symbols();
4332 }
4333 return it;
4334 }
4335
4336 template<typename... ValArgs>
4337 requires(std::is_constructible_v<T, ValArgs...>)
4338 auto emplace(const InStore& key, ValArgs&&... args) {
4339 auto it = try_emplace(key, std::forward<ValArgs>(args)...);
4340 if (!it.second) {
4341 it.first->second = T(std::forward<ValArgs>(args)...);
4342 }
4343 return it;
4344 }
4345
4346 template<typename Key, typename... ValArgs>
4347 requires(std::is_convertible_v<Key, simple_str<K>> && std::is_constructible_v<T, ValArgs...>)
4348 auto emplace(Key&& key, ValArgs&&... args) {
4349 auto it = try_emplace(std::forward<Key>(key), std::forward<ValArgs>(args)...);
4350 if (!it.second) {
4351 it.first->second = T(std::forward<ValArgs>(args)...);
4352 }
4353 return it;
4354 }
4355
4356 auto& operator[](const InStore& key) requires(std::is_default_constructible_v<T>) {
4357 return try_emplace(key).first->second;
4358 }
4359
4360 template<typename Key>
4361 requires(std::is_convertible_v<Key, simple_str<K>> && std::is_default_constructible_v<T>)
4362 auto& operator[](Key&& key) {
4363 return try_emplace(std::forward<Key>(key)).first->second;
4364 }
4365
4366 decltype(auto) at(const InStore& key) {
4367 return hash_t::at(key);
4368 }
4369 decltype(auto) at(const InStore& key) const {
4370 return hash_t::at(key);
4371 }
4372
4373 decltype(auto) at(simple_str<K> key) {
4374 return hash_t::at(toStoreType(key));
4375 }
4376 decltype(auto) at(simple_str<K> key) const {
4377 return hash_t::at(toStoreType(key));
4378 }
4379
4380 auto find(const InStore& key) const {
4381 return hash_t::find(key);
4382 }
4383
4384 auto find(simple_str<K> key) const {
4385 return find(toStoreType(key));
4386 }
4387
4388 auto find(const InStore& key) {
4389 return hash_t::find(key);
4390 }
4391
4392 auto find(simple_str<K> key) {
4393 return find(toStoreType(key));
4394 }
4395
4396 auto erase(typename hash_t::const_iterator it) {
4397 if (it != hash_t::end()) {
4398 ((sstring<K>*)it->first.node)->~sstring();
4399 }
4400 return hash_t::erase(it);
4401 }
4402
4403 auto erase(const InStore& key) {
4404 if (auto it = hash_t::find(key); it != hash_t::end()) {
4405 ((sstring<K>*)it->first.node)->~sstring();
4406 hash_t::erase(it);
4407 return 1;
4408 }
4409 return 0;
4410 }
4411
4412 auto erase(simple_str<K> key) {
4413 return erase(toStoreType(key));
4414 }
4415
4428 template<typename Dst> requires std::is_assignable_v<T, Dst>
4429 bool lookup(simple_str<K> key, Dst& val) const {
4430 if (auto it = find(key); it != hash_t::end()) {
4431 val = it->second;
4432 return true;
4433 }
4434 return false;
4435 }
4436
4448 template<typename Dst> requires std::is_assignable_v<T, Dst>
4449 bool lookup(const InStore& key, Dst& val) const {
4450 if (auto it = find(key); it != hash_t::end()) {
4451 val = it->second;
4452 return true;
4453 }
4454 return false;
4455 }
4456
4467 template<typename Dst = T> requires std::is_constructible_v<Dst, T>
4468 std::optional<Dst> get(simple_str<K> key) const {
4469 if (auto it = find(key); it != hash_t::end()) {
4470 return it->second;
4471 }
4472 return {};
4473 }
4474
4485 template<typename Dst = T> requires std::is_constructible_v<Dst, T>
4486 std::optional<Dst> get(const InStore& key) const {
4487 if (auto it = find(key); it != hash_t::end()) {
4488 return it->second;
4489 }
4490 return {};
4491 }
4492
4504 if (auto it = find(key); it != hash_t::end()) {
4505 return std::addressof(it->second);
4506 }
4507 return nullptr;
4508 }
4509
4520 T* existed(const InStore& key) {
4521 if (auto it = find(key); it != hash_t::end()) {
4522 return std::addressof(it->second);
4523 }
4524 return nullptr;
4525 }
4526
4537 const T* existed(simple_str<K> key) const {
4538 if (auto it = find(key); it != hash_t::end()) {
4539 return std::addressof(it->second);
4540 }
4541 return nullptr;
4542 }
4543
4554 const T* existed(const InStore& key) const {
4555 if (auto it = find(key); it != hash_t::end()) {
4556 return std::addressof(it->second);
4557 }
4558 return nullptr;
4559 }
4560
4561 void clear() {
4562 for (auto& k: *this)
4563 ((sstring<K>*)k.first.node)->~sstring();
4564 hash_t::clear();
4565 }
4566 bool contains(const InStore& key) const {
4567 return hash_t::find(key) != this->end();
4568 }
4569
4570 bool contains(simple_str<K> key) const {
4571 return find(toStoreType(key)) != this->end();
4572 }
4573};
4574
4575template<typename K>
4576struct str_exact {
4577 struct eql {
4578 bool operator()(const StoreType<K, str_exact>& _Left, const StoreType<K, str_exact>& _Right) const {
4579 return _Left.hash == _Right.hash && _Left.str == _Right.str;
4580 }
4581 };
4582 struct hash { // hash functor for basic_string
4583 size_t operator()(simple_str<K> _Keyval) const {
4584 return fnv_hash(_Keyval.symbols(), _Keyval.length());
4585 }
4586 size_t operator()(const StoreType<K, str_exact>& _Keyval) const {
4587 return _Keyval.hash;
4588 }
4589 };
4590};
4591
4592template<typename K>
4593struct str_eqlia {
4594 struct eql {
4595 bool operator()(const StoreType<K, str_eqlia>& _Left, const StoreType<K, str_eqlia>& _Right) const {
4596 return _Left.hash == _Right.hash && _Left.str.equal_ia(_Right.str);
4597 }
4598 };
4599 struct hash {
4600 size_t operator()(simple_str<K> _Keyval) const {
4601 return fnv_hash_ia(_Keyval.symbols(), _Keyval.length());
4602 }
4603 size_t operator()(const StoreType<K, str_eqlia>& _Keyval) const {
4604 return _Keyval.hash;
4605 }
4606 };
4607};
4608
4609template<typename K>
4610struct str_eqliu {
4611 struct eql {
4612 bool operator()(const StoreType<K, str_eqliu>& _Left, const StoreType<K, str_eqliu>& _Right) const {
4613 return _Left.hash == _Right.hash && _Left.str.equal_iu(_Right.str);
4614 }
4615 };
4616 struct hash {
4617 size_t operator()(simple_str<K> _Keyval) const {
4618 using bc = to_base_char_t<K>;
4619 return unicode_traits<bc>::hashiu((const bc*)_Keyval.symbols(), _Keyval.length());
4620 }
4621 size_t operator()(const StoreType<K, str_eqliu>& _Keyval) const {
4622 return _Keyval.hash;
4623 }
4624 };
4625};
4626
4641template<typename K>
4642class chunked_string_builder : expr_to_std_string<chunked_string_builder<K>> {
4643 using chunk_t = std::pair<std::unique_ptr<K[]>, size_t>;
4644 std::vector<chunk_t> chunks; // блоки и длина данных в них | blocks and data length in them
4645 K* write{}; // Текущая позиция записи | Current write position
4646 size_t len{}; // Общая длина | Total length
4647 size_t remain{}; // Сколько осталось места в текущем блоке | How much space is left in the current block
4648 size_t align{1024};
4649
4650public:
4651 using my_type = chunked_string_builder<K>;
4652 using symb_type = K;
4653 chunked_string_builder() = default;
4654 chunked_string_builder(size_t a) : align(a){};
4655 chunked_string_builder(const my_type&) = delete;
4656 chunked_string_builder(my_type&& other) noexcept
4657 : chunks(std::move(other.chunks)), write(other.write), len(other.len), remain(other.remain), align(other.align) {
4658 other.len = other.remain = 0;
4659 other.write = nullptr;
4660 }
4661 my_type& operator=(my_type other) noexcept {
4662 chunks.swap(other.chunks);
4663 write = other.write;
4664 len = other.len;
4665 remain = other.remain;
4666 align = other.align;
4667 other.len = other.remain = 0;
4668 other.write = nullptr;
4669 return *this;
4670 }
4671
4674 if (data.len) {
4675 len += data.len;
4676 if (data.len <= remain) {
4677 // Добавляемые данные влезают в выделенный блок, просто скопируем их
4678 // The added data fits into the selected block, just copy it
4679 ch_traits<K>::copy(write, data.str, data.len);
4680 write += data.len; // Сдвинем позицию записи | Let's move the recording position
4681 chunks.back().second += data.len; // Увеличим длину хранимых в блоке данных | Let's increase the length of the data stored in the block
4682 remain -= data.len; // Уменьшим остаток места в блоке | Reduce the remaining space in the block
4683 } else {
4684 // Не влезают | They don't fit
4685 if (remain) {
4686 // Сначала запишем сколько влезет
4687 // First, write down as much as we can
4688 ch_traits<K>::copy(write, data.str, remain);
4689 data.len -= remain;
4690 data.str += remain;
4691 chunks.back().second += remain; // Увеличим длину хранимых в блоке данных | Let's increase the length of the data stored in the block
4692 }
4693 // Выделим новый блок и впишем в него данные
4694 // Рассчитаем размер блока, кратного заданному выравниванию
4695 // Select a new block and write data into it
4696 // Calculate the block size that is a multiple of the given alignment
4697 size_t blockSize = (data.len + align - 1) / align * align;
4698 chunks.emplace_back(std::make_unique<K[]>(blockSize), data.len);
4699 write = chunks.back().first.get();
4700 ch_traits<K>::copy(write, data.str, data.len);
4701 write += data.len;
4702 remain = blockSize - data.len;
4703 }
4704 }
4705 return *this;
4706 }
4707
4708 my_type& operator<<(const StrExprForType<K> auto& expr) {
4709 size_t l = expr.length();
4710 if (l) {
4711 if (l < remain) {
4712 write = expr.place(write);
4713 chunks.back().second += l;
4714 len += l;
4715 remain -= l;
4716 } else if (!remain) {
4717 size_t blockSize = (l + align - 1) / align * align; // Рассчитаем размер блока, кратного заданному выравниванию
4718 chunks.emplace_back(std::make_unique<K[]>(blockSize), l);
4719 write = expr.place(chunks.back().first.get());
4720 len += l;
4721 remain = blockSize - l;
4722 } else {
4723 auto store = std::make_unique<K[]>(l);
4724 expr.place(store.get());
4725 return operator<<({store.get(), l});
4726 }
4727 }
4728 return *this;
4729 }
4730
4731 template<typename T>
4732 my_type& operator<<(T data)
4733 requires std::is_same_v<T, K>
4734 {
4735 return operator<<(expr_char<K>(data));
4736 }
4737
4738 constexpr size_t length() const noexcept {
4739 return len;
4740 }
4741
4742 void reset() {
4743 if (chunks.empty()) {
4744 return;
4745 }
4746 if (chunks.size() > 1) {
4747 remain = 0;
4748 chunks.resize(1);
4749 }
4750 remain += chunks[0].second;
4751 chunks[0].second = 0;
4752 len = 0;
4753 write = chunks[0].first.get();
4754 }
4755
4756 constexpr K* place(K* p) const noexcept {
4757 for (const auto& block: chunks) {
4758 ch_traits<K>::copy(p, block.first.get(), block.second);
4759 p += block.second;
4760 }
4761 return p;
4762 }
4771 template<typename Op>
4772 void out(const Op& o) const {
4773 for (const auto& block: chunks)
4774 o(block.first.get(), block.second);
4775 }
4776
4780 bool is_continuous() const {
4781 if (chunks.size()) {
4782 const K* ptr = chunks.front().first.get();
4783 for (const auto& chunk: chunks) {
4784 if (chunk.first.get() != ptr)
4785 return false;
4786 ptr += chunk.second;
4787 }
4788 }
4789 return true;
4790 }
4791
4797 const K* begin() const {
4798 return chunks.size() ? chunks.front().first.get() : simple_str_nt<K>::empty_str.str;
4799 }
4800
4804 void clear() {
4805 chunks.clear();
4806 write = nullptr;
4807 len = 0;
4808 remain = 0;
4809 }
4810
4815 typename decltype(chunks)::const_iterator it, end;
4816 size_t writedFromCurrentChunk;
4821 bool is_end() {
4822 return it == end;
4823 }
4824
4834 size_t store(K* buffer, size_t size) {
4835 size_t writed = 0;
4836 while (size && !is_end()) {
4837 size_t remain = it->second - writedFromCurrentChunk;
4838 size_t write = std::min(size, remain);
4839 ch_traits<K>::copy(buffer, it->first.get() + writedFromCurrentChunk, write);
4840 writed += write;
4841 remain -= write;
4842 size -= write;
4843 if (!remain) {
4844 ++it;
4845 writedFromCurrentChunk = 0;
4846 } else
4847 writedFromCurrentChunk += write;
4848 }
4849 return writed;
4850 }
4851 };
4852
4859 return {chunks.begin(), chunks.end(), 0};
4860 }
4861
4867 const auto& data() const {
4868 return chunks;
4869 }
4870};
4871
4872using stringa = sstring<u8s>;
4873using stringb = sstring<ubs>;
4874using stringw = sstring<wchar_t>;
4875using stringu = sstring<u16s>;
4876using stringuu = sstring<u32s>;
4877static_assert(sizeof(stringa) == (sizeof(void*) == 8 ? 24 : 16), "Bad size of sstring");
4878
4883template<typename T, typename A = allocator_hashstrmap<u8s, str_exact, T>>
4889template<typename T, typename A = allocator_hashstrmap<u8s, str_eqlia, T>>
4895template<typename T, typename A = allocator_hashstrmap<u8s, str_eqliu, T>>
4897
4902template<typename T, typename A = allocator_hashstrmap<ubs, str_exact, T>>
4908template<typename T, typename A = allocator_hashstrmap<ubs, str_eqlia, T>>
4914template<typename T, typename A = allocator_hashstrmap<ubs, str_eqliu, T>>
4916
4921template<typename T, typename A = allocator_hashstrmap<wchar_t, str_exact, T>>
4923
4928template<typename T, typename A = allocator_hashstrmap<wchar_t, str_eqlia, T>>
4930
4935template<typename T, typename A = allocator_hashstrmap<wchar_t, str_eqliu, T>>
4937
4942template<typename T, typename A = allocator_hashstrmap<u16s, str_exact, T>>
4948template<typename T, typename A = allocator_hashstrmap<u16s, str_eqlia, T>>
4954template<typename T, typename A = allocator_hashstrmap<u16s, str_eqliu, T>>
4956
4961template<typename T, typename A = allocator_hashstrmap<u32s, str_exact, T>>
4967template<typename T, typename A = allocator_hashstrmap<u32s, str_eqlia, T>>
4973template<typename T, typename A = allocator_hashstrmap<u32s, str_eqliu, T>>
4975
4976inline constexpr simple_str_nt<u8s> utf8_bom{"\xEF\xBB\xBF", 3}; // NOLINT
4977
4978inline namespace literals {
4979
4990SS_CONSTEVAL simple_str_nt<u8s> operator""_ss(const u8s* ptr, size_t l) {
4991 return simple_str_nt<u8s>{ptr, l};
4992}
4993
5003SS_CONSTEVAL simple_str_nt<ubs> operator""_ss(const ubs* ptr, size_t l) {
5004 return simple_str_nt<ubs>{ptr, l};
5005}
5006
5016SS_CONSTEVAL simple_str_nt<uws> operator""_ss(const uws* ptr, size_t l) {
5017 return simple_str_nt<uws>{ptr, l};
5018}
5019
5029SS_CONSTEVAL simple_str_nt<u16s> operator""_ss(const u16s* ptr, size_t l) {
5030 return simple_str_nt<u16s>{ptr, l};
5031}
5032
5043SS_CONSTEVAL simple_str_nt<u32s> operator""_ss(const u32s* ptr, size_t l) {
5044 return simple_str_nt<u32s>{ptr, l};
5045}
5046
5047template<typename K> using HashKey = StoreType<K, str_exact>;
5048template<typename K> using HashKeyIA = StoreType<K, str_eqlia>;
5049template<typename K> using HashKeyIU = StoreType<K, str_eqliu>;
5050
5061consteval HashKey<u8s> operator""_h(const u8s* ptr, size_t l) {
5062 return HashKey<u8s>{{ptr, l}, fnv_hash_compile(ptr, l)};
5063}
5064
5075consteval HashKeyIA<u8s> operator""_ia(const u8s* ptr, size_t l) {
5076 return HashKeyIA<u8s>{{ptr, l}, fnv_hash_ia_compile(ptr, l)};
5077}
5078
5089inline HashKeyIU<u8s> operator""_iu(const u8s* ptr, size_t l) {
5090 return HashKeyIU<u8s>{{ptr, l}, str_eqliu<u8s>::hash{}(simple_str<u8s>{ptr, l})};
5091}
5092
5103consteval HashKey<ubs> operator""_h(const ubs* ptr, size_t l) {
5104 return HashKey<ubs>{{ptr, l}, fnv_hash_compile(ptr, l)};
5105}
5106
5117consteval HashKeyIA<ubs> operator""_ia(const ubs* ptr, size_t l) {
5118 return HashKeyIA<ubs>{{ptr, l}, fnv_hash_ia_compile(ptr, l)};
5119}
5120
5131inline HashKeyIU<ubs> operator""_iu(const ubs* ptr, size_t l) {
5132 return HashKeyIU<ubs>{{ptr, l}, str_eqliu<u8s>::hash{}(simple_str<u8s>{(const u8s*)ptr, l})};
5133}
5134
5145consteval HashKey<u16s> operator""_h(const u16s* ptr, size_t l) {
5146 return HashKey<u16s>{{ptr, l}, fnv_hash_compile(ptr, l)};
5147}
5148
5159consteval HashKeyIA<u16s> operator""_ia(const u16s* ptr, size_t l) {
5160 return HashKeyIA<u16s>{{ptr, l}, fnv_hash_ia_compile(ptr, l)};
5161}
5162
5173inline HashKeyIU<u16s> operator""_iu(const u16s* ptr, size_t l) {
5174 return HashKeyIU<u16s>{{ptr, l}, str_eqliu<u16s>::hash{}(simple_str<u16s>{ptr, l})};
5175}
5176
5187consteval HashKey<u32s> operator""_h(const u32s* ptr, size_t l) {
5188 return HashKey<u32s>{{ptr, l}, fnv_hash_compile(ptr, l)};
5189}
5190
5201consteval HashKeyIA<u32s> operator""_ia(const u32s* ptr, size_t l) {
5202 return HashKeyIA<u32s>{{ptr, l}, fnv_hash_ia_compile(ptr, l)};
5203}
5204
5215inline HashKeyIU<u32s> operator""_iu(const u32s* ptr, size_t l) {
5216 return HashKeyIU<u32s>{{ptr, l}, str_eqliu<u32s>::hash{}(simple_str<u32s>{ptr, l})};
5217}
5218
5229consteval HashKey<uws> operator""_h(const uws* ptr, size_t l) {
5230 return HashKey<uws>{{ptr, l}, fnv_hash_compile(ptr, l)};
5231}
5232
5243consteval HashKeyIA<uws> operator""_ia(const uws* ptr, size_t l) {
5244 return HashKeyIA<uws>{{ptr, l}, fnv_hash_ia_compile(ptr, l)};
5245}
5246
5257inline HashKeyIU<uws> operator""_iu(const uws* ptr, size_t l) {
5258 return HashKeyIU<uws>{{ptr, l}, str_eqliu<uws>::hash{}(simple_str<uws>{ptr, l})};
5259}
5260} // namespace literals
5261
5272inline std::ostream& operator<<(std::ostream& stream, ssa text) {
5273 return stream << std::string_view{text.symbols(), text.length()};
5274}
5275
5286inline std::wostream& operator<<(std::wostream& stream, ssw text) {
5287 return stream << std::wstring_view{text.symbols(), text.length()};
5288}
5289
5300inline std::wostream& operator<<(std::wostream& stream, simple_str<wchar_type> text) {
5301 return stream << std::wstring_view{from_w(text.symbols()), text.length()};
5302}
5303
5314inline std::ostream& operator<<(std::ostream& stream, const stringa& text) {
5315 return stream << std::string_view{text.symbols(), text.length()};
5316}
5317
5328inline std::wostream& operator<<(std::wostream& stream, const stringw& text) {
5329 return stream << std::wstring_view{text.symbols(), text.length()};
5330}
5331
5342inline std::wostream& operator<<(std::wostream& stream, const sstring<wchar_type>& text) {
5343 return stream << std::wstring_view{from_w(text.symbols()), text.length()};
5344}
5345
5356template<size_t N, bool S, simstr::Allocatable A>
5357inline std::ostream& operator<<(std::ostream& stream, const lstring<u8s, N, S, A>& text) {
5358 return stream << std::string_view{text.symbols(), text.length()};
5359}
5360
5371template<size_t N, bool S, simstr::Allocatable A>
5372inline std::wostream& operator<<(std::wostream& stream, const lstring<uws, N, S, A>& text) {
5373 return stream << std::wstring_view{text.symbols(), text.length()};
5374}
5375
5386template<size_t N, bool S, simstr::Allocatable A>
5387inline std::wostream& operator<<(std::wostream& stream, const lstring<wchar_type, N, S, A>& text) {
5388 return stream << std::wstring_view{from_w(text.symbols()), text.length()};
5389}
5390
5391} // namespace simstr
5392
5397template<typename K>
5398struct std::formatter<simstr::simple_str<K>, K> : std::formatter<std::basic_string_view<K>, K> {
5399 // Define format() by calling the base class implementation with the wrapped value
5400 template<typename FormatContext>
5401 auto format(simstr::simple_str<K> t, FormatContext& fc) const {
5402 return std::formatter<std::basic_string_view<K>, K>::format({t.str, t.len}, fc);
5403 }
5404};
5405
5410template<typename K>
5411struct std::formatter<simstr::simple_str_nt<K>, K> : std::formatter<std::basic_string_view<K>, K> {
5412 // Define format() by calling the base class implementation with the wrapped value
5413 template<typename FormatContext>
5414 auto format(simstr::simple_str_nt<K> t, FormatContext& fc) const {
5415 return std::formatter<std::basic_string_view<K>, K>::format({t.str, t.len}, fc);
5416 }
5417};
5418
5423template<typename K>
5424struct std::formatter<simstr::sstring<K>, K> : std::formatter<std::basic_string_view<K>, K> {
5425 // Define format() by calling the base class implementation with the wrapped value
5426 template<typename FormatContext>
5427 auto format(const simstr::sstring<K>& t, FormatContext& fc) const {
5428 return std::formatter<std::basic_string_view<K>, K>::format({t.symbols(), t.length()}, fc);
5429 }
5430};
5431
5436template<typename K, size_t N, bool S, typename A>
5437struct std::formatter<simstr::lstring<K, N, S, A>, K> : std::formatter<std::basic_string_view<K>, K> {
5438 // Define format() by calling the base class implementation with the wrapped value
5439 template<typename FormatContext>
5440 auto format(const simstr::lstring<K, N, S, A>& t, FormatContext& fc) const {
5441 return std::formatter<std::basic_string_view<K>, K>::format({t.symbols(), t.length()}, fc);
5442 }
5443};
5444
5449template<>
5450struct std::formatter<simstr::simple_str<char8_t>, char> : std::formatter<std::basic_string_view<char>, char> {
5451 // Define format() by calling the base class implementation with the wrapped value
5452 template<typename FormatContext>
5453 auto format(simstr::simple_str<char8_t> t, FormatContext& fc) const {
5454 return std::formatter<std::basic_string_view<char>, char>::format({(const char*)t.str, t.len}, fc);
5455 }
5456};
5457
5462template<>
5463struct std::formatter<simstr::simple_str_nt<char8_t>, char> : std::formatter<std::basic_string_view<char>, char> {
5464 // Define format() by calling the base class implementation with the wrapped value
5465 template<typename FormatContext>
5466 auto format(simstr::simple_str_nt<char8_t> t, FormatContext& fc) const {
5467 return std::formatter<std::basic_string_view<char>, char>::format({(const char*)t.str, t.len}, fc);
5468 }
5469};
5470
5475template<>
5476struct std::formatter<simstr::sstring<char8_t>, char> : std::formatter<std::basic_string_view<char>, char> {
5477 // Define format() by calling the base class implementation with the wrapped value
5478 template<typename FormatContext>
5479 auto format(const simstr::sstring<char8_t>& t, FormatContext& fc) const {
5480 return std::formatter<std::basic_string_view<char>, char>::format({(const char*)t.symbols(), t.length()}, fc);
5481 }
5482};
5483
5488template<size_t N, bool S, typename A>
5489struct std::formatter<simstr::lstring<char8_t, N, S, A>, char> : std::formatter<std::basic_string_view<char>, char> {
5490 // Define format() by calling the base class implementation with the wrapped value
5491 template<typename FormatContext>
5492 auto format(const simstr::lstring<char8_t, N, S, A>& t, FormatContext& fc) const {
5493 return std::formatter<std::basic_string_view<char>, char>::format({(const char*)t.symbols(), t.length()}, fc);
5494 }
5495};
5496
5501template<>
5502struct std::formatter<simstr::simple_str<simstr::wchar_type>, wchar_t> : std::formatter<std::basic_string_view<wchar_t>, wchar_t> {
5503 // Define format() by calling the base class implementation with the wrapped value
5504 template<typename FormatContext>
5505 auto format(simstr::simple_str<simstr::wchar_type> t, FormatContext& fc) const {
5506 return std::formatter<std::basic_string_view<wchar_t>, wchar_t>::format({(const wchar_t*)t.str, t.len}, fc);
5507 }
5508};
5509
5514template<>
5515struct std::formatter<simstr::simple_str_nt<simstr::wchar_type>, wchar_t> : std::formatter<std::basic_string_view<wchar_t>, wchar_t> {
5516 // Define format() by calling the base class implementation with the wrapped value
5517 template<typename FormatContext>
5518 auto format(simstr::simple_str_nt<simstr::wchar_type> t, FormatContext& fc) const {
5519 return std::formatter<std::basic_string_view<wchar_t>, wchar_t>::format({(const wchar_t*)t.str, t.len}, fc);
5520 }
5521};
5522
5527template<>
5528struct std::formatter<simstr::sstring<simstr::wchar_type>, wchar_t> : std::formatter<std::basic_string_view<wchar_t>, wchar_t> {
5529 // Define format() by calling the base class implementation with the wrapped value
5530 template<typename FormatContext>
5531 auto format(const simstr::sstring<simstr::wchar_type>& t, FormatContext& fc) const {
5532 return std::formatter<std::basic_string_view<wchar_t>, wchar_t>::format({(const wchar_t*)t.symbols(), t.length()}, fc);
5533 }
5534};
5535
5540template<size_t N, bool S, typename A>
5541struct std::formatter<simstr::lstring<simstr::wchar_type, N, S, A>, wchar_t> : std::formatter<std::basic_string_view<wchar_t>, wchar_t> {
5542 // Define format() by calling the base class implementation with the wrapped value
5543 template<typename FormatContext>
5544 auto format(const simstr::lstring<simstr::wchar_type, N, S, A>& t, FormatContext& fc) const {
5545 return std::formatter<std::basic_string_view<wchar_t>, wchar_t>::format({(const wchar_t*)t.symbols(), t.length()}, fc);
5546 }
5547};
Класс для последовательного получения подстрок по заданному разделителю.
Определения strexpr.h:3230
my_type & operator<<(simple_str< K > data)
Добавление порции данных.
Определения sstring.h:4673
portion_store get_portion() const
Получить portion_store, через который можно последовательно извлекать данные во внешний буфер.
Определения sstring.h:4858
constexpr size_t length() const noexcept
Длина сохранённого текста.
Определения sstring.h:4738
my_type & operator<<(T data)
Добавление символа.
Определения sstring.h:4732
void reset()
Сбрасывает содержимое, но при этом не удаляет первый буфер, чтобы потом избежать аллокации.
Определения sstring.h:4742
void clear()
Очистить объект, освободив все выделенные буфера.
Определения sstring.h:4804
my_type & operator<<(const StrExprForType< K > auto &expr)
Добавление строкового выражения.
Определения sstring.h:4708
bool is_continuous() const
Проверяет, расположен ли весь текст одним непрерывным куском в памяти.
Определения sstring.h:4780
void out(const Op &o) const
Применяет функтор к каждому сохранённому буферу.
Определения sstring.h:4772
const auto & data() const
Получить внутренние буфера с данными.
Определения sstring.h:4867
const K * begin() const
Получить указатель на начало первого буфера. Имеет смысл применять только если is_continuous true.
Определения sstring.h:4797
Контейнер для более эффективного поиска по строковым ключам.
Определения sstring.h:4256
std::optional< Dst > get(const InStore &key) const
Поиск и извлечение значения.
Определения sstring.h:4486
bool lookup(const InStore &key, Dst &val) const
Поиск и извлечение значения.
Определения sstring.h:4449
std::optional< Dst > get(simple_str< K > key) const
Поиск и извлечение значения.
Определения sstring.h:4468
T * existed(simple_str< K > key)
Поиск существующего значения.
Определения sstring.h:4503
const T * existed(simple_str< K > key) const
Поиск существующего значения.
Определения sstring.h:4537
T * existed(const InStore &key)
Поиск существующего значения.
Определения sstring.h:4520
const T * existed(const InStore &key) const
Поиск существующего значения.
Определения sstring.h:4554
bool lookup(simple_str< K > key, Dst &val) const
Поиск и извлечение значения.
Определения sstring.h:4429
Класс мутабельной, владеющей строки. Содержит внутренний буфер для строк заданного размера.
Определения sstring.h:2751
constexpr void define_size()
Определить длину строки. Ищет символ 0 в буфере строки до его ёмкости, после чего устанавливает длину...
Определения sstring.h:3298
constexpr lstring(T &&value, Args &&... args)
Конструктор из строкового литерала.
Определения sstring.h:3024
my_type & operator=(T &&other)
Оператор присваивания строкового литерала.
Определения sstring.h:3169
constexpr void reset()
Делает строку пустой и освобождает внешний буфер, если он был.
Определения sstring.h:3333
@ LocalCapacity
Определения sstring.h:2759
constexpr bool is_local() const noexcept
Узнать, локальный или внешний буфер используется для символов.
Определения sstring.h:3289
my_type & operator=(my_type &&other) noexcept
Оператор присваивания перемещением из строки такого же типа.
Определения sstring.h:3112
constexpr size_t length() const noexcept
Длина строки.
Определения sstring.h:3192
constexpr lstring(s_str other, Args &&... args)
Конструктор из другого строкового объекта.
Определения sstring.h:2891
constexpr lstring(const From &f, s_str pattern, s_str repl, size_t offset=0, size_t maxCount=0, Args &&... args)
Конструктор из строкового источника с заменой.
Определения sstring.h:2961
constexpr lstring(size_t repeat, s_str pattern, Args &&... args)
Конструктор повторения строки.
Определения sstring.h:2906
constexpr lstring(const my_type &other)
Копирование из другой строки такого же типа.
Определения sstring.h:2980
constexpr lstring(const my_type &other, Args &&... args)
Копирование из другой строки такого же типа, но с другим аллокатором.
Определения sstring.h:3007
my_type & operator=(const StrExprForType< K > auto &expr)
Оператор присваивания строкового выражения.
Определения sstring.h:3182
constexpr K * reserve_no_preserve(size_t newSize)
Определения sstring.h:3227
my_type & operator=(const my_type &other)
Оператор присваивания копией из строки такого же типа.
Определения sstring.h:3095
constexpr bool is_empty() const noexcept
Пустая ли строка.
Определения sstring.h:3204
lstring(const Op &op, Args &&... args)
Конструктор заполнения с помощью функтора (см. str_mutable::fill).
Определения sstring.h:3066
constexpr K * set_size(size_t newSize)
Устанавливает размер текущей строки, при необходимости выделяя место.
Определения sstring.h:3272
constexpr lstring(size_t count, K pad, Args &&... args)
Конструктор повторения символа.
Определения sstring.h:2921
constexpr lstring(const StrExprForType< K > auto &expr, Args &&... args)
Конструктор из строкового выражения.
Определения sstring.h:2940
constexpr const K * symbols() const noexcept
Указатель на константные символы.
Определения sstring.h:3196
constexpr void clear()
Делает строку пустой, не меняя буфер строки.
Определения sstring.h:3329
my_type & operator=(simple_str< K > other)
Оператор присваивания из simple_str.
Определения sstring.h:3157
constexpr bool empty() const noexcept
Пустая ли строка, для совместимости с std::string.
Определения sstring.h:3208
constexpr void shrink_to_fit()
Уменьшает размер внешнего буфера до минимально возможного для хранения строки. Если строка уместится ...
Определения sstring.h:3315
constexpr lstring(my_type &&other) noexcept
Конструктор перемещения из строки такого же типа.
Определения sstring.h:3039
constexpr K * reserve(size_t newSize)
Выделить буфер, достаточный для размещения newSize символов плюс завершающий ноль.
Определения sstring.h:3249
constexpr K * str() noexcept
Указатель на буфер строки.
Определения sstring.h:3200
constexpr size_t capacity() const noexcept
Текущая ёмкость буфера строки.
Определения sstring.h:3212
constexpr lstring(Args &&... args) noexcept(std::is_nothrow_constructible_v< allocator_t, Args... >)
Создать пустой объект.
Определения sstring.h:2876
Класс иммутабельной владеющей строки.
Определения sstring.h:3444
constexpr my_type & operator=(const lstring< K, N, forShared, A > &other)
Оператор присвоения другой строки типа lstring.
Определения sstring.h:3788
constexpr bool empty() const noexcept
Пустая ли строка, для совместимости с std::string.
Определения sstring.h:3840
constexpr bool is_empty() const noexcept
Пустая ли строка.
Определения sstring.h:3836
sstring(s_str other, Args &&... args)
Конструктор из другого строкового объекта.
Определения sstring.h:3549
sstring(size_t count, K pad, Args &&... args)
Конструктор повторения символа.
Определения sstring.h:3579
constexpr const K * symbols() const noexcept
Указатель на символы строки.
Определения sstring.h:3828
constexpr sstring(const my_type &other) noexcept
Конструктор копирования строки.
Определения sstring.h:3635
static my_type format(const FmtString< to_std_char_t< K >, T... > &fmtString, T &&... args)
Получить строку, отформатированную с помощью std::format.
Определения sstring.h:3870
constexpr my_type & operator=(T &&other)
Оператор присвоения строкового литерала.
Определения sstring.h:3776
sstring(size_t repeat, s_str pattern, Args &&... args)
Конструктор повторения строки.
Определения sstring.h:3564
constexpr my_type & operator=(my_type other) noexcept
Оператор присвоения другой строки того же типа.
Определения sstring.h:3752
static my_type printf(const K *pattern, T &&... args)
Получить строку, отформатированную с помощью std::sprintf.
Определения sstring.h:3856
constexpr sstring(lstring< K, N, true, Allocator > &&src)
Конструктор перемещения из lstring с совместимым с sstring внешним буфером.
Определения sstring.h:3662
constexpr size_t length() const noexcept
Длина строки.
Определения sstring.h:3832
constexpr sstring(my_type &&other) noexcept
Конструктор перемещения.
Определения sstring.h:3646
static my_type vformat(simple_str< K > fmtString, T &&... args)
Получить строку, отформатированную с помощью std::vformat.
Определения sstring.h:3884
sstring(simple_str< O > init)
Инициализация из строкового источника с другим типом символов. Конвертирует через UTF.
Определения sstring.h:3727
constexpr my_type & operator=(simple_str< K > other)
Оператор присвоения другой строки другого типа.
Определения sstring.h:3764
constexpr my_type & make_empty() noexcept
Сделать строку пустой.
Определения sstring.h:3822
constexpr my_type & operator=(const StrExprForType< K > auto &expr)
Оператор присвоения строкового выражения.
Определения sstring.h:3813
sstring(T &&s, Args &&... args)
Инициализация из строкового литерала.
Определения sstring.h:3714
constexpr my_type & operator=(lstring< K, N, true, Allocator > &&other)
Оператор присвоения перемещаемой строки типа lstring с совместимым буфером.
Определения sstring.h:3800
constexpr sstring(const StrExprForType< K > auto &expr, Args &&... args)
Конструктор из строкового выражения.
Определения sstring.h:3598
sstring(Args &&... args) noexcept(std::is_nothrow_constructible_v< allocator_t, Args... >)
Конструктор пустой строки.
Определения sstring.h:3534
constexpr ~sstring()
Деструктор строки.
Определения sstring.h:3626
sstring(const From &f, s_str pattern, s_str repl, size_t offset=0, size_t maxCount=0, Args &&... args)
Конструктор из строкового источника с заменой.
Определения sstring.h:3619
Класс с дополнительными константными строковыми алгоритмами.
Определения sstring.h:193
bool starts_with_iu(str_piece prefix) const noexcept
Начинается ли строка с заданной подстроки без учёта регистра Unicode символов первой плоскости (<0xFF...
Определения sstring.h:266
int compare_iu(str_piece text) const noexcept
Сравнение строк посимвольно без учёта регистра Unicode символов первой плоскости (<0xFFFF).
Определения sstring.h:230
bool less_iu(str_piece text) const noexcept
Меньше ли строка другой строки посимвольно без учёта регистра Unicode символов первой плоскости (<0xF...
Определения sstring.h:252
constexpr bool ends_with_iu(str_piece suffix) const noexcept
Заканчивается ли строка указанной подстрокой без учёта регистра Unicode символов первой плоскости (<0...
Определения sstring.h:281
R upperred() const
Получить копию строки в верхнем регистре Unicode символов первой плоскости (<0xFFFF).
Определения sstring.h:293
constexpr std::optional< R > strip_prefix_iu(str_piece prefix) const
Получить строку без префикса, если она начинается с него без учёта регистра Unicode символов до 0xFFF...
Определения sstring.h:389
constexpr R trimmed_prefix_iu(str_piece prefix, size_t max_count=0) const
Возвращает строку, в которой удалено начало строки, если она начинается с указанного префикса без учё...
Определения sstring.h:427
R lowered() const
Получить копию строки в нижнем регистре Unicode символов первой плоскости (<0xFFFF).
Определения sstring.h:305
std::optional< double > to_double() const noexcept
Преобразовать строку в double.
Определения sstring.h:315
constexpr std::optional< R > strip_suffix_iu(str_piece suffix) const
Получить строку без суффикса, если она заканчивается им без учёта регистра Unicode символов до 0xFFFF...
Определения sstring.h:408
constexpr void as_number(T &t) const
Преобразовать строку в целое число.
Определения sstring.h:373
bool equal_iu(str_piece text) const noexcept
Равна ли строка другой строке посимвольно без учёта регистра Unicode символов первой плоскости (<0xFF...
Определения sstring.h:241
constexpr R trimmed_suffix_iu(str_piece suffix) const
Возвращает строку, в которой удалён конец строки, если она заканчивается указанным суффиксом без учёт...
Определения sstring.h:450
void as_number(double &t) const
Преобразовать строку в double.
Определения sstring.h:356
Базовый класс работы с изменяемыми строками
Определения sstring.h:1499
Impl & insert(size_t to, const A &expr)
Вставить строковое выражение в указанную позицию.
Определения sstring.h:2039
Impl & operator<<=(const Op &fillFunction)
Заполняет строку методом fill после конца строки.
Определения sstring.h:2313
Impl & append(const A &expr)
Добавить строковое выражение в конец строки.
Определения sstring.h:1923
Impl & operator<<(const Op &fillFunction)
Вызывает переданный функтор, передав ссылку на себя.
Определения sstring.h:2326
Impl & trim(str_piece pattern)
Удалить символы, входящие в переданную строку, в начале и в конце строки.
Определения sstring.h:1733
Impl & upper_only_ascii()
Преобразовать в верхний регистр ASCII символы.
Определения sstring.h:1797
Impl & lower_only_ascii()
Преобразовать в нижний регистр ASCII символы.
Определения sstring.h:1812
Impl & trim_left()
Удалить пробельные символы в начале строки.
Определения sstring.h:1635
Impl & append_printf(const K *format, T &&... args)
Добавляет отформатированный с помощью sprintf вывод в конец строки.
Определения sstring.h:2415
Impl & trim_right_with_wpaces(T &&pattern)
Удалить символы, входящие в строковый литерал, а также пробельные символы, в конце строки.
Определения sstring.h:1722
Impl & trim_left(str_piece pattern)
Удалить символы, входящие в переданную строку, в начале строки.
Определения sstring.h:1744
Impl & trim_with_spaces(T &&pattern)
Удалить символы, входящие в строковый литерал, а также пробельные символы, в начале и в конце строки.
Определения sstring.h:1696
Impl & prepend(str_piece other)
Добавить другую строку в начало строки.
Определения sstring.h:2063
Impl & append_formatted(const FmtString< fmt_type, T... > &format, T &&... args)
Добавляет отформатированный с помощью std::format вывод в конец строки.
Определения sstring.h:2553
my_type & format(const FmtString< fmt_type, T... > &pattern, T &&... args)
Определения sstring.h:2537
Impl & printf(const K *format, T &&... args)
Форматирует строку помощью sprintf.
Определения sstring.h:2399
Impl & with(const Op &fillFunction, Args &&... args)
Вызов функтора со строкой и переданными аргументами.
Определения sstring.h:2635
Impl & append_vformatted_n(size_t max_write, str_piece format, T &&... args)
Добавляет отформатированный с помощью std::vformat вывод в конец строки, записывая не более указанног...
Определения sstring.h:2621
Impl & operator<<(const Op &fillFunction)
Заполняет строку методом fill с нулевой позиции.
Определения sstring.h:2300
Impl & vformat(str_piece format, T &&... args)
Форматирует строку с помощью std::vformat.
Определения sstring.h:2569
Impl & change(size_t from, size_t len, const A &expr)
Заменить кусок строки на строковое выражение.
Определения sstring.h:2012
Impl & fill(size_t from, const Op &fillFunction)
Заполнение буфера строки с помощью функтора.
Определения sstring.h:2272
Impl & change(size_t from, size_t len, str_piece other)
Заменить кусок строки на другую строку.
Определения sstring.h:1996
Impl & remove(size_t from, size_t len)
Удалить часть строки.
Определения sstring.h:2052
Impl & trim_left_with_spaces(T &&pattern)
Удалить символы, входящие в строковый литерал, а также пробельные символы, в начале строки.
Определения sstring.h:1709
Impl & trim_left(T &&pattern)
Удалить символы, входящие в строковый литерал, в начале строки.
Определения sstring.h:1670
Impl & trim_right(T &&pattern)
Удалить символы, входящие в строковый литерал, в конце строки.
Определения sstring.h:1683
Impl & trim_right_with_spaces(str_piece pattern)
Удалить символы, входящие в переданную строку, а также пробельные символы, в конце строки.
Определения sstring.h:1788
Impl & append_in(size_t pos, str_piece other)
Добавить другую строку, начиная с заданной позиции.
Определения sstring.h:1963
Impl & vformat_from(size_t from, size_t max_write, str_piece format, T &&... args)
Добавляет отформатированный с помощью std::vformat вывод, начиная с указанной позиции.
Определения sstring.h:2502
Impl & trim_left_with_spaces(str_piece pattern)
Удалить символы, входящие в переданную строку, а также пробельные символы, в начале строки.
Определения sstring.h:1777
Impl & insert(size_t to, str_piece other)
Вставить строку в указанную позицию.
Определения sstring.h:2025
Impl & vformat_n(size_t max_write, str_piece format, T &&... args)
Форматирует строку с помощью std::vformat не более указанного размера.
Определения sstring.h:2603
Impl & printf_from(size_t from, const K *format, T &&... args)
Добавляет отформатированный с помощью sprintf вывод, начиная с указанной позиции.
Определения sstring.h:2345
Impl & operator+=(str_piece other)
Добавить другую строку в конец строки.
Определения sstring.h:1934
Impl & trim_right()
Удалить пробельные символы в конце строки.
Определения sstring.h:1644
Impl & append(str_piece other)
Добавить другую строку в конец строки.
Определения sstring.h:1911
Impl & trim_right(str_piece pattern)
Удалить символы, входящие в переданную строку, в конце строки.
Определения sstring.h:1755
Impl & trim_with_spaces(str_piece pattern)
Удалить символы, входящие в переданную строку, а также пробельные символы, в начале и в конце строки.
Определения sstring.h:1766
K * str() noexcept
Получить указатель на буфер строки.
Определения sstring.h:1608
Impl & prepend(const A &expr)
Добавить строковое выражение в начало строки.
Определения sstring.h:2075
Impl & trim()
Удалить пробельные символы в начале и в конце строки.
Определения sstring.h:1626
Impl & lower()
Преобразовать в нижний регистр Unicode символы первой плоскости (<0xFFFF).
Определения sstring.h:1846
Impl & replace(str_piece pattern, str_piece repl, size_t offset=0, size_t maxCount=0)
Заменить вхождения подстроки на другую строку.
Определения sstring.h:2092
Impl & upper()
Преобразовать в верхний регистр Unicode символы первой плоскости (<0xFFFF).
Определения sstring.h:1831
Impl & replace_from(const From &f, str_piece pattern, str_piece repl, size_t offset=0, size_t maxCount=0)
Скопировать строку-источник, заменив вхождения подстрок на другую строку.
Определения sstring.h:2210
Impl & append_vformatted(str_piece format, T &&... args)
Добавляет отформатированный с помощью std::vformat вывод в конец строки.
Определения sstring.h:2585
Impl & append_in(size_t pos, const A &expr)
Добавить строковое выражение, начиная с заданной позиции.
Определения sstring.h:1981
my_type & format_from(size_t from, const FmtString< fmt_type, T... > &format, T &&... args)
Определения sstring.h:2473
Impl & trim(T &&pattern)
Удалить символы, входящие в строковый литерал, в начале и в конце строки.
Определения sstring.h:1657
Impl & operator+=(const A &expr)
Добавить строковое выражение в конец строки.
Определения sstring.h:1946
constexpr str_piece to_str() const noexcept
Преобразовать себя в "кусок строки", включающий всю строку.
Определения strexpr.h:3469
constexpr str_piece slice(S start, E end) const noexcept
Получить часть строки как "str_src".
Определения strexpr.h:3574
constexpr size_t size() const
Определения strexpr.h:3410
constexpr str_piece prefix(E count) const noexcept
Обертка вокруг slice(0, count). Также позволяет задавать границу поисковым способом.
Определения strexpr.h:3659
constexpr str_piece tail(E count) const noexcept
Обертка вокруг slice(count, to_end). Также позволяет задавать границу поисковым способом.
Определения strexpr.h:3667
constexpr str_piece suffix(E count) const noexcept
Обертка вокруг slice(from_end(count), to_end). Также позволяет задавать границу поисковым способом.
Определения strexpr.h:3675
constexpr void as_number(T &t) const
Преобразовать строку в целое число.
Определения strexpr.h:4683
constexpr str_storable(Args &&... args)
Создать пустой объект.
Определения sstring.h:1062
void init_replaced(const From &f, s_str pattern, s_str repl, size_t offset=0, size_t maxCount=0)
Инициализация из строкового источника с заменой.
Определения sstring.h:1149
static my_type upperred_from(const From &f, Args &&... args)
Создать копию переданной строки в верхнем регистре символов Unicode первой плоскости (<0xFFFF).
Определения sstring.h:1343
constexpr void init_from_str_other(s_str other)
Инициализация из другого строкового объекта.
Определения sstring.h:1070
constexpr allocator_t & allocator()
Получить аллокатор.
Определения sstring.h:1039
constexpr void init_symb_repeat(size_t count, K pad)
Инициализация повторением символа.
Определения sstring.h:1106
constexpr void init_str_expr(const A &expr)
Инициализация из строкового выражения.
Определения sstring.h:1127
static my_type upperred_only_ascii_from(const From &f, Args &&... args)
Создать строку, копию переданной в верхнем регистре символов ASCII.
Определения sstring.h:1313
static my_type lowered_from(const From &f, Args &&... args)
Создать копию переданной строки в нижнем регистре символов Unicode первой плоскости (<0xFFFF).
Определения sstring.h:1360
constexpr void init_str_repeat(size_t repeat, s_str pattern)
Инициализация повторением строки.
Определения sstring.h:1086
static my_type lowered_only_ascii_from(const From &f, Args &&... args)
Создать копию переданной строки в нижнем регистре символов ASCII.
Определения sstring.h:1326
static my_type join(const T &strings, s_str delimiter, bool tail=false, bool skip_empty=false, Args &&... args)
Конкатенация строк из контейнера в одну строку.
Определения sstring.h:1262
static my_type replaced_from(const From &f, s_str pattern, s_str repl, size_t offset=0, size_t maxCount=0, Args &&... args)
Создать копию переданной строки с заменой подстрок.
Определения sstring.h:1381
constexpr s_str_nt to_nts(size_t from=0) const
Получить simple_str_nt, начиная с заданного символа.
Определения sstring.h:1206
Концепт типа, управляющего памятью
Определения sstring.h:1411
Концепт типа, управляющего памятью
Определения sstring.h:1391
Концепт типа, управляющего памятью
Определения sstring.h:1401
Концепт строкового выражения, совместимого с заданным типом символов.
Определения strexpr.h:525
Концепт типа, который не может модифицировать хранимую строку.
Определения sstring.h:987
Концепт типа, который может модифицировать хранимую строку.
Определения sstring.h:980
Концепт типа, который может сохранить строку.
Определения sstring.h:970
Небольшое пространство для методов работы со стандартными строками.
Определения strexpr.h:1596
Пространство имён для объектов библиотеки
Определения sstring.cpp:12
hashStrMap< u16s, T, str_eqlia, A > hashStrMapUIA
Тип хеш-словаря для char16_t строк, регистронезависимый поиск для ASCII символов.
Определения sstring.h:4949
hashStrMap< ubs, T, str_exact, A > hashStrMapB
Тип хеш-словаря для char8_t строк, регистрозависимый поиск.
Определения sstring.h:4903
hashStrMap< wchar_t, T, str_eqliu, A > hashStrMapWIU
Тип хеш-словаря для wchar_t строк, регистронезависимый поиск для Unicode символов до 0xFFFF.
Определения sstring.h:4936
hashStrMap< u16s, T, str_exact, A > hashStrMapU
Тип хеш-словаря для char16_t строк, регистрозависимый поиск.
Определения sstring.h:4943
hashStrMap< u8s, T, str_exact, A > hashStrMapA
Тип хеш-словаря для char строк, регистрозависимый поиск.
Определения sstring.h:4884
hashStrMap< u32s, T, str_exact, A > hashStrMapUU
Тип хеш-словаря для char32_t строк, регистрозависимый поиск.
Определения sstring.h:4962
hashStrMap< ubs, T, str_eqliu, A > hashStrMapBIU
Тип хеш-словаря для char8_t строк, регистронезависимый поиск для Unicode символов до 0xFFFF.
Определения sstring.h:4915
hashStrMap< wchar_t, T, str_eqlia, A > hashStrMapWIA
Тип хеш-словаря для wchar_t строк, регистронезависимый поиск для ASCII символов.
Определения sstring.h:4929
hashStrMap< u32s, T, str_eqliu, A > hashStrMapUUIU
Тип хеш-словаря для char32_t строк, регистронезависимый поиск для Unicode символов до 0xFFFF.
Определения sstring.h:4974
expr_utf< From, To > e_utf(simple_str< From > from)
Возвращает строковое выражение, преобразующую строку из одного типа символов в другой тип,...
Определения sstring.h:873
hashStrMap< ubs, T, str_eqlia, A > hashStrMapBIA
Тип хеш-словаря для char8_t строк, регистронезависимый поиск для ASCII символов.
Определения sstring.h:4909
hashStrMap< u8s, T, str_eqliu, A > hashStrMapAIU
Тип хеш-словаря для char строк, регистронезависимый поиск для Unicode символов до 0xFFFF.
Определения sstring.h:4896
hashStrMap< wchar_t, T, str_exact, A > hashStrMapW
Тип хеш-словаря для wchar_t строк, регистрозависимый поиск.
Определения sstring.h:4922
hashStrMap< u32s, T, str_eqlia, A > hashStrMapUUIA
Тип хеш-словаря для char32_t строк, регистронезависимый поиск для ASCII символов.
Определения sstring.h:4968
hashStrMap< u8s, T, str_eqlia, A > hashStrMapAIA
Тип хеш-словаря для char строк, регистронезависимый поиск для ASCII символов.
Определения sstring.h:4890
hashStrMap< u16s, T, str_eqliu, A > hashStrMapUIU
Тип хеш-словаря для char16_t строк, регистронезависимый поиск для Unicode символов до 0xFFFF.
Определения sstring.h:4955
Некоторые методы для работы с стандартными строками.
Определения strexpr.h:8056
Объект, позволяющий последовательно копировать содержимое в буфер заданного размера.
Определения sstring.h:4814
bool is_end()
Проверить, что данные ещё не кончились.
Определения sstring.h:4821
size_t store(K *buffer, size_t size)
Сохранить очередную порцию данных в буфер.
Определения sstring.h:4834
Генерирует строку на основе исходной, заменяя все ASCII прописные буквы (A-Z) на строчные.
Определения strexpr.h:7496
Генерирует строку на основе исходной, заменяя все ASCII строчные буквы (a-z) на прописные.
Определения strexpr.h:7473
Генерирует строку на основе исходной, заменяя все прописные буквы первой плоскости Юникода на строчны...
Определения sstring.h:957
Генерирует строку на основе исходной, заменяя все строчные буквы первой плоскости Юникода на прописны...
Определения sstring.h:934
Базовый класс для преобразования строковых выражений в стандартные строки
Определения strexpr.h:659
Строковое выражение для конвертации строк в разные виды UTF.
Определения sstring.h:835
Класс, заявляющий, что ссылается на нуль-терминированную строку.
Определения sstring.h:617
constexpr my_type to_nts(size_t from)
Получить нуль-терминированную строку, сдвинув начало на заданное количество символов.
Определения sstring.h:680
constexpr simple_str_nt(const std::basic_string< K, std::char_traits< K >, A > &s) noexcept
Конструктор из std::basic_string.
Определения sstring.h:669
constexpr simple_str_nt(T &&v) noexcept
Конструктор из строкового литерала.
Определения sstring.h:651
constexpr simple_str_nt(const K *p, size_t l) noexcept
Конструктор из указателя и длины.
Определения sstring.h:657
constexpr simple_str_nt(T &&p) noexcept
Явный конструктор из С-строки.
Определения sstring.h:642
Простейший класс иммутабельной не владеющей строки.
Определения sstring.h:481
constexpr simple_str(T &&v) noexcept
Конструктор из строкового литерала.
Определения sstring.h:497
constexpr K operator[](size_t idx) const
Получить символ из указанной позиции. Проверка границ не выполняется.
Определения sstring.h:561
constexpr my_type & remove_suffix(size_t delta)
Укорачивает строку на заданное количество символов.
Определения sstring.h:585
constexpr size_t length() const noexcept
Получить длину строки.
Определения sstring.h:518
constexpr const symb_type * symbols() const noexcept
Получить указатель на константный буфер с символами строки.
Определения sstring.h:525
constexpr my_type & remove_prefix(size_t delta)
Сдвигает начало строки на заданное количество символов.
Определения sstring.h:572
constexpr simple_str(const std::basic_string_view< K, std::char_traits< K > > &s) noexcept
Конструктор из std::basic_string_view.
Определения sstring.h:513
constexpr simple_str(const K *p, size_t l) noexcept
Конструктор из указателя и длины.
Определения sstring.h:502
constexpr simple_str(const std::basic_string< K, std::char_traits< K >, A > &s) noexcept
Конструктор из std::basic_string.
Определения sstring.h:508
constexpr bool is_empty() const noexcept
Проверить, не пуста ли строка.
Определения sstring.h:532
constexpr bool is_same(simple_str< K > other) const noexcept
Проверить, не указывают ли два объекта на одну строку.
Определения sstring.h:541
constexpr bool is_part_of(simple_str< K > other) const noexcept
Проверить, не является ли строка частью другой строки.
Определения sstring.h:550
Простейший класс иммутабельной не владеющей строки.
Определения strexpr.h:5513
constexpr const symb_type * symbols() const noexcept
Получить указатель на константный буфер с символами строки.
Определения strexpr.h:5560
Класс - источник строкового выражения для utf конвертации в другую кодировку.
Определения sstring.h:817