This repository has been archived by the owner on Feb 21, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 230
/
roaring.go
7712 lines (7004 loc) · 194 KB
/
roaring.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 2022 Molecula Corp. (DBA FeatureBase).
// SPDX-License-Identifier: Apache-2.0
// Package roaring implements roaring bitmaps with support for incremental changes.
package roaring
import (
"bytes"
"encoding/binary"
"fmt"
"hash/fnv"
"io"
"math/bits"
"sort"
"unsafe"
"github.com/pkg/errors"
)
const (
// MagicNumber is an identifier, in bytes 0-1 of the file.
MagicNumber = uint32(12348)
// storageVersion indicates the storage version, in byte 2.
storageVersion = uint32(0)
// NOTE: byte 3 stores user-defined flags.
// cookie is the first 3 bytes in a roaring bitmap file,
// formed by joining MagicNumber and storageVersion
cookie = MagicNumber + storageVersion<<16
// headerBaseSize is the size in bytes of the cookie, flags, and key count
// at the beginning of a file.
headerBaseSize = 3 + 1 + 4
// runCountHeaderSize is the size in bytes of the run count stored
// at the beginning of every serialized run container.
runCountHeaderSize = 2
// interval16Size is the size of a single run in a container.runs.
interval16Size = 4
// bitmapN is the number of values in a container.bitmap.
bitmapN = (1 << 16) / 64
MaxContainerVal = 0xffff
// maxContainerKey is the key representing the last container in a full row.
// It is the full bitmap space (2^64) divided by container width (2^16).
maxContainerKey = (1 << 48) - 1
)
const (
ContainerNil byte = iota // no container
ContainerArray // slice of bit position values
ContainerBitmap // slice of 1024 uint64s
ContainerRun // container of run-encoded bits
)
// map used for a more descriptive print
var containerTypeNames = map[byte]string{
ContainerArray: "array",
ContainerBitmap: "bitmap",
ContainerRun: "run",
}
var fullContainer = NewContainerRun([]Interval16{{Start: 0, Last: MaxContainerVal}}).Freeze()
// AdvisoryError is used for the special case where we probably want to *report*
// an error reading a file, but don't want to actually count the file as not
// being read. For instance, a partial ops-log entry is *probably* harmless;
// we probably crashed while writing (?) and as such didn't report the write
// as successful. We hope.
type AdvisoryError interface {
error
AdvisoryOnly()
}
type advisoryError struct {
e error
}
func (a advisoryError) Error() string {
return a.e.Error()
}
// This marks the error as safe to ignore.
func (a advisoryError) AdvisoryOnly() {
}
type FileShouldBeTruncatedError interface {
AdvisoryError
SuggestedLength() int64
}
type fileShouldBeTruncatedError struct {
advisoryError
offset int64
}
func (f *fileShouldBeTruncatedError) SuggestedLength() int64 {
return f.offset
}
func newFileShouldBeTruncatedError(err error, offset int64) *fileShouldBeTruncatedError {
return &fileShouldBeTruncatedError{advisoryError: advisoryError{e: err}, offset: offset}
}
type Containers interface {
// Get returns nil if the key does not exist.
Get(key uint64) *Container
// Put adds the container at key.
Put(key uint64, c *Container)
// Remove takes the container at key out.
Remove(key uint64)
// GetOrCreate returns the container at key, creating a new empty container if necessary.
GetOrCreate(key uint64) *Container
// Clone does a deep copy of Containers, including cloning all containers contained.
Clone() Containers
// Freeze creates a shallow copy of Containers, freezing all the containers
// contained. The new copy is a distinct Containers, but the individual containers
// are shared (but marked as frozen).
Freeze() Containers
// Last returns the highest key and associated container.
Last() (key uint64, c *Container)
// Size returns the number of containers stored.
Size() int
// Update calls fn (existing-container, existed), and expects
// (new-container, write). If write is true, the container is used to
// replace the given container.
Update(key uint64, fn func(*Container, bool) (*Container, bool))
// UpdateEvery calls fn (existing-container, existed), and expects
// (new-container, write). If write is true, the container is used to
// replace the given container.
UpdateEvery(fn func(uint64, *Container, bool) (*Container, bool))
// Iterator returns a ContainterIterator which after a call to Next(), a call to Value() will
// return the first container at or after key. found will be true if a
// container is found at key.
Iterator(key uint64) (citer ContainerIterator, found bool)
Count() uint64
// Reset clears the containers collection to allow for recycling during snapshot
Reset()
// ResetN clears the collection but hints at a needed size.
ResetN(int)
// Repair will repair the cardinality of any containers whose cardinality were corrupted
// due to optimized operations.
Repair()
}
type ContainerIterator interface {
Next() bool
Value() (uint64, *Container)
Close()
}
type nopContainerIterator struct{}
func (n nopContainerIterator) Next() bool { return false }
func (n nopContainerIterator) Value() (uint64, *Container) { return 0, nil }
func (n nopContainerIterator) Close() {}
type unionContainerIterator struct {
iters []ContainerIterator
curs []containerWithKey
cur FilterKey
}
// NewUnionContainerIterator unions multiple container iterators to one.
func NewUnionContainerIterator(iters ...ContainerIterator) ContainerIterator {
return &unionContainerIterator{
iters: iters,
curs: make([]containerWithKey, len(iters)),
cur: 0,
}
}
func (u *unionContainerIterator) Next() bool {
if u.cur == KEY_DONE {
return false
}
// Next all iters that are at cur and save lowest
lowest := uint64(KEY_DONE)
for i, iter := range u.iters {
if u.curs[i].key == u.cur {
if iter.Next() {
key, c := iter.Value()
u.curs[i].key, u.curs[i].Container = FilterKey(key), c
if key < lowest {
lowest = key
}
} else {
u.curs[i].key = KEY_DONE
u.curs[i].Container = nil
}
}
}
u.cur = FilterKey(lowest)
return u.cur != KEY_DONE
}
func (u *unionContainerIterator) Value() (uint64, *Container) {
if u.cur == KEY_DONE {
return uint64(KEY_DONE), nil
}
var ret *Container
for _, cur := range u.curs {
if cur.key == u.cur {
ret = ret.UnionInPlace(cur.Container)
}
}
ret.Repair()
return uint64(u.cur), ret
}
func (u *unionContainerIterator) Close() {}
// Bitmap represents a roaring bitmap.
type Bitmap struct {
Containers Containers
// User-defined flags.
Flags byte
// should we try to keep things mapped?
preferMapping bool
// Number of bit change operations written to the writer. Some operations
// contain multiple values, so "ops" represents the number of distinct
// operations, while "opN" represents expected bit changes.
ops int
opN int
// Writer where operations are appended to.
OpWriter io.Writer
}
// NewBitmap returns a Bitmap with an initial set of values.
func NewBitmap(a ...uint64) *Bitmap {
b := &Bitmap{
Containers: newSliceContainers(),
}
// We have no way to report this. We aren't in a server context
// so we haven't got a logger, nothing is checking for nil returns
// from this.
// Because we just created Bitmap, its OpWriter is nil, so there
// is no code path which would cause AddN() to return an error.
// Therefore, it's safe to swallow this error.
_, _ = b.AddN(a...)
return b
}
// NewBitMatrix is a convenience function which returns a new bitmap
// which is the concatenation of all the rows, with each row shifted
// by a shardwdith. For example, all values in the second row will
// have shardWidth added to them before being added to the bitmap.
// Modifies rows in place.
func NewBitMatrix(shardWidth uint64, rows ...[]uint64) *Bitmap {
bm := NewBitmap()
for rowNum, row := range rows {
for i, col := range row {
row[i] = uint64(rowNum)*shardWidth + col
}
bm.AddN(row...)
}
return bm
}
// NewSliceBitmap makes a new bitmap, explicitly selecting the slice containers
// type, which performs better in cases where we expect a contiguous block of
// containers added in ascending order, such as when extracting a range from
// another bitmap.
func NewSliceBitmap(a ...uint64) *Bitmap {
b := &Bitmap{
Containers: newSliceContainers(),
}
// We have no way to report this. We aren't in a server context
// so we haven't got a logger, nothing is checking for nil returns
// from this.
// Because we just created Bitmap, its OpWriter is nil, so there
// is no code path which would cause AddN() to return an error.
// Therefore, it's safe to swallow this error.
_, _ = b.AddN(a...)
return b
}
// NewFileBitmap returns a Bitmap with an initial set of values, used for file storage.
var NewFileBitmap = NewBTreeBitmap
// Clone returns a heap allocated copy of the bitmap.
// Note: The OpWriter IS NOT copied to the new bitmap.
func (b *Bitmap) Clone() *Bitmap {
if b == nil {
return nil
}
// Create a copy of the bitmap structure.
other := &Bitmap{
Containers: b.Containers.Clone(),
}
return other
}
// Freeze returns a shallow copy of the bitmap. The new bitmap
// is a distinct bitmap, with a new Containers object, but the
// actual containers it holds are the same as the parent's
// containers, but have been frozen.
func (b *Bitmap) Freeze() *Bitmap {
if b == nil {
return nil
}
// Create a copy of the bitmap structure.
other := &Bitmap{
Containers: b.Containers.Freeze(),
}
return other
}
// Add adds values to the bitmap. TODO(2.0) deprecate - use the more general
// AddN (though be aware that it modifies 'a' in place).
func (b *Bitmap) Add(a ...uint64) (changed bool, err error) {
changed = false
for _, v := range a {
// Create an add operation.
op := &op{typ: opTypeAdd, value: v}
// Write operation to op log.
if err := b.writeOp(op); err != nil {
return false, err
}
// Apply to the in-memory bitmap.
if b.DirectAdd(v) {
changed = true
}
}
return changed, nil
}
// AddN adds values to the bitmap, appending them all to the op log in a batched
// write. It returns the number of changed bits.
// The input slice may be reordered, and the set of changed bits will end up in a[:changed].
func (b *Bitmap) AddN(a ...uint64) (changed int, err error) {
if len(a) == 0 {
return 0, nil
}
changed = b.DirectAddN(a...) // modifies a in-place
if b.OpWriter != nil && changed > 0 {
op := &op{
typ: opTypeAddBatch,
values: a[:changed],
}
if err := b.writeOp(op); err != nil {
b.DirectRemoveN(op.values...) // reset data since we're returning an error
return 0, errors.Wrap(err, "writing to op log")
}
}
return changed, nil
}
// DirectAddN sets multiple bits in the bitmap, returning how many changed. It
// modifies the slice 'a' in place such that once it's complete a[:changed] will
// be list of changed bits. It is more efficient than repeated calls to
// DirectAdd for semi-dense sorted data because it reuses the container from the
// previous value if the new value has the same highbits instead of looking it
// up each time. TODO: if Containers implementations cached the last few
// Container objects returned from calls like Get and GetOrCreate, this
// optimization would be less useful.
func (b *Bitmap) DirectAddN(a ...uint64) (changed int) {
return b.directOpN((*Container).add, a...)
}
// DirectRemoveN behaves analgously to DirectAddN.
func (b *Bitmap) DirectRemoveN(a ...uint64) (changed int) {
return b.directOpN((*Container).remove, a...)
}
// directOpN contains the logic for DirectAddN and DirectRemoveN. Theoretically,
// it could be used by anything that wanted to apply a boolean-returning
// container level operation across a list of values and return the number of
// trues while modifying the list of values in place to contain the
// true-returning values in order.
func (b *Bitmap) directOpN(op func(c *Container, v uint16) (*Container, bool), a ...uint64) (changed int) {
hb := uint64(0xFFFFFFFFFFFFFFFF) // impossible sentinel value
var cont *Container
for _, v := range a {
if newhb := highbits(v); newhb != hb {
hb = newhb
cont = b.Containers.GetOrCreate(hb)
}
newC, change := op(cont, lowbits(v))
if change {
a[changed] = v
changed++
}
if newC != cont {
b.Containers.Put(hb, newC)
cont = newC
}
}
return changed
}
// DirectAdd adds a value to the bitmap by bypassing the op log. TODO(2.0)
// deprecate in favor of DirectAddN.
func (b *Bitmap) DirectAdd(v uint64) bool {
cont := b.Containers.GetOrCreate(highbits(v))
newC, changed := cont.add(lowbits(v))
if newC != cont {
// avoid returning invalid container, and avoid a slow optimize call.
switch newC.typeID {
case ContainerArray:
if len(newC.array()) > ArrayMaxSize {
newC = newC.arrayToBitmap()
}
case ContainerRun:
if len(newC.runs()) > runMaxSize {
newC = newC.runToBitmap()
}
}
b.Containers.Put(highbits(v), newC)
}
return changed
}
// Contains returns true if v is in the bitmap.
func (b *Bitmap) Contains(v uint64) bool {
if b == nil {
return false
}
c := b.Containers.Get(highbits(v))
if c == nil {
return false
}
return c.Contains(lowbits(v))
}
// Remove removes values from the bitmap (writing to the op log if available).
// TODO(2.0) deprecate - use the more general RemoveN (though be aware that it
// modifies 'a' in place).
func (b *Bitmap) Remove(a ...uint64) (changed bool, err error) {
changed = false
for _, v := range a {
// Create an add operation.
op := &op{typ: opTypeRemove, value: v}
// Write operation to op log.
if err := b.writeOp(op); err != nil {
return false, err
}
// Apply operation to the bitmap.
if op.apply(b) {
changed = true
}
}
return changed, nil
}
// RemoveN behaves analagously to AddN.
func (b *Bitmap) RemoveN(a ...uint64) (changed int, err error) {
if len(a) == 0 {
return 0, nil
}
changed = b.DirectRemoveN(a...) // modifies a in-place
if b.OpWriter != nil && changed > 0 {
op := &op{
typ: opTypeRemoveBatch,
values: a[:changed],
}
if err := b.writeOp(op); err != nil {
b.DirectAddN(op.values...) // reset data since we're returning an error
return 0, errors.Wrap(err, "writing to op log")
}
}
return changed, nil
}
func (b *Bitmap) remove(v uint64) bool {
c := b.Containers.Get(highbits(v))
newC, changed := c.remove(lowbits(v))
if newC != c {
if newC != nil {
b.Containers.Put(highbits(v), newC)
} else {
b.Containers.Remove(highbits(v))
}
}
return changed
}
// Min returns the lowest value in the bitmap.
// Second return value is true if containers exist in the bitmap.
func (b *Bitmap) Min() (uint64, bool) {
v, eof := b.Iterator().Next()
return v, !eof
}
// MinAt returns the lowest value in the bitmap at least equal to its argument.
// Second return value is true if containers exist in the bitmap.
func (b *Bitmap) MinAt(start uint64) (uint64, bool) {
v, eof := b.IteratorAt(start).Next()
return v, !eof
}
// Max returns the highest value in the bitmap.
// Returns zero if the bitmap is empty.
func (b *Bitmap) Max() uint64 {
if b.Containers.Size() == 0 {
return 0
}
hb, c := b.Containers.Last()
lb := c.max()
return hb<<16 | uint64(lb)
}
// Count returns the number of bits set in the bitmap.
func (b *Bitmap) Count() (n uint64) {
return b.Containers.Count()
}
// Any checks whether there are any set bits within the bitmap.
func (b *Bitmap) Any() bool {
iter, _ := b.Containers.Iterator(0)
// TODO (jaffee) I'm not sure if it's possible/legal to have an empty
// container, so this loop may be totally unnecessary. In theory, any empty
// container should be removed from the bitmap though.
for iter.Next() {
_, c := iter.Value()
if c.N() > 0 {
return true
}
}
return false
}
// Size returns the number of bytes required for the bitmap.
func (b *Bitmap) Size() int {
numbytes := 0
citer, _ := b.Containers.Iterator(0)
for citer.Next() {
_, c := citer.Value()
numbytes += c.size()
}
return numbytes
}
// CountRange returns the number of bits set between [start, end).
func (b *Bitmap) CountRange(start, end uint64) (n uint64) {
if roaringSentinel {
if start > end {
panic(fmt.Sprintf("counting in range but %v > %v", start, end))
}
}
if b.Containers.Size() == 0 {
return
}
skey := highbits(start)
ekey := highbits(end)
citer, found := b.Containers.Iterator(highbits(start))
// If range is entirely in one container then just count that range.
if found && skey == ekey {
citer.Next()
_, c := citer.Value()
return uint64(c.countRange(int32(lowbits(start)), int32(lowbits(end))))
}
for citer.Next() {
k, c := citer.Value()
if k < skey {
// TODO remove once we've validated this stuff works
panic("should be impossible for k to be less than skey")
}
// k > ekey handles the case when start > end and where start and end
// are in different containers. Same container case is already handled above.
if k > ekey {
break
}
if k == skey {
n += uint64(c.countRange(int32(lowbits(start)), MaxContainerVal+1))
continue
}
if k < ekey {
n += uint64(c.N())
continue
}
if k == ekey {
n += uint64(c.countRange(0, int32(lowbits(end))))
break
}
}
return n
}
// Slice returns a slice of all integers in the bitmap.
func (b *Bitmap) Slice() []uint64 {
var a []uint64
itr := b.Iterator()
itr.Seek(0)
for v, eof := itr.Next(); !eof; v, eof = itr.Next() {
a = append(a, v)
}
return a
}
// SliceRange returns a slice of integers between [start, end).
func (b *Bitmap) SliceRange(start, end uint64) []uint64 {
if roaringSentinel {
if start > end {
panic(fmt.Sprintf("getting slice in range but %v > %v", start, end))
}
}
var a []uint64
itr := b.Iterator()
itr.Seek(start)
for v, eof := itr.Next(); !eof && v < end; v, eof = itr.Next() {
a = append(a, v)
}
return a
}
// ForEach executes fn for each value in the bitmap.
func (b *Bitmap) ForEach(fn func(uint64) error) error {
itr := b.Iterator()
itr.Seek(0)
for v, eof := itr.Next(); !eof; v, eof = itr.Next() {
if err := fn(v); err != nil {
return err
}
}
return nil
}
// ForEachRange executes fn for each value in the bitmap between [start, end).
func (b *Bitmap) ForEachRange(start, end uint64, fn func(uint64) error) error {
itr := b.Iterator()
itr.Seek(start)
for v, eof := itr.Next(); !eof && v < end; v, eof = itr.Next() {
if err := fn(v); err != nil {
return err
}
}
return nil
}
// OffsetRange returns a new bitmap with a containers offset by start.
// The containers themselves are shared, so they get frozen so it will
// be safe to interact with them.
func (b *Bitmap) OffsetRange(offset, start, end uint64) *Bitmap {
if lowbits(offset) != 0 {
panic("offset must not contain low bits")
}
if lowbits(start) != 0 {
panic("range start must not contain low bits")
}
if lowbits(end) != 0 {
panic("range end must not contain low bits")
}
off := highbits(offset)
hi0, hi1 := highbits(start), highbits(end)
citer, _ := b.Containers.Iterator(hi0)
other := NewSliceBitmap()
for citer.Next() {
k, c := citer.Value()
if k >= hi1 {
break
}
other.Containers.Put(off+(k-hi0), c.Freeze())
}
return other
}
// container returns the container with the given key.
func (b *Bitmap) container(key uint64) *Container {
return b.Containers.Get(key)
}
// IntersectionCount returns the number of set bits that would result in an
// intersection between b and other. It is more efficient than actually
// intersecting the two and counting the result.
func (b *Bitmap) IntersectionCount(other *Bitmap) uint64 {
var n uint64
iiter, _ := b.Containers.Iterator(0)
jiter, _ := other.Containers.Iterator(0)
i, j := iiter.Next(), jiter.Next()
ki, ci := iiter.Value()
kj, cj := jiter.Value()
for i && j {
if ki < kj {
i = iiter.Next()
ki, ci = iiter.Value()
} else if ki > kj {
j = jiter.Next()
kj, cj = jiter.Value()
} else {
n += uint64(intersectionCount(ci, cj))
i, j = iiter.Next(), jiter.Next()
ki, ci = iiter.Value()
kj, cj = jiter.Value()
}
}
return n
}
// Intersect returns the intersection of b and other.
func (b *Bitmap) Intersect(other *Bitmap) *Bitmap {
output := NewBitmap()
iiter, _ := b.Containers.Iterator(0)
jiter, _ := other.Containers.Iterator(0)
i, j := iiter.Next(), jiter.Next()
ki, ci := iiter.Value()
kj, cj := jiter.Value()
for i && j {
if ki < kj {
i = iiter.Next()
ki, ci = iiter.Value()
} else if ki > kj {
j = jiter.Next()
kj, cj = jiter.Value()
} else { // ki == kj
newC := intersect(ci, cj)
output.Containers.Put(ki, newC)
i, j = iiter.Next(), jiter.Next()
ki, ci = iiter.Value()
kj, cj = jiter.Value()
}
}
return output
}
func (b *Bitmap) Hash(hash uint64) uint64 {
const (
offset = 14695981039346656037
prime = 1099511628211
)
if hash == 0 {
hash = uint64(offset)
}
it, _ := b.Containers.Iterator(0)
for it.Next() {
ki, _ := it.Value()
hash ^= uint64(ki)
hash *= prime
}
it, _ = b.Containers.Iterator(0)
for it.Next() {
_, ci := it.Value()
hash ^= 0
hash *= prime
if ci.N() > 0 {
var bytes []byte
switch ci.typ() {
case ContainerArray:
bytes = fromArray16(ci.array())
case ContainerBitmap:
bytes = fromArray64(ci.bitmap())
case ContainerRun:
bytes = fromInterval16(ci.runs())
}
for _, b := range bytes {
hash ^= uint64(b)
hash *= prime
}
}
}
return hash
}
type mutableContainersIterator struct {
c Containers
cit ContainerIterator
sit *sliceIterator
}
func newMutableContainersIterator(cs Containers, key uint64) *mutableContainersIterator {
it := &mutableContainersIterator{c: cs}
if sc, ok := cs.(*sliceContainers); ok {
if i, found := sc.seek(key); found {
it.sit = &sliceIterator{e: sc, i: i, index: i}
return it
}
}
it.cit, _ = cs.Iterator(key)
return it
}
func (it *mutableContainersIterator) update(key uint64, newCont *Container) {
if it.sit != nil {
if key == it.sit.key {
it.sit.e.containers[it.sit.index] = newCont
}
}
it.c.Update(key, func(_ *Container, _ bool) (*Container, bool) {
return newCont, true
})
}
func (it *mutableContainersIterator) Next() bool {
if it.sit != nil {
return it.sit.Next()
}
return it.cit.Next()
}
func (it *mutableContainersIterator) Value() (uint64, *Container) {
if it.sit != nil {
return it.sit.Value()
}
return it.cit.Value()
}
func (it *mutableContainersIterator) Close() {}
// IntersectInPlace returns the bitwise intersection of b and others,
// modifying b in place.
func (b *Bitmap) IntersectInPlace(others ...*Bitmap) {
var bSize int
if bSize = b.Size(); bSize == 0 {
// If b doesn't have any containers then return early.
return
}
otherIters := make(handledIters, 0, len(others))
for _, other := range others {
it, _ := other.Containers.Iterator(0)
if !it.Next() {
// An empty bitmap - reset all
b.Containers.Reset()
return
}
otherIters = append(otherIters, handledIter{
iter: it,
hasNext: true,
})
}
bIter := newMutableContainersIterator(b.Containers, 0)
for bIter.Next() {
bKey, bCont := bIter.Value()
if bCont.N() == 0 {
// No point in intersecting things from an empty container.
bIter.update(bKey, nil)
continue
}
// Loop until every iters current value has been handled.
for _, otherIter := range otherIters {
if !otherIter.hasNext {
continue
}
otherKey, otherCont := otherIter.iter.Value()
for otherKey < bKey {
otherIter.hasNext = otherIter.iter.Next()
if !otherIter.hasNext {
break
}
otherKey, otherCont = otherIter.iter.Value()
}
if bKey == otherKey {
// Note: a nil container is valid, and has N == 0.
if otherCont.N() != 0 {
if bCont.frozen() {
bCont = bCont.Clone()
b.Containers.Put(bKey, bCont)
}
bCont = bCont.intersectInPlace(otherCont)
bIter.update(bKey, bCont)
if bCont == nil || bCont.N() == 0 {
break
}
otherIter.hasNext = otherIter.iter.Next()
continue
}
}
bIter.update(bKey, nil)
break
}
}
b.Containers.Repair()
}
func (c *Container) intersectInPlace(other *Container) *Container {
// short-circuit the trivial cases
if c == nil || other == nil || c.N() == 0 || other.N() == 0 {
c = nil
return c
}
cFull, otherFull := (c.N() == MaxContainerVal+1), (other.N() == MaxContainerVal+1)
if cFull && otherFull {
return c
}
if cFull {
return c.copyInPlace(other)
}
if otherFull {
return c
}
switch c.typ() {
case ContainerArray:
switch other.typ() {
case ContainerArray:
return intersectArrayArrayInPlace(c, other)
case ContainerBitmap:
return intersectArrayBitmapInPlace(c, other)
case ContainerRun:
return intersectArrayRunInPlace(c, other)
}
case ContainerBitmap:
switch other.typ() {
case ContainerArray:
return intersectBitmapArrayInPlace(c, other)
case ContainerBitmap:
return intersectBitmapBitmapInPlace(c, other)
case ContainerRun:
return intersectBitmapRunInPlace(c, other)
}
case ContainerRun:
switch other.typ() {
case ContainerArray:
return intersectRunArrayInPlace(c, other)
case ContainerBitmap:
return intersectRunBitmapInPlace(c, other)
case ContainerRun:
return intersectRunRunInPlace(c, other)
}
}
panic(fmt.Errorf("invalid intersect op: unknown types %d/%d", c.typ(), other.typ()))
}
func (c *Container) copyInPlace(other *Container) *Container {
switch other.typ() {
case ContainerArray:
c.setTyp(ContainerArray)
c.setArrayMaybeCopy(other.array(), true)
case ContainerBitmap:
c.setTyp(ContainerBitmap)
c.setBitmapCopy(other.bitmap())
c.setN(other.N())
case ContainerRun:
c.setTyp(ContainerRun)
c.setRunsMaybeCopy(other.runs(), true)
c.setN(other.N())
default:
panic(fmt.Errorf("invalid container type: %v", c.typ()))
}
return c
}