forked from dgraph-io/sroar
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbitmap.go
1358 lines (1189 loc) · 33.8 KB
/
bitmap.go
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 2021 Dgraph Labs, Inc. and Contributors
*
* 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.
*/
package sroar
import (
"fmt"
"math"
"sort"
"strings"
"sync"
"github.com/pkg/errors"
)
var empty = make([]uint16, 16<<20)
const mask = uint64(0xFFFFFFFFFFFF0000)
type Bitmap struct {
data []uint16
keys node
// This _ptr is only used when we start with a []byte instead of a
// []uint16. Because we do an unsafe conversion to []uint16 data, and hence,
// do NOT own a valid pointer to the underlying array.
_ptr []byte
// memMoved keeps track of how many uint16 moves we had to do. The smaller
// this number, the more efficient we have been.
memMoved int
}
// FromBuffer returns a pointer to bitmap corresponding to the given buffer. This bitmap shouldn't
// be modified because it might corrupt the given buffer.
func FromBuffer(data []byte) *Bitmap {
assert(len(data)%2 == 0)
if len(data) < 8 {
return NewBitmap()
}
du := toUint16Slice(data)
x := toUint64Slice(du[:4])[indexNodeSize]
return &Bitmap{
data: du,
_ptr: data, // Keep a hold of data, otherwise GC would do its thing.
keys: toUint64Slice(du[:x]),
}
}
// FromBufferWithCopy creates a copy of the given buffer and returns a bitmap based on the copied
// buffer. This bitmap is safe for both read and write operations.
func FromBufferWithCopy(src []byte) *Bitmap {
assert(len(src)%2 == 0)
if len(src) < 8 {
return NewBitmap()
}
src16 := toUint16Slice(src)
dst16 := make([]uint16, len(src16))
copy(dst16, src16)
x := toUint64Slice(dst16[:4])[indexNodeSize]
return &Bitmap{
data: dst16,
keys: toUint64Slice(dst16[:x]),
}
}
func (ra *Bitmap) ToBuffer() []byte {
if ra.IsEmpty() {
return nil
}
return toByteSlice(ra.data)
}
func (ra *Bitmap) ToBufferWithCopy() []byte {
if ra.IsEmpty() {
return nil
}
buf := make([]uint16, len(ra.data))
copy(buf, ra.data)
return toByteSlice(buf)
}
func NewBitmap() *Bitmap {
return NewBitmapWith(2)
}
func NewBitmapWith(numKeys int) *Bitmap {
if numKeys < 2 {
panic("Must contain at least two keys.")
}
ra := &Bitmap{
// Each key must also keep an offset. So, we need to double the number
// of uint64s allocated. Plus, we need to make space for the first 2
// uint64s to store the number of keys and node size.
data: make([]uint16, 4*(2*numKeys+2)),
}
ra.keys = toUint64Slice(ra.data)
ra.keys.setNodeSize(len(ra.data))
// Always generate a container for key = 0x00. Otherwise, node gets confused
// about whether a zero key is a new key or not.
offset := ra.newContainer(minContainerSize)
// First two are for num keys. index=2 -> 0 key. index=3 -> offset.
ra.keys.setAt(indexNodeStart+1, offset)
ra.keys.setNumKeys(1)
return ra
}
func (ra *Bitmap) initSpaceForKeys(N int) {
if N == 0 {
return
}
curSize := uint64(len(ra.keys) * 4) // U64 -> U16
bySize := uint64(N * 8) // 2xU64 (key, value) -> 2x4xU16
// The following code is borrowed from setKey.
ra.scootRight(curSize, bySize)
ra.keys = toUint64Slice(ra.data[:curSize+bySize])
ra.keys.setNodeSize(int(curSize + bySize))
assert(1 == ra.keys.numKeys()) // This initialization assumes that the number of keys are 1.
// The containers have moved to the right bySize. So, update their offsets.
// Currently, there's only one container.
val := ra.keys.val(0)
ra.keys.setAt(valOffset(0), val+uint64(bySize))
}
// setKey sets a key and container offset.
func (ra *Bitmap) setKey(k uint64, offset uint64) uint64 {
if added := ra.keys.set(k, offset); !added {
// No new key was added. So, we can just return.
return offset
}
// A new key was added. Let's ensure that ra.keys is not full.
if !ra.keys.isFull() {
return offset
}
// ra.keys is full. We should expand its size.
bySize := ra.expandKeys(0)
return offset + bySize
}
func (ra *Bitmap) expandKeys(bySize uint64) uint64 {
curSize := uint64(len(ra.keys) * 4) // Multiply by 4 for U64 -> U16.
if bySize == 0 {
bySize = curSize
}
if bySize > math.MaxUint16 {
bySize = math.MaxUint16
}
ra.scootRight(curSize, bySize)
ra.keys = uint16To64SliceUnsafe(ra.data[:curSize+bySize])
ra.keys.setNodeSize(int(curSize + bySize))
// All containers have moved to the right by bySize bytes.
// Update their offsets.
n := ra.keys
for i := 0; i < n.maxKeys(); i++ {
val := n.val(i)
if val > 0 {
n.setAt(valOffset(i), val+uint64(bySize))
}
}
return bySize
}
func (ra *Bitmap) fastExpand(bySize uint64) {
toSize := ra.expandNoLengthChange(bySize)
ra.data = ra.data[:toSize]
}
func (ra *Bitmap) expandNoLengthChange(bySize uint64) (toSize int) {
// This following statement also works. But, given how much fastExpand gets
// called (a lot), probably better to control allocation.
// ra.data = append(ra.data, empty[:bySize]...)
toSize = len(ra.data) + int(bySize)
if toSize <= cap(ra.data) {
return
}
growBy := cap(ra.data)
if growBy < int(bySize) {
growBy = int(bySize)
}
out := make([]uint16, len(ra.data), cap(ra.data)+growBy)
copy(out, ra.data)
prev := len(ra.keys) * 4 // Multiply by 4 to convert from u16 to u64.
ra.data = out
ra._ptr = nil // Allow Go to GC whatever this was pointing to.
// Re-reference ra.keys correctly because underlying array has changed.
ra.keys = uint16To64SliceUnsafe(ra.data[:prev])
return
}
// scootRight isn't aware of containers. It's going to create empty space of
// bySize at the given offset in ra.data. The offset doesn't need to line up
// with a container.
func (ra *Bitmap) scootRight(offset uint64, bySize uint64) {
left := ra.data[offset:]
ra.fastExpand(bySize) // Expand the buffer.
right := ra.data[len(ra.data)-len(left):]
n := copy(right, left) // Move data right.
ra.memMoved += n
Memclr(ra.data[offset : offset+uint64(bySize)]) // Zero out the space in the middle.
}
// scootLeft removes size number of uint16s starting from the given offset.
func (ra *Bitmap) scootLeft(offset uint64, size uint64) {
n := uint64(len(ra.data))
right := ra.data[offset+size:]
ra.memMoved += copy(ra.data[offset:], right)
ra.data = ra.data[:n-size]
}
func (ra *Bitmap) newContainer(sz uint16) uint64 {
offset := ra.newContainerNoClr(sz)
ra.data[offset] = sz
Memclr(ra.data[offset+1 : offset+uint64(sz)])
return offset
}
func (ra *Bitmap) newContainerNoClr(sz uint16) uint64 {
offset := uint64(len(ra.data))
ra.fastExpand(uint64(sz))
return offset
}
// expandContainer would expand a container at the given offset. It would typically double the size
// of the container, until it reaches a threshold, where the size of the container would reach 2^16.
// Expressed in uint16s, that'd be (2^16)/(2^4) = 2^12 = 4096. So, if the container size >= 2048,
// then doubling that would put it above 4096. That's why in the code below, you see the checks for
// size 2048.
func (ra *Bitmap) expandContainer(offset uint64) {
sz := ra.data[offset]
if sz == 0 {
panic("Container size should NOT be zero")
}
bySize := uint16(sz)
if sz >= 2048 {
// Size is in uint16. Half of max allowed size. If we're expanding the container by more
// than 2048, we should just cap it to max size of 4096.
assert(sz < maxContainerSize)
bySize = maxContainerSize - sz
}
// Select the portion to the right of the container, beyond its right boundary.
ra.scootRight(offset+uint64(sz), uint64(bySize))
ra.keys.updateOffsets(offset, uint64(bySize), true)
if sz < 2048 {
ra.data[offset] = sz + bySize
} else {
// Convert to bitmap container.
src := array(ra.getContainer(offset))
buf := src.toBitmapContainer(nil)
assert(copy(ra.data[offset:], buf) == maxContainerSize)
}
}
// stepSize is used for container expansion. For a container of given size n,
// stepSize would return the target size. This function is used to reduce the
// number of times expansion needs to happen for each container.
func stepSize(n uint16) uint16 {
// <=64 -> 128
// <=128 -> 256
// <=256 -> 512
// <=512 -> 1024
// <=1024 -> 2048
// >1024 -> maxSize (convert to bitmap)
for i := uint16(64); i <= 1024; i *= 2 {
if n <= i {
return i * 2
}
}
return maxContainerSize
}
// copyAt would copy over a given container via src, into the container at
// offset. If src is a bitmap, it would copy it over directly. If src is an
// array container, then it would follow these paths:
// - If src is smaller than dst, copy it over.
// - If not, look for target size for dst using the stepSize function.
// - If target size is maxSize, then convert src to a bitmap container, and
// copy to dst.
// - If target size is not max size, then expand dst container and copy src.
func (ra *Bitmap) copyAt(offset uint64, src []uint16) {
dstSize := ra.data[offset]
if dstSize == 0 {
panic("Container size should NOT be zero")
}
// The src is a bitmapContainer. Just copy it over.
if src[indexType] == typeBitmap {
assert(src[indexSize] == maxContainerSize)
bySize := uint16(maxContainerSize) - dstSize
// Select the portion to the right of the container, beyond its right boundary.
ra.scootRight(offset+uint64(dstSize), uint64(bySize))
ra.keys.updateOffsets(offset, uint64(bySize), true)
assert(copy(ra.data[offset:], src) == len(src))
return
}
// src is an array container. Check if dstSize >= src. If so, just copy.
// But, do keep dstSize intact, otherwise we'd lose portion of our container.
if dstSize >= src[indexSize] {
assert(copy(ra.data[offset:], src) == len(src))
ra.data[offset] = dstSize
return
}
// dstSize < src. Determine the target size of the container.
targetSz := stepSize(dstSize)
for targetSz < src[indexSize] {
targetSz = stepSize(targetSz)
}
if targetSz == maxContainerSize {
// Looks like the targetSize is now maxSize. So, convert src to bitmap container.
s := array(src)
bySize := uint16(maxContainerSize) - dstSize
// Select the portion to the right of the container, beyond its right boundary.
ra.scootRight(offset+uint64(dstSize), uint64(bySize))
ra.keys.updateOffsets(offset, uint64(bySize), true)
// Update the space of the container, so getContainer would work correctly.
ra.data[offset] = maxContainerSize
// Convert the src array to bitmap and write it directly over to the container.
out := ra.getContainer(offset)
Memclr(out)
s.toBitmapContainer(out)
return
}
// targetSize is not maxSize. Let's expand to targetSize and copy array.
bySize := targetSz - dstSize
ra.scootRight(offset+uint64(dstSize), uint64(bySize))
ra.keys.updateOffsets(offset, uint64(bySize), true)
assert(copy(ra.data[offset:], src) == len(src))
ra.data[offset] = targetSz
}
func (ra *Bitmap) insertAt(offset uint64, src []uint16) {
dstSize := ra.data[offset]
targetSz := src[indexSize]
bySize := targetSz - dstSize
ra.scootRight(offset+uint64(dstSize), uint64(bySize))
ra.keys.updateOffsets(offset, uint64(bySize), true)
assert(copy(ra.data[offset:], src) == len(src))
ra.data[offset] = targetSz
}
func (ra *Bitmap) getContainer(offset uint64) []uint16 {
data := ra.data[offset:]
if len(data) == 0 {
panic(fmt.Sprintf("No container found at offset: %d\n", offset))
}
sz := data[0]
return data[:sz]
}
func (ra *Bitmap) Clone() *Bitmap {
abuf := ra.ToBuffer()
bbuf := make([]byte, len(abuf))
copy(bbuf, abuf)
return FromBuffer(bbuf)
}
func (ra *Bitmap) IsEmpty() bool {
if ra == nil {
return true
}
N := ra.keys.numKeys()
for i := 0; i < N; i++ {
offset := ra.keys.val(i)
cont := ra.getContainer(offset)
if c := getCardinality(cont); c > 0 {
return false
}
}
return true
}
func (ra *Bitmap) Set(x uint64) bool {
key := x & mask
offset, has := ra.keys.getValue(key)
if !has {
// We need to add a container.
o := ra.newContainer(minContainerSize)
// offset might have been updated by setKey.
offset = ra.setKey(key, o)
}
// make sure there is enough space to put new value in array container
c := ra.getContainer(offset)
if c[indexType] == typeArray && array(c).isFull() {
ra.expandContainer(offset)
// not sure if needed after expanding,
// just in case get offset and container again
offset, has = ra.keys.getValue(key)
if !has {
// We need to add a container.
o := ra.newContainer(minContainerSize)
// offset might have been updated by setKey.
offset = ra.setKey(key, o)
}
c = ra.getContainer(offset)
}
switch c[indexType] {
case typeArray:
p := array(c)
return p.add(uint16(x))
case typeBitmap:
b := bitmap(c)
return b.add(uint16(x))
}
panic("we shouldn't reach here")
}
func FromSortedList(vals []uint64) *Bitmap {
var arr []uint16
var hi, lastHi, off uint64
ra := NewBitmap()
if len(vals) == 0 {
return ra
}
// Set the keys beforehand so that we don't need to move a lot of memory because of adding keys.
var numKeys int
for _, x := range vals {
hi = x & mask
if hi != 0 && hi != lastHi {
numKeys++
}
lastHi = hi
}
ra.initSpaceForKeys(numKeys)
finalize := func(l []uint16, key uint64) {
if len(l) == 0 {
return
}
if len(l) <= 2048 {
// 4 uint16s for the header, and extra 4 uint16s so that adding more elements using
// Set operation doesn't fail.
sz := uint16(8 + len(l))
off = ra.newContainer(sz)
c := ra.getContainer(off)
c[indexSize] = sz
c[indexType] = typeArray
setCardinality(c, len(l))
for i := 0; i < len(l); i++ {
c[int(startIdx)+i] = l[i]
}
} else {
off = ra.newContainer(maxContainerSize)
c := ra.getContainer(off)
c[indexSize] = maxContainerSize
c[indexType] = typeBitmap
for _, v := range l {
bitmap(c).add(v)
}
}
ra.setKey(key, off)
return
}
lastHi = 0
for _, x := range vals {
hi = x & mask
// Finalize the last container before proceeding ahead
if hi != 0 && hi != lastHi {
finalize(arr, lastHi)
arr = arr[:0]
}
arr = append(arr, uint16(x))
lastHi = hi
}
finalize(arr, lastHi)
return ra
}
// TODO: Potentially this can be optimized.
func (ra *Bitmap) SetMany(vals []uint64) {
for _, k := range vals {
ra.Set(k)
}
}
// Select returns the element at the xth index. (0-indexed)
func (ra *Bitmap) Select(x uint64) (uint64, error) {
if x >= uint64(ra.GetCardinality()) {
return 0, errors.Errorf("index %d is not less than the cardinality: %d",
x, ra.GetCardinality())
}
n := ra.keys.numKeys()
for i := 0; i < n; i++ {
off := ra.keys.val(i)
con := ra.getContainer(off)
c := uint64(getCardinality(con))
assert(c != uint64(invalidCardinality))
if x < c {
key := ra.keys.key(i)
switch con[indexType] {
case typeArray:
return key | uint64(array(con).all()[x]), nil
case typeBitmap:
return key | uint64(bitmap(con).selectAt(int(x))), nil
}
}
x -= c
}
panic("should not reach here")
}
func (ra *Bitmap) Contains(x uint64) bool {
if ra == nil {
return false
}
key := x & mask
offset, has := ra.keys.getValue(key)
if !has {
return false
}
y := uint16(x)
c := ra.getContainer(offset)
switch c[indexType] {
case typeArray:
p := array(c)
return p.has(y)
case typeBitmap:
b := bitmap(c)
return b.has(y)
}
return false
}
func (ra *Bitmap) Remove(x uint64) bool {
if ra == nil {
return false
}
key := x & mask
offset, has := ra.keys.getValue(key)
if !has {
return false
}
c := ra.getContainer(offset)
switch c[indexType] {
case typeArray:
p := array(c)
return p.remove(uint16(x))
case typeBitmap:
b := bitmap(c)
return b.remove(uint16(x))
}
return true
}
// Remove range removes [lo, hi) from the bitmap.
func (ra *Bitmap) RemoveRange(lo, hi uint64) {
if lo > hi {
panic("lo should not be more than hi")
}
if lo == hi {
return
}
k1 := lo & mask
k2 := hi & mask
defer ra.Cleanup()
// Complete range lie in a single container
if k1 == k2 {
if off, has := ra.keys.getValue(k1); has {
c := ra.getContainer(off)
removeRangeContainer(c, uint16(lo), uint16(hi)-1)
}
return
}
// Remove all the containers in range [k1+1, k2-1].
n := ra.keys.numKeys()
st := ra.keys.search(k1)
key := ra.keys.key(st)
if key == k1 {
st++
}
for i := st; i < n; i++ {
key := ra.keys.key(i)
if key >= k2 {
break
}
if off, has := ra.keys.getValue(key); has {
zeroOutContainer(ra.getContainer(off))
}
}
// Remove elements >= lo in k1's container
if off, has := ra.keys.getValue(k1); has {
c := ra.getContainer(off)
if uint16(lo) == 0 {
zeroOutContainer(c)
} else {
removeRangeContainer(c, uint16(lo), math.MaxUint16)
}
}
if uint16(hi) == 0 {
return
}
// Remove all elements < hi in k2's container
if off, has := ra.keys.getValue(k2); has {
c := ra.getContainer(off)
removeRangeContainer(c, 0, uint16(hi)-1)
}
}
func (ra *Bitmap) Reset() {
// reset ra.data to size enough for one container and corresponding key.
// 2 u64 is needed for header and another 2 u16 for the key 0.
ra.data = ra.data[:16+minContainerSize]
ra.keys = toUint64Slice(ra.data)
offset := ra.newContainer(minContainerSize)
ra.keys.setAt(indexNodeStart+1, offset)
ra.keys.setNumKeys(1)
}
func (ra *Bitmap) GetCardinality() int {
if ra == nil {
return 0
}
N := ra.keys.numKeys()
var sz int
for i := 0; i < N; i++ {
offset := ra.keys.val(i)
c := ra.getContainer(offset)
sz += getCardinality(c)
}
return sz
}
func (ra *Bitmap) ToArray() []uint64 {
if ra == nil {
return nil
}
res := make([]uint64, 0, ra.GetCardinality())
N := ra.keys.numKeys()
for i := 0; i < N; i++ {
key := ra.keys.key(i)
off := ra.keys.val(i)
c := ra.getContainer(off)
switch c[indexType] {
case typeArray:
a := array(c)
for _, lo := range a.all() {
res = append(res, key|uint64(lo))
}
case typeBitmap:
b := bitmap(c)
out := b.all()
for _, x := range out {
res = append(res, key|uint64(x))
}
}
}
return res
}
func (ra *Bitmap) String() string {
var b strings.Builder
b.WriteRune('\n')
var usedSize, card int
usedSize += 4 * (ra.keys.numKeys())
for i := 0; i < ra.keys.numKeys(); i++ {
k := ra.keys.key(i)
v := ra.keys.val(i)
c := ra.getContainer(v)
sz := c[indexSize]
usedSize += int(sz)
card += getCardinality(c)
b.WriteString(fmt.Sprintf(
"[%03d] Key: %#8x. Offset: %7d. Size: %4d. Type: %d. Card: %6d. Uint16/Uid: %.2f\n",
i, k, v, sz, c[indexType], getCardinality(c), float64(sz)/float64(getCardinality(c))))
}
b.WriteString(fmt.Sprintf("Number of containers: %d. Cardinality: %d\n",
ra.keys.numKeys(), card))
amp := float64(len(ra.data)-usedSize) / float64(usedSize)
b.WriteString(fmt.Sprintf(
"Size in Uint16s. Used: %d. Total: %d. Space Amplification: %.2f%%. Moved: %.2fx\n",
usedSize, len(ra.data), amp*100.0, float64(ra.memMoved)/float64(usedSize)))
b.WriteString(fmt.Sprintf("Used Uint16/Uid: %.2f. Total Uint16/Uid: %.2f",
float64(usedSize)/float64(card), float64(len(ra.data))/float64(card)))
return b.String()
}
const fwd int = 0x01
const rev int = 0x02
func (ra *Bitmap) Minimum() uint64 { return ra.extreme(fwd) }
func (ra *Bitmap) Maximum() uint64 { return ra.extreme(rev) }
func (ra *Bitmap) Debug(x uint64) string {
var b strings.Builder
hi := x & mask
off, found := ra.keys.getValue(hi)
if !found {
b.WriteString(fmt.Sprintf("Unable to find the container for x: %#x\n", hi))
b.WriteString(ra.String())
}
c := ra.getContainer(off)
lo := uint16(x)
b.WriteString(fmt.Sprintf("x: %#x lo: %#x. offset: %d\n", x, lo, off))
switch c[indexType] {
case typeArray:
case typeBitmap:
idx := lo / 16
pos := lo % 16
b.WriteString(fmt.Sprintf("At idx: %d. Pos: %d val: %#b\n", idx, pos, c[startIdx+idx]))
}
return b.String()
}
func (ra *Bitmap) extreme(dir int) uint64 {
N := ra.keys.numKeys()
if N == 0 {
return 0
}
var k uint64
var c []uint16
if dir == fwd {
for i := 0; i < N; i++ {
offset := ra.keys.val(i)
c = ra.getContainer(offset)
if getCardinality(c) > 0 {
k = ra.keys.key(i)
break
}
}
} else {
for i := N - 1; i >= 0; i-- {
offset := ra.keys.val(i)
c = ra.getContainer(offset)
if getCardinality(c) > 0 {
k = ra.keys.key(i)
break
}
}
}
switch c[indexType] {
case typeArray:
a := array(c)
if dir == fwd {
return k | uint64(a.minimum())
}
return k | uint64(a.maximum())
case typeBitmap:
b := bitmap(c)
if dir == fwd {
return k | uint64(b.minimum())
}
return k | uint64(b.maximum())
default:
panic("We don't support this type of container")
}
}
func (ra *Bitmap) AndOld(bm *Bitmap) {
if bm == nil {
ra.Reset()
return
}
a, b := ra, bm
ai, an := 0, a.keys.numKeys()
bi, bn := 0, b.keys.numKeys()
for ai < an && bi < bn {
ak := a.keys.key(ai)
bk := b.keys.key(bi)
if ak == bk {
off := a.keys.val(ai)
ac := a.getContainer(off)
off = b.keys.val(bi)
bc := b.getContainer(off)
// do the intersection
// TODO: See if we can do containerAnd operation in-place.
c := containerAnd(ac, bc)
// create a new container and update the key offset to this container.
offset := a.newContainer(uint16(len(c)))
copy(a.data[offset:], c)
a.setKey(ak, offset)
ai++
bi++
} else if ak < bk {
off := a.keys.val(ai)
zeroOutContainer(a.getContainer(off))
ai++
} else {
bi++
}
}
for ai < an {
off := a.keys.val(ai)
zeroOutContainer(a.getContainer(off))
ai++
}
}
func AndOld(a, b *Bitmap) *Bitmap {
ai, an := 0, a.keys.numKeys()
bi, bn := 0, b.keys.numKeys()
res := NewBitmap()
for ai < an && bi < bn {
ak := a.keys.key(ai)
bk := a.keys.key(bi)
if ak == bk {
// Do the intersection.
off := a.keys.val(ai)
ac := a.getContainer(off)
off = b.keys.val(bi)
bc := b.getContainer(off)
outc := containerAnd(ac, bc)
if getCardinality(outc) > 0 {
offset := res.newContainer(uint16(len(outc)))
copy(res.data[offset:], outc)
res.setKey(ak, offset)
}
ai++
bi++
} else if ak < bk {
ai++
} else {
bi++
}
}
return res
}
func (ra *Bitmap) AndNotOld(bm *Bitmap) {
if bm == nil {
return
}
a, b := ra, bm
var ai, bi int
buf := make([]uint16, maxContainerSize)
for ai < a.keys.numKeys() && bi < b.keys.numKeys() {
ak := a.keys.key(ai)
bk := b.keys.key(bi)
if ak == bk {
off := a.keys.val(ai)
ac := a.getContainer(off)
off = b.keys.val(bi)
bc := b.getContainer(off)
// TODO: See if we can do containerAndNot operation in-place.
c := containerAndNot(ac, bc, buf)
// create a new container and update the key offset to this container.
offset := a.newContainer(uint16(len(c)))
copy(a.data[offset:], c)
a.setKey(ak, offset)
ai++
bi++
continue
}
if ak < bk {
ai++
} else {
bi++
}
}
}
// TODO: Check if we want to use lazyMode
func (dst *Bitmap) OrOld(src *Bitmap) {
if src == nil {
return
}
dst.or(src, runInline)
}
func (dst *Bitmap) or(src *Bitmap, runMode int) {
srcIdx, numKeys := 0, src.keys.numKeys()
buf := make([]uint16, maxContainerSize)
for ; srcIdx < numKeys; srcIdx++ {
srcCont := src.getContainer(src.keys.val(srcIdx))
if getCardinality(srcCont) == 0 {
continue
}
key := src.keys.key(srcIdx)
dstIdx := dst.keys.search(key)
if dstIdx >= dst.keys.numKeys() || dst.keys.key(dstIdx) != key {
// srcCont doesn't exist in dst. So, copy it over.
offset := dst.newContainer(uint16(len(srcCont)))
copy(dst.getContainer(offset), srcCont)
dst.setKey(key, offset)
} else {
// Container exists in dst as well. Do an inline containerOr.
offset := dst.keys.val(dstIdx)
dstCont := dst.getContainer(offset)
if c := containerOr(dstCont, srcCont, buf, runMode|runInline); len(c) > 0 {
dst.copyAt(offset, c)
dst.setKey(key, offset)
}
}
}
}
func OrOld(a, b *Bitmap) *Bitmap {
ai, an := 0, a.keys.numKeys()
bi, bn := 0, b.keys.numKeys()
buf := make([]uint16, maxContainerSize)
res := NewBitmap()
for ai < an && bi < bn {
ak := a.keys.key(ai)
ac := a.getContainer(a.keys.val(ai))
bk := b.keys.key(bi)
bc := b.getContainer(b.keys.val(bi))
if ak == bk {
// Do the union.
outc := containerOr(ac, bc, buf, 0)
offset := res.newContainer(uint16(len(outc)))
copy(res.data[offset:], outc)
res.setKey(ak, offset)
ai++
bi++
} else if ak < bk {
off := res.newContainer(uint16(len(ac)))
copy(res.getContainer(off), ac)
res.setKey(ak, off)
ai++
} else {
off := res.newContainer(uint16(len(bc)))
copy(res.getContainer(off), bc)
res.setKey(bk, off)
bi++
}
}
for ai < an {
ak := a.keys.key(ai)
ac := a.getContainer(a.keys.val(ai))