/
RangeBitmap.java
1632 lines (1532 loc) · 54.8 KB
/
RangeBitmap.java
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 org.roaringbitmap;
import org.roaringbitmap.buffer.MappeableArrayContainer;
import org.roaringbitmap.buffer.MappeableBitmapContainer;
import org.roaringbitmap.buffer.MappeableContainer;
import org.roaringbitmap.buffer.MappeableRunContainer;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.LongBuffer;
import java.util.Arrays;
import java.util.function.Consumer;
import java.util.function.IntFunction;
import static java.nio.ByteOrder.LITTLE_ENDIAN;
import static org.roaringbitmap.Util.cardinalityInBitmapRange;
import static org.roaringbitmap.Util.resetBitmapRange;
import static org.roaringbitmap.Util.setBitmapRange;
/**
* A 2D bitmap which associates values with a row index and can perform range queries.
*/
public final class RangeBitmap {
private static final int COOKIE = 0xF00D;
private static final int BITMAP = 0;
private static final int RUN = 1;
private static final int ARRAY = 2;
private static final int BITMAP_SIZE = 8192;
/**
* Append values to the RangeBitmap before sealing it.
*
* @param maxValue the maximum value to be appended, values larger than this
* value will be rejected.
* @param bufferSupplier provides ByteBuffers.
* @return an appender.
*/
public static Appender appender(long maxValue,
IntFunction<ByteBuffer> bufferSupplier,
Consumer<ByteBuffer> cleaner) {
return new Appender(maxValue, bufferSupplier, cleaner);
}
/**
* Append values to the RangeBitmap before sealing it, defaults to on heap ByteBuffers.
*
* @param maxValue the maximum value to be appended, values larger than this
* value will be rejected.
* @return an appender.
*/
public static Appender appender(long maxValue) {
return appender(maxValue,
capacity -> ByteBuffer.allocate(capacity).order(LITTLE_ENDIAN), b -> {
});
}
/**
* Maps the RangeBitmap from the buffer with minimal allocation.
* The buffer must not be reused while the mapped RangeBitmap is live.
*
* @param buffer a buffer containing a serialized RangeBitmap.
* @return a RangeBitmap backed by the buffer.
*/
public static RangeBitmap map(ByteBuffer buffer) {
ByteBuffer source = buffer.slice().order(LITTLE_ENDIAN);
int cookie = source.getChar();
if (cookie != COOKIE) {
throw new InvalidRoaringFormat("invalid cookie for range bitmap (expected "
+ COOKIE + " but got " + cookie + ")");
}
int base = source.get() & 0xFF;
if (base != 2) {
throw new InvalidRoaringFormat("Unsupported base for range bitmap: " + cookie);
}
int sliceCount = source.get() & 0xFF;
int maxKey = source.getChar();
long mask = -1L >>> (64 - sliceCount);
byte bytesPerMask = (byte) ((sliceCount + 7) >>> 3);
long maxRid = source.getInt() & 0xFFFFFFFFL;
int masksOffset = source.position();
int containersOffset = masksOffset + maxKey * bytesPerMask;
return new RangeBitmap(mask, maxRid, (ByteBuffer) source.position(buffer.position()),
masksOffset, containersOffset, bytesPerMask);
}
private final ByteBuffer buffer;
private final int masksOffset;
private final int containersOffset;
private final long mask;
private final long max;
private final byte bytesPerMask;
RangeBitmap(long mask, long max, ByteBuffer buffer, int masksOffset, int containersOffset,
byte bytesPerMask) {
this.mask = mask;
this.max = max;
this.buffer = buffer;
this.masksOffset = masksOffset;
this.containersOffset = containersOffset;
this.bytesPerMask = bytesPerMask;
}
/**
* Returns a RoaringBitmap of rows which have a value in between the thresholds.
*
* @param min the inclusive minimum value.
* @param max the inclusive maximum value.
* @return a bitmap of matching rows.
*/
public RoaringBitmap between(long min, long max) {
if (min == 0 || Long.numberOfLeadingZeros(min) < Long.numberOfLeadingZeros(mask)) {
return lte(max);
}
if (Long.numberOfLeadingZeros(max) < Long.numberOfLeadingZeros(mask)) {
return gte(min);
}
return new DoubleEvaluation().compute(min - 1, max);
}
/**
* Returns the number of rows which have a value in between the thresholds.
*
* @param min the inclusive minimum value.
* @param max the inclusive maximum value.
* @return the number of matching rows.
*/
public long betweenCardinality(long min, long max) {
if (min == 0 || Long.numberOfLeadingZeros(min) < Long.numberOfLeadingZeros(mask)) {
return lteCardinality(max);
}
if (Long.numberOfLeadingZeros(max) < Long.numberOfLeadingZeros(mask)) {
return gteCardinality(min);
}
return new DoubleEvaluation().count(min - 1, max);
}
/**
* Returns the number of rows which have a value in between the thresholds.
*
* @param min the inclusive minimum value.
* @param max the inclusive maximum value.
* @param context to be intersected with.
* @return the number of matching rows.
*/
public long betweenCardinality(long min, long max, RoaringBitmap context) {
if (min == 0 || Long.numberOfLeadingZeros(min) < Long.numberOfLeadingZeros(mask)) {
return lteCardinality(max, context);
}
if (Long.numberOfLeadingZeros(max) < Long.numberOfLeadingZeros(mask)) {
return gteCardinality(min, context);
}
return new DoubleEvaluation().count(min - 1, max, context);
}
/**
* Returns a RoaringBitmap of rows which have a value less than or equal to the threshold.
*
* @param threshold the inclusive maximum value.
* @return a bitmap of matching rows.
*/
public RoaringBitmap lte(long threshold) {
return new SingleEvaluation().computeRange(threshold, true);
}
/**
* Returns a RoaringBitmap of rows which have a value less than or equal to the threshold,
* and intersect with the context bitmap, which will not be modified.
*
* @param threshold the inclusive maximum value.
* @param context to be intersected with.
* @return a bitmap of matching rows.
*/
public RoaringBitmap lte(long threshold, RoaringBitmap context) {
return new SingleEvaluation().computeRange(threshold, true, context);
}
/**
* Returns the number of rows which have a value less than or equal to the threshold.
*
* @param threshold the inclusive maximum value.
* @return the number of matching rows.
*/
public long lteCardinality(long threshold) {
return new SingleEvaluation().countRange(threshold, true);
}
/**
* Returns the number of rows which have a value less than or equal to the threshold,
* and intersect with the context bitmap, which will not be modified.
*
* @param threshold the inclusive maximum value.
* @param context to be intersected with.
* @return the number of matching rows.
*/
public long lteCardinality(long threshold, RoaringBitmap context) {
return new SingleEvaluation().countRange(threshold, true, context);
}
/**
* Returns a RoaringBitmap of rows which have a value less than the threshold.
*
* @param threshold the exclusive maximum value.
* @return a bitmap of matching rows.
*/
public RoaringBitmap lt(long threshold) {
return threshold == 0 ? new RoaringBitmap() : lte(threshold - 1);
}
/**
* Returns a RoaringBitmap of rows which have a value less than the threshold,
* and intersect with the context bitmap, which will not be modified.
*
* @param threshold the exclusive maximum value.
* @param context to be intersected with.
* @return a bitmap of matching rows which intersect .
*/
public RoaringBitmap lt(long threshold, RoaringBitmap context) {
return threshold == 0 ? new RoaringBitmap() : lte(threshold - 1, context);
}
/**
* Returns the number of rows which have a value less than the threshold.
*
* @param threshold the exclusive maximum value.
* @return the number of matching rows.
*/
public long ltCardinality(long threshold) {
return threshold == 0 ? 0L : lteCardinality(threshold - 1);
}
/**
* Returns the number of rows which have a value less than the threshold,
* and intersect with the context bitmap, which will not be modified.
*
* @param threshold the exclusive maximum value.
* @param context to be intersected with.
* @return the number of matching rows which intersect .
*/
public long ltCardinality(long threshold, RoaringBitmap context) {
return threshold == 0 ? 0L : lteCardinality(threshold - 1, context);
}
/**
* Returns a RoaringBitmap of rows which have a value greater than the threshold.
*
* @param threshold the exclusive minimum value.
* @return a bitmap of matching rows.
*/
public RoaringBitmap gt(long threshold) {
return new SingleEvaluation().computeRange(threshold, false);
}
/**
* Returns a RoaringBitmap of rows which have a value greater than the threshold,
* and intersect with the context bitmap, which will not be modified.
*
* @param threshold the exclusive minimum value.
* @param context to be intersected with.
* @return a bitmap of matching rows.
*/
public RoaringBitmap gt(long threshold, RoaringBitmap context) {
return new SingleEvaluation().computeRange(threshold, false, context);
}
/**
* Returns the number of rows which have a value greater than the threshold.
*
* @param threshold the exclusive minimum value.
* @return the number of matching rows.
*/
public long gtCardinality(long threshold) {
return new SingleEvaluation().countRange(threshold, false);
}
/**
* Returns the number of rows which have a value greater than the threshold,
* and intersect with the context bitmap, which will not be modified.
*
* @param threshold the exclusive minimum value.
* @param context to be intersected with.
* @return the number of matching rows.
*/
public long gtCardinality(long threshold, RoaringBitmap context) {
return new SingleEvaluation().countRange(threshold, false, context);
}
/**
* Returns a RoaringBitmap of rows which have a value greater than or equal to the threshold.
*
* @param threshold the inclusive minimum value.
* @return a bitmap of matching rows.
*/
public RoaringBitmap gte(long threshold) {
return threshold == 0 ? RoaringBitmap.bitmapOfRange(0, max) : gt(threshold - 1);
}
/**
* Returns a RoaringBitmap of rows which have a value greater than or equal to the threshold,
* and intersect with the context bitmap, which will not be modified.
*
* @param threshold the inclusive minimum value.
* @param context to be intersected with.
* @return a bitmap of matching rows.
*/
public RoaringBitmap gte(long threshold, RoaringBitmap context) {
return threshold == 0 ? context.clone() : gt(threshold - 1, context);
}
/**
* Returns the number of rows which have a value greater than or equal to the threshold.
*
* @param threshold the inclusive minimum value.
* @return the number of matching rows.
*/
public long gteCardinality(long threshold) {
return threshold == 0 ? max : gtCardinality(threshold - 1);
}
/**
* Returns the number of rows which have a value greater than or equal to the threshold,
* and intersect with the context bitmap, which will not be modified.
*
* @param threshold the inclusive minimum value.
* @param context to be intersected with.
* @return the number of matching rows.
*/
public long gteCardinality(long threshold, RoaringBitmap context) {
return threshold == 0 ? context.getLongCardinality() : gtCardinality(threshold - 1, context);
}
/**
* Returns a RoaringBitmap of rows which have a value equal to the value.
*
* @param value the value to filter by.
* @return a bitmap of matching rows.
*/
public RoaringBitmap eq(long value) {
return new SingleEvaluation().computePoint(value, false);
}
/**
* Returns a RoaringBitmap of rows which have a value equal to the value.
*
* @param value the value to filter by.
* @param context to be intersected with.
* @return a bitmap of matching rows.
*/
public RoaringBitmap eq(long value, RoaringBitmap context) {
return new SingleEvaluation().computePoint(value, false, context);
}
/**
* Returns the number of rows which have a value equal to the value.
*
* @param value the inclusive minimum value.
* @return the number of matching rows.
*/
public long eqCardinality(long value) {
return new SingleEvaluation().countPoint(value, false);
}
/**
* Returns the number of rows which have a value equal to the value,
* and intersect with the context bitmap, which will not be modified.
*
* @param value the inclusive minimum value.
* @param context to be intersected with.
* @return the number of matching rows.
*/
public long eqCardinality(long value, RoaringBitmap context) {
return new SingleEvaluation().countPoint(value, false, context);
}
/**
* Returns a RoaringBitmap of rows which have a value not equal to the value.
*
* @param value the value to filter by.
* @return a bitmap of matching rows.
*/
public RoaringBitmap neq(long value) {
return new SingleEvaluation().computePoint(value, true);
}
/**
* Returns a RoaringBitmap of rows which have a value not equal to the value.
*
* @param value the value to filter by.
* @param context to be intersected with.
* @return a bitmap of matching rows.
*/
public RoaringBitmap neq(long value, RoaringBitmap context) {
return new SingleEvaluation().computePoint(value, true, context);
}
/**
* Returns the number of rows which have a value not equal to the value.
*
* @param value the inclusive minimum value.
* @return the number of matching rows.
*/
public long neqCardinality(long value) {
return new SingleEvaluation().countPoint(value, true);
}
/**
* Returns the number of rows which have a value not equal to the value,
* and intersect with the context bitmap, which will not be modified.
*
* @param value the inclusive minimum value.
* @param context to be intersected with.
* @return the number of matching rows.
*/
public long neqCardinality(long value, RoaringBitmap context) {
return new SingleEvaluation().countPoint(value, true, context);
}
private final class SingleEvaluation {
private final long[] bits = new long[1024];
private final ByteBuffer buffer = RangeBitmap.this.buffer.slice().order(LITTLE_ENDIAN);
private int position = containersOffset;
private boolean empty = true;
public RoaringBitmap computePoint(long value, boolean negate) {
if (Long.numberOfLeadingZeros(value) < Long.numberOfLeadingZeros(mask)) {
return negate ? RoaringBitmap.bitmapOfRange(0, max) : new RoaringBitmap();
}
RoaringArray output = new RoaringArray();
long remaining = max;
int mPos = masksOffset;
char key = 0;
while (remaining > 0) {
long containerMask = getContainerMask(buffer, mPos, mask, bytesPerMask);
int limit = Math.min((int) remaining, 0x10000);
evaluateHorizontalSlicePoint(limit, value, containerMask);
if (negate) {
Util.flipBitmapRange(bits, 0, limit);
empty = false;
}
if (!empty) {
Container toAppend = new BitmapContainer(bits, -1).repairAfterLazy().runOptimize();
if (!toAppend.isEmpty()) {
output.append(key, toAppend instanceof BitmapContainer ? toAppend.clone() : toAppend);
}
}
key++;
remaining -= 0x10000;
mPos += bytesPerMask;
}
return new RoaringBitmap(output);
}
public RoaringBitmap computePoint(long value, boolean negate, RoaringBitmap context) {
if (context.isEmpty()) {
return new RoaringBitmap();
}
if (Long.numberOfLeadingZeros(value) < Long.numberOfLeadingZeros(mask)) {
return negate ? context.clone() : new RoaringBitmap();
}
RoaringArray output = new RoaringArray();
RoaringArray contextArray = context.highLowContainer;
int contextPos = 0;
int maxContextKey = contextArray.keys[contextArray.size - 1];
long remaining = max;
int mPos = masksOffset;
for (int prefix = 0; prefix <= maxContextKey && remaining > 0; prefix++) {
long containerMask = getContainerMask(buffer, mPos, mask, bytesPerMask);
if (prefix < contextArray.keys[contextPos]) {
skipContainers(containerMask);
} else {
int limit = Math.min((int) remaining, 0x10000);
evaluateHorizontalSlicePoint(limit, value, containerMask);
if (negate) {
Util.flipBitmapRange(bits, 0, limit);
empty = false;
}
if (!empty) {
Container toAppend = new BitmapContainer(bits, -1)
.iand(contextArray.values[contextPos])
.repairAfterLazy()
.runOptimize();
if (!toAppend.isEmpty()) {
output.append((char) prefix,
toAppend instanceof BitmapContainer ? toAppend.clone() : toAppend);
}
}
contextPos++;
}
remaining -= 0x10000;
mPos += bytesPerMask;
}
return new RoaringBitmap(output);
}
public long countPoint(long value, boolean negate) {
if (Long.numberOfLeadingZeros(value) < Long.numberOfLeadingZeros(mask)) {
return negate ? max : 0L;
}
long count = 0;
long remaining = max;
int mPos = masksOffset;
while (remaining > 0) {
long containerMask = getContainerMask(buffer, mPos, mask, bytesPerMask);
int limit = Math.min((int) remaining, 0x10000);
evaluateHorizontalSlicePoint(limit, value, containerMask);
int cardinality = cardinalityInBitmapRange(bits, 0, limit);
count += negate ? (limit - cardinality) : cardinality;
remaining -= 0x10000;
mPos += bytesPerMask;
}
return count;
}
private long countPoint(long threshold, boolean negate, RoaringBitmap context) {
if (context.isEmpty()) {
return 0L;
}
if (Long.numberOfLeadingZeros(threshold) < Long.numberOfLeadingZeros(mask)) {
return negate ? context.getLongCardinality() : 0L;
}
RoaringArray contextArray = context.highLowContainer;
int contextPos = 0;
int maxContextKey = contextArray.keys[contextArray.size - 1];
long count = 0;
long remaining = max;
int mPos = masksOffset;
for (int prefix = 0; prefix <= maxContextKey && remaining > 0; prefix++) {
int limit = Math.min(0x10000, (int) remaining);
long containerMask = getContainerMask(buffer, mPos, mask, bytesPerMask);
if (prefix < contextArray.keys[contextPos]) {
skipContainers(containerMask);
} else {
evaluateHorizontalSlicePoint(limit, threshold, containerMask);
if (negate) {
Util.flipBitmapRange(bits, 0, limit);
empty = false;
}
Container container = contextArray.values[contextPos];
int cardinality = container.andCardinality(new BitmapContainer(bits, -1));
count += cardinality;
contextPos++;
}
remaining -= 0x10000;
mPos += bytesPerMask;
}
return count;
}
public RoaringBitmap computeRange(long threshold, boolean upper) {
if (Long.numberOfLeadingZeros(threshold) < Long.numberOfLeadingZeros(mask)) {
return upper ? RoaringBitmap.bitmapOfRange(0, max) : new RoaringBitmap();
}
RoaringArray output = new RoaringArray();
long remaining = max;
int mPos = masksOffset;
char key = 0;
while (remaining > 0) {
long containerMask = getContainerMask(buffer, mPos, mask, bytesPerMask);
evaluateHorizontalSliceRange(remaining, threshold, containerMask);
if (!upper) {
Util.flipBitmapRange(bits, 0, Math.min(0x10000, (int) remaining));
empty = false;
}
if (!empty) {
Container toAppend = new BitmapContainer(bits, -1).repairAfterLazy().runOptimize();
if (!toAppend.isEmpty()) {
output.append(key, toAppend instanceof BitmapContainer ? toAppend.clone() : toAppend);
}
}
key++;
remaining -= 0x10000;
mPos += bytesPerMask;
}
return new RoaringBitmap(output);
}
private RoaringBitmap computeRange(long threshold, boolean upper, RoaringBitmap context) {
if (context.isEmpty()) {
return new RoaringBitmap();
}
if (Long.numberOfLeadingZeros(threshold) < Long.numberOfLeadingZeros(mask)) {
return upper ? context.clone() : new RoaringBitmap();
}
RoaringArray contextArray = context.highLowContainer;
int contextPos = 0;
int maxContextKey = contextArray.keys[contextArray.size - 1];
RoaringArray output = new RoaringArray();
long remaining = max;
int mPos = masksOffset;
for (int prefix = 0; prefix <= maxContextKey && remaining > 0; prefix++) {
long containerMask = getContainerMask(buffer, mPos, mask, bytesPerMask);
if (prefix < contextArray.keys[contextPos]) {
skipContainers(containerMask);
} else {
evaluateHorizontalSliceRange(remaining, threshold, containerMask);
if (!upper) {
Util.flipBitmapRange(bits, 0, Math.min(0x10000, (int) remaining));
empty = false;
}
if (!empty) {
Container toAppend = new BitmapContainer(bits, -1)
.iand(contextArray.values[contextPos])
.repairAfterLazy()
.runOptimize();
if (!toAppend.isEmpty()) {
output.append((char) prefix,
toAppend instanceof BitmapContainer ? toAppend.clone() : toAppend);
}
}
contextPos++;
}
remaining -= 0x10000;
mPos += bytesPerMask;
}
return new RoaringBitmap(output);
}
public long countRange(long threshold, boolean upper) {
if (Long.numberOfLeadingZeros(threshold) < Long.numberOfLeadingZeros(mask)) {
return upper ? max : 0L;
}
long count = 0;
long remaining = max;
int mPos = masksOffset;
while (remaining > 0) {
long containerMask = getContainerMask(buffer, mPos, mask, bytesPerMask);
evaluateHorizontalSliceRange(remaining, threshold, containerMask);
int remainder = Math.min((int) remaining, 0x10000);
int cardinality = cardinalityInBitmapRange(bits, 0, remainder);
count += upper ? cardinality : (remainder - cardinality);
remaining -= 0x10000;
mPos += bytesPerMask;
}
return count;
}
private long countRange(long threshold, boolean upper, RoaringBitmap context) {
if (context.isEmpty()) {
return 0L;
}
if (Long.numberOfLeadingZeros(threshold) < Long.numberOfLeadingZeros(mask)) {
return upper ? context.getLongCardinality() : 0L;
}
RoaringArray contextArray = context.highLowContainer;
int contextPos = 0;
int maxContextKey = contextArray.keys[contextArray.size - 1];
long count = 0;
long remaining = max;
int mPos = masksOffset;
for (int prefix = 0; prefix <= maxContextKey && remaining > 0; prefix++) {
long containerMask = getContainerMask(buffer, mPos, mask, bytesPerMask);
if (prefix < contextArray.keys[contextPos]) {
skipContainers(containerMask);
} else {
evaluateHorizontalSliceRange(remaining, threshold, containerMask);
Container container = contextArray.values[contextPos];
int cardinality = upper
? container.andCardinality(new BitmapContainer(bits, -1))
: container.andNot(new BitmapContainer(bits, -1).repairAfterLazy()).getCardinality();
count += cardinality;
contextPos++;
}
remaining -= 0x10000;
mPos += bytesPerMask;
}
return count;
}
private void evaluateHorizontalSliceRange(long remaining, long threshold, long containerMask) {
// most significant absent bit in the threshold for which there is no container;
// everything before this is wasted work, so we just skip over the containers
int skip = 64 - Long.numberOfLeadingZeros((~(threshold | containerMask) & mask));
int slice = 0;
if (skip > 0) {
for (; slice < skip; ++slice) {
if (((containerMask >>> slice) & 1) == 1) {
skipContainer();
}
}
if (!empty) {
Arrays.fill(bits, 0L);
empty = true;
}
} else {
// the first slice is special: if the threshold includes this slice,
// fill the buffer, otherwise copy the slice
if ((threshold & 1) == 1) {
if (remaining >= 0x10000) {
Arrays.fill(bits, -1L);
} else {
setBitmapRange(bits, 0, (int) remaining);
if (!empty) {
resetBitmapRange(bits, (int) remaining, 0x10000);
}
}
if ((containerMask & 1) == 1) {
skipContainer();
}
empty = false;
} else {
if (!empty) {
Arrays.fill(bits, 0L);
empty = true;
}
if ((containerMask & 1) == 1) {
if ((threshold & 1) == 0) {
orNextIntoBits();
empty = false;
} else {
skipContainer();
}
}
}
slice++;
}
for (; slice < Long.bitCount(mask); ++slice) {
if ((containerMask >>> slice & 1) == 1) {
if ((threshold >>> slice & 1) == 1) {
// bit present in both both, include bits from slice
orNextIntoBits();
empty = false;
} else {
// bit present in container, absent from threshold, filter
if (empty) {
skipContainer();
} else {
andNextIntoBits();
}
}
}
}
}
private void evaluateHorizontalSlicePoint(int limit, long value, long containerMask) {
// this could be skipped if the last slice resulted in a full bitset
setBitmapRange(bits, 0, limit);
resetBitmapRange(bits, limit, 0x10000);
empty = false;
// for each i
// - if the bit i is not set in the value, intersect the container with the bits
// - if the bit i is set in value, remove the container from the bits
for (int slice = 0; slice < Long.bitCount(mask); slice++) {
if (((value >>> slice) & 1) == 1) {
// bit present, need to remove the container values from bits (bits &= ~container)
if (((containerMask >>> slice) & 1) == 1) {
if (empty) {
skipContainer();
} else {
removeNextFromBits();
}
}
} else {
// bit not present, need to intersect the container bits (bits &= container)
if (((containerMask >>> slice) & 1) == 1) {
if (empty) {
skipContainer();
} else {
andNextIntoBits();
}
} else if (!empty) {
// there's no container so we can just clear the bits
// but it can be skipped if the bits are already known to be empty
resetBitmapRange(bits, 0, limit);
empty = true;
}
}
}
}
private void andNextIntoBits() {
int type = buffer.get(position);
position++;
int size = buffer.getChar(position) & 0xFFFF;
position += Character.BYTES;
switch (type) {
case ARRAY: {
int skip = size << 1;
CharBuffer cb = (CharBuffer) ((ByteBuffer) buffer.position(position)).asCharBuffer()
.limit(skip >>> 1);
MappeableArrayContainer array = new MappeableArrayContainer(cb, size);
array.andInto(bits);
position += skip;
}
break;
case BITMAP: {
LongBuffer lb = (LongBuffer) ((ByteBuffer) buffer.position(position)).asLongBuffer()
.limit(1024);
MappeableBitmapContainer bitmap = new MappeableBitmapContainer(lb, size);
bitmap.andInto(bits);
position += BITMAP_SIZE;
}
break;
case RUN: {
int skip = size << 2;
CharBuffer cb = (CharBuffer) ((ByteBuffer) buffer.position(position)).asCharBuffer()
.limit(skip >>> 1);
MappeableRunContainer run = new MappeableRunContainer(cb, size);
run.andInto(bits);
position += skip;
}
break;
default:
throw new IllegalStateException("Unknown type " + type
+ " (this is a bug, please report it.)");
}
}
private void orNextIntoBits() {
int type = buffer.get(position);
position++;
int size = buffer.getChar(position) & 0xFFFF;
position += Character.BYTES;
switch (type) {
case ARRAY: {
int skip = size << 1;
CharBuffer cb = (CharBuffer) ((ByteBuffer) buffer.position(position)).asCharBuffer()
.limit(skip >>> 1);
MappeableArrayContainer array = new MappeableArrayContainer(cb, size);
array.orInto(bits);
position += skip;
}
break;
case BITMAP: {
LongBuffer lb = (LongBuffer) ((ByteBuffer) buffer.position(position)).asLongBuffer()
.limit(1024);
MappeableBitmapContainer bitmap = new MappeableBitmapContainer(lb, size);
bitmap.orInto(bits);
position += BITMAP_SIZE;
}
break;
case RUN: {
int skip = size << 2;
CharBuffer cb = (CharBuffer) ((ByteBuffer) buffer.position(position)).asCharBuffer()
.limit(skip >>> 1);
MappeableRunContainer run = new MappeableRunContainer(cb, size);
run.orInto(bits);
position += skip;
}
break;
default:
throw new IllegalStateException("Unknown type " + type
+ " (this is a bug, please report it.)");
}
}
private void removeNextFromBits() {
int type = buffer.get(position);
position++;
int size = buffer.getChar(position) & 0xFFFF;
position += Character.BYTES;
switch (type) {
case ARRAY: {
int skip = size << 1;
CharBuffer cb = (CharBuffer) ((ByteBuffer) buffer.position(position)).asCharBuffer()
.limit(skip >>> 1);
MappeableArrayContainer array = new MappeableArrayContainer(cb, size);
array.removeFrom(bits);
position += skip;
}
break;
case BITMAP: {
LongBuffer lb = (LongBuffer) ((ByteBuffer) buffer.position(position)).asLongBuffer()
.limit(1024);
MappeableBitmapContainer bitmap = new MappeableBitmapContainer(lb, size);
bitmap.removeFrom(bits);
position += BITMAP_SIZE;
}
break;
case RUN: {
int skip = size << 2;
CharBuffer cb = (CharBuffer) ((ByteBuffer) buffer.position(position)).asCharBuffer()
.limit(skip >>> 1);
MappeableRunContainer run = new MappeableRunContainer(cb, size);
run.removeFrom(bits);
position += skip;
}
break;
default:
throw new IllegalStateException("Unknown type " + type
+ " (this is a bug, please report it.)");
}
}
private void skipContainer() {
int type = buffer.get(position);
int size = buffer.getChar(position + 1) & 0xFFFF;
if (type == BITMAP) {
position += 3 + BITMAP_SIZE;
} else {
position += 3 + (size << (type == RUN ? 2 : 1));
}
}
private void skipContainers(long mask) {
for (int i = 0; i < Long.bitCount(mask); i++) {
skipContainer();
}
}
}
private final class DoubleEvaluation {
private final ByteBuffer buffer = RangeBitmap.this.buffer.slice().order(LITTLE_ENDIAN);
private final Bits low = new Bits();
private final Bits high = new Bits();
private int position = containersOffset;
public RoaringBitmap compute(long lower, long upper) {
RoaringArray output = new RoaringArray();
long remaining = max;
int mPos = masksOffset;
char key = 0;
while (remaining > 0) {
long containerMask = getContainerMask(buffer, mPos, mask, bytesPerMask);
evaluateHorizontalSlice(containerMask, remaining, lower, upper);
if (!low.empty && !high.empty) {
if (low.full && high.full) {
output.append(key, RunContainer.full());
} else {
final long[] bits;
if (low.full) {
bits = high.bits;
} else if (high.full) {
bits = low.bits;
} else {
bits = low.bits;
for (int i = 0; i < Math.min(bits.length, high.bits.length); i++) {
bits[i] &= high.bits[i];
}
}
Container toAppend = new BitmapContainer(bits, -1).repairAfterLazy().runOptimize();
if (!toAppend.isEmpty()) {
output.append(key, toAppend instanceof BitmapContainer ? toAppend.clone() : toAppend);
}
}
}
key++;
remaining -= 0x10000;
mPos += bytesPerMask;
}
return new RoaringBitmap(output);
}
public long count(long lower, long upper) {
long count = 0;
long remaining = max;
int mPos = masksOffset;
while (remaining > 0) {
long containerMask = getContainerMask(buffer, mPos, mask, bytesPerMask);
evaluateHorizontalSlice(containerMask, remaining, lower, upper);
if (!low.empty && !high.empty) {
int remainder = Math.min((int) remaining, 0x10000);
if (low.full && high.full) {
count += remainder;
} else {
if (low.full) {
count += cardinalityInBitmapRange(high.bits, 0, remainder);
} else if (high.full) {
count += cardinalityInBitmapRange(low.bits, 0, remainder);
} else {
for (int i = 0; i < Math.min(low.bits.length, high.bits.length); i++) {
high.bits[i] &= low.bits[i];
}
count += cardinalityInBitmapRange(high.bits, 0, remainder);
}
}
}
remaining -= 0x10000;
mPos += bytesPerMask;
}
return count;
}
public long count(long lower, long upper, RoaringBitmap context) {
long count = 0;
long remaining = max;
int mPos = masksOffset;
RoaringArray contextArray = context.highLowContainer;
int contextPos = 0;
int maxContextKey = contextArray.keys[contextArray.size - 1];
for (int prefix = 0; prefix <= maxContextKey && remaining > 0; prefix++) {
long containerMask = getContainerMask(buffer, mPos, mask, bytesPerMask);
if (prefix < contextArray.keys[contextPos]) {
for (int i = 0; i < Long.bitCount(containerMask); i++) {
skipContainer();
}
} else {
evaluateHorizontalSlice(containerMask, remaining, lower, upper);
if (!low.empty && !high.empty) {
Container container = contextArray.values[contextPos];
if (low.full && high.full) {
count += container.getCardinality();
} else {
if (low.full) {
count += new BitmapContainer(high.bits, -1).andCardinality(container);
} else if (high.full) {
count += new BitmapContainer(low.bits, -1).andCardinality(container);