-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwany.h
2363 lines (2239 loc) · 121 KB
/
wany.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/** This file is part of the uFser project which is released under the MIT license.
* See file COPYING for full license details.
* Copyright 2024 Ericsson AB
*/
#pragma once
#include "ufser.h"
#include <memory>
#include <map>
#include <iostream>
#include <forward_list>
#include <atomic>
#define XSTR(x) STR(x)
#define STR(x) #x
#define LOC __FILE__ ":" XSTR(__LINE__)
using namespace std::string_literals;
namespace uf {
struct string_variant : public std::variant<std::string_view, std::string>
{
string_variant(std::string_view v) : std::variant<std::string_view, std::string>(v) {}
string_variant(std::string&& v) : std::variant<std::string_view, std::string>(std::move(v)) {}
operator std::string_view() const noexcept { if (index()) return std::get<1>(*this); else return std::get<0>(*this); }
operator std::string()&& { if (index()) return std::move(std::get<1>(*this)); else return std::string(std::get<0>(*this)); }
std::string_view as_view() const noexcept { return *this; }
std::string_view sub_view(uint32_t off, uint32_t len = -1) const noexcept { return as_view().substr(off, len); }
uint32_t size() const noexcept { return as_view().size(); }
bool empty() const noexcept { return as_view().empty(); }
bool operator ==(const std::string_view& sv) const noexcept { return as_view() == sv; }
bool operator ==(const string_variant& o) const noexcept { return as_view() == o.as_view(); }
bool has_view() const noexcept { return index() == 0; }
};
struct any_variant : public std::variant<any_view, any>
{
any_variant(any_view v) : variant<any_view, any>(v) {}
any_variant(any&& v) : variant<any_view, any>(std::move(v)) {}
operator any_view() const noexcept { if (has_view()) return std::get<0>(*this); else return std::get<1>(*this); }
any_view as_view() const noexcept { return *this; }
[[nodiscard]] std::string print(unsigned max_len = 0, std::string_view chars = {}, char escape_char = '%', bool json_like = false) const {
if (index())
return std::get<1>(*this).print(max_len, chars,escape_char, json_like);
return std::get<0>(*this).print(max_len, chars,escape_char, json_like);
}
bool has_view() const noexcept { return index() == 0; }
};
namespace impl {
inline std::string x_escape(std::string_view v) {
auto s = print_escaped(v);
for (size_t p = 0; p < s.size(); ++p)
if (s[p] == '%') {
s[p++] = '\\';
s.insert(p, 1, 'x');
}
return s;
}
/** A base class for (potentially) shared pointers for objects (potentially) with a refcount field.
* in case of 'has_refc' is set, 'object' must have a refc_inc() and refc_dec() function, both returning the (epheremal) new value of the refcount.
* 'object' must have get_memsize() to return how much to deallocate. May default to sizeof(object)*/
template <typename object, bool has_refc, template <typename> typename Allocator>
class shared_ref_base
{
protected:
object* p = nullptr;
void unref() const noexcept
{
if constexpr (has_refc) if (p && p->refc_dec() == 0) {
const size_t size = p->get_memsize();
p->~object();
Allocator<char>().deallocate((char*)(void*)p, size);
}
}
public:
constexpr static bool has_refcount = has_refc;
shared_ref_base() noexcept = default;
shared_ref_base(const shared_ref_base & o) noexcept : p(o.p) {
if constexpr (has_refc)
if (p) { [[maybe_unused]] auto c = p->refc_inc(); assert(c); }
}
shared_ref_base(shared_ref_base && o) noexcept : p(o.p) { o.p = nullptr; }
shared_ref_base& operator =(const shared_ref_base & o) noexcept {
if (this != &o) {
if constexpr (has_refc) {
unref();
if (o.p) { [[maybe_unused]] auto c = o.p->refc_inc(); assert(c); }
}
p = o.p;
}
return *this;
}
shared_ref_base& operator =(shared_ref_base && o) noexcept { if (this != &o) { unref(); p = o.p; o.p = nullptr; } return *this; }
~shared_ref_base() noexcept { unref(); }
bool operator ==(const shared_ref_base& o) const noexcept { return p == o.p; }
bool operator !=(const shared_ref_base& o) const noexcept { return p != o.p; }
void clear() noexcept { unref(); p = nullptr; }
object* operator ->() const noexcept { return p; }
object& operator *() const noexcept { return *p; }
explicit operator bool() const noexcept { return bool(p); }
auto get_refcount() noexcept { return has_refc && p ? p->get_refcount() : 0; } //returned value may be invalid right after if multi-threaded
};
/** A reference count. This makes the descendant objects
* non-copyable and non-movable as pointers point to it and
* any such operation would mess with the refcount.*/
class RefCount {
std::atomic<uint16_t> refcount = 1;
public:
RefCount() noexcept = default;
RefCount(const RefCount&) = delete;
RefCount(RefCount&&) noexcept = delete;
RefCount& operator=(const RefCount&) = delete;
RefCount& operator=(RefCount&&) = delete;
auto refc_inc() noexcept { return refcount.fetch_add(1, std::memory_order_acq_rel)+1; }
auto refc_dec() noexcept { return refcount.fetch_sub(1, std::memory_order_acq_rel)-1; }
auto get_refcount() const noexcept { return refcount.load(std::memory_order_relaxed); }
};
struct NoRefCount {};
/// A shared writable string view. Not thread safe
template <bool has_refc, template <typename> typename Allocator = std::allocator>
class sview : private std::conditional_t<has_refc, RefCount, NoRefCount> {
public:
class ptr : public shared_ref_base<sview, has_refc, Allocator> {
public:
using shared_ref_base<sview, has_refc, Allocator>::shared_ref_base;
using shared_ref_base<sview, has_refc, Allocator>::p;
constexpr static size_t memsize(size_t string_len) noexcept { return std::max(sizeof(sview), sizeof(sview) + string_len - 4); }
//Note: all sview ctors are noexcept, so no need to protect against
//exceptions during placement new that would cause leaks.
/** Create a read-only, non-owning or writeable, owning (latter is default). */
ptr(std::string_view sv, bool copy = true) {
void* mem = Allocator<char>().allocate(memsize(sv.length()));
p = copy ? new(mem) sview(sv.length(), sv.data()) : new(mem) sview(sv);
}
/** Create a read-only, non-owning or writeable, owning (latter is default). */
ptr(const char *sv, bool copy = true)
{
const size_t len = strlen(sv);
void* mem = Allocator<char>().allocate(memsize(len));
p = copy ? new(mem) sview(len, sv) : new(mem) sview(std::string_view(sv, len));
}
/** Create a read-only, non-owning or writeable, owning (latter is default). */
ptr(uint32_t len, const char* sv, bool copy = true) {
void* mem = Allocator<char>().allocate(memsize(len));
p = copy ? new(mem) sview(len, sv) : new(mem) sview(std::string_view(sv, len));
}
/** Create a writable, non-owning or owning (latter is default). */
ptr(std::string& ss, bool copy = true) {
void* mem = Allocator<char>().allocate(memsize(ss.length()));
p = copy ? new(mem) sview(ss.length(), ss.data()) : new(mem) sview(ss);
}
/** Create a writable, owning. Always copy. */
ptr(std::string&& ss) {
void* mem = Allocator<char>().allocate(memsize(ss.length()));
p = new(mem) sview(ss.length(), ss.data());
}
/** Create a writable, non-owning or owning (latter is default). */
ptr(char *ss, bool copy = true)
{
const size_t len = strlen(ss);
void* mem = Allocator<char>().allocate(memsize(len));
p = copy ? new(mem) sview(len, ss) : new(mem) sview(ss);
}
/** Create a writable, non-owning or owning (latter is default). */
ptr(uint32_t len, char* ss, bool copy = true) {
void* mem = Allocator<char>().allocate(memsize(len));
p = copy ? new(mem) sview(len, ss) : new(mem) sview(ss, len);
}
/** Create a non-owning, non-writeable from a C string literal. */
template <uint32_t LEN>
ptr(const char (&c)[LEN]) : ptr(std::string_view(c, LEN-1), false) {assert(c[LEN-1]==0);} //null terminated string literal
/** Create a fresh, uninitialized, owning, writable string of size 'l'. */
ptr(uint32_t l) {
void* mem = Allocator<char>().allocate(memsize(l));
p = new(mem) sview(l);
}
/** Creates a copy of this string, trimmed & writable. */
ptr clone(uint32_t off_ = 0, uint32_t len_ = (uint32_t)-1) const {
assert(p);
assert(off_ <= p->length);
len_ = std::min(len_, p->length - off_);
ptr ret;
void* mem = Allocator<char>().allocate(memsize(len_));
ret.p = new(mem) sview(len_, p->data() + off_); //copy
return ret;
}
};
friend class shared_ref_base<sview, has_refc, Allocator>;
uint32_t size() const noexcept { return length; }
const char* data() const noexcept { return owning ? data_ : ptr_; }
std::string_view as_view() const noexcept { return { data(), size() }; }
char* data_writable() noexcept { assert(is_writable()); return owning ? data_ : ptr_; }
bool is_writable() const noexcept { return writable.load(std::memory_order_acquire); }
bool is_unique() const noexcept { if constexpr (has_refc) return this->get_refcount() == 1; else return false; } //We are never unique if we do not manage refcount
void make_read_only() noexcept { writable.store(false, std::memory_order_release); }
private:
const uint32_t length;
std::atomic_bool writable;
public:
bool const owning;
constexpr size_t get_memsize() const noexcept { return owning ? ptr::memsize(length) : sizeof(sview); }
private:
union {
char* const ptr_; //if we are non-owning
struct { char data_[]; }; //if we are owning
};
//delete the big five. The latter four would mess with the refount.
sview() = delete;
explicit sview(std::string_view s) noexcept : length(s.length()), writable(false), owning(false), ptr_(const_cast<char*>(s.data())) {}
explicit sview(std::string &s) noexcept : length(s.length()), writable(true), owning(false), ptr_(s.data()) {}
explicit sview(char *c, uint32_t len) noexcept : length(len), writable(true), owning(false), ptr_(c) {}
explicit sview(uint32_t l, const char *initial_data=nullptr) noexcept
: length(l), writable(true), owning(true) { if (initial_data && l) memcpy(data_, initial_data, l); }
~sview() noexcept = default;
};
/// A chunk of a serialized uf::any that holds either a (part of a) typestring or some part of the value string.
/// If a value string, it should contain one or more full basic types' worth of data.
/// The chunk is a view into either a read-only area, or a managed sview
template <bool has_refc, template <typename> typename Allocator= std::allocator>
class chunk : private std::conditional_t<has_refc, RefCount, NoRefCount> {
using sview_ptr = typename sview<has_refc, Allocator>::ptr;
sview_ptr root; ///< a managed underlying string object. Never null;
uint32_t off; ///< offset inside root
uint32_t len; ///< size of this view
/** Allocate a new owning/writable chunk */
explicit chunk(uint32_t l) : root(l), off(0), len(l)
{ assert(l <= std::numeric_limits<decltype(len)>::max()); }
/** Sub-chunk of an existing shared string (writable or non-writable alike) */
explicit chunk(char const* b, uint32_t l, sview_ptr&& r) noexcept :
root(std::move(r)), off(b - root->data()), len(l) {
assert(l <= std::numeric_limits<decltype(len)>::max());
assert(!l || root);
assert(!l || b >= root->data());
assert(!l || b + l <= root->data() + root->size());
}
/** Create chunk from an sview in its entirety. */
explicit chunk(sview_ptr&& r) noexcept :
root(std::move(r)), off(0), len(root ? root->size() : 0) {}
public:
class ptr : public shared_ref_base<chunk, has_refc, Allocator>
{
using shared_ref_base<chunk, has_refc, Allocator>::p;
public:
using shared_ref_base<chunk, has_refc, Allocator>::shared_ref_base;
explicit ptr(uint32_t l) {
char* mem = Allocator<char>().allocate(sizeof(chunk));
//This chunk ctor may throw, so deallocate if it does.
try { p = new(mem) chunk(l); }
catch (...) { Allocator<char>().deallocate(mem, sizeof(chunk)); throw; }
}
/** Sub-chunk of an existing shared string (writable or non-writable alike) */
explicit ptr(char const* b, uint32_t l, sview_ptr&& r)
{ p = new(Allocator<char>().allocate(sizeof(chunk))) chunk(b, l, std::move(r)); } //non-throwing chunk ctor
/** Create chunk from an sview in its entirety. */
explicit ptr(sview_ptr&& r)
{ p = new(Allocator<char>().allocate(sizeof(chunk))) chunk(std::move(r)); } //non-throwing chunk ctor
ptr& operator++() noexcept {
if (p) *this = p->next;
return *this;
}
using difference_type = std::ptrdiff_t;
using iterator_category = std::input_iterator_tag;
using value_type = chunk const;
using pointer = chunk const*;
using reference = chunk const&;
};
friend class shared_ref_base<chunk, has_refc, Allocator>;
ptr next;///< The next item in a forward list of chunks connected to the same wview
static constexpr size_t get_memsize() noexcept { return sizeof(chunk); }
char const* data() const noexcept { return root ? root->data() + off : nullptr; }
char* data_writable() noexcept {
if (!root) return nullptr;
//since for writable only we own 'root' (refocunt must be 1),
//there is no chance of a change of writable status between this check and the final line
if (!root->is_writable()) {
root = root.clone(off, len);
off = 0;
}
return root->data_writable()+off;
}
uint32_t size() const noexcept { return len; }
std::string_view as_view() const noexcept {return std::string_view{data(), size()}; }
/// @name Chunk pointer builders
/// @{
/// Creates a chunk from us using offset and length. The next field is set to null. Excess length is trimmed.
ptr sub_chunk(uint32_t offset, uint32_t l = -1) const {
assert(offset <= size());
return ptr(data() + offset, std::min(size() - offset, l), sview_ptr(root));
}
/// Creates copy of us with next set to null.
ptr clone() const { return sub_chunk(0); }
/// @}
/** Ensures that the current chunk is writable, and at least this big and returns a writable char array.
* If not writable or not large enough, we allocate (and loose existing content)
* We pay attention to preserve the 'next' field.*/
char* reserve(decltype(len) l) & {
if (!is_writable() || l > len) {
root = sview_ptr(l);
off = 0;
len = l;
}
return data_writable();
}
/** Resizes the chunk. If we need to enlarge, we re-allocate and loose existing content.
* We pay attention to preserve the 'next' field.*/
chunk& resize(uint32_t l) & { if (l > len) reserve(l); else len = l; return *this; }
bool is_writable() const noexcept { return root && root->is_writable(); }
/** Assigns content to us, by ensuring we are writable and then copying over.
* We pay attention to preserve the 'next' field.*/
chunk& assign(std::string_view s) & {
memcpy(reserve(s.size()), s.data(), s.size());
len = s.size();
return *this;
}
/** Ensure that either it is a non-writable swview or I have it for myself.
* If read-only is set then it is ensured that the resulting sview will be
* read-only.*/
chunk& unshare() & {
if (!is_writable()) return *this;
if (root->is_unique()) return *this;
root = root.clone(off, len);
off = 0;
return *this;
}
/** Assigns content to us.
* We pay attention to preserve the 'next' field.*/
chunk& assign(sview_ptr s) & {
root = std::move(s);
off = 0;
len = root->size();
return *this;
}
/** Copy content to us from another chunk.
* We pay attention to *copy* the 'next' field, as well.*/
chunk& copy_from(const chunk &c) & {
root = c.root;
off = c.off;
len = c.len;
next = c.next;
return *this;
}
/** Swap our content with that of another chunk.
* We pay attention to swap the 'next' field, as well.*/
void swap_content_with(chunk& c)
{
std::swap(root, c.root);
std::swap(off, c.off);
std::swap(len, c.len);
std::swap(next, c.next);
}
/** We reset the chunk to be the empty chunk. We also clear the 'next' field.*/
void reset() { root = {}; len = 0; next = {}; }
/** Try appending a chunk if it follows us directly in memory.
* Return false if failed. */
bool try_append(const chunk& ch) {
if (root == ch.root && off + len == ch.off) { len += ch.len; return true; }
return false;
}
operator std::string() const { return uf::concat("chunk{len: ", len, ", buf: \"", x_escape(as_view()), "\", mode: \"",
is_writable() ? "" : "non-", "writable\""
/*", next: " + std::to_string(uint32_t(next.get())) + ", root: " + std::to_string(uint32_t(root.get())) +*/ "}"); }
// better use std::ostringstream s; s << (void const *)ptr; s.str();
// or even usafge count from root, etc
std::string ATTR_NOINLINE__ print() const { return uf::concat('\"', x_escape(as_view()), "\"[", len, is_writable() ? "]*" : "]"); }
};
template <bool has_refc, template <typename> typename Allocator>
inline std::string to_string(typename chunk<has_refc, Allocator>::ptr i) { return i ? std::string(*i) : ""; }
/** Clones a linked list of chunks ['begin'..'end'). It also clones the underlying sviews if not read-only.
* If 'into' is empty, a new first element will be allocated. If not empty, the first element will be copied to
* 'into'. The end will point to 'new_end'.
* If into is the same as begin, then we create a new chunk in it - effectively creating a new chunk list head.
* @returns the last chunk ('next' member of which was set to 'new_end')*/
template <bool has_refc, template <typename> typename Allocator>
inline typename chunk<has_refc, Allocator>::ptr
clone_into(typename chunk<has_refc, Allocator>::ptr& into,
typename chunk<has_refc, Allocator>::ptr begin,
typename chunk<has_refc, Allocator>::ptr end,
typename chunk<has_refc, Allocator>::ptr new_end = {})
{
assert(begin);
assert(begin != end);
//First create a copy of chunks with merging if possible
//Note that 'into' may be in the middle of the 'begin'->'end'
//chunk chain, so we will not modify it while creating this copy.
auto out = begin->clone();
auto start = out;
for (auto in = begin->next; in != end; in = in->next)
if (!out->try_append(*in)) //optimize consecutive chunks
out->next = in->clone(), out = out->next;
out->next = new_end;
//Only after we have created the copy shall we modify 'begin' as 'begin may be part of the chain we have copied.
if (into == begin || !into)
into = std::move(start);
else
into->copy_from(*start);
//Then make the (potentially merged) sviews read-only or single-owner
for (auto c = into; c!=new_end; c = c->next)
c->unshare();
return out;
}
/** Helper to create a fresh copy of a linked list of chunks.
* 'new_end' is set at the last element.*/
template <bool has_refc, template <typename> typename Allocator>
inline typename chunk<has_refc, Allocator>::ptr clone_anew(typename chunk<has_refc, Allocator>::ptr begin,
typename chunk<has_refc, Allocator>::ptr end,
typename chunk<has_refc, Allocator>::ptr new_end = {})
{
typename chunk<has_refc, Allocator>::ptr c;
clone_into<has_refc, Allocator>(c, begin, end, new_end);
return c;
}
template <bool has_refc, template <typename> typename Allocator>
inline void copy_into(std::string_view what,
typename chunk<has_refc, Allocator>::ptr& into,
typename chunk<has_refc, Allocator>::ptr end = {})
{
if (into)
into->assign(what);
else
into = typename chunk<has_refc, Allocator>::ptr(typename sview<has_refc, Allocator>::ptr(what));
into->next = end;
}
/// @return a (char*,len) pair to the whole range if it is consecutive in memory,
/// (may also be a a single empty chunk: {"",0}), or an empty optional if not consecutive
template <bool has_refc, template <typename> typename Allocator>
inline std::optional<std::string_view>
get_consecutive(typename chunk<has_refc, Allocator>::ptr from,
typename chunk<has_refc, Allocator>::ptr const to) noexcept {
if (!from || from==to)
return std::string_view{};
auto b = from->data();
auto l = from->size();
for (++from; from && from != to; l += from->size(), ++from)
if (from->size() && b + l != from->data())
return {};
return std::string_view{b,l};
}
/// @return the size required for storing the chunks in the given range
template <bool has_refc, template <typename> typename Allocator>
inline uint32_t flatten_size(typename chunk<has_refc, Allocator>::ptr from,
typename chunk<has_refc, Allocator>::ptr to) noexcept
{
return std::accumulate(std::move(from), std::move(to), uint32_t{ 0 }, [](uint32_t n, auto &i) { return n + i.size(); });
}
/// Stores chunk data starting at the given address.
/// @param buf is assumed to accomodate flatten_size(from,to) bytes
template <bool has_refc, template <typename> typename Allocator>
inline void flatten_to(typename chunk<has_refc, Allocator>::ptr from,
typename chunk<has_refc, Allocator>::ptr to,
char *buf) noexcept {
std::for_each(std::move(from), std::move(to), [&](auto& i) { memcpy(buf, i.data(), i.size()); buf += i.size(); });
}
template <bool has_refc, template <typename> typename Allocator>
inline string_variant flatten(typename chunk<has_refc, Allocator>::ptr from,
typename chunk<has_refc, Allocator>::ptr to)
{
if (auto v = get_consecutive<has_refc, Allocator>(from, to)) return *v;
std::string ret;
ret.resize(flatten_size<has_refc, Allocator>(from, to));
flatten_to<has_refc, Allocator>(std::move(from), std::move(to), ret.data());
return ret;
}
/// Checks if [from1,off1->to1) starts with the content of [from2,off2->last2,last2_off2)
template <bool has_refc, template <typename> typename Allocator>
inline bool startswidth(typename chunk<has_refc, Allocator>::ptr from1, size_t off1,
typename chunk<has_refc, Allocator>::ptr const to1,
typename chunk<has_refc, Allocator>::ptr from2, size_t off2,
typename chunk<has_refc, Allocator>::ptr const last2, size_t last2_off) noexcept {
while (true) {
assert(from2); if (!from2) return false;
if (from2==last2) {
if (off2>=last2_off) return true;
} else if (from2->size()<=off2) {
from2 = from2->next;
off2 = 0;
continue;
}
if (from1==to1) return false;
assert(from1); if (!from1) return false;
if (from1->size()<=off1) {
from1 = from1->next;
off1 = 0;
continue;
}
const size_t size2 = from2==last2 ? last2_off : from2->size();
const int len = std::min(from1->size()-off1, size2-off2);
if (memcmp(from1->data()+off1, from2->data()+off2, len)) return false;
off1 += len;
off2 += len;
}
}
/// Call the functor with each non-empty chunk
template <bool has_refc, template<typename> typename Allocator, typename F>
inline void for_nonempty(typename chunk<has_refc, Allocator>::ptr const from,
typename chunk<has_refc, Allocator>::ptr const to,
F&& f)
{ std::for_each(from, to, [f=std::move(f)](auto& i){ if (i.size()) f(i); }); }
/// Return the first non-empty chunk, or null
template <bool has_refc, template <typename> typename Allocator>
inline typename chunk<has_refc, Allocator>::ptr const
find_nonempty(typename chunk<has_refc, Allocator>::ptr const from,
typename chunk<has_refc, Allocator>::ptr const to = {}) noexcept {
auto i = std::find_if(from, to, [](auto& i){ return i.size(); });
return i != to ? i : typename chunk<has_refc, Allocator>::ptr{};
}
/// Return the chunk before 'what' or null if 'what' is not on the list or equal to 'from'
/// 'what' may be equal to 'to'
template <bool has_refc, template <typename> typename Allocator>
inline typename chunk<has_refc, Allocator>::ptr
find_before(typename chunk<has_refc, Allocator>::ptr const &what,
typename chunk<has_refc, Allocator>::ptr const& from,
typename chunk<has_refc, Allocator>::ptr const& to = {}) noexcept
{
auto i = std::find_if(from, to, [&what](auto& c) { return what == c.next; });
return i != to ? i : typename chunk<has_refc, Allocator>::ptr{};
}
/** Find the chunk+offset that is 'off' bytes further.
* Return true if we have run out of chunks - in that case the value in 'ch_off' is undetermined.
* It is also possible to have a ch_off.second that is already pointing beyond the end of ch_off.first.*/
template <bool has_refc, template <typename> typename Allocator>
inline bool advance(typename std::pair<typename chunk<has_refc, Allocator>::ptr, uint32_t>& ch_off,
uint32_t off,
typename chunk<has_refc, Allocator>::ptr const& to = {})
{
assert(ch_off.first);
ch_off.second += off;
while (ch_off.first != to && ch_off.first->size() <= off)
ch_off.second -= ch_off.first->size(), ch_off.first = ch_off.first->next;
return ch_off.first == to;
}
/// Append a comma separated text rep of the chunks.
template <bool has_refc, template <typename> typename Allocator>
inline void append_to(std::string& out, typename chunk<has_refc, Allocator>::ptr const from, typename chunk<has_refc, Allocator>::ptr const to = {}) {
bool first = true;
for_nonempty<has_refc, Allocator>(from, to, [&](auto& i) { if (!first) out.append(", "); out.append(std::string(i)); first = false; });
}
/// Append a -> separated print() of the chunks.
template <bool has_refc, template <typename> typename Allocator>
inline void append_to_print(std::string& out, typename chunk<has_refc, Allocator>::ptr const from, typename chunk<has_refc, Allocator>::ptr const to = {}) {
bool first = true;
for_nonempty<has_refc, Allocator>(from, to, [&](auto& i) { if (!first) out.append("->"); out.append(i.print()); first = false; });
}
/** Chop up a chunk such that the part identified by off/len is in a chunk of its own.
* We keep the split sub-chunks properly linked.
* @Returns the new chunk. We assert that off/len is fully inside 'c'.*/
template <bool has_refc, template <typename> typename Allocator>
typename chunk<has_refc, Allocator>::ptr split(typename chunk<has_refc, Allocator>::ptr c, uint32_t off, uint32_t len) {
assert(c);
assert(off + len <= c->size());
// Four cases:
if (off + len >= c->size()) { //The element is aligned to the end of 'c'
if (off) { //The element is aligned to the end, but not at the beginning
auto elem = c->sub_chunk(off, len);
elem->next = c->next;
c->resize(off).next = elem;
return elem;
} else //The element is the whole of 'c'
return c;
} else { //The element is not aligned to the end
if (off == 0) { // the element is at the beginning of this chunk
auto rest = c->sub_chunk(len);
rest->next = c->next;
c->resize(len).next = rest;
return c;
} else { //there is unparsed stuff both before and after the new elem
auto elem = c->sub_chunk(off, len);
auto rest = c->sub_chunk(off + len);
elem->next = rest;
rest->next = c->next;
c->resize(off).next = elem;
return elem;
}
}
}
/** Split a chunk into two.
* If off==size(), nothing happens and we return c->next (even if off==0)
* If off==0, but size()>0 nothing happens and we return c.
* We keep the split sub-chunks properly linked.
* @Returns the new chunk. We assert that off<size().*/
template <bool has_refc, template <typename> typename Allocator>
typename chunk<has_refc, Allocator>::ptr split(typename chunk<has_refc, Allocator>::ptr c, uint32_t off)
{
assert(c);
assert(off <= c->size());
if (off == c->size()) return c->next;
if (!off) return c;
auto ret = c->sub_chunk(off);
ret->next = std::move(c->next);
c->resize(off);
c->next = ret;
return ret;
}
/** Inserts a zero length chunk between 'c' and 'c->next'.*/
template <bool has_refc, template <typename> typename Allocator>
typename chunk<has_refc, Allocator>::ptr insert_empty_chunk_after(typename chunk<has_refc, Allocator>::ptr c)
{
typename chunk<has_refc, Allocator>::ptr ret(0);
ret->next = std::move(c->next);
c->next = ret;
return ret;
}
/** Returns the first 'n' member of a tuple type.
* if n==0 we return 't'.
* if n==1 we allow 't' to be a non-tuple type (and return 't'),
* but for tuple types, we return the first member.
* For n>1 we return the concatenated types of the first n members.
* @returns a human readable text on error.*/
inline std::pair<std::string_view, std::string> parse_tuple_type(std::string_view t, int n) {
if (t.empty()) return{{}, "Empty type."};
if (n<0) return {{}, uf::concat("Negative number of requested elements: ", n)};
if (n==0) return {t, {}};
if (t.front()!='t') {
if (n==1) return {t, {}};
return {{}, "Non-tuple type."};
}
t.remove_prefix(1);
int size = 0;
while (t.size() && '0'<=t.front() && t.front()<='9') {
size = size*10 + t.front() - '0';
t.remove_prefix(1);
}
if (size<2) return {{}, std::string{ser_error_str(ser::num)}};
if (n>size) return {{}, uf::concat("Tuple of size ", size, " too small for requested ", n, " elements.")};
std::string_view ret = t;
size_t len = 0;
if (n==0) n = 1;
while (n--)
if (auto [l, problem] = uf::impl::parse_type(t, false); !problem) {
t.remove_prefix(l);
len += l;
} else
return {{}, std::string{ser_error_str(problem)}};
return {ret.substr(0, len), {}};
}
/// A writable view of a serialized uf:: something
template <bool has_refc, template <typename> typename Allocator= std::allocator>
class wview : private std::conditional_t<has_refc, RefCount, NoRefCount>{
using sview_ptr = typename sview<has_refc, Allocator>::ptr;
using chunk_ptr = typename chunk<has_refc, Allocator>::ptr;
public:
class ptr : public shared_ref_base<wview, has_refc, Allocator>
{
using shared_ref_base<wview, has_refc, Allocator>::p;
public:
using shared_ref_base<wview, has_refc, Allocator>::shared_ref_base;
using shared_ref_base<wview, has_refc, Allocator>::clear;
/** This constructor is technically public, since we need it when emplacing to 'children'
* Do not use otherwise.*/
explicit ptr(chunk_ptr&& tb, chunk_ptr&& te,
chunk_ptr&& vb, const chunk_ptr& ve, wview *parent)
{ p = new(Allocator<char>().allocate(sizeof(wview))) wview(std::move(tb), std::move(te), std::move(vb), ve, parent); } //noexcept wview ctor
/** Construct a wview from a read-only or writable type/value pair.
* Note that sview::ptr can be initialized from std::string_view or std::string{&,&&} with
* an optional second bool parameter, which dictates if we copy the data or the lifetime of
* the provided object outlives the wview created. (Defaults to true, meaning copy.)
* For std::string&& no second parameter is possible, we make a copy in any case.
* For (std::string&, false) the memory provided will be written in case the wview is modified.
* (But it no longer may be used as a serialized value or a coherent typestring, it becomes
* essentially random.)*/
explicit ptr(sview_ptr &&t, sview_ptr &&v) {
char* mem = Allocator<char>().allocate(sizeof(wview));
try { p = new(mem) wview(std::move(t), std::move(v)); }
catch (...) { Allocator<char>().deallocate(mem, sizeof(wview)); throw; }
}
/** Construct a wview from a read-only or writable serialized any.
* Note that sview::ptr can be initialized from std::string_view or std::string{&,&&} with
* an optional second bool parameter, which dictates if we copy the data or the lifetime of
* the provided object outlives the wview created. (Defaults to true, meaning copy.)
* For std::string&& no second parameter is possible, we make a copy in any case.
* For (std::string&, false) the memory provided will be written in case the wview is modified.
* (But it no longer may be used as a serialized value or a coherent typestring, it becomes
* essentially random.)*/
explicit ptr(sview_ptr&& raw) {
char* mem = Allocator<char>().allocate(sizeof(wview));
try { p = new(mem) wview(std::move(raw)); }
catch (...) { Allocator<char>().deallocate(mem, sizeof(wview)); throw; }
}
/** Constructs a wview by serializing a C++ type.*/
template<typename T>
explicit ptr(T const& t) {
static_assert(is_serializable_v<T>);
char* mem = Allocator<char>().allocate(sizeof(wview));
try { p = new(mem) wview(t); }
catch (...) { Allocator<char>().deallocate(mem, sizeof(wview)); throw; }
}
/** Construct a wview from an any. If you write anything in the resulting wview,
* the memory area of the 'any' may be overwritten rendering the 'any' invalid.
* Thus do not use the supplied 'any' after this ctor - but keep it allocated
* as the resulting wview refers to it. The lifetime of the supplied 'any'
* (even if it enters an undefined, but destoryable state) shall be longer than
* that of the resulting wview.
* This is done to save on memory allocations and copies. If you want the
* 'any' to remain utouched, use a const ref or an any_view.*/
explicit ptr(uf::from_raw_t, uf::any& a)
: ptr(sview_ptr(a.type().size(), const_cast<char*>(a.type().data()), false),
sview_ptr(a.value().size(), const_cast<char*>(a.value().data()), false)) {}
/** Construct a wview from an any_view. This is a no-copy operation.
* The lifetime of the resulting wview shall be shorter than that of 'a'.*/
explicit ptr(uf::from_raw_t, const uf::any_view& a)
: ptr(sview_ptr(a.type(), false),
sview_ptr(a.value(), false)) {}
ptr() noexcept = default;
ptr(const ptr&) noexcept = default;
ptr(ptr&&) noexcept = default;
/** To avoid wv1[0] = wv2 type of operations.
* These are a no-op (assigning one iterator to a temporary iterator)
* and are almost always 'intend wv1[0].set(wv2)'. */
ptr&& operator =(const ptr&) && = delete;
ptr& operator =(const ptr&) & noexcept = default;
ptr& operator =(ptr&&) & noexcept = default;
bool is_same_as(const ptr& o) const noexcept { return p == o.p; }
/** Returns our type character or zero if empty.*/
char typechar() const noexcept { return p ? p->typechar() : 0; }
/** Returns our flattened typestring. */
string_variant type() const { return p ? p->type() : string_variant(std::string_view()); }
/** Returns our flattened serialized value. */
string_variant value() const { return p ? p->value() : string_variant(std::string_view()); }
/// @return view into the value IFF consecutive, else empty optional
std::optional<std::string_view> get_consecutive_value() const noexcept { return p ? get_consecutive<has_refc, Allocator>(p->vbegin, p->vend) : std::string_view{}; }
/** Returns how many contained elements we have. For tuples it is the tuple size,
* for lm it is the number of elements in the list/map. For optionals it is 0/1 depending on
* if the optional has a value or not. For expected and any, it is always 1. For the
* rest of the primitives (including string) it is always zero.*/
uint32_t size() const { return p ? p->size() : 0; }
/** Returns our index in our parent or none if we have no parent.*/
std::optional<uint32_t> indexof() const noexcept {
if (p && p->parent)
return p->parent->indexof(*this);
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wmaybe-uninitialized"
return {}; //Safely ignore "'<anonymous>' may be used uninitialized in this function" warnings. See https://gcc.gnu.org/bugzilla/show_bug.cgi?id=80635
#pragma GCC diagnostic pop
}
/** Try to extract the content of us into a C++ value.
* We throw uf::type_mismatch_error if we cannot. No conversion
* For uf::any or uf::any_view consider using as_any() instead.*/
template<typename T>
auto get_as(uf::serpolicy convpolicy = uf::allow_converting_all) const {
static_assert(!std::is_reference<T>::value);
static_assert(!std::is_const<T>::value);
static_assert(!std::is_volatile<T>::value);
assert(p);
return p->template get_as<T>(convpolicy);
}
/** Flatten both type and value into an uf::any/uf::any_view. If both type and value
* are in consecutive chunks, we return an uf::any_view, else we copy to an uf::any.*/
any_variant as_any() const { assert(p); return p->as_any(); }
/** Assuming the wview contains a string, we return either a string_view or string
* depending on if the value is in one chunk. If wview is not a string we throw
* an uf::type_mismatch_error.*/
string_variant as_string() const { assert(p); return p->as_string(); }
/** Prints the chunks in a more verbose way. For debug only.*/
operator std::string() const { return p ? std::string(*p) : std::string("<empty>"); }
/** Prints the chunks in a less verbose way. For debug only.*/
[[nodiscard]] std::string print() const { return p ? p->print() : std::string("<empty>");; }
/** How long would our type be when flattened? */
uint32_t flatten_type_size() const noexcept { return p ? p->flatten_type_size() : 0; }
/** How long would our value be when flattened? */
uint32_t flatten_size() const noexcept { return p ? p->flatten_size() : 0; }
/** Flatten our bytes to a pre-allocated buffer of appropriate size. */
void flatten_to(char* buf) const { if (p) p->flatten_to(buf); }
/** Get a wview to one of our constitutent. 'idx' starts at zero and
* must be lower than size() (or we throw std::out_of_range).
* For types having no constitutent, we throw uf::type_mismatch_error.*/
ptr operator[](uint32_t idx) const { return p ? p->operator[](idx) : ptr{}; }
/** Set the value pointed to by us to the content of another wview. We make a copy,
* so there is no link remaining between the wview we change and 'o', so chaning 'o'
* will have no effect on 'this' or its parents.
* If we have wviews to any of our constitutent elements, we break any link with them:
* any such wviews continue to hold their value, but changes to them will have no effect
* on 'this' or any parent of it.
* If a type change is not possible, but needed we throw an uf::type_mismatch_error.*/
ptr& set(const ptr& o) & { assert(p); if (o) p->set(*o); else clear(); return *this; }
/** Set the value pointed to by us to the content of another wview. We make a copy,
* so there is no link remaining between the wview we change and 'o', so chaning 'o'
* will have no effect on 'this' or its parents.
* If we have wviews to any of our constitutent elements, we break any link with them:
* any such wviews continue to hold their value, but changes to them will have no effect
* on 'this' or any parent of it.
* If a type change is not possible, but needed we throw an uf::type_mismatch_error.*/
ptr&& set(const ptr& o) && { assert(p); if (o) p->set(*o); else clear(); return std::move(*this); }
/** Set the value pointed to by us to a new type and value.
* If we have wviews to any of our constitutent elements, we break any link with them:
* any such wviews continue to hold their value, but changes to them will have no effect
* on 'this' or any parent of it.
* If a type change is not possible, but needed we throw an uf::type_mismatch_error.*/
template<typename T>
ptr& set(T const& t) & {
static_assert(is_serializable_v<T>);
assert(p);
p->set(uf::serialize_type(t), uf::serialize(t));
return *this;
}
/** Set the value pointed to by us to a new type and value.
* If we have wviews to any of our constitutent elements, we break any link with them:
* any such wviews continue to hold their value, but changes to them will have no effect
* on 'this' or any parent of it.
* If a type change is not possible, but needed we throw an uf::type_mismatch_error.*/
template<typename T>
ptr&& set(T const& t)&& {
static_assert(is_serializable_v<T>);
assert(p);
p->set(uf::serialize_type(t), uf::serialize(t));
return std::move(*this);
}
/** Set the value pointed to by us to a new type and value.
* If we have wviews to any of our constitutent elements, we break any link with them:
* any such wviews continue to hold their value, but changes to them will have no effect
* on 'this' or any parent of it.
* If a type change is not possible, we throw an uf::type_mismatch_error.*/
ptr& set(std::string_view type, std::string_view value) & { assert(p); p->set(type, value); return *this; }
/** Set the value pointed to by us to a new type and value.
* If we have wviews to any of our constitutent elements, we break any link with them:
* any such wviews continue to hold their value, but changes to them will have no effect
* on 'this' or any parent of it.
* If a type change is not possible, but needed we throw an uf::type_mismatch_error.*/
ptr&& set(std::string_view type, std::string_view value) && { assert(p); p->set(type, value); return std::move(*this); }
/** Set the value pointed to by us to void.
* If we have wviews to any of our constitutent elements, we break any link with them:
* any such wviews continue to hold their value, but changes to them will have no effect
* on 'this' or any parent of it.
* If a type change is not possible, but needed we throw an uf::type_mismatch_error.*/
ptr& set_void() & { return set({}, {}); }
/** Set the value pointed to by us to void.
* If we have wviews to any of our constituent elements, we break any link with them:
* any such wviews continue to hold their value, but changes to them will have no effect
* on 'this' or any parent of it.
* If a type change is not possible, but needed we throw an uf::type_mismatch_error.*/
ptr&& set_void() && { return std::move(*this).set({}, {}); }
/** Erase one of our constitutent.
* We throw an std::out_of_range if 'idx' is >= size().
* If this incurs a type change (for tuples), and that is not possible, we throw
* an uf::type_mismatch_error.*/
void erase(uint32_t idx) {
if (!p) throw std::out_of_range("Cannot erase from empty wview.");
int32_t cindex;
try {
auto ci = p->cindexof(operator[](idx));
assert(ci);
if (!ci) return;
cindex = *ci;
} catch (const uf::type_mismatch_error& e) {
throw uf::type_mismatch_error("erase() is not valid for type <%1>.", type().as_view(), {});
} catch (const std::out_of_range & e) {
throw std::out_of_range(uf::concat("Index (", idx, ") out of range [0..", size() - 1, "] in erase() for type <", type().as_view(), ">."));
}
if (p->do_erase(cindex))
throw uf::type_mismatch_error("Cannot erase a child of <%1>.", type(), {});
}
/** Erase one of our constitutent.
* If 'what' is not a member of us, we throw std::invalid_argument.
* If this incurs a type change (for tuples), and that is not possible, we throw
* an uf::type_mismatch_error.*/
void erase(const ptr &what) {
if (p)
if (auto cindex = p->cindexof(what)) {
if (p->do_erase(*cindex))
throw uf::type_mismatch_error("Cannot erase a child of <%1>.", type(), {});
return;
}
throw std::invalid_argument("Wview to erase is not my child.");
}
/** Insert one more constitutent after 'idx'. To insert to the beginning
* use any negative value for 'idx'.
* We throw an std::out_of_range if 'idx' is >= size().
* If this incurs a type change (for tuples), and that is not possible, we throw
* an uf::type_mismatch_error.
* If the type of what is not appropriate (for 'lmo') we also throw an uf::type_mismatch_error.*/
void insert_after(int32_t idx, const ptr &what) {
if (!p) throw std::out_of_range("Cannot insert to empty wview.");
int32_t cindex = -1;
if (idx>=0) try {
auto ci = p->cindexof(operator[](idx));
assert(ci);
if (!ci) return;
cindex = *ci;
} catch (const uf::type_mismatch_error & e) {
throw uf::type_mismatch_error("insert_after() is not valid for type <%1>.", type().as_view(), {});
} catch (const std::out_of_range & e) {
throw std::out_of_range(uf::concat("Index (", idx, ") out of range [0..", size()-1, "] in insert_after() for type <", type().as_view(), ">."));
}
if (p->do_insert_after(cindex, *what))
throw uf::type_mismatch_error("Cannot insert a child into <%1>.", type(), {});
}
/** Insert one more constitutent after 'where'.
* We throw an std::invalid_argument if 'where' is not a member of us.
* If this incurs a type change (for tuples), and that is not possible, we throw
* an uf::type_mismatch_error.
* If the type of what is not appropriate (for 'lmo') we also throw an uf::type_mismatch_error.*/
void insert_after(const ptr& where, const ptr& what)
{
if (!p) throw std::out_of_range("Cannot insert to empty wview.");
if (auto cindex = p->cindexof(where)) {
if (p->do_insert_after(*cindex, *what))
throw uf::type_mismatch_error("Cannot insert into a <%1>.", type(), {});
return;
}
throw std::invalid_argument("Wview to insert after is not my child.");
}
/** Creates a copy of the current wview, with creating new chunks.
* @returns a wview with no parents that can be modified without
* modifying 'this'.*/
ptr clone() const {
return p ? ptr{ impl::clone_anew<has_refc, Allocator>(p->tbegin, p->tend), {},
impl::clone_anew<has_refc, Allocator>(p->vbegin, p->vend), {}, nullptr } :
ptr{};
}
/** Create a wview containing an optional with the value (and type) provided.
* We copy 'o' so it will not be linked to the result in any way.
* For void 'o' we return null.*/
static ptr create_optional_from(const ptr& o)
{
if (!o.typechar()) return {};
chunk_ptr tb = chunk_ptr(sview_ptr("o", true));
chunk_ptr vb = chunk_ptr(sview_ptr(std::string_view("\x1", 1), true));
clone_into<has_refc, Allocator>(tb->next, o->tbegin, o->tend);
clone_into<has_refc, Allocator>(vb->next, o->vbegin, o->vend);
return ptr(std::move(tb), chunk_ptr(), std::move(vb), chunk_ptr(), nullptr);
}
/** Create a wview containing an expected with the value (and type) provided.
* We copy 'o' so it will not be linked to the result in any way.*/
static ptr create_expected_from(const ptr& o)
{
chunk_ptr vb = chunk_ptr(sview_ptr(std::string_view("\x1", 1), true));
chunk_ptr tb;
if (o.typechar()) {
tb = chunk_ptr(sview_ptr("x", true));
clone_into<has_refc, Allocator>(tb->next, o->tbegin, o->tend);
clone_into<has_refc, Allocator>(vb->next, o->vbegin, o->vend);
} else
tb = chunk_ptr(sview_ptr("X", true));
return ptr(std::move(tb), chunk_ptr(), std::move(vb), chunk_ptr(), nullptr);
}
/** Create a wview containing an expected with the error provided.
* We copy 'o' so it will not be linked to the result in any way.
* @param [in] o An wview containing an error.
* @param [in] type The type of the expected (without the leading 'x').
* @returns null, if 'o' does not contain an error.*/
static ptr create_expected_from_error(const ptr& o, std::string_view type)
{
if (o.typechar() != 'e') return {};
chunk_ptr tb;
if (type.length()) {
tb = chunk_ptr(sview_ptr("x", true));
copy_into<has_refc, Allocator>(type, tb->next);
} else
tb = chunk_ptr(sview_ptr("X", true));
chunk_ptr vb = chunk_ptr(sview_ptr(std::string_view("\x0", 1), true));