-
Notifications
You must be signed in to change notification settings - Fork 174
/
Copy pathdictionary.cpp
1247 lines (1106 loc) · 35.5 KB
/
dictionary.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*************************************************************************
*
* Copyright 2019 Realm Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
**************************************************************************/
#include <realm/dictionary.hpp>
#include <realm/aggregate_ops.hpp>
#include <realm/array_mixed.hpp>
#include <realm/array_ref.hpp>
#include <realm/group.hpp>
#include <realm/list.hpp>
#include <realm/set.hpp>
#include <realm/replication.hpp>
#include <algorithm>
namespace realm {
namespace {
void validate_key_value(const Mixed& key)
{
if (key.is_type(type_String)) {
auto str = key.get_string();
if (str.size()) {
if (str[0] == '$')
throw Exception(ErrorCodes::InvalidDictionaryKey, "Dictionary::insert: key must not start with '$'");
if (memchr(str.data(), '.', str.size()))
throw Exception(ErrorCodes::InvalidDictionaryKey, "Dictionary::insert: key must not contain '.'");
}
}
}
} // namespace
/******************************** Dictionary *********************************/
Dictionary::Dictionary(ColKey col_key, size_t level)
: Base(col_key)
, CollectionParent(level)
{
if (!(col_key.is_dictionary() || col_key.get_type() == col_type_Mixed)) {
throw InvalidArgument(ErrorCodes::TypeMismatch, "Property not a dictionary");
}
}
Dictionary::Dictionary(Allocator& alloc, ColKey col_key, ref_type ref)
: Base(Obj{}, col_key)
, m_key_type(type_String)
{
set_alloc(alloc);
REALM_ASSERT(ref);
m_dictionary_top.reset(new Array(alloc));
m_dictionary_top->init_from_ref(ref);
m_keys.reset(new BPlusTree<StringData>(alloc));
m_values.reset(new BPlusTreeMixed(alloc));
m_keys->set_parent(m_dictionary_top.get(), 0);
m_values->set_parent(m_dictionary_top.get(), 1);
m_keys->init_from_parent();
m_values->init_from_parent();
}
Dictionary::~Dictionary() = default;
Dictionary& Dictionary::operator=(const Dictionary& other)
{
Base::operator=(static_cast<const Base&>(other));
if (this != &other) {
// Back to scratch
m_dictionary_top.reset();
reset_content_version();
}
return *this;
}
size_t Dictionary::size() const
{
if (!update())
return 0;
return m_values->size();
}
DataType Dictionary::get_key_data_type() const
{
return m_key_type;
}
DataType Dictionary::get_value_data_type() const
{
return DataType(m_col_key.get_type());
}
bool Dictionary::is_null(size_t ndx) const
{
return get_any(ndx).is_null();
}
Mixed Dictionary::get_any(size_t ndx) const
{
// Note: `size()` calls `update_if_needed()`.
auto current_size = size();
CollectionBase::validate_index("get_any()", ndx, current_size);
return do_get(ndx);
}
std::pair<Mixed, Mixed> Dictionary::get_pair(size_t ndx) const
{
// Note: `size()` calls `update_if_needed()`.
auto current_size = size();
CollectionBase::validate_index("get_pair()", ndx, current_size);
return do_get_pair(ndx);
}
Mixed Dictionary::get_key(size_t ndx) const
{
// Note: `size()` calls `update_if_needed()`.
CollectionBase::validate_index("get_key()", ndx, size());
return do_get_key(ndx);
}
size_t Dictionary::find_any(Mixed value) const
{
return size() ? m_values->find_first(value) : realm::not_found;
}
size_t Dictionary::find_any_key(Mixed key) const noexcept
{
if (update()) {
return do_find_key(key);
}
return realm::npos;
}
template <typename AggregateType>
void Dictionary::do_accumulate(size_t* return_ndx, AggregateType& agg) const
{
size_t ndx = realm::npos;
m_values->traverse([&](BPlusTreeNode* node, size_t offset) {
auto leaf = static_cast<BPlusTree<Mixed>::LeafNode*>(node);
size_t e = leaf->size();
for (size_t i = 0; i < e; i++) {
auto val = leaf->get(i);
if (agg.accumulate(val)) {
ndx = i + offset;
}
}
// Continue
return IteratorControl::AdvanceToNext;
});
if (return_ndx)
*return_ndx = ndx;
}
util::Optional<Mixed> Dictionary::do_min(size_t* return_ndx) const
{
aggregate_operations::Minimum<Mixed> agg;
do_accumulate(return_ndx, agg);
return agg.is_null() ? Mixed{} : agg.result();
}
util::Optional<Mixed> Dictionary::do_max(size_t* return_ndx) const
{
aggregate_operations::Maximum<Mixed> agg;
do_accumulate(return_ndx, agg);
return agg.is_null() ? Mixed{} : agg.result();
}
util::Optional<Mixed> Dictionary::do_sum(size_t* return_cnt) const
{
auto type = get_value_data_type();
if (type == type_Int) {
aggregate_operations::Sum<Int> agg;
do_accumulate(nullptr, agg);
if (return_cnt)
*return_cnt = agg.items_counted();
return Mixed{agg.result()};
}
else if (type == type_Double) {
aggregate_operations::Sum<Double> agg;
do_accumulate(nullptr, agg);
if (return_cnt)
*return_cnt = agg.items_counted();
return Mixed{agg.result()};
}
else if (type == type_Float) {
aggregate_operations::Sum<Float> agg;
do_accumulate(nullptr, agg);
if (return_cnt)
*return_cnt = agg.items_counted();
return Mixed{agg.result()};
}
aggregate_operations::Sum<Mixed> agg;
do_accumulate(nullptr, agg);
if (return_cnt)
*return_cnt = agg.items_counted();
return Mixed{agg.result()};
}
util::Optional<Mixed> Dictionary::do_avg(size_t* return_cnt) const
{
auto type = get_value_data_type();
if (type == type_Int) {
aggregate_operations::Average<Int> agg;
do_accumulate(nullptr, agg);
if (return_cnt)
*return_cnt = agg.items_counted();
return agg.is_null() ? Mixed{} : agg.result();
}
else if (type == type_Double) {
aggregate_operations::Average<Double> agg;
do_accumulate(nullptr, agg);
if (return_cnt)
*return_cnt = agg.items_counted();
return agg.is_null() ? Mixed{} : agg.result();
}
else if (type == type_Float) {
aggregate_operations::Average<Float> agg;
do_accumulate(nullptr, agg);
if (return_cnt)
*return_cnt = agg.items_counted();
return agg.is_null() ? Mixed{} : agg.result();
}
// Decimal128 is covered with mixed as well.
aggregate_operations::Average<Mixed> agg;
do_accumulate(nullptr, agg);
if (return_cnt)
*return_cnt = agg.items_counted();
return agg.is_null() ? Mixed{} : agg.result();
}
namespace {
bool can_minmax(DataType type)
{
switch (type) {
case type_Int:
case type_Float:
case type_Double:
case type_Decimal:
case type_Mixed:
case type_Timestamp:
return true;
default:
return false;
}
}
bool can_sum(DataType type)
{
switch (type) {
case type_Int:
case type_Float:
case type_Double:
case type_Decimal:
case type_Mixed:
return true;
default:
return false;
}
}
} // anonymous namespace
util::Optional<Mixed> Dictionary::min(size_t* return_ndx) const
{
if (!can_minmax(get_value_data_type())) {
return std::nullopt;
}
if (update()) {
return do_min(return_ndx);
}
if (return_ndx)
*return_ndx = realm::not_found;
return Mixed{};
}
util::Optional<Mixed> Dictionary::max(size_t* return_ndx) const
{
if (!can_minmax(get_value_data_type())) {
return std::nullopt;
}
if (update()) {
return do_max(return_ndx);
}
if (return_ndx)
*return_ndx = realm::not_found;
return Mixed{};
}
util::Optional<Mixed> Dictionary::sum(size_t* return_cnt) const
{
if (!can_sum(get_value_data_type())) {
return std::nullopt;
}
if (update()) {
return do_sum(return_cnt);
}
if (return_cnt)
*return_cnt = 0;
return Mixed{0};
}
util::Optional<Mixed> Dictionary::avg(size_t* return_cnt) const
{
if (!can_sum(get_value_data_type())) {
return std::nullopt;
}
if (update()) {
return do_avg(return_cnt);
}
if (return_cnt)
*return_cnt = 0;
return Mixed{};
}
void Dictionary::align_indices(std::vector<size_t>& indices) const
{
auto sz = size();
auto sz2 = indices.size();
indices.reserve(sz);
if (sz < sz2) {
// If list size has decreased, we have to start all over
indices.clear();
sz2 = 0;
}
for (size_t i = sz2; i < sz; i++) {
// If list size has increased, just add the missing indices
indices.push_back(i);
}
}
namespace {
template <class T>
void do_sort(std::vector<size_t>& indices, bool ascending, const std::vector<T>& values)
{
auto b = indices.begin();
auto e = indices.end();
std::sort(b, e, [ascending, &values](size_t i1, size_t i2) {
return ascending ? values[i1] < values[i2] : values[i2] < values[i1];
});
}
} // anonymous namespace
void Dictionary::sort(std::vector<size_t>& indices, bool ascending) const
{
align_indices(indices);
do_sort(indices, ascending, m_values->get_all());
}
void Dictionary::distinct(std::vector<size_t>& indices, util::Optional<bool> ascending) const
{
align_indices(indices);
auto values = m_values->get_all();
do_sort(indices, ascending.value_or(true), values);
indices.erase(std::unique(indices.begin(), indices.end(),
[&values](size_t i1, size_t i2) {
return values[i1] == values[i2];
}),
indices.end());
if (!ascending) {
// need to return indices in original ordering
std::sort(indices.begin(), indices.end(), std::less<size_t>());
}
}
void Dictionary::sort_keys(std::vector<size_t>& indices, bool ascending) const
{
align_indices(indices);
#ifdef REALM_DEBUG
if (indices.size() > 1) {
// We rely in the design that the keys are already sorted
switch (m_key_type) {
case type_String: {
IteratorAdapter help(static_cast<BPlusTree<StringData>*>(m_keys.get()));
auto is_sorted = std::is_sorted(help.begin(), help.end());
REALM_ASSERT(is_sorted);
break;
}
case type_Int: {
IteratorAdapter help(static_cast<BPlusTree<Int>*>(m_keys.get()));
auto is_sorted = std::is_sorted(help.begin(), help.end());
REALM_ASSERT(is_sorted);
break;
}
default:
break;
}
}
#endif
if (ascending) {
std::sort(indices.begin(), indices.end());
}
else {
std::sort(indices.begin(), indices.end(), std::greater<size_t>());
}
}
void Dictionary::distinct_keys(std::vector<size_t>& indices, util::Optional<bool>) const
{
// we rely on the design of dictionary to assume that the keys are unique
align_indices(indices);
}
Obj Dictionary::create_and_insert_linked_object(Mixed key)
{
Table& t = *get_target_table();
auto o = t.is_embedded() ? t.create_linked_object() : t.create_object();
insert(key, o.get_key());
return o;
}
void Dictionary::insert_collection(const PathElement& path_elem, CollectionType dict_or_list)
{
if (dict_or_list == CollectionType::Set) {
throw IllegalOperation("Set nested in Dictionary is not supported");
}
check_level();
ensure_created();
Mixed new_val(0, dict_or_list);
auto old_val = try_get(path_elem.get_key());
if (!old_val || *old_val != new_val) {
m_values->ensure_keys();
auto [it, inserted] = insert(path_elem.get_key(), new_val);
set_key(*m_values, it.index());
}
}
DictionaryPtr Dictionary::get_dictionary(const PathElement& path_elem) const
{
update();
auto weak = const_cast<Dictionary*>(this)->weak_from_this();
auto shared = weak.expired() ? std::make_shared<Dictionary>(*this) : weak.lock();
DictionaryPtr ret = std::make_shared<Dictionary>(m_col_key, get_level() + 1);
ret->set_owner(shared, build_index(path_elem.get_key()));
return ret;
}
std::shared_ptr<Lst<Mixed>> Dictionary::get_list(const PathElement& path_elem) const
{
update();
auto weak = const_cast<Dictionary*>(this)->weak_from_this();
auto shared = weak.expired() ? std::make_shared<Dictionary>(*this) : weak.lock();
std::shared_ptr<Lst<Mixed>> ret = std::make_shared<Lst<Mixed>>(m_col_key, get_level() + 1);
ret->set_owner(shared, build_index(path_elem.get_key()));
return ret;
}
Mixed Dictionary::get(Mixed key) const
{
if (auto opt_val = try_get(key)) {
return *opt_val;
}
throw KeyNotFound("Dictionary::get");
}
util::Optional<Mixed> Dictionary::try_get(Mixed key) const
{
if (update()) {
auto ndx = do_find_key(key);
if (ndx != realm::npos) {
return do_get(ndx);
}
}
return {};
}
Dictionary::Iterator Dictionary::begin() const
{
// Need an update because the `Dictionary::Iterator` constructor relies on
// `m_clusters` to determine if it was already at end.
update();
return Iterator(this, 0);
}
Dictionary::Iterator Dictionary::end() const
{
return Iterator(this, size());
}
std::pair<Dictionary::Iterator, bool> Dictionary::insert(Mixed key, Mixed value)
{
auto my_table = get_table_unchecked();
if (key.get_type() != m_key_type) {
throw InvalidArgument(ErrorCodes::InvalidDictionaryKey, "Dictionary::insert: Invalid key type");
}
if (m_col_key) {
if (value.is_null()) {
if (!m_col_key.is_nullable()) {
throw InvalidArgument(ErrorCodes::InvalidDictionaryValue, "Dictionary::insert: Value cannot be null");
}
}
else {
if (m_col_key.get_type() == col_type_Link && value.get_type() == type_TypedLink) {
if (my_table->get_opposite_table_key(m_col_key) != value.get<ObjLink>().get_table_key()) {
throw InvalidArgument(ErrorCodes::InvalidDictionaryValue,
"Dictionary::insert: Wrong object type");
}
}
else if (m_col_key.get_type() != col_type_Mixed && value.get_type() != DataType(m_col_key.get_type())) {
throw InvalidArgument(ErrorCodes::InvalidDictionaryValue, "Dictionary::insert: Wrong value type");
}
else if (value.is_type(type_Link) && m_col_key.get_type() != col_type_Link) {
throw InvalidArgument(ErrorCodes::InvalidDictionaryValue,
"Dictionary::insert: No target table for link");
}
}
}
validate_key_value(key);
ensure_created();
ObjLink new_link;
if (value.is_type(type_TypedLink)) {
new_link = value.get<ObjLink>();
if (!new_link.is_unresolved())
my_table->get_parent_group()->validate(new_link);
}
else if (value.is_type(type_Link)) {
auto target_table = my_table->get_opposite_table(m_col_key);
auto key = value.get<ObjKey>();
if (!key.is_unresolved() && !target_table->is_valid(key)) {
throw InvalidArgument(ErrorCodes::KeyNotFound, "Target object not found");
}
new_link = ObjLink(target_table->get_key(), key);
value = Mixed(new_link);
}
if (!m_dictionary_top) {
throw StaleAccessor("Stale dictionary");
}
bool old_entry = false;
auto [ndx, actual_key] = find_impl(key);
if (actual_key != key) {
// key does not already exist
switch (m_key_type) {
case type_String:
static_cast<BPlusTree<StringData>*>(m_keys.get())->insert(ndx, key.get_string());
break;
case type_Int:
static_cast<BPlusTree<Int>*>(m_keys.get())->insert(ndx, key.get_int());
break;
default:
break;
}
m_values->insert(ndx, value);
}
else {
old_entry = true;
}
if (Replication* repl = get_replication()) {
if (old_entry) {
repl->dictionary_set(*this, ndx, key, value);
}
else {
repl->dictionary_insert(*this, ndx, key, value);
}
}
bump_content_version();
ObjLink old_link;
if (old_entry) {
Mixed old_value = m_values->get(ndx);
if (old_value.is_type(type_TypedLink)) {
old_link = old_value.get<ObjLink>();
}
m_values->set(ndx, value);
}
if (new_link != old_link) {
CascadeState cascade_state(CascadeState::Mode::Strong);
bool recurse = Base::replace_backlink(m_col_key, old_link, new_link, cascade_state);
if (recurse)
_impl::TableFriend::remove_recursive(*my_table, cascade_state); // Throws
}
return {Iterator(this, ndx), !old_entry};
}
const Mixed Dictionary::operator[](Mixed key)
{
auto ret = try_get(key);
if (!ret) {
ret = Mixed{};
insert(key, Mixed{});
}
return *ret;
}
Obj Dictionary::get_object(StringData key)
{
if (auto val = try_get(key)) {
if ((*val).is_type(type_TypedLink)) {
return get_table()->get_parent_group()->get_object((*val).get_link());
}
}
return {};
}
bool Dictionary::contains(Mixed key) const noexcept
{
return find_any_key(key) != realm::npos;
}
Dictionary::Iterator Dictionary::find(Mixed key) const noexcept
{
auto ndx = find_any_key(key);
if (ndx != realm::npos) {
return Iterator(this, ndx);
}
return end();
}
void Dictionary::translate_path(const StablePath& stable_path, Path& path) const
{
auto& index = stable_path[m_level];
auto ndx = find_index(index);
StringData key = do_get_key(ndx).get_string();
path.emplace_back(key);
if (stable_path.size() > size_t(m_level) + 1) {
Mixed val = do_get(ndx);
if (val.is_type(type_Dictionary)) {
DummyParent parent(this->get_table(), val.get_ref());
Dictionary dict(parent, 0);
dict.translate_path(stable_path, path);
}
else if (val.is_type(type_List)) {
DummyParent parent(this->get_table(), val.get_ref());
Lst<Mixed> list(parent, 0);
list.translate_path(stable_path, path);
}
}
}
void Dictionary::add_index(Path& path, const Index& index) const
{
auto ndx = m_values->find_key(index.get_salt());
auto keys = static_cast<BPlusTree<StringData>*>(m_keys.get());
path.emplace_back(keys->get(ndx));
}
size_t Dictionary::find_index(const Index& index) const
{
update();
return m_values->find_key(index.get_salt());
}
UpdateStatus Dictionary::do_update_if_needed(bool allow_create) const
{
switch (get_update_status()) {
case UpdateStatus::Detached: {
m_dictionary_top.reset();
return UpdateStatus::Detached;
}
case UpdateStatus::NoChange: {
if (m_dictionary_top && m_dictionary_top->is_attached()) {
return UpdateStatus::NoChange;
}
// The tree has not been initialized yet for this accessor, so
// perform lazy initialization by treating it as an update.
[[fallthrough]];
}
case UpdateStatus::Updated:
return init_from_parent(allow_create);
}
REALM_UNREACHABLE();
}
UpdateStatus Dictionary::update_if_needed() const
{
constexpr bool allow_create = false;
return do_update_if_needed(allow_create);
}
void Dictionary::ensure_created()
{
constexpr bool allow_create = true;
if (do_update_if_needed(allow_create) == UpdateStatus::Detached) {
throw StaleAccessor("Dictionary no longer exists");
}
}
bool Dictionary::try_erase(Mixed key)
{
validate_key_value(key);
if (!update())
return false;
auto ndx = do_find_key(key);
if (ndx == realm::npos) {
return false;
}
do_erase(ndx, key);
return true;
}
void Dictionary::erase(Mixed key)
{
if (!try_erase(key)) {
throw KeyNotFound(util::format("Cannot remove key %1 from dictionary: key not found", key));
}
}
auto Dictionary::erase(Iterator it) -> Iterator
{
auto pos = it.m_ndx;
CollectionBase::validate_index("erase()", pos, size());
do_erase(pos, do_get_key(pos));
if (pos < size())
pos++;
return {this, pos};
}
void Dictionary::nullify(size_t ndx)
{
REALM_ASSERT(m_dictionary_top);
REALM_ASSERT(ndx != realm::npos);
if (Replication* repl = get_replication()) {
auto key = do_get_key(ndx);
repl->dictionary_set(*this, ndx, key, Mixed());
}
m_values->set(ndx, Mixed());
}
bool Dictionary::nullify(ObjLink target_link)
{
size_t ndx = find_first(target_link);
if (ndx != realm::not_found) {
nullify(ndx);
return true;
}
else {
// There must be a link in a nested collection
size_t sz = size();
for (size_t ndx = 0; ndx < sz; ndx++) {
auto val = m_values->get(ndx);
auto key = do_get_key(ndx);
if (val.is_type(type_Dictionary)) {
auto dict = get_dictionary(key.get_string());
if (dict->nullify(target_link)) {
return true;
}
}
if (val.is_type(type_List)) {
auto list = get_list(key.get_string());
if (list->nullify(target_link)) {
return true;
}
}
}
}
return false;
}
bool Dictionary::replace_link(ObjLink old_link, ObjLink replace_link)
{
size_t ndx = find_first(old_link);
if (ndx != realm::not_found) {
auto key = do_get_key(ndx);
insert(key, replace_link);
return true;
}
else {
// There must be a link in a nested collection
size_t sz = size();
for (size_t ndx = 0; ndx < sz; ndx++) {
auto val = m_values->get(ndx);
auto key = do_get_key(ndx);
if (val.is_type(type_Dictionary)) {
auto dict = get_dictionary(key.get_string());
if (dict->replace_link(old_link, replace_link)) {
return true;
}
}
if (val.is_type(type_List)) {
auto list = get_list(key.get_string());
if (list->replace_link(old_link, replace_link)) {
return true;
}
}
}
}
return false;
}
bool Dictionary::remove_backlinks(CascadeState& state) const
{
size_t sz = size();
bool recurse = false;
for (size_t ndx = 0; ndx < sz; ndx++) {
if (clear_backlink(ndx, state)) {
recurse = true;
}
}
return recurse;
}
size_t Dictionary::find_first(Mixed value) const
{
return update() ? m_values->find_first(value) : realm::not_found;
}
void Dictionary::clear()
{
if (size() > 0) {
if (Replication* repl = get_replication()) {
repl->dictionary_clear(*this);
}
CascadeState cascade_state(CascadeState::Mode::Strong);
bool recurse = remove_backlinks(cascade_state);
// Just destroy the whole cluster
m_dictionary_top->destroy_deep();
m_dictionary_top.reset();
update_child_ref(0, 0);
if (recurse)
_impl::TableFriend::remove_recursive(*get_table_unchecked(), cascade_state); // Throws
}
}
UpdateStatus Dictionary::init_from_parent(bool allow_create) const
{
Base::update_content_version();
try {
auto ref = Base::get_collection_ref();
if ((ref || allow_create) && !m_dictionary_top) {
Allocator& alloc = get_alloc();
m_dictionary_top.reset(new Array(alloc));
m_dictionary_top->set_parent(const_cast<Dictionary*>(this), 0);
switch (m_key_type) {
case type_String: {
m_keys.reset(new BPlusTree<StringData>(alloc));
break;
}
case type_Int: {
m_keys.reset(new BPlusTree<Int>(alloc));
break;
}
default:
break;
}
m_keys->set_parent(m_dictionary_top.get(), 0);
m_values.reset(new BPlusTreeMixed(alloc));
m_values->set_parent(m_dictionary_top.get(), 1);
}
if (ref) {
m_dictionary_top->init_from_ref(ref);
m_keys->init_from_parent();
m_values->init_from_parent();
}
else {
// dictionary detached
if (!allow_create) {
m_dictionary_top.reset();
return UpdateStatus::Detached;
}
// Create dictionary
m_dictionary_top->create(Array::type_HasRefs, false, 2, 0);
m_values->create();
m_keys->create();
m_dictionary_top->update_parent();
}
return UpdateStatus::Updated;
}
catch (...) {
m_dictionary_top.reset();
throw;
}
}
size_t Dictionary::do_find_key(Mixed key) const noexcept
{
auto [ndx, actual_key] = find_impl(key);
if (actual_key == key) {
return ndx;
}
return realm::npos;
}
std::pair<size_t, Mixed> Dictionary::find_impl(Mixed key) const noexcept
{
auto sz = m_keys->size();
Mixed actual;
if (sz && key.is_type(m_key_type)) {
switch (m_key_type) {
case type_String: {
auto keys = static_cast<BPlusTree<StringData>*>(m_keys.get());
StringData val = key.get<StringData>();
IteratorAdapter help(keys);
auto it = std::lower_bound(help.begin(), help.end(), val);
if (it.index() < sz) {
actual = *it;
}
return {it.index(), actual};
break;
}
case type_Int: {
auto keys = static_cast<BPlusTree<Int>*>(m_keys.get());
Int val = key.get<Int>();
IteratorAdapter help(keys);
auto it = std::lower_bound(help.begin(), help.end(), val);
if (it.index() < sz) {
actual = *it;
}
return {it.index(), actual};
break;
}
default:
break;
}
}
return {sz, actual};
}
Mixed Dictionary::do_get(size_t ndx) const
{
Mixed val = m_values->get(ndx);
// Filter out potential unresolved links
if (val.is_type(type_TypedLink) && val.get<ObjKey>().is_unresolved()) {
return {};
}
return val;
}
void Dictionary::do_erase(size_t ndx, Mixed key)
{
CascadeState cascade_state(CascadeState::Mode::Strong);
bool recurse = clear_backlink(ndx, cascade_state);
if (recurse)
_impl::TableFriend::remove_recursive(*get_table_unchecked(), cascade_state); // Throws
if (Replication* repl = get_replication()) {
repl->dictionary_erase(*this, ndx, key);
}
m_keys->erase(ndx);
m_values->erase(ndx);
bump_content_version();
}
Mixed Dictionary::do_get_key(size_t ndx) const
{
switch (m_key_type) {
case type_String: {
return static_cast<BPlusTree<StringData>*>(m_keys.get())->get(ndx);
}
case type_Int: {
return static_cast<BPlusTree<Int>*>(m_keys.get())->get(ndx);
}
default:
break;
}
return {};
}
std::pair<Mixed, Mixed> Dictionary::do_get_pair(size_t ndx) const
{
return {do_get_key(ndx), do_get(ndx)};
}
bool Dictionary::clear_backlink(size_t ndx, CascadeState& state) const
{