forked from RoaringBitmap/roaring
-
Notifications
You must be signed in to change notification settings - Fork 0
/
rle.go
1667 lines (1472 loc) · 42.3 KB
/
rle.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
package roaring
//
// Copyright (c) 2016 by the roaring authors.
// Licensed under the Apache License, Version 2.0.
//
// We derive a few lines of code from the sort.Search
// function in the golang standard library. That function
// is Copyright 2009 The Go Authors, and licensed
// under the following BSD-style license.
/*
Copyright (c) 2009 The Go Authors. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following disclaimer
in the documentation and/or other materials provided with the
distribution.
* Neither the name of Google Inc. nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
import (
"fmt"
"sort"
"unsafe"
)
//go:generate msgp -unexported
// runContainer32 does run-length encoding of sets of
// uint32 integers.
type runContainer32 struct {
iv []interval32
card int64
// avoid allocation during search
myOpts searchOptions `msg:"-"`
}
// interval32 is the internal to runContainer32
// structure that maintains the individual [Start, last]
// closed intervals.
type interval32 struct {
start uint32
last uint32
}
// runlen returns the count of integers in the interval.
func (iv interval32) runlen() int64 {
return 1 + int64(iv.last) - int64(iv.start)
}
// String produces a human viewable string of the contents.
func (iv interval32) String() string {
return fmt.Sprintf("[%d, %d]", iv.start, iv.last)
}
func ivalString32(iv []interval32) string {
var s string
var j int
var p interval32
for j, p = range iv {
s += fmt.Sprintf("%v:[%d, %d], ", j, p.start, p.last)
}
return s
}
// String produces a human viewable string of the contents.
func (rc *runContainer32) String() string {
if len(rc.iv) == 0 {
return "runContainer32{}"
}
is := ivalString32(rc.iv)
return `runContainer32{` + is + `}`
}
// uint32Slice is a sort.Sort convenience method
type uint32Slice []uint32
// Len returns the length of p.
func (p uint32Slice) Len() int { return len(p) }
// Less returns p[i] < p[j]
func (p uint32Slice) Less(i, j int) bool { return p[i] < p[j] }
// Swap swaps elements i and j.
func (p uint32Slice) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
//msgp:ignore addHelper
// addHelper helps build a runContainer32.
type addHelper32 struct {
runstart uint32
runlen uint32
actuallyAdded uint32
m []interval32
rc *runContainer32
}
func (ah *addHelper32) storeIval(runstart, runlen uint32) {
mi := interval32{start: runstart, last: runstart + runlen}
ah.m = append(ah.m, mi)
}
func (ah *addHelper32) add(cur, prev uint32, i int) {
if cur == prev+1 {
ah.runlen++
ah.actuallyAdded++
} else {
if cur < prev {
panic(fmt.Sprintf("newRunContainer32FromVals sees "+
"unsorted vals; vals[%v]=cur=%v < prev=%v. Sort your vals"+
" before calling us with alreadySorted == true.", i, cur, prev))
}
if cur == prev {
// ignore duplicates
} else {
ah.actuallyAdded++
ah.storeIval(ah.runstart, ah.runlen)
ah.runstart = cur
ah.runlen = 0
}
}
}
// newRunContainerRange makes a new container made of just the specified closed interval [rangestart,rangelast]
func newRunContainer32Range(rangestart uint32, rangelast uint32) *runContainer32 {
rc := &runContainer32{}
rc.iv = append(rc.iv, interval32{start: rangestart, last: rangelast})
return rc
}
// newRunContainer32FromVals makes a new container from vals.
//
// For efficiency, vals should be sorted in ascending order.
// Ideally vals should not contain duplicates, but we detect and
// ignore them. If vals is already sorted in ascending order, then
// pass alreadySorted = true. Otherwise, for !alreadySorted,
// we will sort vals before creating a runContainer32 of them.
// We sort the original vals, so this will change what the
// caller sees in vals as a side effect.
func newRunContainer32FromVals(alreadySorted bool, vals ...uint32) *runContainer32 {
// keep this in sync with newRunContainer32FromArray below
rc := &runContainer32{}
ah := addHelper32{rc: rc}
if !alreadySorted {
sort.Sort(uint32Slice(vals))
}
n := len(vals)
var cur, prev uint32
switch {
case n == 0:
// nothing more
case n == 1:
ah.m = append(ah.m, interval32{start: vals[0], last: vals[0]})
ah.actuallyAdded++
default:
ah.runstart = vals[0]
ah.actuallyAdded++
for i := 1; i < n; i++ {
prev = vals[i-1]
cur = vals[i]
ah.add(cur, prev, i)
}
ah.storeIval(ah.runstart, ah.runlen)
}
rc.iv = ah.m
rc.card = int64(ah.actuallyAdded)
return rc
}
// newRunContainer32FromBitmapContainer makes a new run container from bc,
// somewhat efficiently. For reference, see the Java
// https://github.com/RoaringBitmap/RoaringBitmap/blob/master/src/main/java/org/roaringbitmap/RunContainer.java#L145-L192
func newRunContainer32FromBitmapContainer(bc *bitmapContainer) *runContainer32 {
rc := &runContainer32{}
nbrRuns := bc.numberOfRuns()
if nbrRuns == 0 {
return rc
}
rc.iv = make([]interval32, nbrRuns)
longCtr := 0 // index of current long in bitmap
curWord := bc.bitmap[0] // its value
runCount := 0
for {
// potentially multiword advance to first 1 bit
for curWord == 0 && longCtr < len(bc.bitmap)-1 {
longCtr++
curWord = bc.bitmap[longCtr]
}
if curWord == 0 {
// wrap up, no more runs
return rc
}
localRunStart := countTrailingZerosDeBruijn(curWord)
runStart := localRunStart + 64*longCtr
// stuff 1s into number's LSBs
curWordWith1s := curWord | (curWord - 1)
// find the next 0, potentially in a later word
runEnd := 0
for curWordWith1s == maxWord && longCtr < len(bc.bitmap)-1 {
longCtr++
curWordWith1s = bc.bitmap[longCtr]
}
if curWordWith1s == maxWord {
// a final unterminated run of 1s
runEnd = wordSizeInBits + longCtr*64
rc.iv[runCount].start = uint32(runStart)
rc.iv[runCount].last = uint32(runEnd) - 1
return rc
}
localRunEnd := countTrailingZerosDeBruijn(^curWordWith1s)
runEnd = localRunEnd + longCtr*64
rc.iv[runCount].start = uint32(runStart)
rc.iv[runCount].last = uint32(runEnd) - 1
runCount++
// now, zero out everything right of runEnd.
curWord = curWordWith1s & (curWordWith1s + 1)
// We've lathered and rinsed, so repeat...
}
}
//
// newRunContainer32FromArray populates a new
// runContainer32 from the contents of arr.
//
func newRunContainer32FromArray(arr *arrayContainer) *runContainer32 {
// keep this in sync with newRunContainer32FromVals above
rc := &runContainer32{}
ah := addHelper32{rc: rc}
n := arr.getCardinality()
var cur, prev uint32
switch {
case n == 0:
// nothing more
case n == 1:
ah.m = append(ah.m, interval32{start: uint32(arr.content[0]), last: uint32(arr.content[0])})
ah.actuallyAdded++
default:
ah.runstart = uint32(arr.content[0])
ah.actuallyAdded++
for i := 1; i < n; i++ {
prev = uint32(arr.content[i-1])
cur = uint32(arr.content[i])
ah.add(cur, prev, i)
}
ah.storeIval(ah.runstart, ah.runlen)
}
rc.iv = ah.m
rc.card = int64(ah.actuallyAdded)
return rc
}
// set adds the integers in vals to the set. Vals
// must be sorted in increasing order; if not, you should set
// alreadySorted to false, and we will sort them in place for you.
// (Be aware of this side effect -- it will affect the callers
// view of vals).
//
// If you have a small number of additions to an already
// big runContainer32, calling Add() may be faster.
func (rc *runContainer32) set(alreadySorted bool, vals ...uint32) {
rc2 := newRunContainer32FromVals(alreadySorted, vals...)
un := rc.union(rc2)
rc.iv = un.iv
rc.card = 0
}
// canMerge returns true iff the intervals
// a and b either overlap or they are
// contiguous and so can be merged into
// a single interval.
func canMerge32(a, b interval32) bool {
if int64(a.last)+1 < int64(b.start) {
return false
}
return int64(b.last)+1 >= int64(a.start)
}
// haveOverlap differs from canMerge in that
// it tells you if the intersection of a
// and b would contain an element (otherwise
// it would be the empty set, and we return
// false).
func haveOverlap32(a, b interval32) bool {
if int64(a.last)+1 <= int64(b.start) {
return false
}
return int64(b.last)+1 > int64(a.start)
}
// mergeInterval32s joins a and b into a
// new interval, and panics if it cannot.
func mergeInterval32s(a, b interval32) (res interval32) {
if !canMerge32(a, b) {
panic(fmt.Sprintf("cannot merge %#v and %#v", a, b))
}
if b.start < a.start {
res.start = b.start
} else {
res.start = a.start
}
if b.last > a.last {
res.last = b.last
} else {
res.last = a.last
}
return
}
// intersectInterval32s returns the intersection
// of a and b. The isEmpty flag will be true if
// a and b were disjoint.
func intersectInterval32s(a, b interval32) (res interval32, isEmpty bool) {
if !haveOverlap32(a, b) {
isEmpty = true
return
}
if b.start > a.start {
res.start = b.start
} else {
res.start = a.start
}
if b.last < a.last {
res.last = b.last
} else {
res.last = a.last
}
return
}
// union merges two runContainer32s, producing
// a new runContainer32 with the union of rc and b.
func (rc *runContainer32) union(b *runContainer32) *runContainer32 {
// rc is also known as 'a' here, but golint insisted we
// call it rc for consistency with the rest of the methods.
var m []interval32
alim := int64(len(rc.iv))
blim := int64(len(b.iv))
var na int64 // next from a
var nb int64 // next from b
// merged holds the current merge output, which might
// get additional merges before being appended to m.
var merged interval32
var mergedUsed bool // is merged being used at the moment?
var cura interval32 // currently considering this interval32 from a
var curb interval32 // currently considering this interval32 from b
pass := 0
for na < alim && nb < blim {
pass++
cura = rc.iv[na]
curb = b.iv[nb]
if mergedUsed {
mergedUpdated := false
if canMerge32(cura, merged) {
merged = mergeInterval32s(cura, merged)
na = rc.indexOfIntervalAtOrAfter(int64(merged.last)+1, na+1)
mergedUpdated = true
}
if canMerge32(curb, merged) {
merged = mergeInterval32s(curb, merged)
nb = b.indexOfIntervalAtOrAfter(int64(merged.last)+1, nb+1)
mergedUpdated = true
}
if !mergedUpdated {
// we know that merged is disjoint from cura and curb
m = append(m, merged)
mergedUsed = false
}
continue
} else {
// !mergedUsed
if !canMerge32(cura, curb) {
if cura.start < curb.start {
m = append(m, cura)
na++
} else {
m = append(m, curb)
nb++
}
} else {
merged = mergeInterval32s(cura, curb)
mergedUsed = true
na = rc.indexOfIntervalAtOrAfter(int64(merged.last)+1, na+1)
nb = b.indexOfIntervalAtOrAfter(int64(merged.last)+1, nb+1)
}
}
}
var aDone, bDone bool
if na >= alim {
aDone = true
}
if nb >= blim {
bDone = true
}
// finish by merging anything remaining into merged we can:
if mergedUsed {
if !aDone {
aAdds:
for na < alim {
cura = rc.iv[na]
if canMerge32(cura, merged) {
merged = mergeInterval32s(cura, merged)
na = rc.indexOfIntervalAtOrAfter(int64(merged.last)+1, na+1)
} else {
break aAdds
}
}
}
if !bDone {
bAdds:
for nb < blim {
curb = b.iv[nb]
if canMerge32(curb, merged) {
merged = mergeInterval32s(curb, merged)
nb = b.indexOfIntervalAtOrAfter(int64(merged.last)+1, nb+1)
} else {
break bAdds
}
}
}
m = append(m, merged)
}
if na < alim {
m = append(m, rc.iv[na:]...)
}
if nb < blim {
m = append(m, b.iv[nb:]...)
}
res := &runContainer32{iv: m}
return res
}
// unionCardinality returns the cardinality of the merger of two runContainer32s, the union of rc and b.
func (rc *runContainer32) unionCardinality(b *runContainer32) uint64 {
// rc is also known as 'a' here, but golint insisted we
// call it rc for consistency with the rest of the methods.
answer := uint64(0)
alim := int64(len(rc.iv))
blim := int64(len(b.iv))
var na int64 // next from a
var nb int64 // next from b
// merged holds the current merge output, which might
// get additional merges before being appended to m.
var merged interval32
var mergedUsed bool // is merged being used at the moment?
var cura interval32 // currently considering this interval32 from a
var curb interval32 // currently considering this interval32 from b
pass := 0
for na < alim && nb < blim {
pass++
cura = rc.iv[na]
curb = b.iv[nb]
if mergedUsed {
mergedUpdated := false
if canMerge32(cura, merged) {
merged = mergeInterval32s(cura, merged)
na = rc.indexOfIntervalAtOrAfter(int64(merged.last)+1, na+1)
mergedUpdated = true
}
if canMerge32(curb, merged) {
merged = mergeInterval32s(curb, merged)
nb = b.indexOfIntervalAtOrAfter(int64(merged.last)+1, nb+1)
mergedUpdated = true
}
if !mergedUpdated {
// we know that merged is disjoint from cura and curb
//m = append(m, merged)
answer += uint64(merged.last) - uint64(merged.start) + 1
mergedUsed = false
}
continue
} else {
// !mergedUsed
if !canMerge32(cura, curb) {
if cura.start < curb.start {
answer += uint64(cura.last) - uint64(cura.start) + 1
//m = append(m, cura)
na++
} else {
answer += uint64(curb.last) - uint64(curb.start) + 1
//m = append(m, curb)
nb++
}
} else {
merged = mergeInterval32s(cura, curb)
mergedUsed = true
na = rc.indexOfIntervalAtOrAfter(int64(merged.last)+1, na+1)
nb = b.indexOfIntervalAtOrAfter(int64(merged.last)+1, nb+1)
}
}
}
var aDone, bDone bool
if na >= alim {
aDone = true
}
if nb >= blim {
bDone = true
}
// finish by merging anything remaining into merged we can:
if mergedUsed {
if !aDone {
aAdds:
for na < alim {
cura = rc.iv[na]
if canMerge32(cura, merged) {
merged = mergeInterval32s(cura, merged)
na = rc.indexOfIntervalAtOrAfter(int64(merged.last)+1, na+1)
} else {
break aAdds
}
}
}
if !bDone {
bAdds:
for nb < blim {
curb = b.iv[nb]
if canMerge32(curb, merged) {
merged = mergeInterval32s(curb, merged)
nb = b.indexOfIntervalAtOrAfter(int64(merged.last)+1, nb+1)
} else {
break bAdds
}
}
}
//m = append(m, merged)
answer += uint64(merged.last) - uint64(merged.start) + 1
}
for _, r := range rc.iv[na:] {
answer += uint64(r.last) - uint64(r.start) + 1
}
for _, r := range b.iv[nb:] {
answer += uint64(r.last) - uint64(r.start) + 1
}
return answer
}
// indexOfIntervalAtOrAfter is a helper for union.
func (rc *runContainer32) indexOfIntervalAtOrAfter(key int64, startIndex int64) int64 {
rc.myOpts.startIndex = startIndex
rc.myOpts.endxIndex = 0
w, already, _ := rc.search(key, &rc.myOpts)
if already {
return int64(w)
}
return int64(w) + 1
}
// intersect returns a new runContainer32 holding the
// intersection of rc (also known as 'a') and b.
func (rc *runContainer32) intersect(b *runContainer32) *runContainer32 {
a := rc
numa := int64(len(a.iv))
numb := int64(len(b.iv))
res := &runContainer32{}
if numa == 0 || numb == 0 {
return res
}
if numa == 1 && numb == 1 {
if !haveOverlap32(a.iv[0], b.iv[0]) {
return res
}
}
var output []interval32
var acuri int64
var bcuri int64
astart := int64(a.iv[acuri].start)
bstart := int64(b.iv[bcuri].start)
var intersection interval32
var leftoverstart int64
var isOverlap, isLeftoverA, isLeftoverB bool
var done bool
pass := 0
toploop:
for acuri < numa && bcuri < numb {
pass++
isOverlap, isLeftoverA, isLeftoverB, leftoverstart, intersection = intersectWithLeftover32(astart, int64(a.iv[acuri].last), bstart, int64(b.iv[bcuri].last))
if !isOverlap {
switch {
case astart < bstart:
acuri, done = a.findNextIntervalThatIntersectsStartingFrom(acuri+1, bstart)
if done {
break toploop
}
astart = int64(a.iv[acuri].start)
case astart > bstart:
bcuri, done = b.findNextIntervalThatIntersectsStartingFrom(bcuri+1, astart)
if done {
break toploop
}
bstart = int64(b.iv[bcuri].start)
//default:
// panic("impossible that astart == bstart, since !isOverlap")
}
} else {
// isOverlap
output = append(output, intersection)
switch {
case isLeftoverA:
// note that we change astart without advancing acuri,
// since we need to capture any 2ndary intersections with a.iv[acuri]
astart = leftoverstart
bcuri++
if bcuri >= numb {
break toploop
}
bstart = int64(b.iv[bcuri].start)
case isLeftoverB:
// note that we change bstart without advancing bcuri,
// since we need to capture any 2ndary intersections with b.iv[bcuri]
bstart = leftoverstart
acuri++
if acuri >= numa {
break toploop
}
astart = int64(a.iv[acuri].start)
default:
// neither had leftover, both completely consumed
// optionally, assert for sanity:
//if a.iv[acuri].endx != b.iv[bcuri].endx {
// panic("huh? should only be possible that endx agree now!")
//}
// advance to next a interval
acuri++
if acuri >= numa {
break toploop
}
astart = int64(a.iv[acuri].start)
// advance to next b interval
bcuri++
if bcuri >= numb {
break toploop
}
bstart = int64(b.iv[bcuri].start)
}
}
} // end for toploop
if len(output) == 0 {
return res
}
res.iv = output
return res
}
// intersectCardinality returns the cardinality of the
// intersection of rc (also known as 'a') and b.
func (rc *runContainer32) intersectCardinality(b *runContainer32) int64 {
answer := int64(0)
a := rc
numa := int64(len(a.iv))
numb := int64(len(b.iv))
if numa == 0 || numb == 0 {
return 0
}
if numa == 1 && numb == 1 {
if !haveOverlap32(a.iv[0], b.iv[0]) {
return 0
}
}
var acuri int64
var bcuri int64
astart := int64(a.iv[acuri].start)
bstart := int64(b.iv[bcuri].start)
var intersection interval32
var leftoverstart int64
var isOverlap, isLeftoverA, isLeftoverB bool
var done bool
pass := 0
toploop:
for acuri < numa && bcuri < numb {
pass++
isOverlap, isLeftoverA, isLeftoverB, leftoverstart, intersection = intersectWithLeftover32(astart, int64(a.iv[acuri].last), bstart, int64(b.iv[bcuri].last))
if !isOverlap {
switch {
case astart < bstart:
acuri, done = a.findNextIntervalThatIntersectsStartingFrom(acuri+1, bstart)
if done {
break toploop
}
astart = int64(a.iv[acuri].start)
case astart > bstart:
bcuri, done = b.findNextIntervalThatIntersectsStartingFrom(bcuri+1, astart)
if done {
break toploop
}
bstart = int64(b.iv[bcuri].start)
//default:
// panic("impossible that astart == bstart, since !isOverlap")
}
} else {
// isOverlap
answer += int64(intersection.last) - int64(intersection.start) + 1
switch {
case isLeftoverA:
// note that we change astart without advancing acuri,
// since we need to capture any 2ndary intersections with a.iv[acuri]
astart = leftoverstart
bcuri++
if bcuri >= numb {
break toploop
}
bstart = int64(b.iv[bcuri].start)
case isLeftoverB:
// note that we change bstart without advancing bcuri,
// since we need to capture any 2ndary intersections with b.iv[bcuri]
bstart = leftoverstart
acuri++
if acuri >= numa {
break toploop
}
astart = int64(a.iv[acuri].start)
default:
// neither had leftover, both completely consumed
// optionally, assert for sanity:
//if a.iv[acuri].endx != b.iv[bcuri].endx {
// panic("huh? should only be possible that endx agree now!")
//}
// advance to next a interval
acuri++
if acuri >= numa {
break toploop
}
astart = int64(a.iv[acuri].start)
// advance to next b interval
bcuri++
if bcuri >= numb {
break toploop
}
bstart = int64(b.iv[bcuri].start)
}
}
} // end for toploop
return answer
}
// get returns true iff key is in the container.
func (rc *runContainer32) contains(key uint32) bool {
_, in, _ := rc.search(int64(key), nil)
return in
}
// numIntervals returns the count of intervals in the container.
func (rc *runContainer32) numIntervals() int {
return len(rc.iv)
}
// search returns alreadyPresent to indicate if the
// key is already in one of our interval32s.
//
// If key is alreadyPresent, then whichInterval32 tells
// you where.
//
// If key is not already present, then whichInterval32 is
// set as follows:
//
// a) whichInterval32 == len(rc.iv)-1 if key is beyond our
// last interval32 in rc.iv;
//
// b) whichInterval32 == -1 if key is before our first
// interval32 in rc.iv;
//
// c) whichInterval32 is set to the minimum index of rc.iv
// which comes strictly before the key;
// so rc.iv[whichInterval32].last < key,
// and if whichInterval32+1 exists, then key < rc.iv[whichInterval32+1].start
// (Note that whichInterval32+1 won't exist when
// whichInterval32 is the last interval.)
//
// runContainer32.search always returns whichInterval32 < len(rc.iv).
//
// If not nil, opts can be used to further restrict
// the search space.
//
func (rc *runContainer32) search(key int64, opts *searchOptions) (whichInterval32 int64, alreadyPresent bool, numCompares int) {
n := int64(len(rc.iv))
if n == 0 {
return -1, false, 0
}
startIndex := int64(0)
endxIndex := int64(n)
if opts != nil {
startIndex = opts.startIndex
// let endxIndex == 0 mean no effect
if opts.endxIndex > 0 {
endxIndex = opts.endxIndex
}
}
// sort.Search returns the smallest index i
// in [0, n) at which f(i) is true, assuming that on the range [0, n),
// f(i) == true implies f(i+1) == true.
// If there is no such index, Search returns n.
// For correctness, this began as verbatim snippet from
// sort.Search in the Go standard lib.
// We inline our comparison function for speed, and
// annotate with numCompares
// to observe and test that extra bounds are utilized.
i, j := startIndex, endxIndex
for i < j {
h := i + (j-i)/2 // avoid overflow when computing h as the bisector
// i <= h < j
numCompares++
if !(key < int64(rc.iv[h].start)) {
i = h + 1
} else {
j = h
}
}
below := i
// end std lib snippet.
// The above is a simple in-lining and annotation of:
/* below := sort.Search(n,
func(i int) bool {
return key < rc.iv[i].start
})
*/
whichInterval32 = int64(below) - 1
if below == n {
// all falses => key is >= start of all interval32s
// ... so does it belong to the last interval32?
if key < int64(rc.iv[n-1].last)+1 {
// yes, it belongs to the last interval32
alreadyPresent = true
return
}
// no, it is beyond the last interval32.
// leave alreadyPreset = false
return
}
// INVAR: key is below rc.iv[below]
if below == 0 {
// key is before the first first interval32.
// leave alreadyPresent = false
return
}
// INVAR: key is >= rc.iv[below-1].start and
// key is < rc.iv[below].start
// is key in below-1 interval32?
if key >= int64(rc.iv[below-1].start) && key < int64(rc.iv[below-1].last)+1 {
// yes, it is. key is in below-1 interval32.
alreadyPresent = true
return
}
// INVAR: key >= rc.iv[below-1].endx && key < rc.iv[below].start
// leave alreadyPresent = false
return
}
// cardinality returns the count of the integers stored in the
// runContainer32.
func (rc *runContainer32) cardinality() int64 {
if len(rc.iv) == 0 {
rc.card = 0
return 0
}
if rc.card > 0 {
return rc.card // already cached
}
// have to compute it
var n int64
for _, p := range rc.iv {
n += int64(p.runlen())
}
rc.card = n // cache it
return n
}
// AsSlice decompresses the contents into a []uint32 slice.
func (rc *runContainer32) AsSlice() []uint32 {
s := make([]uint32, rc.cardinality())
j := 0
for _, p := range rc.iv {
for i := p.start; i <= p.last; i++ {
s[j] = uint32(i)
j++
}
}
return s
}
// newRunContainer32 creates an empty run container.
func newRunContainer32() *runContainer32 {
return &runContainer32{}
}
// newRunContainer32CopyIv creates a run container, initializing
// with a copy of the supplied iv slice.
//
func newRunContainer32CopyIv(iv []interval32) *runContainer32 {
rc := &runContainer32{
iv: make([]interval32, len(iv)),
}
copy(rc.iv, iv)
return rc
}
func (rc *runContainer32) Clone() *runContainer32 {
rc2 := newRunContainer32CopyIv(rc.iv)
return rc2
}
// newRunContainer32TakeOwnership returns a new runContainer32
// backed by the provided iv slice, which we will
// assume exclusive control over from now on.
//
func newRunContainer32TakeOwnership(iv []interval32) *runContainer32 {