-
Notifications
You must be signed in to change notification settings - Fork 3
/
ShadowDB.h
4531 lines (3815 loc) · 125 KB
/
ShadowDB.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
#pragma once
#include <map>
#include <set>
#include <memory>
#include <string>
#include <vector>
#include <list>
#include <iostream>
#include <climits>
#include <queue>
#include <chrono>
#include <algorithm>
#include <unordered_map>
#include <string.h>
#include <assert.h>
#include <stdarg.h>
#include <stdio.h>
namespace shadow {
using namespace std;
namespace adl {
template <typename T>
struct HasToString
{
template <typename U>
static char foo(U*, decltype(((U*)0)->toString())*);
template <typename U>
static short foo(U*, ...);
static const bool value = sizeof(foo((T*)0, nullptr)) == sizeof(char);
};
template <typename T>
struct StdToString
{
template <typename U>
static char foo(U*, decltype(std::to_string(*((U*)0)))*);
template <typename U>
static short foo(U*, ...);
static const bool value = sizeof(foo((T*)0, nullptr)) == sizeof(char);
};
template <typename T>
struct IsString
{
static const bool value = std::is_same<typename std::remove_cv<T>::type, std::string>::value
|| std::is_same<typename std::remove_cv<T>::type, char*>::value
|| std::is_same<typename std::remove_cv<T>::type, const char*>::value;
};
template <typename T>
static typename std::enable_if<StdToString<T>::value, string>::type
to_string(T const& t)
{
return std::to_string(t);
}
template <typename T>
static typename std::enable_if<HasToString<T>::value, string>::type
to_string(T const& t)
{
return const_cast<T&>(t).toString();
}
template <typename T>
static typename std::enable_if<IsString<T>::value, string>::type
to_string(T const& t)
{
return string{t};
}
template <typename T>
static typename std::enable_if<
!HasToString<T>::value && !StdToString<T>::value && !IsString<T>::value,
string
>::type
to_string(T const& t)
{
return "Unsupport-type";
}
template <typename V>
map<size_t, string> & field_maps()
{
static map<size_t, string> m;
return m;
}
template <typename V, typename F>
void register_to_string(F V::* memptr, string fieldname)
{
size_t offset = reinterpret_cast<size_t>(&(((V*)0) ->* memptr));
map<size_t, string> & m = field_maps<V>();
m[offset] = fieldname;
}
#define SHADOW_DB_DEBUG_FIELD(V, F) \
struct SHADOW_DB_DEBUG_FIELD__ ## V ## F \
{ \
SHADOW_DB_DEBUG_FIELD__ ## V ## F () { \
::shadow::adl::register_to_string<V>(&V::F, #V "::" #F);\
} \
} gShadowDBDebugRegister_ ## V ## F
template <typename V>
string field_to_string(size_t offset)
{
map<size_t, string> & m = field_maps<V>();
auto it = m.find(offset);
return (m.end() == it) ? "" : it->second;
}
}
string P(const char* fmt = "", ...) __attribute__((format(printf,1,2)));
string fmt(const char* fmt = "", ...) __attribute__((format(printf,1,2)));
inline size_t & tlsTab() {
static thread_local size_t t = 0;
return t;
}
inline string P(const char* fmt, ...)
{
va_list ap;
va_start(ap, fmt);
char buf[4096];
size_t tt = tlsTab();
if (tt) {
memset(buf, ' ', tt);
}
int len = vsnprintf((char*)buf + tt, sizeof(buf) - tt - 1, fmt, ap) + tt;
buf[len] = '\n';
va_end(ap);
return std::string(buf, len + 1);
}
inline string fmt(const char* fmt, ...)
{
va_list ap;
va_start(ap, fmt);
char buf[4096];
int len = vsnprintf((char*)buf, sizeof(buf) - 1, fmt, ap);
va_end(ap);
return std::string(buf, len);
}
// 条件
enum class e_cond_op : char
{
none = 0,
lt = 1, // <
le = 2, // <=
eq = 3, // ==
ge = 4, // >=
gt = 5, // >
ne = 6, // !=
};
inline const char* e_cond_op_2_str(e_cond_op op)
{
switch ((int)op)
{
case (int)e_cond_op::lt:
return "<";
case (int)e_cond_op::le:
return "<=";
case (int)e_cond_op::eq:
return "==";
case (int)e_cond_op::ge:
return ">=";
case (int)e_cond_op::gt:
return ">";
case (int)e_cond_op::ne:
return "!=";
}
return "";
}
struct Debugger
{
struct IndexHintInfo
{
string indexName;
size_t nLeftMatched = 0; // 最左匹配
size_t nMatchedCond = 0; // 匹配到的条件数量
bool bOrderByMatched = false; // orderby是否最左前缀匹配
size_t nForkLevels = 0; // 数据层数
size_t nScanIndexKeys = 0; // 遍历过的索引key
size_t nScanRows = 0; // 遍历过的数据行
size_t nResultRows = 0; // 返回的结果行数
string toString(bool matched = false) const
{
string s;
s += P("[%s]", indexName.c_str());
++tlsTab();
s += P("left-matched: %d", (int)nLeftMatched);
s += P("matched-cond: %d", (int)nMatchedCond);
s += P("order-by-matched: %d", (int)bOrderByMatched);
if (matched) {
s += P("fork-levels: %d", (int)nForkLevels);
s += P("scan-index-k: %d", (int)nScanIndexKeys);
s += P("scan-rows: %d", (int)nScanRows);
s += P("result-rows: %d", (int)nResultRows);
}
--tlsTab();
return s;
}
};
// 追踪单次索引使用
struct OnceIndexQueryTrace
{
string cond;
std::vector<IndexHintInfo> tryMatchIndexes;
IndexHintInfo matched;
string toString() const
{
string s;
s += P("cond: %s", cond.c_str());
s += P("tryMatchIndexes:");
++tlsTab();
for (size_t i = 0; i < tryMatchIndexes.size(); ++i) {
s += P("[%d]", (int)i);
++tlsTab();
s += tryMatchIndexes[i].toString(false);
--tlsTab();
}
--tlsTab();
s += P("matched-index:");
++tlsTab();
s += matched.toString(true);
--tlsTab();
return s;
}
};
struct QueryTrace
{
string or_cond;
string optimizedCond;
std::list<OnceIndexQueryTrace> querys;
int64_t beginTimestampUS = 0;
int64_t endTimestampUS = 0;
static int64_t us()
{
return std::chrono::duration_cast<std::chrono::microseconds>(
std::chrono::system_clock::now().time_since_epoch()).count();
}
// 遍历过的索引key
size_t getScanIndexKeys() const {
size_t n = 0;
for (auto const& q : querys)
n += q.matched.nScanIndexKeys;
return n;
}
// 遍历过的数据行
size_t getScanRows() const {
size_t n = 0;
for (auto const& q : querys)
n += q.matched.nScanRows;
return n;
}
// 返回的结果行数
size_t getResultRows() const {
size_t n = 0;
for (auto const& q : querys)
n += q.matched.nResultRows;
return n;
}
// 查询耗时(us)
int64_t queryCostUS() const
{
return (endTimestampUS ? endTimestampUS : us()) - beginTimestampUS;
}
OnceIndexQueryTrace* newQuery()
{
querys.push_back(OnceIndexQueryTrace{});
return &querys.back();
}
string toString() const
{
string s;
s += P("time: %ld us", queryCostUS());
s += P("cond: %s", or_cond.c_str());
s += P("optimized-cond: %s", optimizedCond.c_str());
s += P("scan-index-k: %d", (int)getScanIndexKeys());
s += P("scan-rows: %d", (int)getScanRows());
s += P("result-rows: %d", (int)getResultRows());
s += P("querys (size=%d):", (int)querys.size());
++tlsTab();
int i = 0;
for (auto & q : querys) {
s += P("[%d]", (int)i++);
++tlsTab();
s += q.toString();
--tlsTab();
}
--tlsTab();
return s;
}
};
QueryTrace queryTrace;
string toString()
{
string s;
s += P("[Debugger]");
++tlsTab();
s += P("query-trace:");
++tlsTab();
s += queryTrace.toString();
--tlsTab();
--tlsTab();
return s;
}
};
// 多层结构
// 最上面一层当做logs使用, 可修改, 底层不可变更
template <
typename K,
typename V,
template <typename K1, typename V1> class Table
>
struct ShadowBase
{
public:
struct VStorage : public V
{
VStorage() = default;
VStorage(VStorage const&) = default;
VStorage(VStorage &&) = default;
VStorage& operator=(VStorage const&) = default;
VStorage& operator=(VStorage &&) = default;
VStorage(V const& v) : V(v) {}
VStorage(V && v) : V(std::move(v)) {}
VStorage& operator=(V const& v) {
static_cast<V&>(*this) = v;
return *this;
}
VStorage& operator=(V && v) {
static_cast<V&>(*this) = std::move(v);
return *this;
}
string toString() const
{
string s;
s = fmt("%s{%s}", deleted ? "(D)" : "",
adl::to_string(static_cast<V const&>(*this)).c_str());
return s;
}
bool deleted = false;
};
typedef Table<K, VStorage> table_t;
typedef shared_ptr<table_t> table_ptr;
ShadowBase() = default;
ShadowBase(ShadowBase const&) = delete;
ShadowBase& operator=(ShadowBase const&) = delete;
virtual table_ptr makeTable() = 0;
virtual void forUniqueTable(table_t & table) {} // 初始化成单层table(不清理数据)
virtual void forBaseTable(table_t & table) {} // 初始化成底层table, 上层还有logs(不清理数据)
virtual void forLogsTable(table_t & table) {} // 初始化成顶层table(不清理数据)
virtual void mergeTable(table_t & from, table_t & to) = 0; // 覆盖合并
virtual string tableToString(table_t & table, bool simple) const = 0;
void reset() {
levels_.clear();
levels_.push_back(makeTable());
forUniqueTable(*logs());
}
void fork(ShadowBase & other)
{
if (logs()->empty() && level() == 1) {
// 空的
other.reset();
return ;
}
other.levels_.clear();
if (logs()->empty()) {
// 没有logs, 顶层不需要共享
for (size_t i = 0; i + 1 < level(); ++i) {
other.levels_.push_back(levels_[i]);
}
} else {
// 所有层共享
for (auto & ht : levels_) {
other.levels_.push_back(ht);
}
addLevel();
}
other.addLevel();
}
void merge()
{
size_t mergeStartLevel = 0;
table_ptr htp;
table_ptr & base = levels_.front();
if (base.unique()) {
// 没有别的共享了, 可以直接merge到最底层
mergeStartLevel = 1;
htp = base;
} else {
// 最底层有共享的, 需要创建一个新的hashtable
htp = makeTable();
}
forUniqueTable(*htp);
// 逐层合并
for (size_t i = mergeStartLevel; i < levels_.size(); ++i)
{
table_t & ht = *levels_[i];
mergeTable(ht, *htp);
}
levels_.clear();
levels_.push_back(htp);
}
size_t level() const {
return levels_.size();
}
string toString(bool simple = false) const
{
string s;
s += P("[Shadow-Table] (level=%d)", (int)level());
++tlsTab();
for (size_t i = 0; i < level(); ++i) {
table_ptr const& tp = table(i);
s += P("[%d](ref=%d)(0x%p) %s",
(int)i, (int)tp.use_count(), (void*)tp.get(),
(i == 0) ? "-> top" : "");
++tlsTab();
s += tableToString(*tp, simple);
--tlsTab();
}
--tlsTab();
return s;
}
protected:
inline table_ptr & logs()
{
return levels_.back();
}
inline table_ptr & table(size_t lv)
{
assert(lv < levels_.size());
return levels_[levels_.size() - lv - 1];
}
inline table_ptr const& table(size_t lv) const
{
assert(lv < levels_.size());
return levels_[levels_.size() - lv - 1];
}
void addLevel()
{
// 冻结上一层的rehash
if (level() == 1) {
forBaseTable(*logs());
}
// 新增一层, bucket_count和上一层保持一致, 并冻结rehash
table_ptr ht = makeTable();
forLogsTable(*ht);
levels_.push_back(ht);
}
protected:
vector<table_ptr> levels_;
};
template <typename K, typename V>
using hashtable = std::unordered_map<K, V>;
template <typename K, typename V>
struct ShadowHashTable : public ShadowBase<K, V, hashtable>
{
public:
typedef ShadowHashTable<K, V> this_t;
typedef ShadowBase<K, V, hashtable> base_t;
typedef typename base_t::VStorage VStorage;
typedef typename base_t::table_t table_t;
typedef typename base_t::table_ptr table_ptr;
using base_t::reset;
using base_t::logs;
using base_t::level;
using base_t::table;
struct ref_t
{
K key;
size_t bucket_count = 0;
size_t bucket_index = 0;
ref_t() = default;
explicit ref_t(K const& k) : key(k) {}
friend bool operator<(ref_t const& lhs, ref_t const& rhs) {
return lhs.key < rhs.key;
}
friend bool operator==(ref_t const& lhs, ref_t const& rhs) {
return lhs.key == rhs.key;
}
string toString() const
{
string s;
s += fmt("{key=%s, bc=%d, bi=%d}",
adl::to_string(key).c_str(),
(int)bucket_count, (int)bucket_index);
return s;
}
};
struct iterator
{
public:
iterator() = default;
explicit iterator(this_t * hashtable) : ht(hashtable) {}
iterator(iterator &&) = default;
iterator& operator=(iterator &&) = default;
iterator(iterator const&) = delete;
iterator& operator=(iterator const&) = delete;
bool isEnd() const { return bEnd; }
explicit operator bool() const { return !isEnd(); }
typename table_t::value_type & operator*() { return *it; }
typename table_t::value_type const& operator*() const { return *it; }
typename table_t::value_type * operator->() { return &*it; }
typename table_t::value_type const* operator->() const { return &*it; }
ref_t & getRef() { return ref; }
ref_t const& getRef() const { return ref; }
iterator & operator++()
{
next();
return *this;
}
void setBegin()
{
bucket = 0;
level = 0;
bucketUnique.clear();
bEnd = false;
it = ht->table(level)->begin(bucket);
if (!begin()) {
setEnd();
}
}
void setEnd() { bEnd = true; }
friend bool operator==(iterator const& lhs, iterator const& rhs)
{
if (lhs.isEnd() && rhs.isEnd()) return true;
if (lhs.ht != rhs.ht) return false;
return lhs.bucket == rhs.bucket && lhs.level == rhs.level
&& lhs.it == rhs.it;
}
friend bool operator!=(iterator const& lhs, iterator const& rhs)
{
return !(lhs == rhs);
}
private:
void next()
{
++it;
if (!begin()) {
setEnd();
}
}
bool begin()
{
while (bucket < ht->logs()->bucket_count()) {
while (level < ht->level()) {
if (ht->table(level)->end(bucket) == it) {
++level;
if (level == ht->level())
break;
it = ht->table(level)->begin(bucket);
continue;
}
if (!bucketUnique.insert(it->first).second) {
++it;
continue;
}
if (it->second.deleted) {
++it;
continue;
}
ref.key = it->first;
ref.bucket_count = ht->logs()->bucket_count();
ref.bucket_index = bucket;
return true;
}
level = 0;
bucketUnique.clear();
++bucket;
if (bucket == ht->logs()->bucket_count())
break;
it = ht->table(level)->begin(bucket);
}
return false;
}
private:
this_t * ht;
size_t bucket = 0;
size_t level = 0;
typename table_t::local_iterator it;
std::set<K> bucketUnique;
bool bEnd = true;
ref_t ref;
};
bool foreach(std::function<bool(K const&, ref_t const&, V*)> pred)
{
iterator it(this);
it.setBegin();
for (; it; ++it) {
if (!pred(it->first, it.getRef(), static_cast<V*>(&it->second)))
return false;
}
return true;
}
explicit ShadowHashTable(size_t minBucketCount = 1024)
: minBucketCount_(minBucketCount)
{
reset();
}
iterator begin()
{
iterator it(this);
it.setBegin();
return std::move(it);
}
void fork(ShadowHashTable & other)
{
other.minBucketCount_ = minBucketCount_;
base_t::fork(other);
}
void set(K const& key, V const& value)
{
VStorage & vs = (*logs())[key];
static_cast<V&>(vs) = value;
vs.deleted = false;
}
void set(K const& key, V && value)
{
VStorage & vs = (*logs())[key];
static_cast<V&>(vs) = std::move(value);
vs.deleted = false;
}
void del(K const& key)
{
if (level() == 1) {
logs()->erase(key);
return ;
}
// 查看logs以下的层中是否有key
ref_t keyRef(key);
ref_t out;
for (size_t i = 1; i < level(); ++i) {
table_ptr & htp = table(i);
std::pair<V*, bool> res = get(htp, keyRef, out);
if (res.first) {
// 底层有, logs追加一个deleted记录
VStorage & vs = (*logs())[key];
vs.deleted = true;
return ;
}
if (res.second) { // 顶层已删除, 底层无需再看
break;
}
}
// 底层没有or已删除, logs里直接删除即可
logs()->erase(key);
}
V* get(K const& key)
{
ref_t out;
return get(key, out);
}
V* get(K const& key, ref_t & out)
{
ref_t keyRef;
keyRef.key = key;
return get(keyRef, out);
}
V* get(ref_t const& keyRef, ref_t & out)
{
// 自顶向下, 逐层查找
for (size_t i = 0; i < level(); ++i) {
table_ptr & htp = table(i);
std::pair<V*, bool> res = get(htp, keyRef, out);
if (res.first) {
return res.first;
}
if (res.second) { // 顶层已删除, 底层无需再看
return nullptr;
}
}
return nullptr;
}
static float& default_load_factor()
{
static float load_factor = 0.5;
return load_factor;
}
protected:
virtual table_ptr makeTable() override
{
return std::make_shared<table_t>();
}
virtual void forUniqueTable(table_t & table) override
{
// 打开rehash
table.max_load_factor(default_load_factor());
table.reserve(minBucketCount_ * default_load_factor());
}
virtual void forBaseTable(table_t & table) override
{
// 冻结rehash
table.max_load_factor(std::numeric_limits<float>::max());
}
virtual void forLogsTable(table_t & table) override
{
// 和上一层保持相同bucket_count & 冻结rehash
table.max_load_factor(1);
table.reserve(logs()->bucket_count());
table.max_load_factor(std::numeric_limits<float>::max());
}
virtual void mergeTable(table_t & from, table_t & to) override
{
for (auto const& kv : from)
{
if (kv.second.deleted) {
to.erase(kv.first);
} else {
to[kv.first] = kv.second;
}
}
}
virtual string tableToString(table_t & table, bool simple) const override
{
string s;
s += P("Hashtable[size=%d bucket=%d load_factor=%.3f max_load_factor=%.3f]",
(int)table.size(), (int)table.bucket_count(),
(float)table.load_factor(), (float)table.max_load_factor());
if (simple)
return s;
++tlsTab();
for (size_t i = 0; i < table.bucket_count(); ++i)
{
for (auto it = table.begin(i); it != table.end(i); ++it)
{
s += P("[%d] K=%s V=%s", (int)i,
adl::to_string(it->first).c_str(),
adl::to_string(it->second).c_str());
}
}
--tlsTab();
return s;
}
// @return: <pointer, isDeleted>
std::pair<V*, bool> get(table_ptr & htp, ref_t const& keyRef, ref_t & out)
{
size_t bucket_index = keyRef.bucket_index;
if (htp->bucket_count() != keyRef.bucket_count) {
// bucket index失效, 重新hash
bucket_index = htp->bucket(keyRef.key);
}
for (auto it = htp->begin(bucket_index);
it != htp->end(bucket_index); ++it)
{
if (it->first != keyRef.key)
continue;
VStorage & vs = it->second;
if (vs.deleted) {
return {nullptr, true};
}
out.key = it->first;
out.bucket_count = htp->bucket_count();
out.bucket_index = bucket_index;
return {static_cast<V*>(&vs), false};
}
return {nullptr, false};
}
private:
size_t minBucketCount_;
};
// 备选结构:rbtree
// 优点: 遍历有序, fork快
// 缺点: 查询慢, fork多层以后更慢
//template <typename K, typename V>
//using rbtree = std::map<K, V>;
//
//template <typename K, typename V>
//struct ShadowRBTree : public ShadowBase<K, V, rbtree>;
// 递归map-set结构
// map->map->map->...->set
template <typename K, typename V>
struct RecursiveMapSet
{
public:
typedef RecursiveMapSet<K, V> this_t;
typedef std::set<V> set_t;
typedef typename set_t::iterator set_iterator;
typedef void* map_value_type;
typedef std::map<K, void*> map_t;
typedef typename map_t::iterator map_iterator;
typedef std::vector<K> keys_t;
typedef std::pair<K, e_cond_op> cond_t;
typedef std::vector<cond_t> condition_vec_t;
typedef std::vector<condition_vec_t> condition_vec2_t;
typedef std::pair<map_iterator, map_iterator> map_iterator_range_t;
typedef std::vector<map_iterator_range_t> map_iterator_range_list_t;
struct map_range_iterator
{
public:
map_iterator & get() { return it; }
map_iterator const& get() const { return it; }
map_range_iterator& operator++()
{
next();
return *this;
}
bool next()
{
if (isEnd()) return false;
++it;
if (it == range[idx].second) {
if (idx == range.size() - 1) {
return false;
}
++idx;
it = range[idx].first;
}
return true;
}
bool isEnd() const {
if (range.empty()) return true;
return idx == range.size() - 1 && it == range[idx].second;
}
explicit operator bool() const { return !isEnd(); }
public:
map_iterator it;
map_iterator_range_list_t range;
size_t idx = 0;
};
struct iterator
{
public:
iterator() = default;
explicit iterator(this_t * t) : self(t) {}
keys_t keys()
{
keys_t ks;
ks.reserve(mapItrs.size());
for (map_iterator & it : mapItrs)
ks.push_back(it->first);
return ks;
}
V const& get() { return *setItr; }
iterator & operator++()
{
if (isEnd())
return *this;
assert(mapItrs.size() == self->depth_ + 1);
set_t * s = reinterpret_cast<set_t*>(mapItrs.back()->second);
++setItr;
if (s->end() != setItr)
return *this;
// 逐层回退, ++
while (!mapItrs.empty()) {
map_iterator & it = mapItrs.back();
map_t* parent = (mapItrs.size() == 1) ? root()
: reinterpret_cast<map_t*>(mapItrs[mapItrs.size() - 2]->second);
map_iterator last = parent->end();
++it;
for (; it != last; ++it) {
if (begin(reinterpret_cast<map_t*>(it->second), mapItrs.size()))
// next完成
return *this;
}
// 本层遍历到底了, 需要回退
mapItrs.pop_back();
}
setEnd();
return *this;
}
iterator operator++(int)
{