/
index_string.cpp
1802 lines (1499 loc) · 62.6 KB
/
index_string.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 2016 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 <cstdio>
#include <iomanip>
#ifdef REALM_DEBUG
#include <iostream>
#endif
#include <realm/exceptions.hpp>
#include <realm/index_string.hpp>
#include <realm/column.hpp>
#include <realm/column_string.hpp>
#include <realm/column_string_enum.hpp>
#include <realm/column_timestamp.hpp> // Timestamp
using namespace realm;
using namespace realm::util;
namespace {
void get_child(Array& parent, size_t child_ref_ndx, Array& child) noexcept
{
ref_type child_ref = parent.get_as_ref(child_ref_ndx);
child.init_from_ref(child_ref);
child.set_parent(&parent, child_ref_ndx);
}
} // anonymous namespace
namespace realm {
StringData GetIndexData<Timestamp>::get_index_data(const Timestamp& dt, StringIndex::StringConversionBuffer& buffer)
{
if (dt.is_null())
return null{};
int64_t s = dt.get_seconds();
int32_t ns = dt.get_nanoseconds();
constexpr size_t index_size = sizeof(s) + sizeof(ns);
static_assert(index_size <= StringIndex::string_conversion_buffer_size,
"Index string conversion buffer too small");
const char* s_buf = reinterpret_cast<const char*>(&s);
const char* ns_buf = reinterpret_cast<const char*>(&ns);
realm::safe_copy_n(s_buf, sizeof(s), buffer.data());
realm::safe_copy_n(ns_buf, sizeof(ns), buffer.data() + sizeof(s));
return StringData{buffer.data(), index_size};
}
template <>
size_t IndexArray::from_list<index_FindFirst>(StringData value, InternalFindResult& /* result_ref */,
const IntegerColumn& rows, ColumnBase* column) const
{
SortedListComparator slc(*column);
IntegerColumn::const_iterator it_end = rows.cend();
IntegerColumn::const_iterator lower = std::lower_bound(rows.cbegin(), it_end, value, slc);
if (lower == it_end)
return not_found;
const size_t first_row_ndx = to_size_t(*lower);
// The buffer is needed when for when this is an integer index.
StringIndex::StringConversionBuffer buffer;
StringData str = column->get_index_data(first_row_ndx, buffer);
if (str != value)
return not_found;
return first_row_ndx;
}
template <>
size_t IndexArray::from_list<index_Count>(StringData value, InternalFindResult& /* result_ref */,
const IntegerColumn& rows, ColumnBase* column) const
{
SortedListComparator slc(*column);
IntegerColumn::const_iterator it_end = rows.cend();
IntegerColumn::const_iterator lower = std::lower_bound(rows.cbegin(), it_end, value, slc);
if (lower == it_end)
return 0;
const size_t first_row_ndx = to_size_t(*lower);
// The buffer is needed when for when this is an integer index.
StringIndex::StringConversionBuffer buffer;
StringData str = column->get_index_data(first_row_ndx, buffer);
if (str != value)
return 0;
IntegerColumn::const_iterator upper = std::upper_bound(lower, it_end, value, slc);
size_t cnt = upper - lower;
return cnt;
}
template <>
size_t IndexArray::from_list<index_FindAll_nocopy>(StringData value, InternalFindResult& result_ref,
const IntegerColumn& rows, ColumnBase* column) const
{
SortedListComparator slc(*column);
IntegerColumn::const_iterator it_end = rows.cend();
IntegerColumn::const_iterator lower = std::lower_bound(rows.cbegin(), it_end, value, slc);
if (lower == it_end)
return size_t(FindRes_not_found);
const size_t first_row_ndx = to_size_t(*lower);
// The buffer is needed when for when this is an integer index.
StringIndex::StringConversionBuffer buffer;
StringData str = column->get_index_data(first_row_ndx, buffer);
if (str != value)
return size_t(FindRes_not_found);
// Optimization: check the last entry before trying upper bound.
IntegerColumn::const_iterator upper = it_end;
--upper;
// Single result if upper matches lower
if (upper == lower) {
result_ref.payload = to_size_t(*lower);
return size_t(FindRes_single);
}
// Check string value at upper, if equal return matches in (lower, upper]
const size_t last_row_ndx = to_size_t(*upper);
str = column->get_index_data(last_row_ndx, buffer);
if (str == value) {
result_ref.payload = rows.get_ref();
result_ref.start_ndx = lower.get_col_ndx();
result_ref.end_ndx = upper.get_col_ndx() + 1; // one past last match
return size_t(FindRes_column);
}
// Last result is not equal, find the upper bound of the range of results.
// Note that we are passing upper which is cend() - 1 here as we already
// checked the last item manually.
upper = std::upper_bound(lower, upper, value, slc);
result_ref.payload = to_ref(rows.get_ref());
result_ref.start_ndx = lower.get_col_ndx();
result_ref.end_ndx = upper.get_col_ndx();
return size_t(FindRes_column);
}
template <IndexMethod method>
size_t IndexArray::index_string(StringData value, InternalFindResult& result_ref, ColumnBase* column) const
{
// Return`realm::not_found`, or an index to the (any) match
constexpr bool first(method == index_FindFirst);
// Return 0, or the number of items that match the specified `value`
constexpr bool get_count(method == index_Count);
// Same as `index_FindAll` but does not copy matching rows into `column`
// returns FindRes_not_found if there are no matches
// returns FindRes_single and the row index (literal) in result_ref.payload
// or returns FindRes_column and the reference to a column of duplicates in
// result_ref.result with the results in the bounds start_ndx, and end_ndx
constexpr bool allnocopy(method == index_FindAll_nocopy);
constexpr size_t local_not_found = allnocopy ? size_t(FindRes_not_found) : first ? not_found : 0;
const char* data = m_data;
const char* header;
uint_least8_t width = m_width;
bool is_inner_node = m_is_inner_bptree_node;
typedef StringIndex::key_type key_type;
size_t stringoffset = 0;
// Create 4 byte index key
key_type key = StringIndex::create_key(value, stringoffset);
for (;;) {
// Get subnode table
ref_type offsets_ref = to_ref(get_direct(data, width, 0));
// Find the position matching the key
const char* offsets_header = m_alloc.translate(offsets_ref);
const char* offsets_data = get_data_from_header(offsets_header);
size_t offsets_size = get_size_from_header(offsets_header);
size_t pos = ::lower_bound<32>(offsets_data, offsets_size, key); // keys are always 32 bits wide
// If key is outside range, we know there can be no match
if (pos == offsets_size)
return local_not_found;
// Get entry under key
size_t pos_refs = pos + 1; // first entry in refs points to offsets
int64_t ref = get_direct(data, width, pos_refs);
if (is_inner_node) {
// Set vars for next iteration
header = m_alloc.translate(to_ref(ref));
data = get_data_from_header(header);
width = get_width_from_header(header);
is_inner_node = get_is_inner_bptree_node_from_header(header);
continue;
}
key_type stored_key = key_type(get_direct<32>(offsets_data, pos));
if (stored_key != key)
return local_not_found;
// Literal row index (tagged)
if (ref & 1) {
size_t row_ndx = size_t(uint64_t(ref) >> 1);
// The buffer is needed when for when this is an integer index.
StringIndex::StringConversionBuffer buffer;
StringData str = column->get_index_data(row_ndx, buffer);
if (str == value) {
result_ref.payload = row_ndx;
return first ? row_ndx : get_count ? 1 : FindRes_single;
}
return local_not_found;
}
const char* sub_header = m_alloc.translate(to_ref(ref));
const bool sub_isindex = get_context_flag_from_header(sub_header);
// List of row indices with common prefix up to this point, in sorted order.
if (!sub_isindex) {
const IntegerColumn sub(m_alloc, to_ref(ref));
return from_list<method>(value, result_ref, sub, column);
}
// Recurse into sub-index;
header = sub_header;
data = get_data_from_header(header);
width = get_width_from_header(header);
is_inner_node = get_is_inner_bptree_node_from_header(header);
// Go to next key part of the string. If the offset exceeds the string length, the key will be 0
stringoffset += 4;
// Update 4 byte index key
key = StringIndex::create_key(value, stringoffset);
}
}
void IndexArray::from_list_all_ins(StringData upper_value, std::vector<size_t>& result, const IntegerColumn& rows,
ColumnBase* column) const
{
// The buffer is needed when for when this is an integer index.
StringIndex::StringConversionBuffer buffer;
// optimization for the most common case, where all the strings under a given subindex are equal
StringData first_str = column->get_index_data(to_size_t(*rows.cbegin()), buffer);
StringData last_str = column->get_index_data(to_size_t(*(rows.cend() - 1)), buffer);
if (first_str == last_str) {
auto first_str_upper = case_map(first_str, true);
if (first_str_upper != upper_value) {
return;
}
for (IntegerColumn::const_iterator it = rows.cbegin(); it != rows.cend(); ++it) {
const size_t row_ndx = to_size_t(*it);
result.push_back(row_ndx);
}
return;
}
// special case for very long strings, where they might have a common prefix and end up in the
// same subindex column, but still not be identical
for (IntegerColumn::const_iterator it = rows.cbegin(); it != rows.cend(); ++it) {
const size_t row_ndx = to_size_t(*it);
StringData str = column->get_index_data(row_ndx, buffer);
auto upper_str = case_map(str, true);
if (upper_str == upper_value) {
result.push_back(row_ndx);
}
}
return;
}
void IndexArray::from_list_all(StringData value, IntegerColumn& result, const IntegerColumn& rows,
ColumnBase* column) const
{
SortedListComparator slc(*column);
IntegerColumn::const_iterator it_end = rows.cend();
IntegerColumn::const_iterator lower = std::lower_bound(rows.cbegin(), it_end, value, slc);
if (lower == it_end)
return;
const size_t first_row_ndx = to_size_t(*lower);
// The buffer is needed when for when this is an integer index.
StringIndex::StringConversionBuffer buffer;
StringData str = column->get_index_data(first_row_ndx, buffer);
if (str != value)
return;
IntegerColumn::const_iterator upper = std::upper_bound(lower, it_end, value, slc);
// Copy all matches into result column
for (IntegerColumn::const_iterator it = lower; it != upper; ++it) {
const size_t cur_row_ndx = to_size_t(*it);
result.add(cur_row_ndx);
}
return;
}
namespace {
// Helper functions for SearchList (index_string_all_ins) for generating permutations of index keys
// replicates the 4 least significant bits each times 8
// eg: abcd -> aaaaaaaabbbbbbbbccccccccdddddddd
int32_t replicate_4_lsb_x8(int32_t i) {
REALM_ASSERT_DEBUG(0 <= i && i <= 15);
i *= 0x204081;
i &= 0x1010101;
i *= 0xff;
return i;
}
int32_t select_from_mask(int32_t a, int32_t b, int32_t mask) {
return a ^ ((a ^ b) & mask);
}
// Given upper and lower keys: "ABCD" and "abcd", the 4 LSBs in the permutation argument determine the
// final key:
// Permutation 0 = "ABCD"
// Permutation 1 = "ABCd"
// Permutation 8 = "aBCD"
// Permutation 15 = "abcd"
using key_type = StringIndex::key_type;
key_type generate_key(key_type upper, key_type lower, int permutation) {
return select_from_mask(upper, lower, replicate_4_lsb_x8(permutation));
}
// Helper structure for IndexArray::index_string_all_ins to generate and keep track of search key permutations,
// when traversing the trees.
struct SearchList {
struct Item {
const char* header;
size_t string_offset;
key_type key;
};
SearchList(const util::Optional<std::string>& upper_value, const util::Optional<std::string>& lower_value)
: m_upper_value(upper_value)
, m_lower_value(lower_value)
{
m_keys_seen.reserve(num_permutations);
}
// Add all unique keys for this level to the internal work stack
void add_all_for_level(const char* header, size_t string_offset)
{
m_keys_seen.clear();
const key_type upper_key = StringIndex::create_key(m_upper_value, string_offset);
const key_type lower_key = StringIndex::create_key(m_lower_value, string_offset);
for (int p = 0; p < num_permutations; ++p) {
// FIXME: This might still be incorrect due to multi-byte unicode characters (crossing the 4 byte key
// size) being combined incorrectly.
const key_type key = generate_key(upper_key, lower_key, p);
const bool new_key = std::find(m_keys_seen.cbegin(), m_keys_seen.cend(), key) == m_keys_seen.cend();
if (new_key) {
m_keys_seen.push_back(key);
add_next(header, string_offset, key);
}
}
}
bool empty() const
{
return m_items.empty();
}
Item get_next()
{
Item item = m_items.back();
m_items.pop_back();
return item;
}
// Add a single entry to the internal work stack. Used to traverse the inner trees (same key)
void add_next(const char* header, size_t string_offset, key_type key)
{
m_items.push_back({header, string_offset, key});
}
private:
static constexpr int num_permutations = 1 << sizeof(key_type); // 4 bytes gives up to 16 search keys
std::vector<Item> m_items;
const util::Optional<std::string> m_upper_value;
const util::Optional<std::string> m_lower_value;
std::vector<key_type> m_keys_seen;
};
} // namespace
void IndexArray::index_string_all_ins(StringData value, IntegerColumn& result, ColumnBase* column) const
{
if (value.is_null()) {
// we can't use case_map on null strings because it currently returns an
// empty string ("") in that case which is different than a null StringData
return index_string_all(value, result, column);
}
const util::Optional<std::string> upper_value = case_map(value, true);
const util::Optional<std::string> lower_value = case_map(value, false);
SearchList search_list(upper_value, lower_value);
std::vector<size_t> tmp_result;
const char* top_header = get_header_from_data(m_data);
search_list.add_all_for_level(top_header, 0);
while (!search_list.empty()) {
SearchList::Item item = search_list.get_next();
const char* const header = item.header;
const size_t string_offset = item.string_offset;
const key_type key = item.key;
const char* const data = get_data_from_header(header);
const uint_least8_t width = get_width_from_header(header);
const bool is_inner_node = get_is_inner_bptree_node_from_header(header);
// Get subnode table
ref_type offsets_ref = to_ref(get_direct(data, width, 0));
// Find the position matching the key
const char* const offsets_header = m_alloc.translate(offsets_ref);
const char* const offsets_data = get_data_from_header(offsets_header);
const size_t offsets_size = get_size_from_header(offsets_header);
const size_t pos = ::lower_bound<32>(offsets_data, offsets_size, key); // keys are always 32 bits wide
// If key is outside range, we know there can be no match
if (pos == offsets_size)
continue;
// Get entry under key
const size_t pos_refs = pos + 1; // first entry in refs points to offsets
const int64_t ref = get_direct(data, width, pos_refs);
if (is_inner_node) {
// Set vars for next iteration
const char* const inner_header = m_alloc.translate(to_ref(ref));
search_list.add_next(inner_header, string_offset, key);
continue;
}
const key_type stored_key = key_type(get_direct<32>(offsets_data, pos));
if (stored_key != key)
continue;
// Literal row index (tagged)
if (ref & 1) {
const size_t row_ndx = size_t(uint64_t(ref) >> 1);
// The buffer is needed when for when this is an integer index.
StringIndex::StringConversionBuffer buffer;
const StringData str = column->get_index_data(row_ndx, buffer);
const util::Optional<std::string> upper_str = case_map(str, true);
if (upper_str == upper_value) {
tmp_result.push_back(row_ndx);
}
continue;
}
const char* const sub_header = m_alloc.translate(to_ref(ref));
const bool sub_isindex = get_context_flag_from_header(sub_header);
// List of row indices with common prefix up to this point, in sorted order.
if (!sub_isindex) {
const IntegerColumn sub(m_alloc, to_ref(ref));
from_list_all_ins(upper_value, tmp_result, sub, column);
continue;
}
// Recurse into sub-index;
search_list.add_all_for_level(sub_header, string_offset + 4);
}
// sort the result and return as IntegerColumn
std::sort(tmp_result.begin(), tmp_result.end());
for (size_t row_ndx : tmp_result) {
result.add(row_ndx);
}
}
void IndexArray::index_string_all(StringData value, IntegerColumn& result, ColumnBase* column) const
{
const char* data = m_data;
const char* header;
uint_least8_t width = m_width;
bool is_inner_node = m_is_inner_bptree_node;
size_t stringoffset = 0;
// Create 4 byte index key
key_type key = StringIndex::create_key(value, stringoffset);
for (;;) {
// Get subnode table
ref_type offsets_ref = to_ref(get_direct(data, width, 0));
// Find the position matching the key
const char* offsets_header = m_alloc.translate(offsets_ref);
const char* offsets_data = get_data_from_header(offsets_header);
size_t offsets_size = get_size_from_header(offsets_header);
size_t pos = ::lower_bound<32>(offsets_data, offsets_size, key); // keys are always 32 bits wide
// If key is outside range, we know there can be no match
if (pos == offsets_size)
return;
// Get entry under key
size_t pos_refs = pos + 1; // first entry in refs points to offsets
int64_t ref = get_direct(data, width, pos_refs);
if (is_inner_node) {
// Set vars for next iteration
header = m_alloc.translate(to_ref(ref));
data = get_data_from_header(header);
width = get_width_from_header(header);
is_inner_node = get_is_inner_bptree_node_from_header(header);
continue;
}
key_type stored_key = key_type(get_direct<32>(offsets_data, pos));
if (stored_key != key)
return;
// Literal row index (tagged)
if (ref & 1) {
size_t row_ndx = size_t(uint64_t(ref) >> 1);
// The buffer is needed when for when this is an integer index.
StringIndex::StringConversionBuffer buffer;
StringData str = column->get_index_data(row_ndx, buffer);
if (str == value) {
result.add(row_ndx);
return;
}
return;
}
const char* sub_header = m_alloc.translate(to_ref(ref));
const bool sub_isindex = get_context_flag_from_header(sub_header);
// List of row indices with common prefix up to this point, in sorted order.
if (!sub_isindex) {
const IntegerColumn sub(m_alloc, to_ref(ref));
return from_list_all(value, result, sub, column);
}
// Recurse into sub-index;
header = sub_header;
data = get_data_from_header(header);
width = get_width_from_header(header);
is_inner_node = get_is_inner_bptree_node_from_header(header);
// Go to next key part of the string. If the offset exceeds the string length, the key will be 0
stringoffset += 4;
// Update 4 byte index key
key = StringIndex::create_key(value, stringoffset);
}
}
} // namespace realm
size_t IndexArray::index_string_find_first(StringData value, ColumnBase* column) const
{
InternalFindResult unused;
return index_string<index_FindFirst>(value, unused, column);
}
void IndexArray::index_string_find_all(IntegerColumn& result, StringData value, ColumnBase* column, bool case_insensitive) const
{
if (case_insensitive) {
index_string_all_ins(value, result, column);
} else {
index_string_all(value, result, column);
}
}
FindRes IndexArray::index_string_find_all_no_copy(StringData value, ColumnBase* column,
InternalFindResult& result) const
{
return static_cast<FindRes>(index_string<index_FindAll_nocopy>(value, result, column));
}
size_t IndexArray::index_string_count(StringData value, ColumnBase* column) const
{
InternalFindResult unused;
return index_string<index_Count>(value, unused, column);
}
IndexArray* StringIndex::create_node(Allocator& alloc, bool is_leaf)
{
Array::Type type = is_leaf ? Array::type_HasRefs : Array::type_InnerBptreeNode;
std::unique_ptr<IndexArray> top(new IndexArray(alloc)); // Throws
top->create(type); // Throws
// Mark that this is part of index
// (as opposed to columns under leaves)
top->set_context_flag(true);
// Add subcolumns for leaves
Array values(alloc);
values.create(Array::type_Normal); // Throws
values.ensure_minimum_width(0x7FFFFFFF); // This ensures 31 bits plus a sign bit
top->add(values.get_ref()); // first entry in refs points to offsets
return top.release();
}
ref_type StringIndex::create_empty(Allocator& alloc)
{
return StringIndex(nullptr, alloc).get_ref(); // Throws
}
void StringIndex::set_target(ColumnBase* target_column) noexcept
{
REALM_ASSERT(target_column);
m_target_column = target_column;
}
StringIndex::key_type StringIndex::get_last_key() const
{
Array offsets(m_array->get_alloc());
get_child(*m_array, 0, offsets);
return key_type(offsets.back());
}
void StringIndex::insert_with_offset(size_t row_ndx, StringData value, size_t offset)
{
// Create 4 byte index key
key_type key = create_key(value, offset);
TreeInsert(row_ndx, key, offset, value); // Throws
}
void StringIndex::insert_to_existing_list_at_lower(size_t row, StringData value, IntegerColumn& list,
const IntegerColumnIterator& lower)
{
SortedListComparator slc(*m_target_column);
// At this point there exists duplicates of this value, we need to
// insert value beside it's duplicates so that rows are also sorted
// in ascending order.
IntegerColumn::const_iterator upper = std::upper_bound(lower, list.cend(), value, slc);
// find insert position (the list has to be kept in sorted order)
// In most cases the refs will be added to the end. So we test for that
// first to see if we can avoid the binary search for insert position
IntegerColumn::const_iterator last = upper - ptrdiff_t(1);
size_t last_ref_of_value = to_size_t(*last);
if (row >= last_ref_of_value) {
list.insert(upper.get_col_ndx(), row);
}
else {
IntegerColumn::const_iterator inner_lower = std::lower_bound(lower, upper, int64_t(row));
list.insert(inner_lower.get_col_ndx(), row);
}
}
void StringIndex::insert_to_existing_list(size_t row, StringData value, IntegerColumn& list)
{
SortedListComparator slc(*m_target_column);
IntegerColumn::const_iterator it_end = list.cend();
IntegerColumn::const_iterator lower = std::lower_bound(list.cbegin(), it_end, value, slc);
if (lower == it_end) {
// Not found and everything is less, just append it to the end.
list.add(row);
}
else {
size_t lower_row = to_size_t(*lower);
StringConversionBuffer buffer; // Used when this is an IntegerIndex
StringData lower_value = get(lower_row, buffer);
if (lower_value != value) {
list.insert(lower.get_col_ndx(), row);
}
else {
// At this point there exists duplicates of this value, we need to
// insert value beside it's duplicates so that rows are also sorted
// in ascending order.
insert_to_existing_list_at_lower(row, value, list, lower);
}
}
}
void StringIndex::insert_row_list(size_t ref, size_t offset, StringData value)
{
REALM_ASSERT(!m_array->is_inner_bptree_node()); // only works in leaves
// Create 4 byte index key
key_type key = create_key(value, offset);
// Get subnode table
Allocator& alloc = m_array->get_alloc();
Array values(alloc);
get_child(*m_array, 0, values);
REALM_ASSERT(m_array->size() == values.size() + 1);
size_t ins_pos = values.lower_bound_int(key);
if (ins_pos == values.size()) {
// When key is outside current range, we can just add it
values.add(key);
m_array->add(ref);
return;
}
#ifdef REALM_DEBUG // LCOV_EXCL_START ignore debug code
// Since we only use this for moving existing values to new
// subindexes, there should never be an existing match.
key_type k = key_type(values.get(ins_pos));
REALM_ASSERT(k != key);
#endif // LCOV_EXCL_STOP ignore debug code
// If key is not present we add it at the correct location
values.insert(ins_pos, key);
m_array->insert(ins_pos + 1, ref);
}
void StringIndex::TreeInsert(size_t row_ndx, key_type key, size_t offset, StringData value)
{
NodeChange nc = do_insert(row_ndx, key, offset, value);
switch (nc.type) {
case NodeChange::none:
return;
case NodeChange::insert_before: {
StringIndex new_node(inner_node_tag(), m_array->get_alloc());
new_node.node_add_key(nc.ref1);
new_node.node_add_key(get_ref());
m_array->init_from_ref(new_node.get_ref());
m_array->update_parent();
return;
}
case NodeChange::insert_after: {
StringIndex new_node(inner_node_tag(), m_array->get_alloc());
new_node.node_add_key(get_ref());
new_node.node_add_key(nc.ref1);
m_array->init_from_ref(new_node.get_ref());
m_array->update_parent();
return;
}
case NodeChange::split: {
StringIndex new_node(inner_node_tag(), m_array->get_alloc());
new_node.node_add_key(nc.ref1);
new_node.node_add_key(nc.ref2);
m_array->init_from_ref(new_node.get_ref());
m_array->update_parent();
return;
}
}
REALM_ASSERT(false); // LCOV_EXCL_LINE; internal Realm error
}
StringIndex::NodeChange StringIndex::do_insert(size_t row_ndx, key_type key, size_t offset, StringData value)
{
Allocator& alloc = m_array->get_alloc();
if (m_array->is_inner_bptree_node()) {
// Get subnode table
Array keys(alloc);
get_child(*m_array, 0, keys);
REALM_ASSERT(m_array->size() == keys.size() + 1);
// Find the subnode containing the item
size_t node_ndx = keys.lower_bound_int(key);
if (node_ndx == keys.size()) {
// node can never be empty, so try to fit in last item
node_ndx = keys.size() - 1;
}
// Get sublist
size_t refs_ndx = node_ndx + 1; // first entry in refs points to offsets
ref_type ref = m_array->get_as_ref(refs_ndx);
StringIndex target(ref, m_array.get(), refs_ndx, m_target_column, alloc);
// Insert item
NodeChange nc = target.do_insert(row_ndx, key, offset, value);
if (nc.type == NodeChange::none) {
// update keys
key_type last_key = target.get_last_key();
keys.set(node_ndx, last_key);
return NodeChange::none; // no new nodes
}
if (nc.type == NodeChange::insert_after) {
++node_ndx;
++refs_ndx;
}
// If there is room, just update node directly
if (keys.size() < REALM_MAX_BPNODE_SIZE) {
if (nc.type == NodeChange::split) {
node_insert_split(node_ndx, nc.ref2);
}
else {
node_insert(node_ndx, nc.ref1); // ::INSERT_BEFORE/AFTER
}
return NodeChange::none;
}
// Else create new node
StringIndex new_node(inner_node_tag(), alloc);
if (nc.type == NodeChange::split) {
// update offset for left node
key_type last_key = target.get_last_key();
keys.set(node_ndx, last_key);
new_node.node_add_key(nc.ref2);
++node_ndx;
++refs_ndx;
}
else {
new_node.node_add_key(nc.ref1);
}
switch (node_ndx) {
case 0: // insert before
return NodeChange(NodeChange::insert_before, new_node.get_ref());
case REALM_MAX_BPNODE_SIZE: // insert after
if (nc.type == NodeChange::split)
return NodeChange(NodeChange::split, get_ref(), new_node.get_ref());
return NodeChange(NodeChange::insert_after, new_node.get_ref());
default: // split
// Move items after split to new node
size_t len = m_array->size();
for (size_t i = refs_ndx; i < len; ++i) {
ref_type ref_i = m_array->get_as_ref(i);
new_node.node_add_key(ref_i);
}
keys.truncate(node_ndx);
m_array->truncate(refs_ndx);
return NodeChange(NodeChange::split, get_ref(), new_node.get_ref());
}
}
else {
// Is there room in the list?
Array old_keys(alloc);
get_child(*m_array, 0, old_keys);
const size_t old_offsets_size = old_keys.size();
REALM_ASSERT_EX(m_array->size() == old_offsets_size + 1, m_array->size(), old_offsets_size + 1);
bool noextend = old_offsets_size >= REALM_MAX_BPNODE_SIZE;
// See if we can fit entry into current leaf
// Works if there is room or it can join existing entries
if (leaf_insert(row_ndx, key, offset, value, noextend))
return NodeChange::none;
// Create new list for item (a leaf)
StringIndex new_list(m_target_column, alloc);
new_list.leaf_insert(row_ndx, key, offset, value);
size_t ndx = old_keys.lower_bound_int(key);
// insert before
if (ndx == 0)
return NodeChange(NodeChange::insert_before, new_list.get_ref());
// insert after
if (ndx == old_offsets_size)
return NodeChange(NodeChange::insert_after, new_list.get_ref());
// split
Array new_keys(alloc);
get_child(*new_list.m_array, 0, new_keys);
// Move items after split to new list
for (size_t i = ndx; i < old_offsets_size; ++i) {
int64_t v2 = old_keys.get(i);
int64_t v3 = m_array->get(i + 1);
new_keys.add(v2);
new_list.m_array->add(v3);
}
old_keys.truncate(ndx);
m_array->truncate(ndx + 1);
return NodeChange(NodeChange::split, get_ref(), new_list.get_ref());
}
}
void StringIndex::node_insert_split(size_t ndx, size_t new_ref)
{
REALM_ASSERT(m_array->is_inner_bptree_node());
REALM_ASSERT(new_ref);
Allocator& alloc = m_array->get_alloc();
Array offsets(alloc);
get_child(*m_array, 0, offsets);
REALM_ASSERT(m_array->size() == offsets.size() + 1);
REALM_ASSERT(ndx < offsets.size());
REALM_ASSERT(offsets.size() < REALM_MAX_BPNODE_SIZE);
// Get sublists
size_t refs_ndx = ndx + 1; // first entry in refs points to offsets
ref_type orig_ref = m_array->get_as_ref(refs_ndx);
StringIndex orig_col(orig_ref, m_array.get(), refs_ndx, m_target_column, alloc);
StringIndex new_col(new_ref, nullptr, 0, m_target_column, alloc);
// Update original key
key_type last_key = orig_col.get_last_key();
offsets.set(ndx, last_key);
// Insert new ref
key_type new_key = new_col.get_last_key();
offsets.insert(ndx + 1, new_key);
m_array->insert(ndx + 2, new_ref);
}
void StringIndex::node_insert(size_t ndx, size_t ref)
{
REALM_ASSERT(ref);
REALM_ASSERT(m_array->is_inner_bptree_node());
Allocator& alloc = m_array->get_alloc();
Array offsets(alloc);
get_child(*m_array, 0, offsets);
REALM_ASSERT(m_array->size() == offsets.size() + 1);
REALM_ASSERT(ndx <= offsets.size());
REALM_ASSERT(offsets.size() < REALM_MAX_BPNODE_SIZE);
StringIndex col(ref, nullptr, 0, m_target_column, alloc);
key_type last_key = col.get_last_key();
offsets.insert(ndx, last_key);
m_array->insert(ndx + 1, ref);
}
bool StringIndex::leaf_insert(size_t row_ndx, key_type key, size_t offset, StringData value, bool noextend)
{
REALM_ASSERT(!m_array->is_inner_bptree_node());
// Get subnode table
Allocator& alloc = m_array->get_alloc();
Array keys(alloc);
get_child(*m_array, 0, keys);
REALM_ASSERT(m_array->size() == keys.size() + 1);
size_t ins_pos = keys.lower_bound_int(key);
if (ins_pos == keys.size()) {
if (noextend)
return false;
// When key is outside current range, we can just add it
keys.add(key);
int64_t shifted = int64_t((uint64_t(row_ndx) << 1) + 1); // shift to indicate literal
m_array->add(shifted);
return true;
}
size_t ins_pos_refs = ins_pos + 1; // first entry in refs points to offsets
key_type k = key_type(keys.get(ins_pos));
// If key is not present we add it at the correct location
if (k != key) {
if (noextend)
return false;
keys.insert(ins_pos, key);
int64_t shifted = int64_t((uint64_t(row_ndx) << 1) + 1); // shift to indicate literal
m_array->insert(ins_pos_refs, shifted);
return true;