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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
// !!! DO NOT EDIT - THIS IS AN AUTO-GENERATED FILE !!!
// Created by amalgamation.sh on 2026-02-24T02:08:17Z
/*
* The CRoaring project is under a dual license (Apache/MIT).
* Users of the library may choose one or the other license.
*/
/*
* Copyright 2016-2022 The CRoaring authors
*
* 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.
*
* SPDX-License-Identifier: Apache-2.0
*/
/*
* MIT License
*
* Copyright 2016-2022 The CRoaring authors
*
* Permission is hereby granted, free of charge, to any
* person obtaining a copy of this software and associated
* documentation files (the "Software"), to deal in the
* Software without restriction, including without
* limitation the rights to use, copy, modify, merge,
* publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software
* is furnished to do so, subject to the following
* conditions:
*
* The above copyright notice and this permission notice
* shall be included in all copies or substantial portions
* of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
* ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
* TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
* SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
* IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
* SPDX-License-Identifier: MIT
*/
#define ROARING_API_NOT_IN_GLOBAL_NAMESPACE // see remarks in roaring.h
#include "roaring.h"
#undef ROARING_API_NOT_IN_GLOBAL_NAMESPACE
/* begin file cpp/roaring/roaring.hh */
/*
A C++ header for Roaring Bitmaps.
*/
#ifndef INCLUDE_ROARING_HH_
#define INCLUDE_ROARING_HH_
#include <algorithm>
#include <cstdarg>
#include <initializer_list>
#include <limits>
#include <new>
#include <stdexcept>
#include <string>
#if !defined(ROARING_EXCEPTIONS)
// __cpp_exceptions is required by C++98 and we require C++11 or better.
#ifndef __cpp_exceptions
#error "__cpp_exceptions should be defined"
#endif
#if __cpp_exceptions
#define ROARING_EXCEPTIONS 1
#else
#define ROARING_EXCEPTIONS 0
#endif
#endif
#ifndef ROARING_TERMINATE
#if ROARING_EXCEPTIONS
#define ROARING_TERMINATE(_s) throw std::runtime_error(_s)
#else
#define ROARING_TERMINATE(_s) std::terminate()
#endif
#endif
#define ROARING_API_NOT_IN_GLOBAL_NAMESPACE // see remarks in roaring.h
#undef ROARING_API_NOT_IN_GLOBAL_NAMESPACE
namespace roaring {
class RoaringSetBitBiDirectionalIterator;
/** DEPRECATED, use `RoaringSetBitBiDirectionalIterator`. */
using RoaringSetBitForwardIterator = RoaringSetBitBiDirectionalIterator;
/**
* A bit of context usable with `*Bulk()` functions.
*
* A context may only be used with a single bitmap, and any modification to a
* bitmap (other than modifications performed with `Bulk()` functions with the
* context passed) will invalidate any contexts associated with that bitmap.
*/
class BulkContext {
public:
friend class Roaring;
using roaring_bitmap_bulk_context_t = api::roaring_bulk_context_t;
BulkContext() : context_{nullptr, 0, 0, 0} {}
BulkContext(const BulkContext &) = delete;
BulkContext &operator=(const BulkContext &) = delete;
BulkContext(BulkContext &&) noexcept = default;
BulkContext &operator=(BulkContext &&) noexcept = default;
private:
roaring_bitmap_bulk_context_t context_;
};
class Roaring {
typedef api::roaring_bitmap_t roaring_bitmap_t; // class-local name alias
public:
/**
* Create an empty bitmap in the existing memory for the class.
* The bitmap will be in the "clear" state with no auxiliary allocations.
*/
Roaring() : roaring{} {
// The empty constructor roaring{} silences warnings from pedantic
// static analyzers.
api::roaring_bitmap_init_cleared(&roaring);
}
/**
* Construct a bitmap from a list of 32-bit integer values.
*/
Roaring(size_t n, const uint32_t *data) : Roaring() {
api::roaring_bitmap_add_many(&roaring, n, data);
}
/**
* Construct a bitmap from an initializer list.
*/
Roaring(std::initializer_list<uint32_t> l) : Roaring() {
addMany(l.size(), l.begin());
}
/**
* Construct a roaring object by taking control of a malloc()'d C struct.
*
* Passing a NULL pointer is unsafe.
* The pointer to the C struct will be invalid after the call.
*/
explicit Roaring(roaring_bitmap_t *s) noexcept : roaring(*s) {
roaring_free(s); // deallocate the passed-in pointer
}
/**
* Copy constructor.
* It may throw std::runtime_error if there is insufficient memory.
*/
Roaring(const Roaring &r) : Roaring() {
if (!api::roaring_bitmap_overwrite(&roaring, &r.roaring)) {
ROARING_TERMINATE("failed roaring_bitmap_overwrite in constructor");
}
api::roaring_bitmap_set_copy_on_write(
&roaring, api::roaring_bitmap_get_copy_on_write(&r.roaring));
}
/**
* Move constructor. The moved-from object remains valid but empty, i.e.
* it behaves as though it was just freshly constructed.
*/
Roaring(Roaring &&r) noexcept : roaring(r.roaring) {
//
// !!! This clones the bits of the roaring structure to a new location
// and then overwrites the old bits...assuming that this will still
// work. There are scenarios where this could break; e.g. if some of
// those bits were pointers into the structure memory itself. If such
// things were possible, a roaring_bitmap_move() API would be needed.
//
api::roaring_bitmap_init_cleared(&r.roaring);
}
/**
* Construct a bitmap from a list of uint32_t values.
*/
static Roaring bitmapOf(size_t n, ...) {
Roaring ans;
va_list vl;
va_start(vl, n);
for (size_t i = 0; i < n; i++) {
ans.add(va_arg(vl, uint32_t));
}
va_end(vl);
return ans;
}
/**
* Copies the content of the provided bitmap, and
* discard the current content.
* It may throw std::runtime_error if there is insufficient memory.
*/
Roaring &operator=(const Roaring &r) {
if (!api::roaring_bitmap_overwrite(&roaring, &r.roaring)) {
ROARING_TERMINATE("failed memory alloc in assignment");
}
api::roaring_bitmap_set_copy_on_write(
&roaring, api::roaring_bitmap_get_copy_on_write(&r.roaring));
return *this;
}
/**
* Moves the content of the provided bitmap, and
* discard the current content.
*/
Roaring &operator=(Roaring &&r) noexcept {
api::roaring_bitmap_clear(&roaring); // free this class's allocations
// !!! See notes in the Move Constructor regarding roaring_bitmap_move()
//
roaring = r.roaring;
api::roaring_bitmap_init_cleared(&r.roaring);
return *this;
}
/**
* Assignment from an initializer list.
*/
Roaring &operator=(std::initializer_list<uint32_t> l) {
// Delegate to move assignment operator
*this = Roaring(l);
return *this;
}
/**
* Construct a bitmap from a list of uint32_t values.
* E.g., bitmapOfList({1,2,3}).
*/
static Roaring bitmapOfList(std::initializer_list<uint32_t> l) {
Roaring ans;
ans.addMany(l.size(), l.begin());
return ans;
}
/**
* Add value x
*/
void add(uint32_t x) noexcept { api::roaring_bitmap_add(&roaring, x); }
/**
* Add value x
* Returns true if a new value was added, false if the value was already
* existing.
*/
bool addChecked(uint32_t x) noexcept {
return api::roaring_bitmap_add_checked(&roaring, x);
}
/**
* Add all values in range [min, max)
*/
void addRange(const uint64_t min, const uint64_t max) noexcept {
return api::roaring_bitmap_add_range(&roaring, min, max);
}
/**
* Add all values in range [min, max]
*/
void addRangeClosed(const uint32_t min, const uint32_t max) noexcept {
return api::roaring_bitmap_add_range_closed(&roaring, min, max);
}
/**
* Add value n_args from pointer vals
*/
void addMany(size_t n_args, const uint32_t *vals) noexcept {
api::roaring_bitmap_add_many(&roaring, n_args, vals);
}
/**
* Add value val, using context from a previous insert for speed
* optimization.
*
* `context` will be used to store information between calls to make bulk
* operations faster. `context` should be default-initialized before the
* first call to this function.
*/
void addBulk(BulkContext &context, uint32_t x) noexcept {
api::roaring_bitmap_add_bulk(&roaring, &context.context_, x);
}
/**
* Check if item x is present, using context from a previous insert or
* search for speed optimization.
*
* `context` will be used to store information between calls to make bulk
* operations faster. `context` should be default-initialized before the
* first call to this function.
*/
bool containsBulk(BulkContext &context, uint32_t x) const noexcept {
return api::roaring_bitmap_contains_bulk(&roaring, &context.context_,
x);
}
/**
* Remove value x
*/
void remove(uint32_t x) noexcept {
api::roaring_bitmap_remove(&roaring, x);
}
/**
* Remove value x
* Returns true if a new value was removed, false if the value was not
* existing.
*/
bool removeChecked(uint32_t x) noexcept {
return api::roaring_bitmap_remove_checked(&roaring, x);
}
/**
* Remove all values in range [min, max)
*/
void removeRange(uint64_t min, uint64_t max) noexcept {
return api::roaring_bitmap_remove_range(&roaring, min, max);
}
/**
* Remove all values in range [min, max]
*/
void removeRangeClosed(uint32_t min, uint32_t max) noexcept {
return api::roaring_bitmap_remove_range_closed(&roaring, min, max);
}
/**
* Clears the bitmap.
*/
void clear() { api::roaring_bitmap_clear(&roaring); }
/**
* Return the largest value (if not empty)
*/
uint32_t maximum() const noexcept {
return api::roaring_bitmap_maximum(&roaring);
}
/**
* Return the smallest value (if not empty)
*/
uint32_t minimum() const noexcept {
return api::roaring_bitmap_minimum(&roaring);
}
/**
* Check if value x is present
*/
bool contains(uint32_t x) const noexcept {
return api::roaring_bitmap_contains(&roaring, x);
}
/**
* Check if all values from x (included) to y (excluded) are present
*/
bool containsRange(const uint64_t x, const uint64_t y) const noexcept {
return api::roaring_bitmap_contains_range(&roaring, x, y);
}
bool containsRangeClosed(const uint32_t x,
const uint32_t y) const noexcept {
return api::roaring_bitmap_contains_range_closed(&roaring, x, y);
}
/**
* Compute the intersection between the current bitmap and the provided
* bitmap, writing the result in the current bitmap. The provided bitmap
* is not modified.
*
* Performance hint: if you are computing the intersection between several
* bitmaps, two-by-two, it is best to start with the smallest bitmap.
*/
Roaring &operator&=(const Roaring &r) noexcept {
api::roaring_bitmap_and_inplace(&roaring, &r.roaring);
return *this;
}
/**
* Compute the difference between the current bitmap and the provided
* bitmap, writing the result in the current bitmap. The provided bitmap
* is not modified.
*/
Roaring &operator-=(const Roaring &r) noexcept {
api::roaring_bitmap_andnot_inplace(&roaring, &r.roaring);
return *this;
}
/**
* Compute the union between the current bitmap and the provided bitmap,
* writing the result in the current bitmap. The provided bitmap is not
* modified.
*
* See also the fastunion function to aggregate many bitmaps more quickly.
*/
Roaring &operator|=(const Roaring &r) noexcept {
api::roaring_bitmap_or_inplace(&roaring, &r.roaring);
return *this;
}
/**
* Compute the symmetric union between the current bitmap and the provided
* bitmap, writing the result in the current bitmap. The provided bitmap
* is not modified.
*/
Roaring &operator^=(const Roaring &r) noexcept {
api::roaring_bitmap_xor_inplace(&roaring, &r.roaring);
return *this;
}
/**
* Exchange the content of this bitmap with another.
*/
void swap(Roaring &r) noexcept { std::swap(r.roaring, roaring); }
/**
* Get the cardinality of the bitmap (number of elements).
*/
uint64_t cardinality() const noexcept {
return api::roaring_bitmap_get_cardinality(&roaring);
}
/**
* Returns true if the bitmap is empty (cardinality is zero).
*/
bool isEmpty() const noexcept {
return api::roaring_bitmap_is_empty(&roaring);
}
/**
* Returns true if the bitmap is full (cardinality is uint32_t max + 1).
* we put std::numeric_limits<>::max/min in parentheses
* to avoid a clash with the Windows.h header under Windows.
*/
bool isFull() const noexcept {
return api::roaring_bitmap_get_cardinality(&roaring) ==
((uint64_t)(std::numeric_limits<uint32_t>::max)()) + 1;
}
/**
* Returns true if the bitmap is subset of the other.
*/
bool isSubset(const Roaring &r) const noexcept {
return api::roaring_bitmap_is_subset(&roaring, &r.roaring);
}
/**
* Returns true if the bitmap is strict subset of the other.
*/
bool isStrictSubset(const Roaring &r) const noexcept {
return api::roaring_bitmap_is_strict_subset(&roaring, &r.roaring);
}
/**
* Convert the bitmap to an array. Write the output to "ans", caller is
* responsible to ensure that there is enough memory allocated
* (e.g., ans = new uint32[mybitmap.cardinality()];)
*/
void toUint32Array(uint32_t *ans) const noexcept {
api::roaring_bitmap_to_uint32_array(&roaring, ans);
}
/**
* To int array with pagination
*/
void rangeUint32Array(uint32_t *ans, size_t offset,
size_t limit) const noexcept {
api::roaring_bitmap_range_uint32_array(&roaring, offset, limit, ans);
}
/**
* Return true if the two bitmaps contain the same elements.
*/
bool operator==(const Roaring &r) const noexcept {
return api::roaring_bitmap_equals(&roaring, &r.roaring);
}
/**
* Compute the negation of the roaring bitmap within the half-open interval
* [range_start, range_end). Areas outside the interval are unchanged.
*/
void flip(uint64_t range_start, uint64_t range_end) noexcept {
api::roaring_bitmap_flip_inplace(&roaring, range_start, range_end);
}
/**
* Compute the negation of the roaring bitmap within the closed interval
* [range_start, range_end]. Areas outside the interval are unchanged.
*/
void flipClosed(uint32_t range_start, uint32_t range_end) noexcept {
api::roaring_bitmap_flip_inplace_closed(&roaring, range_start,
range_end);
}
/**
* Remove run-length encoding even when it is more space efficient.
* Return whether a change was applied.
*/
bool removeRunCompression() noexcept {
return api::roaring_bitmap_remove_run_compression(&roaring);
}
/**
* Convert array and bitmap containers to run containers when it is more
* efficient; also convert from run containers when more space efficient.
* Returns true if the result has at least one run container. Additional
* savings might be possible by calling shrinkToFit().
*/
bool runOptimize() noexcept {
return api::roaring_bitmap_run_optimize(&roaring);
}
/**
* If needed, reallocate memory to shrink the memory usage. Returns
* the number of bytes saved.
*/
size_t shrinkToFit() noexcept {
return api::roaring_bitmap_shrink_to_fit(&roaring);
}
/**
* Iterate over the bitmap elements. The function iterator is called once
* for all the values with ptr (can be NULL) as the second parameter of
* each call.
*
* roaring_iterator is simply a pointer to a function that returns bool
* (true means that the iteration should continue while false means that it
* should stop), and takes (uint32_t,void*) as inputs.
*/
void iterate(api::roaring_iterator iterator, void *ptr) const {
api::roaring_iterate(&roaring, iterator, ptr);
}
/**
* Selects the value at index rnk in the bitmap, where the smallest value
* is at index 0.
*
* If the size of the roaring bitmap is strictly greater than rank, then
* this function returns true and sets element to the element of given rank.
* Otherwise, it returns false.
*/
bool select(uint32_t rnk, uint32_t *element) const noexcept {
return api::roaring_bitmap_select(&roaring, rnk, element);
}
/**
* Computes the size of the intersection between two bitmaps.
*/
uint64_t and_cardinality(const Roaring &r) const noexcept {
return api::roaring_bitmap_and_cardinality(&roaring, &r.roaring);
}
/**
* Check whether the two bitmaps intersect.
*/
bool intersect(const Roaring &r) const noexcept {
return api::roaring_bitmap_intersect(&roaring, &r.roaring);
}
/**
* Computes the Jaccard index between two bitmaps. (Also known as the
* Tanimoto distance,
* or the Jaccard similarity coefficient)
*
* The Jaccard index is undefined if both bitmaps are empty.
*/
double jaccard_index(const Roaring &r) const noexcept {
return api::roaring_bitmap_jaccard_index(&roaring, &r.roaring);
}
/**
* Computes the size of the union between two bitmaps.
*/
uint64_t or_cardinality(const Roaring &r) const noexcept {
return api::roaring_bitmap_or_cardinality(&roaring, &r.roaring);
}
/**
* Computes the size of the difference (andnot) between two bitmaps.
*/
uint64_t andnot_cardinality(const Roaring &r) const noexcept {
return api::roaring_bitmap_andnot_cardinality(&roaring, &r.roaring);
}
/**
* Computes the size of the symmetric difference (andnot) between two
* bitmaps.
*/
uint64_t xor_cardinality(const Roaring &r) const noexcept {
return api::roaring_bitmap_xor_cardinality(&roaring, &r.roaring);
}
/**
* Returns the number of integers that are smaller or equal to x.
* Thus the rank of the smallest element is one. If
* x is smaller than the smallest element, this function will return 0.
* The rank and select functions differ in convention: this function returns
* 1 when ranking the smallest value, but the select function returns the
* smallest value when using index 0.
*/
uint64_t rank(uint32_t x) const noexcept {
return api::roaring_bitmap_rank(&roaring, x);
}
/**
* Get `rank()` values in bulk. The values in `[begin .. end)` must be in
* Ascending order. possible implementation: for(auto* iter = begin; iter !=
* end; ++iter) *(ans++) = rank(*iter);
*/
void rank_many(const uint32_t *begin, const uint32_t *end,
uint64_t *ans) const noexcept {
return api::roaring_bitmap_rank_many(&roaring, begin, end, ans);
}
/**
* Returns the index of x in the set, index start from 0.
* If the set doesn't contain x , this function will return -1.
* The difference with rank function is that this function will return -1
* when x isn't in the set, but the rank function will return a
* non-negative number.
*/
int64_t getIndex(uint32_t x) const noexcept {
return api::roaring_bitmap_get_index(&roaring, x);
}
/**
* Write a bitmap to a char buffer. This is meant to be compatible with
* the Java and Go versions. Returns how many bytes were written which
* should be getSizeInBytes().
*
* Setting the portable flag to false enable a custom format that
* can save space compared to the portable format (e.g., for very
* sparse bitmaps).
*
* Boost users can serialize bitmaps in this manner:
*
* BOOST_SERIALIZATION_SPLIT_FREE(Roaring)
* namespace boost {
* namespace serialization {
*
* template <class Archive>
* void save(Archive& ar, const Roaring& bitmask,
* const unsigned int version) {
* std::size_t expected_size_in_bytes = bitmask.getSizeInBytes();
* std::vector<char> buffer(expected_size_in_bytes);
* std::size_t size_in_bytes = bitmask.write(buffer.data());
*
* ar& size_in_bytes;
* ar& boost::serialization::make_binary_object(buffer.data(),
* size_in_bytes);
* }
* template <class Archive>
* void load(Archive& ar, Roaring& bitmask,
* const unsigned int version) {
* std::size_t size_in_bytes = 0;
* ar& size_in_bytes;
* std::vector<char> buffer(size_in_bytes);
* ar& boost::serialization::make_binary_object(buffer.data(),
* size_in_bytes);
* bitmask = Roaring::readSafe(buffer.data(), size_in_bytes);
* }
* } // namespace serialization
* } // namespace boost
*/
size_t write(char *buf, bool portable = true) const noexcept {
if (portable) {
return api::roaring_bitmap_portable_serialize(&roaring, buf);
} else {
return api::roaring_bitmap_serialize(&roaring, buf);
}
}
/**
* Read a bitmap from a serialized version. This is meant to be compatible
* with the Java and Go versions.
*
* Setting the portable flag to false enable a custom format that
* can save space compared to the portable format (e.g., for very
* sparse bitmaps).
*
* This function is unsafe in the sense that if you provide bad data,
* many, many bytes could be read. See also readSafe.
*
* The function may throw std::runtime_error if a bitmap could not be read.
* Not that even if it does not throw, the bitmap could still be unusable if
* the loaded data does not match the portable Roaring specification: you
* should ensure that the data you load come from a serialized bitmap.
*/
static Roaring read(const char *buf, bool portable = true) {
roaring_bitmap_t *r =
portable ? api::roaring_bitmap_portable_deserialize(buf)
: api::roaring_bitmap_deserialize(buf);
if (r == NULL) {
ROARING_TERMINATE("failed alloc while reading");
}
return Roaring(r);
}
/**
* Read a bitmap from a serialized version, reading no more than maxbytes
* bytes. This is meant to be compatible with the Java and Go versions.
* The function itself is safe in the sense that it will not cause buffer
* overflows. However, for correct operations, it is assumed that the bitmap
* read was once serialized from a valid bitmap. If you provided an
* incorrect input (garbage), then the bitmap read may not be in a valid
* state and following operations may not lead to sensible results. It is
* your responsability to ensure that the input bytes follow the format
* specification if you want a usable bitmap:
* https://github.com/RoaringBitmap/RoaringFormatSpec
* In particular, the serialized array containers need to be in sorted
* order, and the run containers should be in sorted non-overlapping order.
* This is is guaranteed to happen when serializing an existing bitmap, but
* not for random inputs. Note that this function assumes that your bitmap
* was serialized in *portable* mode (which is the default with the 'write'
* method).
*
* The function may throw std::runtime_error if a bitmap could not be read.
* Not that even if it does not throw, the bitmap could still be unusable if
* the loaded data does not match the portable Roaring specification: you
* should ensure that the data you load come from a serialized bitmap.
*/
static Roaring readSafe(const char *buf, size_t maxbytes) {
roaring_bitmap_t *r =
api::roaring_bitmap_portable_deserialize_safe(buf, maxbytes);
if (r == NULL) {
ROARING_TERMINATE("failed alloc while reading");
}
return Roaring(r);
}
/**
* How many bytes are required to serialize this bitmap (meant to be
* compatible with Java and Go versions)
*
* Setting the portable flag to false enable a custom format that
* can save space compared to the portable format (e.g., for very
* sparse bitmaps).
*/
size_t getSizeInBytes(bool portable = true) const noexcept {
if (portable) {
return api::roaring_bitmap_portable_size_in_bytes(&roaring);
} else {
return api::roaring_bitmap_size_in_bytes(&roaring);
}
}
/**
* For advanced users.
* This function may throw std::runtime_error.
*/
static const Roaring frozenView(const char *buf, size_t length) {
const roaring_bitmap_t *s =
api::roaring_bitmap_frozen_view(buf, length);
if (s == NULL) {
ROARING_TERMINATE("failed to read frozen bitmap");
}
Roaring r;
r.roaring = *s;
return r;
}
/**
* For advanced users; see roaring_bitmap_portable_deserialize_frozen.
* This function may throw std::runtime_error.
*/
static const Roaring portableDeserializeFrozen(const char *buf) {
const roaring_bitmap_t *s =
api::roaring_bitmap_portable_deserialize_frozen(buf);
if (s == NULL) {
ROARING_TERMINATE("failed to read portable frozen bitmap");
}
Roaring r;
r.roaring = *s;
return r;
}
/**
* For advanced users.
*/
void writeFrozen(char *buf) const noexcept {
roaring_bitmap_frozen_serialize(&roaring, buf);
}
/**
* For advanced users.
*/
size_t getFrozenSizeInBytes() const noexcept {
return roaring_bitmap_frozen_size_in_bytes(&roaring);
}
/**
* Computes the intersection between two bitmaps and returns new bitmap.
* The current bitmap and the provided bitmap are unchanged.
*
* Performance hint: if you are computing the intersection between several
* bitmaps, two-by-two, it is best to start with the smallest bitmap.
* Consider also using the operator &= to avoid needlessly creating
* many temporary bitmaps.
* This function may throw std::runtime_error.
*/
Roaring operator&(const Roaring &o) const {
roaring_bitmap_t *r = api::roaring_bitmap_and(&roaring, &o.roaring);
if (r == NULL) {
ROARING_TERMINATE("failed materalization in and");
}
return Roaring(r);
}
/**
* Computes the difference between two bitmaps and returns new bitmap.
* The current bitmap and the provided bitmap are unchanged.
* This function may throw std::runtime_error.
*/
Roaring operator-(const Roaring &o) const {
roaring_bitmap_t *r = api::roaring_bitmap_andnot(&roaring, &o.roaring);
if (r == NULL) {
ROARING_TERMINATE("failed materalization in andnot");
}
return Roaring(r);
}
/**
* Computes the union between two bitmaps and returns new bitmap.
* The current bitmap and the provided bitmap are unchanged.
* This function may throw std::runtime_error.
*/
Roaring operator|(const Roaring &o) const {
roaring_bitmap_t *r = api::roaring_bitmap_or(&roaring, &o.roaring);
if (r == NULL) {
ROARING_TERMINATE("failed materalization in or");
}
return Roaring(r);
}
/**
* Computes the symmetric union between two bitmaps and returns new bitmap.
* The current bitmap and the provided bitmap are unchanged.
* This function may throw std::runtime_error.
*/
Roaring operator^(const Roaring &o) const {
roaring_bitmap_t *r = api::roaring_bitmap_xor(&roaring, &o.roaring);
if (r == NULL) {
ROARING_TERMINATE("failed materalization in xor");
}
return Roaring(r);
}
/**
* Whether or not we apply copy and write.
*/
void setCopyOnWrite(bool val) noexcept {
api::roaring_bitmap_set_copy_on_write(&roaring, val);
}
/**
* Print the content of the bitmap
*/
void printf() const noexcept { api::roaring_bitmap_printf(&roaring); }
/**
* Print the content of the bitmap into a string
*/
std::string toString() const noexcept {
struct iter_data {
std::string str{}; // The empty constructor silences warnings from
// pedantic static analyzers.
char first_char = '{';
} outer_iter_data;
if (!isEmpty()) {
iterate(
[](uint32_t value, void *inner_iter_data) -> bool {
((iter_data *)inner_iter_data)->str +=
((iter_data *)inner_iter_data)->first_char;
((iter_data *)inner_iter_data)->str +=
std::to_string(value);
((iter_data *)inner_iter_data)->first_char = ',';
return true;
},
(void *)&outer_iter_data);
} else
outer_iter_data.str = '{';
outer_iter_data.str += '}';
return outer_iter_data.str;
}
/**
* Whether or not copy and write is active.
*/
bool getCopyOnWrite() const noexcept {
return api::roaring_bitmap_get_copy_on_write(&roaring);
}
/**
* Computes the logical or (union) between "n" bitmaps (referenced by a
* pointer).
* This function may throw std::runtime_error.
*/
static Roaring fastunion(size_t n, const Roaring **inputs) {
const roaring_bitmap_t **x = (const roaring_bitmap_t **)roaring_malloc(
n * sizeof(roaring_bitmap_t *));
if (x == NULL) {
ROARING_TERMINATE("failed memory alloc in fastunion");
}
for (size_t k = 0; k < n; ++k) x[k] = &inputs[k]->roaring;
roaring_bitmap_t *c_ans = api::roaring_bitmap_or_many(n, x);
if (c_ans == NULL) {
roaring_free(x);
ROARING_TERMINATE("failed memory alloc in fastunion");
}
Roaring ans(c_ans);
roaring_free(x);
return ans;
}
/**
* Destructor. By contract, calling roaring_bitmap_clear() is enough to
* release all auxiliary memory used by the structure.
*/
~Roaring() {
if (!(roaring.high_low_container.flags & ROARING_FLAG_FROZEN)) {
api::roaring_bitmap_clear(&roaring);
} else {
// The roaring member variable copies the `roaring_bitmap_t` and
// nested `roaring_array_t` structures by value and is freed in the
// constructor, however the underlying memory arena used for the
// container data is not freed with it. Here we derive the arena
// pointer from the second arena allocation in
// `roaring_bitmap_frozen_view` and free it as well.
roaring_bitmap_free(
(roaring_bitmap_t *)((char *)
roaring.high_low_container.containers -
sizeof(roaring_bitmap_t)));
}
}
friend class RoaringSetBitBiDirectionalIterator;
typedef RoaringSetBitBiDirectionalIterator const_iterator;
typedef RoaringSetBitBiDirectionalIterator const_bidirectional_iterator;
/**
* Returns an iterator that can be used to access the position of the set
* bits. The running time complexity of a full scan is proportional to the
* number of set bits: be aware that if you have long strings of 1s, this
* can be very inefficient.
*
* It can be much faster to use the toArray method if you want to retrieve
* the set bits.
*/
const_iterator begin() const;
/**
* A bogus iterator that can be used together with begin()
* for constructions such as for (auto i = b.begin(); * i!=b.end(); ++i) {}
*/
const_iterator &end() const;
roaring_bitmap_t roaring;
};
/**
* Used to go through the set bits. Not optimally fast, but convenient.
*/
class RoaringSetBitBiDirectionalIterator final {
public:
typedef std::bidirectional_iterator_tag iterator_category;
typedef uint32_t *pointer;
typedef uint32_t &reference_type;
typedef uint32_t value_type;
typedef int32_t difference_type;
typedef RoaringSetBitBiDirectionalIterator type_of_iterator;
explicit RoaringSetBitBiDirectionalIterator(const Roaring &parent,
bool exhausted = false) {
if (exhausted) {
i.parent = &parent.roaring;
i.container_index = INT32_MAX;
i.has_value = false;
i.current_value = UINT32_MAX;
} else {
api::roaring_iterator_init(&parent.roaring, &i);
}
}
/**
* Provides the location of the set bit.
*/
value_type operator*() const { return i.current_value; }
bool operator<(const type_of_iterator &o) const {
if (!i.has_value) return false;
if (!o.i.has_value) return true;
return i.current_value < *o;
}
bool operator<=(const type_of_iterator &o) const {
if (!o.i.has_value) return true;
if (!i.has_value) return false;
return i.current_value <= *o;
}
bool operator>(const type_of_iterator &o) const {
if (!o.i.has_value) return false;
if (!i.has_value) return true;
return i.current_value > *o;
}
bool operator>=(const type_of_iterator &o) const {
if (!i.has_value) return true;
if (!o.i.has_value) return false;
return i.current_value >= *o;
}
type_of_iterator &operator++() { // ++i, must returned inc. value
api::roaring_uint32_iterator_advance(&i);
return *this;
}
type_of_iterator operator++(int) { // i++, must return orig. value
RoaringSetBitBiDirectionalIterator orig(*this);
api::roaring_uint32_iterator_advance(&i);
return orig;
}
/**
* Move the iterator to the first value >= val.
* Return true if there is such a value.
*/
bool move_equalorlarger(value_type val) {
return api::roaring_uint32_iterator_move_equalorlarger(&i, val);
}
/** DEPRECATED, use `move_equalorlarger`.*/
CROARING_DEPRECATED void equalorlarger(uint32_t val) {
api::roaring_uint32_iterator_move_equalorlarger(&i, val);
}
type_of_iterator &operator--() { // prefix --
api::roaring_uint32_iterator_previous(&i);
return *this;
}
type_of_iterator operator--(int) { // postfix --
RoaringSetBitBiDirectionalIterator orig(*this);
api::roaring_uint32_iterator_previous(&i);
return orig;
}
bool operator==(const RoaringSetBitBiDirectionalIterator &o) const {
return i.current_value == *o && i.has_value == o.i.has_value;
}
bool operator!=(const RoaringSetBitBiDirectionalIterator &o) const {
return i.current_value != *o || i.has_value != o.i.has_value;
}
api::roaring_uint32_iterator_t
i{}; // The empty constructor silences warnings from pedantic static
// analyzers.
};
inline RoaringSetBitBiDirectionalIterator Roaring::begin() const {
return RoaringSetBitBiDirectionalIterator(*this);
}
inline RoaringSetBitBiDirectionalIterator &Roaring::end() const {
static RoaringSetBitBiDirectionalIterator e(*this, true);
return e;
}
} // namespace roaring
#endif /* INCLUDE_ROARING_HH_ */
/* end file cpp/roaring/roaring.hh */
/* begin file cpp/roaring/roaring64map.hh */
/**
* A C++ header for 64-bit Roaring Bitmaps,
* implemented by way of a map of many
* 32-bit Roaring Bitmaps.
*
* Reference (format specification) :
* https://github.com/RoaringBitmap/RoaringFormatSpec#extention-for-64-bit-implementations
*/
#ifndef INCLUDE_ROARING_64_MAP_HH_
#define INCLUDE_ROARING_64_MAP_HH_
#include <algorithm>
#include <cinttypes> // PRIu64 macro
#include <climits> // for UINT64_MAX
#include <cstdarg> // for va_list handling in bitmapOf()
#include <cstdio> // for std::printf() in the printf() method
#include <cstring> // for std::memcpy()
#include <functional>
#include <initializer_list>
#include <limits>
#include <map>
#include <new>
#include <numeric>
#include <queue>
#include <stdexcept>
#include <string>
#include <utility>
namespace roaring {
using roaring::Roaring;
class Roaring64MapSetBitBiDirectionalIterator;
// For backwards compatibility; there used to be two kinds of iterators
// (forward and bidirectional) and now there's only one.
typedef Roaring64MapSetBitBiDirectionalIterator
Roaring64MapSetBitForwardIterator;
class Roaring64Map {
typedef api::roaring_bitmap_t roaring_bitmap_t;
public:
/**
* Create an empty bitmap
*/
Roaring64Map() = default;
/**
* Construct a bitmap from a list of 32-bit integer values.
*/
Roaring64Map(size_t n, const uint32_t *data) { addMany(n, data); }
/**
* Construct a bitmap from a list of 64-bit integer values.
*/
Roaring64Map(size_t n, const uint64_t *data) { addMany(n, data); }
/**
* Construct a bitmap from an initializer list.
*/
Roaring64Map(std::initializer_list<uint64_t> l) {
addMany(l.size(), l.begin());
}
/**
* Construct a 64-bit map from a 32-bit one
*/
explicit Roaring64Map(const Roaring &r) { emplaceOrInsert(0, r); }
/**
* Construct a 64-bit map from a 32-bit rvalue
*/
explicit Roaring64Map(Roaring &&r) { emplaceOrInsert(0, std::move(r)); }
/**
* Construct a roaring object from the C struct.
*
* Passing a NULL point is unsafe.
*/
explicit Roaring64Map(roaring_bitmap_t *s) {
emplaceOrInsert(0, Roaring(s));
}
Roaring64Map(const Roaring64Map &r) = default;
Roaring64Map(Roaring64Map &&r) noexcept = default;
/**
* Copy assignment operator.
*/
Roaring64Map &operator=(const Roaring64Map &r) = default;
/**
* Move assignment operator.
*/
Roaring64Map &operator=(Roaring64Map &&r) noexcept = default;
/**
* Assignment from an initializer list.
*/
Roaring64Map &operator=(std::initializer_list<uint64_t> l) {
// Delegate to move assignment operator
*this = Roaring64Map(l);
return *this;
}
/**
* Construct a bitmap from a list of uint64_t values.
*/
static Roaring64Map bitmapOf(size_t n...) {
Roaring64Map ans;
va_list vl;
va_start(vl, n);
for (size_t i = 0; i < n; i++) {
ans.add(va_arg(vl, uint64_t));
}
va_end(vl);
return ans;
}
/**
* Construct a bitmap from a list of uint64_t values.
* E.g., bitmapOfList({1,2,3}).
*/
static Roaring64Map bitmapOfList(std::initializer_list<uint64_t> l) {
Roaring64Map ans;
ans.addMany(l.size(), l.begin());
return ans;
}
/**
* Adds value x.
*/
void add(uint32_t x) { lookupOrCreateInner(0).add(x); }
/**
* Adds value x.
*/
void add(uint64_t x) { lookupOrCreateInner(highBytes(x)).add(lowBytes(x)); }
/**
* Adds value x.
* Returns true if a new value was added, false if the value was already
* present.
*/
bool addChecked(uint32_t x) { return lookupOrCreateInner(0).addChecked(x); }
/**
* Adds value x.
* Returns true if a new value was added, false if the value was already
* present.
*/
bool addChecked(uint64_t x) {
return lookupOrCreateInner(highBytes(x)).addChecked(lowBytes(x));
}
/**
* Adds all values in the half-open interval [min, max).
*/
void addRange(uint64_t min, uint64_t max) {
if (min >= max) {
return;
}
addRangeClosed(min, max - 1);
}
/**
* Adds all values in the closed interval [min, max].
*/
void addRangeClosed(uint32_t min, uint32_t max) {
lookupOrCreateInner(0).addRangeClosed(min, max);
}
/**
* Adds all values in the closed interval [min, max]
*/
void addRangeClosed(uint64_t min, uint64_t max) {
if (min > max) {
return;
}
uint32_t start_high = highBytes(min);
uint32_t start_low = lowBytes(min);
uint32_t end_high = highBytes(max);
uint32_t end_low = lowBytes(max);
// We put std::numeric_limits<>::max in parentheses to avoid a
// clash with the Windows.h header under Windows.
const uint32_t uint32_max = (std::numeric_limits<uint32_t>::max)();
// Fill in any nonexistent slots with empty Roarings. This simplifies
// the logic below, allowing it to simply iterate over the map between
// 'start_high' and 'end_high' in a linear fashion.
auto current_iter = ensureRangePopulated(start_high, end_high);
// If start and end land on the same inner bitmap, then we can do the
// whole operation in one call.
if (start_high == end_high) {
auto &bitmap = current_iter->second;
bitmap.addRangeClosed(start_low, end_low);
return;
}
// Because start and end don't land on the same inner bitmap,
// we need to do this in multiple steps:
// 1. Partially fill the first bitmap with values from the closed
// interval [start_low, uint32_max]
// 2. Fill intermediate bitmaps completely: [0, uint32_max]
// 3. Partially fill the last bitmap with values from the closed
// interval [0, end_low]
auto num_intermediate_bitmaps = end_high - start_high - 1;
// Step 1: Partially fill the first bitmap.
{
auto &bitmap = current_iter->second;
bitmap.addRangeClosed(start_low, uint32_max);
++current_iter;
}
// Step 2. Fill intermediate bitmaps completely.
if (num_intermediate_bitmaps != 0) {
auto &first_intermediate = current_iter->second;
first_intermediate.addRangeClosed(0, uint32_max);
++current_iter;
// Now make (num_intermediate_bitmaps - 1) copies of this.
for (uint32_t i = 1; i != num_intermediate_bitmaps; ++i) {
auto &next_intermediate = current_iter->second;
next_intermediate = first_intermediate;
++current_iter;
}
}
// Step 3: Partially fill the last bitmap.
auto &bitmap = current_iter->second;
bitmap.addRangeClosed(0, end_low);
}
/**
* Adds 'n_args' values from the contiguous memory range starting at 'vals'.
*/
void addMany(size_t n_args, const uint32_t *vals) {
lookupOrCreateInner(0).addMany(n_args, vals);
}
/**
* Adds 'n_args' values from the contiguous memory range starting at 'vals'.
*/
void addMany(size_t n_args, const uint64_t *vals) {
// Potentially reduce outer map lookups by optimistically
// assuming that adjacent values will belong to the same inner bitmap.
Roaring *last_inner_bitmap = nullptr;
uint32_t last_value_high = 0;
BulkContext last_bulk_context;
for (size_t lcv = 0; lcv < n_args; lcv++) {
auto value = vals[lcv];
auto value_high = highBytes(value);
auto value_low = lowBytes(value);
if (last_inner_bitmap == nullptr || value_high != last_value_high) {
last_inner_bitmap = &lookupOrCreateInner(value_high);
last_value_high = value_high;
last_bulk_context = BulkContext{};
}
last_inner_bitmap->addBulk(last_bulk_context, value_low);
}
}
/**
* Removes value x.
*/
void remove(uint32_t x) {
auto iter = roarings.begin();
// Since x is a uint32_t, highbytes(x) == 0. The inner bitmap we are
// looking for, if it exists, will be at the first slot of 'roarings'.
if (iter == roarings.end() || iter->first != 0) {
return;
}
auto &bitmap = iter->second;
bitmap.remove(x);
eraseIfEmpty(iter);
}
/**
* Removes value x.
*/
void remove(uint64_t x) {
auto iter = roarings.find(highBytes(x));
if (iter == roarings.end()) {
return;
}
auto &bitmap = iter->second;
bitmap.remove(lowBytes(x));
eraseIfEmpty(iter);
}
/**
* Removes value x
* Returns true if a new value was removed, false if the value was not
* present.
*/
bool removeChecked(uint32_t x) {
auto iter = roarings.begin();
// Since x is a uint32_t, highbytes(x) == 0. The inner bitmap we are
// looking for, if it exists, will be at the first slot of 'roarings'.
if (iter == roarings.end() || iter->first != 0) {
return false;
}
auto &bitmap = iter->second;
if (!bitmap.removeChecked(x)) {
return false;
}
eraseIfEmpty(iter);
return true;
}
/**
* Remove value x
* Returns true if a new value was removed, false if the value was not
* present.
*/
bool removeChecked(uint64_t x) {
auto iter = roarings.find(highBytes(x));
if (iter == roarings.end()) {
return false;
}
auto &bitmap = iter->second;
if (!bitmap.removeChecked(lowBytes(x))) {
return false;
}
eraseIfEmpty(iter);
return true;
}
/**
* Removes all values in the half-open interval [min, max).
*/
void removeRange(uint64_t min, uint64_t max) {
if (min >= max) {
return;
}
return removeRangeClosed(min, max - 1);
}
/**
* Removes all values in the closed interval [min, max].
*/
void removeRangeClosed(uint32_t min, uint32_t max) {
auto iter = roarings.begin();
// Since min and max are uint32_t, highbytes(min or max) == 0. The inner
// bitmap we are looking for, if it exists, will be at the first slot of
// 'roarings'.
if (iter == roarings.end() || iter->first != 0) {
return;
}
auto &bitmap = iter->second;
bitmap.removeRangeClosed(min, max);
eraseIfEmpty(iter);
}
/**
* Removes all values in the closed interval [min, max].
*/
void removeRangeClosed(uint64_t min, uint64_t max) {
if (min > max) {
return;
}
uint32_t start_high = highBytes(min);
uint32_t start_low = lowBytes(min);
uint32_t end_high = highBytes(max);
uint32_t end_low = lowBytes(max);
// We put std::numeric_limits<>::max in parentheses to avoid a
// clash with the Windows.h header under Windows.
const uint32_t uint32_max = (std::numeric_limits<uint32_t>::max)();
// If the outer map is empty, end_high is less than the first key,
// or start_high is greater than the last key, then exit now because
// there is no work to do.
if (roarings.empty() || end_high < roarings.cbegin()->first ||
start_high > (roarings.crbegin())->first) {
return;
}
// If we get here, start_iter points to the first entry in the outer map
// with key >= start_high. Such an entry is known to exist (i.e. the
// iterator will not be equal to end()) because start_high <= the last
// key in the map (thanks to the above if statement).
auto start_iter = roarings.lower_bound(start_high);
// end_iter points to the first entry in the outer map with
// key >= end_high, if such a key exists. Otherwise, it equals end().
auto end_iter = roarings.lower_bound(end_high);
// Note that the 'lower_bound' method will find the start and end slots,
// if they exist; otherwise it will find the next-higher slots.
// In the case where 'start' landed on an existing slot, we need to do a
// partial erase of that slot, and likewise for 'end'. But all the slots
// in between can be fully erased. More precisely:
//
// 1. If the start point falls on an existing entry, there are two
// subcases:
// a. if the end point falls on that same entry, remove the closed
// interval [start_low, end_low] from that entry and we are done.
// b. Otherwise, remove the closed interval [start_low, uint32_max]
// from that entry, advance start_iter, and fall through to
// step 2.
// 2. Completely erase all slots in the half-open interval
// [start_iter, end_iter)
// 3. If the end point falls on an existing entry, remove the closed
// interval [0, end_high] from it.
// Step 1. If the start point falls on an existing entry...
if (start_iter->first == start_high) {
auto &start_inner = start_iter->second;
// 1a. if the end point falls on that same entry...
if (start_iter == end_iter) {
start_inner.removeRangeClosed(start_low, end_low);
eraseIfEmpty(start_iter);
return;
}
// 1b. Otherwise, remove the closed range [start_low, uint32_max]...
start_inner.removeRangeClosed(start_low, uint32_max);
// Advance start_iter, but keep the old value so we can check the
// bitmap we just modified for emptiness and erase if it necessary.
auto temp = start_iter++;
eraseIfEmpty(temp);
}
// 2. Completely erase all slots in the half-open interval...
roarings.erase(start_iter, end_iter);
// 3. If the end point falls on an existing entry...
if (end_iter != roarings.end() && end_iter->first == end_high) {
auto &end_inner = end_iter->second;
end_inner.removeRangeClosed(0, end_low);
eraseIfEmpty(end_iter);
}
}
/**
* Clears the bitmap.
*/
void clear() { roarings.clear(); }
/**
* Return the largest value (if not empty)
*/
uint64_t maximum() const {
for (auto roaring_iter = roarings.crbegin();
roaring_iter != roarings.crend(); ++roaring_iter) {
if (!roaring_iter->second.isEmpty()) {
return uniteBytes(roaring_iter->first,
roaring_iter->second.maximum());
}
}
// we put std::numeric_limits<>::max/min in parentheses
// to avoid a clash with the Windows.h header under Windows
return (std::numeric_limits<uint64_t>::min)();
}
/**
* Return the smallest value (if not empty)
*/
uint64_t minimum() const {
for (auto roaring_iter = roarings.cbegin();
roaring_iter != roarings.cend(); ++roaring_iter) {
if (!roaring_iter->second.isEmpty()) {
return uniteBytes(roaring_iter->first,
roaring_iter->second.minimum());
}
}
// we put std::numeric_limits<>::max/min in parentheses
// to avoid a clash with the Windows.h header under Windows
return (std::numeric_limits<uint64_t>::max)();
}
/**
* Check if value x is present
*/
bool contains(uint32_t x) const {
auto iter = roarings.find(0);
if (iter == roarings.end()) {
return false;
}
return iter->second.contains(x);
}
bool contains(uint64_t x) const {
auto iter = roarings.find(highBytes(x));
if (iter == roarings.end()) {
return false;
}
return iter->second.contains(lowBytes(x));
}
// TODO: implement `containsRange`
/**
* Compute the intersection of the current bitmap and the provided bitmap,
* writing the result in the current bitmap. The provided bitmap is not
* modified.
*
* Performance hint: if you are computing the intersection between several
* bitmaps, two-by-two, it is best to start with the smallest bitmap.
*/
Roaring64Map &operator&=(const Roaring64Map &other) {
if (this == &other) {
// ANDing *this with itself is a no-op.
return *this;
}
// Logic table summarizing what to do when a given outer key is
// present vs. absent from self and other.
//
// self other (self & other) work to do
// --------------------------------------------
// absent absent empty None
// absent present empty None
// present absent empty Erase self
// present present empty or not Intersect self with other, but
// erase self if result is empty.
//
// Because there is only work to do when a key is present in 'self', the
// main for loop iterates over entries in 'self'.
decltype(roarings.begin()) self_next;
for (auto self_iter = roarings.begin(); self_iter != roarings.end();
self_iter = self_next) {
// Do the 'next' operation now, so we don't have to worry about
// invalidation of self_iter down below with the 'erase' operation.
self_next = std::next(self_iter);
auto self_key = self_iter->first;
auto &self_bitmap = self_iter->second;
auto other_iter = other.roarings.find(self_key);
if (other_iter == other.roarings.end()) {
// 'other' doesn't have self_key. In the logic table above,
// this reflects the case (self.present & other.absent).
// So, erase self.
roarings.erase(self_iter);
continue;
}
// Both sides have self_key. In the logic table above, this reflects
// the case (self.present & other.present). So, intersect self with
// other.
const auto &other_bitmap = other_iter->second;
self_bitmap &= other_bitmap;
if (self_bitmap.isEmpty()) {
// ...but if intersection is empty, remove it altogether.
roarings.erase(self_iter);
}
}
return *this;
}
/**
* Compute the difference between the current bitmap and the provided
* bitmap, writing the result in the current bitmap. The provided bitmap
* is not modified.
*/
Roaring64Map &operator-=(const Roaring64Map &other) {
if (this == &other) {
// Subtracting *this from itself results in the empty map.
roarings.clear();
return *this;
}
// Logic table summarizing what to do when a given outer key is
// present vs. absent from self and other.
//
// self other (self - other) work to do
// --------------------------------------------
// absent absent empty None
// absent present empty None
// present absent unchanged None
// present present empty or not Subtract other from self, but
// erase self if result is empty
//
// Because there is only work to do when a key is present in both 'self'
// and 'other', the main while loop ping-pongs back and forth until it
// finds the next key that is the same on both sides.
auto self_iter = roarings.begin();
auto other_iter = other.roarings.cbegin();
while (self_iter != roarings.end() &&
other_iter != other.roarings.cend()) {
auto self_key = self_iter->first;
auto other_key = other_iter->first;
if (self_key < other_key) {
// Because self_key is < other_key, advance self_iter to the
// first point where self_key >= other_key (or end).
self_iter = roarings.lower_bound(other_key);
continue;
}
if (self_key > other_key) {
// Because self_key is > other_key, advance other_iter to the
// first point where other_key >= self_key (or end).
other_iter = other.roarings.lower_bound(self_key);
continue;
}
// Both sides have self_key. In the logic table above, this reflects
// the case (self.present & other.present). So subtract other from
// self.
auto &self_bitmap = self_iter->second;
const auto &other_bitmap = other_iter->second;
self_bitmap -= other_bitmap;
if (self_bitmap.isEmpty()) {
// ...but if subtraction is empty, remove it altogether.
self_iter = roarings.erase(self_iter);
} else {
++self_iter;
}
++other_iter;
}
return *this;
}
/**
* Compute the union of the current bitmap and the provided bitmap,
* writing the result in the current bitmap. The provided bitmap is not
* modified.
*
* See also the fastunion function to aggregate many bitmaps more quickly.
*/
Roaring64Map &operator|=(const Roaring64Map &other) {
if (this == &other) {
// ORing *this with itself is a no-op.
return *this;
}
// Logic table summarizing what to do when a given outer key is
// present vs. absent from self and other.
//
// self other (self | other) work to do
// --------------------------------------------
// absent absent empty None
// absent present not empty Copy other to self and set flags
// present absent unchanged None
// present present not empty self |= other
//
// Because there is only work to do when a key is present in 'other',
// the main for loop iterates over entries in 'other'.
for (const auto &other_entry : other.roarings) {
const auto &other_bitmap = other_entry.second;
// Try to insert other_bitmap into self at other_key. We take
// advantage of the fact that std::map::insert will not overwrite an
// existing entry.
auto insert_result = roarings.insert(other_entry);
auto self_iter = insert_result.first;
auto insert_happened = insert_result.second;
auto &self_bitmap = self_iter->second;
if (insert_happened) {
// Key was not present in self, so insert was performed above.
// In the logic table above, this reflects the case
// (self.absent | other.present). Because the copy has already
// happened, thanks to the 'insert' operation above, we just
// need to set the copyOnWrite flag.
self_bitmap.setCopyOnWrite(copyOnWrite);
continue;
}
// Both sides have self_key, and the insert was not performed. In
// the logic table above, this reflects the case
// (self.present & other.present). So OR other into self.
self_bitmap |= other_bitmap;
}
return *this;
}
/**
* Compute the XOR of the current bitmap and the provided bitmap, writing
* the result in the current bitmap. The provided bitmap is not modified.
*/
Roaring64Map &operator^=(const Roaring64Map &other) {
if (this == &other) {
// XORing *this with itself results in the empty map.
roarings.clear();
return *this;
}
// Logic table summarizing what to do when a given outer key is
// present vs. absent from self and other.
//
// self other (self ^ other) work to do
// --------------------------------------------
// absent absent empty None
// absent present non-empty Copy other to self and set flags
// present absent unchanged None
// present present empty or not XOR other into self, but erase self
// if result is empty.
//
// Because there is only work to do when a key is present in 'other',
// the main for loop iterates over entries in 'other'.
for (const auto &other_entry : other.roarings) {
const auto &other_bitmap = other_entry.second;
// Try to insert other_bitmap into self at other_key. We take
// advantage of the fact that std::map::insert will not overwrite an
// existing entry.
auto insert_result = roarings.insert(other_entry);
auto self_iter = insert_result.first;
auto insert_happened = insert_result.second;
auto &self_bitmap = self_iter->second;
if (insert_happened) {
// Key was not present in self, so insert was performed above.
// In the logic table above, this reflects the case
// (self.absent ^ other.present). Because the copy has already
// happened, thanks to the 'insert' operation above, we just
// need to set the copyOnWrite flag.
self_bitmap.setCopyOnWrite(copyOnWrite);
continue;
}
// Both sides have self_key, and the insert was not performed. In
// the logic table above, this reflects the case
// (self.present ^ other.present). So XOR other into self.
self_bitmap ^= other_bitmap;
if (self_bitmap.isEmpty()) {
// ...but if intersection is empty, remove it altogether.
roarings.erase(self_iter);
}
}
return *this;
}
/**
* Exchange the content of this bitmap with another.
*/
void swap(Roaring64Map &r) { roarings.swap(r.roarings); }
/**
* Get the cardinality of the bitmap (number of elements).
* Throws std::length_error in the special case where the bitmap is full
* (cardinality() == 2^64). Check isFull() before calling to avoid
* exception.
*/
uint64_t cardinality() const {
if (isFull()) {
#if ROARING_EXCEPTIONS
throw std::length_error(
"bitmap is full, cardinality is 2^64, "
"unable to represent in a 64-bit integer");
#else
ROARING_TERMINATE(
"bitmap is full, cardinality is 2^64, "
"unable to represent in a 64-bit integer");
#endif
}
return std::accumulate(
roarings.cbegin(), roarings.cend(), (uint64_t)0,
[](uint64_t previous,
const std::pair<const uint32_t, Roaring> &map_entry) {
return previous + map_entry.second.cardinality();
});
}
/**
* Returns true if the bitmap is empty (cardinality is zero).
*/
bool isEmpty() const {
return std::all_of(
roarings.cbegin(), roarings.cend(),
[](const std::pair<const uint32_t, Roaring> &map_entry) {
return map_entry.second.isEmpty();
});
}
/**
* Returns true if the bitmap is full (cardinality is max uint64_t + 1).
*/
bool isFull() const {
// This function is somewhat absurd. A full 64-bit bitmap would surely
// exceed our memory limits.
#if SIZE_MAX >= UINT64_MAX
// only bother to check if map is fully saturated
//
// we put std::numeric_limits<>::max/min in parentheses
// to avoid a clash with the Windows.h header under Windows
return roarings.size() ==
((uint64_t)(std::numeric_limits<uint32_t>::max)()) + 1
? std::all_of(roarings.cbegin(), roarings.cend(),
[](const std::pair<const uint32_t, Roaring>
&roaring_map_entry) {
return roaring_map_entry.second.isFull();
})
: false;
#else
// if SIZE_MAX < UINT64_MAX, then we cannot represent a full bitmap
// in a 64-bit integer, so we return false.
return false;
#endif
}
/**
* Returns true if the bitmap is subset of the other.
*/
bool isSubset(const Roaring64Map &r) const {
for (const auto &map_entry : roarings) {
if (map_entry.second.isEmpty()) {
continue;
}
auto roaring_iter = r.roarings.find(map_entry.first);
if (roaring_iter == r.roarings.cend())
return false;
else if (!map_entry.second.isSubset(roaring_iter->second))
return false;
}
return true;
}
/**
* Returns true if the bitmap is strict subset of the other.
* Throws std::length_error in the special case where the bitmap is full
* (cardinality() == 2^64). Check isFull() before calling to avoid
* exception.
*/
bool isStrictSubset(const Roaring64Map &r) const {
return isSubset(r) && cardinality() != r.cardinality();
}
/**
* Convert the bitmap to an array. Write the output to "ans",
* caller is responsible to ensure that there is enough memory
* allocated
* (e.g., ans = new uint32[mybitmap.cardinality()];)
*/
void toUint64Array(uint64_t *ans) const {
// Annoyingly, VS 2017 marks std::accumulate() as [[nodiscard]]
(void)std::accumulate(
roarings.cbegin(), roarings.cend(), ans,
[](uint64_t *previous,
const std::pair<const uint32_t, Roaring> &map_entry) {
for (uint32_t low_bits : map_entry.second)
*previous++ = uniteBytes(map_entry.first, low_bits);
return previous;
});
}
/**
* Return true if the two bitmaps contain the same elements.
*/
bool operator==(const Roaring64Map &r) const {
// we cannot use operator == on the map because either side may contain
// empty Roaring Bitmaps
auto lhs_iter = roarings.cbegin();
auto lhs_cend = roarings.cend();
auto rhs_iter = r.roarings.cbegin();
auto rhs_cend = r.roarings.cend();
while (lhs_iter != lhs_cend && rhs_iter != rhs_cend) {
auto lhs_key = lhs_iter->first, rhs_key = rhs_iter->first;
const auto &lhs_map = lhs_iter->second, &rhs_map = rhs_iter->second;
if (lhs_map.isEmpty()) {
++lhs_iter;
continue;
}
if (rhs_map.isEmpty()) {
++rhs_iter;
continue;
}
if (!(lhs_key == rhs_key)) {
return false;
}
if (!(lhs_map == rhs_map)) {
return false;
}
++lhs_iter;
++rhs_iter;
}
while (lhs_iter != lhs_cend) {
if (!lhs_iter->second.isEmpty()) {
return false;
}
++lhs_iter;
}
while (rhs_iter != rhs_cend) {
if (!rhs_iter->second.isEmpty()) {
return false;
}
++rhs_iter;
}
return true;
}
/**
* Computes the negation of the roaring bitmap within the half-open interval
* [min, max). Areas outside the interval are unchanged.
*/
void flip(uint64_t min, uint64_t max) {
if (min >= max) {
return;
}
flipClosed(min, max - 1);
}
/**
* Computes the negation of the roaring bitmap within the closed interval
* [min, max]. Areas outside the interval are unchanged.
*/
void flipClosed(uint32_t min, uint32_t max) {
auto iter = roarings.begin();
// Since min and max are uint32_t, highbytes(min or max) == 0. The inner
// bitmap we are looking for, if it exists, will be at the first slot of
// 'roarings'. If it does not exist, we have to create it.
if (iter == roarings.end() || iter->first != 0) {
iter = roarings.emplace_hint(iter, std::piecewise_construct,
std::forward_as_tuple(0),
std::forward_as_tuple());
auto &bitmap = iter->second;
bitmap.setCopyOnWrite(copyOnWrite);
}
auto &bitmap = iter->second;
bitmap.flipClosed(min, max);
eraseIfEmpty(iter);
}
/**
* Computes the negation of the roaring bitmap within the closed interval
* [min, max]. Areas outside the interval are unchanged.
*/
void flipClosed(uint64_t min, uint64_t max) {
if (min > max) {
return;
}
uint32_t start_high = highBytes(min);
uint32_t start_low = lowBytes(min);
uint32_t end_high = highBytes(max);
uint32_t end_low = lowBytes(max);
// We put std::numeric_limits<>::max in parentheses to avoid a
// clash with the Windows.h header under Windows.
const uint32_t uint32_max = (std::numeric_limits<uint32_t>::max)();
// Fill in any nonexistent slots with empty Roarings. This simplifies
// the logic below, allowing it to simply iterate over the map between
// 'start_high' and 'end_high' in a linear fashion.
auto current_iter = ensureRangePopulated(start_high, end_high);
// If start and end land on the same inner bitmap, then we can do the
// whole operation in one call.
if (start_high == end_high) {
auto &bitmap = current_iter->second;
bitmap.flipClosed(start_low, end_low);
eraseIfEmpty(current_iter);
return;
}
// Because start and end don't land on the same inner bitmap,
// we need to do this in multiple steps:
// 1. Partially flip the first bitmap in the closed interval
// [start_low, uint32_max]
// 2. Flip intermediate bitmaps completely: [0, uint32_max]
// 3. Partially flip the last bitmap in the closed interval
// [0, end_low]
auto num_intermediate_bitmaps = end_high - start_high - 1;
// 1. Partially flip the first bitmap.
{
auto &bitmap = current_iter->second;
bitmap.flipClosed(start_low, uint32_max);
auto temp = current_iter++;
eraseIfEmpty(temp);
}
// 2. Flip intermediate bitmaps completely.
for (uint32_t i = 0; i != num_intermediate_bitmaps; ++i) {
auto &bitmap = current_iter->second;
bitmap.flipClosed(0, uint32_max);
auto temp = current_iter++;
eraseIfEmpty(temp);
}
// 3. Partially flip the last bitmap.
auto &bitmap = current_iter->second;
bitmap.flipClosed(0, end_low);
eraseIfEmpty(current_iter);
}
/**
* Remove run-length encoding even when it is more space efficient
* return whether a change was applied
*/
bool removeRunCompression() {
return std::accumulate(
roarings.begin(), roarings.end(), true,
[](bool previous, std::pair<const uint32_t, Roaring> &map_entry) {
return map_entry.second.removeRunCompression() && previous;
});
}
/**
* Convert array and bitmap containers to run containers when it is more
* efficient; also convert from run containers when more space efficient.
* Returns true if the result has at least one run container.
* Additional savings might be possible by calling shrinkToFit().
*/
bool runOptimize() {
return std::accumulate(
roarings.begin(), roarings.end(), true,
[](bool previous, std::pair<const uint32_t, Roaring> &map_entry) {
return map_entry.second.runOptimize() && previous;
});
}
/**
* If needed, reallocate memory to shrink the memory usage.
* Returns the number of bytes saved.
*/
size_t shrinkToFit() {
size_t savedBytes = 0;
auto iter = roarings.begin();
while (iter != roarings.cend()) {
if (iter->second.isEmpty()) {
// empty Roarings are 84 bytes
savedBytes += 88;
roarings.erase(iter++);
} else {
savedBytes += iter->second.shrinkToFit();
iter++;
}
}
return savedBytes;
}
/**
* Iterate over the bitmap elements in order(start from the smallest one)
* and call iterator once for every element until the iterator function
* returns false. To iterate over all values, the iterator function should
* always return true.
*
* The roaring_iterator64 parameter is a pointer to a function that
* returns bool (true means that the iteration should continue while false
* means that it should stop), and takes (uint64_t element, void* ptr) as
* inputs.
*/
void iterate(api::roaring_iterator64 iterator, void *ptr) const {
for (const auto &map_entry : roarings) {
bool should_continue =
roaring_iterate64(&map_entry.second.roaring, iterator,
uint64_t(map_entry.first) << 32, ptr);
if (!should_continue) {
break;
}
}
}
/**
* Selects the value at index 'rank' in the bitmap, where the smallest value
* is at index 0. If 'rank' < cardinality(), returns true with *element set
* to the element of the specified rank. Otherwise, returns false and the
* contents of *element are unspecified.
*/
bool select(uint64_t rank, uint64_t *element) const {
for (const auto &map_entry : roarings) {
auto key = map_entry.first;
const auto &bitmap = map_entry.second;
uint64_t sub_cardinality = bitmap.cardinality();
if (rank < sub_cardinality) {
uint32_t low_bytes;
// Casting rank to uint32_t is safe because
// rank < sub_cardinality and sub_cardinality <= 2^32.
if (!bitmap.select((uint32_t)rank, &low_bytes)) {
ROARING_TERMINATE(
"Logic error: bitmap.select() "
"returned false despite rank < cardinality()");
}
*element = uniteBytes(key, low_bytes);
return true;
}
rank -= sub_cardinality;
}
return false;
}
/**
* Returns the number of integers that are smaller or equal to x.
*/
uint64_t rank(uint64_t x) const {
uint64_t result = 0;
// Find the first bitmap >= x's bucket. If that is the bucket x would be
// in, find it's rank in that bucket. Either way, we're left with a
// range of all buckets strictly smaller than x's bucket, add all their
// cardinalities together.
auto end = roarings.lower_bound(highBytes(x));
if (end != roarings.cend() && end->first == highBytes(x)) {
result += end->second.rank(lowBytes(x));
}
for (auto iter = roarings.cbegin(); iter != end; ++iter) {
result += iter->second.cardinality();
}
return result;
}
/**
* Returns the index of x in the set, index start from 0.
* If the set doesn't contain x , this function will return -1.
* The difference with rank function is that this function will return -1
* when x isn't in the set, but the rank function will return a
* non-negative number.
*/
int64_t getIndex(uint64_t x) const {
int64_t index = 0;
auto roaring_destination = roarings.find(highBytes(x));
if (roaring_destination != roarings.cend()) {
for (auto roaring_iter = roarings.cbegin();
roaring_iter != roaring_destination; ++roaring_iter) {
index += roaring_iter->second.cardinality();
}
auto low_idx = roaring_destination->second.getIndex(lowBytes(x));
if (low_idx < 0) return -1;
index += low_idx;
return index;
}
return -1;
}
/**
* Write a bitmap to a char buffer. This is meant to be compatible with
* the Java and Go versions. Returns how many bytes were written which
* should be getSizeInBytes().
*
* Setting the portable flag to false enables a custom format that
* can save space compared to the portable format (e.g., for very
* sparse bitmaps).
*/
size_t write(char *buf, bool portable = true) const {
const char *orig = buf;
// push map size
uint64_t map_size = roarings.size();
std::memcpy(buf, &map_size, sizeof(uint64_t));
buf += sizeof(uint64_t);
std::for_each(roarings.cbegin(), roarings.cend(),
[&buf, portable](
const std::pair<const uint32_t, Roaring> &map_entry) {
// push map key
std::memcpy(buf, &map_entry.first, sizeof(uint32_t));
// ^-- Note: `*((uint32_t*)buf) = map_entry.first;` is
// undefined
buf += sizeof(uint32_t);
// push map value Roaring
buf += map_entry.second.write(buf, portable);
});
return buf - orig;
}
/**
* Read a bitmap from a serialized version. This is meant to be compatible
* with the Java and Go versions.
*
* Setting the portable flag to false enable a custom format that
* can save space compared to the portable format (e.g., for very
* sparse bitmaps).
*
* This function is unsafe in the sense that if you provide bad data, many
* bytes could be read, possibly causing a buffer overflow. See also
* readSafe.
*/
static Roaring64Map read(const char *buf, bool portable = true) {
Roaring64Map result;
// get map size
uint64_t map_size;
std::memcpy(&map_size, buf, sizeof(uint64_t));
buf += sizeof(uint64_t);
for (uint64_t lcv = 0; lcv < map_size; lcv++) {
// get map key
uint32_t key;
std::memcpy(&key, buf, sizeof(uint32_t));
// ^-- Note: `uint32_t key = *((uint32_t*)buf);` is undefined
buf += sizeof(uint32_t);
// read map value Roaring
Roaring read_var = Roaring::read(buf, portable);
// forward buffer past the last Roaring Bitmap
buf += read_var.getSizeInBytes(portable);
result.emplaceOrInsert(key, std::move(read_var));
}
return result;
}
/**
* Read a bitmap from a serialized version, reading no more than maxbytes
* bytes. This is meant to be compatible with the Java and Go versions.
*
* Setting the portable flag to false enable a custom format that can save
* space compared to the portable format (e.g., for very sparse bitmaps).
*/
static Roaring64Map readSafe(const char *buf, size_t maxbytes) {
if (maxbytes < sizeof(uint64_t)) {
ROARING_TERMINATE("ran out of bytes");
}
Roaring64Map result;
uint64_t map_size;
std::memcpy(&map_size, buf, sizeof(uint64_t));
buf += sizeof(uint64_t);
maxbytes -= sizeof(uint64_t);
for (uint64_t lcv = 0; lcv < map_size; lcv++) {
if (maxbytes < sizeof(uint32_t)) {
ROARING_TERMINATE("ran out of bytes");
}
uint32_t key;
std::memcpy(&key, buf, sizeof(uint32_t));
// ^-- Note: `uint32_t key = *((uint32_t*)buf);` is undefined
buf += sizeof(uint32_t);
maxbytes -= sizeof(uint32_t);
// read map value Roaring
Roaring read_var = Roaring::readSafe(buf, maxbytes);
// forward buffer past the last Roaring Bitmap
size_t tz = read_var.getSizeInBytes(true);
buf += tz;
maxbytes -= tz;
result.emplaceOrInsert(key, std::move(read_var));
}
return result;
}
/**
* Return the number of bytes required to serialize this bitmap (meant to
* be compatible with Java and Go versions)
*
* Setting the portable flag to false enable a custom format that can save
* space compared to the portable format (e.g., for very sparse bitmaps).
*/
size_t getSizeInBytes(bool portable = true) const {
// start with, respectively, map size and size of keys for each map
// entry
return std::accumulate(
roarings.cbegin(), roarings.cend(),
sizeof(uint64_t) + roarings.size() * sizeof(uint32_t),
[=](size_t previous,
const std::pair<const uint32_t, Roaring> &map_entry) {
// add in bytes used by each Roaring
return previous + map_entry.second.getSizeInBytes(portable);
});
}
/**
* For advanced users only. This function is unsafe. You must ensure that
* the provided buffer is 32-byte aligned.
*/
static const Roaring64Map frozenView(const char *buf) {
// We do not check that buf is 32-byte aligned. Caller is responsible.
// size of bitmap buffer and key
const size_t metadata_size = sizeof(size_t) + sizeof(uint32_t);
Roaring64Map result;
// get map size
uint64_t map_size;
memcpy(&map_size, buf, sizeof(uint64_t));
buf += sizeof(uint64_t);
for (uint64_t lcv = 0; lcv < map_size; lcv++) {
// pad to 32 bytes minus the metadata size
while (((uintptr_t)buf + metadata_size) % 32 != 0) buf++;
// get bitmap size
size_t len;
memcpy(&len, buf, sizeof(size_t));
buf += sizeof(size_t);
// get map key
uint32_t key;
memcpy(&key, buf, sizeof(uint32_t));
buf += sizeof(uint32_t);
// read map value Roaring
const Roaring read = Roaring::frozenView(buf, len);
result.emplaceOrInsert(key, read);
// forward buffer past the last Roaring Bitmap
buf += len;
}
return result;
}
/**
* For advanced users only. This function is unsafe in the sense that
* that it may trigger unaligned memory access. Use with caution.
*/
static const Roaring64Map portableDeserializeFrozen(const char *buf) {
Roaring64Map result;
// get map size
uint64_t map_size;
std::memcpy(&map_size, buf, sizeof(uint64_t));
buf += sizeof(uint64_t);
for (uint64_t lcv = 0; lcv < map_size; lcv++) {
// get map key
uint32_t key;
std::memcpy(&key, buf, sizeof(uint32_t));
buf += sizeof(uint32_t);
// read map value Roaring
Roaring read_var = Roaring::portableDeserializeFrozen(buf);
// forward buffer past the last Roaring bitmap
buf += read_var.getSizeInBytes(true);
result.emplaceOrInsert(key, std::move(read_var));
}
return result;
}
/**
* For advanced users only. Offered on a best-effort basis.
* If you use this function in production, you are responsible for
* testing it on your target platforms. This function is unsafe.
*/
// As with serialized 64-bit bitmaps, 64-bit frozen bitmaps are serialized
// by concatenating one or more Roaring::write output buffers with the
// preceeding map key. Like the 32-bit bitmaps, it expects that the provided
// buffer is 32-byte aligned. The caller is responsible to check the
// alignment. Unlike standard bitmap serialization, frozen bitmaps must be
// 32-byte aligned and requires a buffer length to parse. As a result, each
// concatenated output of Roaring::writeFrozen is preceeded by padding, the
// buffer size (size_t), and the map key (uint32_t). The padding is used to
// ensure 32-byte alignment, but since it is followed by the buffer size and
// map key, it actually pads to `(x - sizeof(size_t) + sizeof(uint32_t)) mod
// 32` to leave room for the metadata.
void writeFrozen(char *buf) const {
// We do not check that buf is 32-byte aligned. Caller is responsible.
// size of bitmap buffer and key
const size_t metadata_size = sizeof(size_t) + sizeof(uint32_t);
// push map size
uint64_t map_size = roarings.size();
memcpy(buf, &map_size, sizeof(uint64_t));
buf += sizeof(uint64_t);
for (auto &map_entry : roarings) {
size_t frozenSizeInBytes = map_entry.second.getFrozenSizeInBytes();
// pad to 32 bytes minus the metadata size
while (((uintptr_t)buf + metadata_size) % 32 != 0) buf++;
// push bitmap size
memcpy(buf, &frozenSizeInBytes, sizeof(size_t));
buf += sizeof(size_t);
// push map key
memcpy(buf, &map_entry.first, sizeof(uint32_t));
buf += sizeof(uint32_t);
// push map value Roaring
map_entry.second.writeFrozen(buf);
buf += map_entry.second.getFrozenSizeInBytes();
}
}
/**
* For advanced users only. This function is unsafe.
*/
size_t getFrozenSizeInBytes() const {
// size of bitmap size and map key
const size_t metadata_size = sizeof(size_t) + sizeof(uint32_t);
size_t ret = 0;
// map size
ret += sizeof(uint64_t);
for (auto &map_entry : roarings) {
// pad to 32 bytes minus the metadata size
while ((ret + metadata_size) % 32 != 0) ret++;
ret += metadata_size;
// frozen bitmaps must be 32-byte aligned
ret += map_entry.second.getFrozenSizeInBytes();
}
return ret;
}
/**
* Computes the intersection between two bitmaps and returns new bitmap.
* The current bitmap and the provided bitmap are unchanged.
*
* Performance hint: if you are computing the intersection between several
* bitmaps, two-by-two, it is best to start with the smallest bitmap.
* Consider also using the operator &= to avoid needlessly creating
* many temporary bitmaps.
*/
Roaring64Map operator&(const Roaring64Map &o) const {
return Roaring64Map(*this) &= o;
}
/**
* Computes the difference between two bitmaps and returns new bitmap.
* The current bitmap and the provided bitmap are unchanged.
*/
Roaring64Map operator-(const Roaring64Map &o) const {
return Roaring64Map(*this) -= o;
}
/**
* Computes the union between two bitmaps and returns new bitmap.
* The current bitmap and the provided bitmap are unchanged.
*/
Roaring64Map operator|(const Roaring64Map &o) const {
return Roaring64Map(*this) |= o;
}
/**
* Computes the symmetric union between two bitmaps and returns new bitmap.
* The current bitmap and the provided bitmap are unchanged.
*/
Roaring64Map operator^(const Roaring64Map &o) const {
return Roaring64Map(*this) ^= o;
}
/**
* Whether or not we apply copy and write.
*/
void setCopyOnWrite(bool val) {
if (copyOnWrite == val) return;
copyOnWrite = val;
std::for_each(roarings.begin(), roarings.end(),
[=](std::pair<const uint32_t, Roaring> &map_entry) {
map_entry.second.setCopyOnWrite(val);
});
}
/**
* Print the contents of the bitmap to stdout.
* Note: this method adds a final newline, but toString() does not.
*/
void printf() const {
auto sink = [](const std::string &s) { fputs(s.c_str(), stdout); };
printToSink(sink);
sink("\n");
}
/**
* Print the contents of the bitmap into a string.
*/
std::string toString() const {
std::string result;
auto sink = [&result](const std::string &s) { result += s; };
printToSink(sink);
return result;
}
/**
* Whether or not copy and write is active.
*/
bool getCopyOnWrite() const { return copyOnWrite; }
/**
* Computes the logical or (union) between "n" bitmaps (referenced by a
* pointer).
*/
static Roaring64Map fastunion(size_t n, const Roaring64Map **inputs) {
// The strategy here is to basically do a "group by" operation.
// We group the input roarings by key, do a 32-bit
// roaring_bitmap_or_many on each group, and collect the results.
// We accomplish the "group by" operation using a priority queue, which
// tracks the next key for each of our input maps. At each step, our
// algorithm takes the next subset of maps that share the same next key,
// runs roaring_bitmap_or_many on those bitmaps, and then advances the
// current_iter on all the affected entries and then repeats.
// There is an entry in our priority queue for each of the 'n' inputs.
// For a given Roaring64Map, we look at its underlying 'roarings'
// std::map, and take its begin() and end(). This forms our half-open
// interval [current_iter, end_iter), which we keep in the priority
// queue as a pq_entry. These entries are updated (removed and then
// reinserted with the pq_entry.iterator field advanced by one step) as
// our algorithm progresses. But when a given interval becomes empty
// (i.e. pq_entry.iterator == pq_entry.end) it is not returned to the
// priority queue.
struct pq_entry {
roarings_t::const_iterator iterator;
roarings_t::const_iterator end;
};
// Custom comparator for the priority queue.
auto pq_comp = [](const pq_entry &lhs, const pq_entry &rhs) {
auto left_key = lhs.iterator->first;
auto right_key = rhs.iterator->first;
// We compare in the opposite direction than normal because priority
// queues normally order from largest to smallest, but we want
// smallest to largest.
return left_key > right_key;
};
// Create and populate the priority queue.
std::priority_queue<pq_entry, std::vector<pq_entry>, decltype(pq_comp)>
pq(pq_comp);
for (size_t i = 0; i < n; ++i) {
const auto &roarings = inputs[i]->roarings;
if (roarings.begin() != roarings.end()) {
pq.push({roarings.begin(), roarings.end()});
}
}
// A reusable vector that holds the pointers to the inner bitmaps that
// we pass to the underlying 32-bit fastunion operation.
std::vector<const roaring_bitmap_t *> group_bitmaps;
// Summary of the algorithm:
// 1. While the priority queue is not empty:
// A. Get its lowest key. Call this group_key
// B. While the lowest entry in the priority queue has a key equal to
// group_key:
// 1. Remove this entry (the pair {current_iter, end_iter}) from
// the priority queue.
// 2. Add the bitmap pointed to by current_iter to a list of
// 32-bit bitmaps to process.
// 3. Advance current_iter. Now it will point to a bitmap entry
// with some key greater than group_key (or it will point to
// end()).
// 4. If current_iter != end_iter, reinsert the pair into the
// priority queue.
// C. Invoke the 32-bit roaring_bitmap_or_many() and add to result
Roaring64Map result;
while (!pq.empty()) {
// Find the next key (the lowest key) in the priority queue.
auto group_key = pq.top().iterator->first;
// The purpose of the inner loop is to gather all the inner bitmaps
// that share "group_key" into "group_bitmaps" so that they can be
// fed to roaring_bitmap_or_many(). While we are doing this, we
// advance those iterators to their next value and reinsert them
// into the priority queue (unless they reach their end).
group_bitmaps.clear();
while (!pq.empty()) {
auto candidate_current_iter = pq.top().iterator;
auto candidate_end_iter = pq.top().end;
auto candidate_key = candidate_current_iter->first;
const auto &candidate_bitmap = candidate_current_iter->second;
// This element will either be in the group (having
// key == group_key) or it will not be in the group (having
// key > group_key). (Note it cannot have key < group_key
// because of the ordered nature of the priority queue itself
// and the ordered nature of all the underlying roaring maps).
if (candidate_key != group_key) {
// This entry, and (thanks to the nature of the priority
// queue) all other entries as well, are all greater than
// group_key, so we're done collecting elements for the
// current group. Because of the way this loop was written,
// the group will will always contain at least one element.
break;
}
group_bitmaps.push_back(&candidate_bitmap.roaring);
// Remove this entry from the priority queue. Note this
// invalidates pq.top() so make sure you don't have any dangling
// references to it.
pq.pop();
// Advance 'candidate_current_iter' and insert a new entry
// {candidate_current_iter, candidate_end_iter} into the
// priority queue (unless it has reached its end).
++candidate_current_iter;
if (candidate_current_iter != candidate_end_iter) {
pq.push({candidate_current_iter, candidate_end_iter});
}
}
// Use the fast inner union to combine these.
auto *inner_result = roaring_bitmap_or_many(group_bitmaps.size(),
group_bitmaps.data());
// Insert the 32-bit result at end of the 'roarings' map of the
// result we are building.
result.roarings.insert(
result.roarings.end(),
std::make_pair(group_key, Roaring(inner_result)));
}
return result;
}
friend class Roaring64MapSetBitBiDirectionalIterator;
typedef Roaring64MapSetBitBiDirectionalIterator const_iterator;
typedef Roaring64MapSetBitBiDirectionalIterator
const_bidirectional_iterator;
/**
* Returns an iterator that can be used to access the position of the set
* bits. The running time complexity of a full scan is proportional to the
* number of set bits: be aware that if you have long strings of 1s, this
* can be very inefficient.
*
* It can be much faster to use the toArray method if you want to
* retrieve the set bits.
*/
const_iterator begin() const;
/**
* A bogus iterator that can be used together with begin()
* for constructions such as: for (auto i = b.begin(); * i!=b.end(); ++i) {}
*/
const_iterator end() const;
private:
typedef std::map<uint32_t, Roaring> roarings_t;
roarings_t roarings{}; // The empty constructor silences warnings from
// pedantic static analyzers.
bool copyOnWrite{false};
static constexpr uint32_t highBytes(const uint64_t in) {
return uint32_t(in >> 32);
}
static constexpr uint32_t lowBytes(const uint64_t in) {
return uint32_t(in);
}
static constexpr uint64_t uniteBytes(const uint32_t highBytes,
const uint32_t lowBytes) {
return (uint64_t(highBytes) << 32) | uint64_t(lowBytes);
}
// this is needed to tolerate gcc's C++11 libstdc++ lacking emplace
// prior to version 4.8
void emplaceOrInsert(const uint32_t key, const Roaring &value) {
#if defined(__GLIBCXX__) && __GLIBCXX__ < 20130322
roarings.insert(std::make_pair(key, value));
#else
roarings.emplace(std::make_pair(key, value));
#endif
}
void emplaceOrInsert(const uint32_t key, Roaring &&value) {
#if defined(__GLIBCXX__) && __GLIBCXX__ < 20130322
roarings.insert(std::make_pair(key, std::move(value)));
#else
roarings.emplace(key, std::move(value));
#endif
}
/*
* Look up 'key' in the 'roarings' map. If it does not exist, create it.
* Also, set its copyOnWrite flag to 'copyOnWrite'. Then return a reference
* to the (already existing or newly created) inner bitmap.
*/
Roaring &lookupOrCreateInner(uint32_t key) {
auto &bitmap = roarings[key];
bitmap.setCopyOnWrite(copyOnWrite);
return bitmap;
}
/**
* Prints the contents of the bitmap to a caller-provided sink function.
*/
void printToSink(
const std::function<void(const std::string &)> &sink) const {
sink("{");
// Storage for snprintf. Big enough to store the decimal representation
// of the largest uint64_t value and trailing \0.
char buffer[32];
const char *separator = "";
// Reusable, and therefore avoids many repeated heap allocations.
std::string callback_string;
for (const auto &entry : roarings) {
auto high_bits = entry.first;
const auto &bitmap = entry.second;
for (const auto low_bits : bitmap) {
auto value = uniteBytes(high_bits, low_bits);
snprintf(buffer, sizeof(buffer), "%" PRIu64, value);
callback_string = separator;
callback_string.append(buffer);
sink(callback_string);
separator = ",";
}
}
sink("}");
}
/**
* Ensures that every key in the closed interval [start_high, end_high]
* refers to a Roaring bitmap rather being an empty slot. Inserts empty
* Roaring bitmaps if necessary. The interval must be valid and non-empty.
* Returns an iterator to the bitmap at start_high.
*/
roarings_t::iterator ensureRangePopulated(uint32_t start_high,
uint32_t end_high) {
if (start_high > end_high) {
ROARING_TERMINATE("Logic error: start_high > end_high");
}
// next_populated_iter points to the first entry in the outer map with
// key >= start_high, or end().
auto next_populated_iter = roarings.lower_bound(start_high);
// Use uint64_t to avoid an infinite loop when end_high == uint32_max.
roarings_t::iterator start_iter{}; // Definitely assigned in loop.
for (uint64_t slot = start_high; slot <= end_high; ++slot) {
roarings_t::iterator slot_iter;
if (next_populated_iter != roarings.end() &&
next_populated_iter->first == slot) {
// 'slot' index has caught up to next_populated_iter.
// Note it here and advance next_populated_iter.
slot_iter = next_populated_iter++;
} else {
// 'slot' index has not yet caught up to next_populated_iter.
// Make a fresh entry {key = 'slot', value = Roaring()}, insert
// it just prior to next_populated_iter, and set its copy
// on write flag. We take pains to use emplace_hint and
// piecewise_construct to minimize effort.
slot_iter = roarings.emplace_hint(
next_populated_iter, std::piecewise_construct,
std::forward_as_tuple(uint32_t(slot)),
std::forward_as_tuple());
auto &bitmap = slot_iter->second;
bitmap.setCopyOnWrite(copyOnWrite);
}
// Make a note of the iterator of the starting slot. It will be
// needed for the return value.
if (slot == start_high) {
start_iter = slot_iter;
}
}
return start_iter;
}
/**
* Erases the entry pointed to by 'iter' from the 'roarings' map. Warning:
* this invalidates 'iter'.
*/
void eraseIfEmpty(roarings_t::iterator iter) {
const auto &bitmap = iter->second;
if (bitmap.isEmpty()) {
roarings.erase(iter);
}
}
};
/**
* Used to go through the set bits. Not optimally fast, but convenient.
*
* Recommend to explicitly construct this iterator.
*/
class Roaring64MapSetBitBiDirectionalIterator {
public:
typedef std::bidirectional_iterator_tag iterator_category;
typedef uint64_t *pointer;
typedef uint64_t &reference;
typedef uint64_t value_type;
typedef int64_t difference_type;
typedef Roaring64MapSetBitBiDirectionalIterator type_of_iterator;
Roaring64MapSetBitBiDirectionalIterator(const Roaring64Map &parent,
bool exhausted = false)
: p(&parent.roarings) {
if (exhausted || parent.roarings.empty()) {
map_iter = p->cend();
} else {
map_iter = parent.roarings.cbegin();
roaring_iterator_init(&map_iter->second.roaring, &i);
while (!i.has_value) {
map_iter++;
if (map_iter == p->cend()) return;
roaring_iterator_init(&map_iter->second.roaring, &i);
}
}
}
/**
* Provides the location of the set bit.
*/
value_type operator*() const {
return Roaring64Map::uniteBytes(map_iter->first, i.current_value);
}
bool operator<(const type_of_iterator &o) const {
if (map_iter == p->cend()) return false;
if (o.map_iter == o.p->cend()) return true;
return **this < *o;
}
bool operator<=(const type_of_iterator &o) const {
if (o.map_iter == o.p->cend()) return true;
if (map_iter == p->cend()) return false;
return **this <= *o;
}
bool operator>(const type_of_iterator &o) const {
if (o.map_iter == o.p->cend()) return false;
if (map_iter == p->cend()) return true;
return **this > *o;
}
bool operator>=(const type_of_iterator &o) const {
if (map_iter == p->cend()) return true;
if (o.map_iter == o.p->cend()) return false;
return **this >= *o;
}
type_of_iterator &operator++() { // ++i, must returned inc. value
if (i.has_value == true) roaring_uint32_iterator_advance(&i);
while (!i.has_value) {
++map_iter;
if (map_iter == p->cend()) return *this;
roaring_iterator_init(&map_iter->second.roaring, &i);
}
return *this;
}
type_of_iterator operator++(int) { // i++, must return orig. value
Roaring64MapSetBitBiDirectionalIterator orig(*this);
roaring_uint32_iterator_advance(&i);
while (!i.has_value) {
++map_iter;
if (map_iter == p->cend()) return orig;
roaring_iterator_init(&map_iter->second.roaring, &i);
}
return orig;
}
/**
* Move the iterator to the first value >= val.
* Return true if there is such a value.
*/
bool move_equalorlarger(const value_type &x) {
map_iter = p->lower_bound(Roaring64Map::highBytes(x));
if (map_iter != p->cend()) {
roaring_iterator_init(&map_iter->second.roaring, &i);
if (map_iter->first == Roaring64Map::highBytes(x)) {
if (roaring_uint32_iterator_move_equalorlarger(
&i, Roaring64Map::lowBytes(x)))
return true;
++map_iter;
if (map_iter == p->cend()) return false;
roaring_iterator_init(&map_iter->second.roaring, &i);
}
return true;
}
return false;
}
/** DEPRECATED, use `move_equalorlarger`. */
CROARING_DEPRECATED bool move(const value_type &x) {
return move_equalorlarger(x);
}
type_of_iterator &operator--() { // --i, must return dec.value
if (map_iter == p->cend()) {
--map_iter;
roaring_iterator_init_last(&map_iter->second.roaring, &i);
if (i.has_value) return *this;
}
roaring_uint32_iterator_previous(&i);
while (!i.has_value) {
if (map_iter == p->cbegin()) return *this;
map_iter--;
roaring_iterator_init_last(&map_iter->second.roaring, &i);
}
return *this;
}
type_of_iterator operator--(int) { // i--, must return orig. value
Roaring64MapSetBitBiDirectionalIterator orig(*this);
if (map_iter == p->cend()) {
--map_iter;
roaring_iterator_init_last(&map_iter->second.roaring, &i);
return orig;
}
roaring_uint32_iterator_previous(&i);
while (!i.has_value) {
if (map_iter == p->cbegin()) return orig;
map_iter--;
roaring_iterator_init_last(&map_iter->second.roaring, &i);
}
return orig;
}
bool operator==(const Roaring64MapSetBitBiDirectionalIterator &o) const {
if (map_iter == p->cend() && o.map_iter == o.p->cend()) return true;
if (o.map_iter == o.p->cend()) return false;
return **this == *o;
}
bool operator!=(const Roaring64MapSetBitBiDirectionalIterator &o) const {
if (map_iter == p->cend() && o.map_iter == o.p->cend()) return false;
if (o.map_iter == o.p->cend()) return true;
return **this != *o;
}
private:
const std::map<uint32_t, Roaring> *p{nullptr};
std::map<uint32_t, Roaring>::const_iterator
map_iter{}; // The empty constructor silences warnings from pedantic
// static analyzers.
api::roaring_uint32_iterator_t
i{}; // The empty constructor silences warnings from pedantic static
// analyzers.
};
inline Roaring64MapSetBitBiDirectionalIterator Roaring64Map::begin() const {
return Roaring64MapSetBitBiDirectionalIterator(*this);
}
inline Roaring64MapSetBitBiDirectionalIterator Roaring64Map::end() const {
return Roaring64MapSetBitBiDirectionalIterator(*this, true);
}
} // namespace roaring
#endif /* INCLUDE_ROARING_64_MAP_HH_ */
/* end file cpp/roaring/roaring64map.hh */