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
mod alloc;
mod probe;
pub(crate) mod utils;
use std::hash::{BuildHasher, Hash};
use std::mem::MaybeUninit;
use std::sync::atomic::{AtomicPtr, AtomicU8, AtomicUsize, Ordering};
use std::sync::Mutex;
use std::{hint, panic, ptr};
use self::alloc::{RawTable, Table};
use self::probe::Probe;
#[allow(unused_imports)] // Contains polyfills for APIs that stabilized after MSRV.
use self::utils::{untagged, AtomicPtrFetchOps, Counter, Parker, StrictProvenance, Tagged};
use crate::map::{Compute, Operation, ResizeMode};
use crate::Equivalent;
use seize::{Collector, LocalGuard, OwnedGuard};
use utils::{MapGuard, Stack, VerifiedGuard};
/// A lock-free hash-table.
pub struct HashMap<K, V, S> {
/// A pointer to the root table.
table: AtomicPtr<RawTable<Entry<K, V>>>,
/// Collector for memory reclamation.
collector: Collector,
/// The resize mode, either blocking or incremental.
resize: ResizeMode,
/// An atomic counter of the number of keys in the table.
count: Counter,
/// The initial capacity provided to `HashMap::new`.
///
/// The table is guaranteed to never shrink below this capacity.
initial_capacity: usize,
/// Hasher for keys.
pub hasher: S,
}
/// Resize state for the hash-table.
pub struct State<T> {
/// The next table used for resizing.
pub next: AtomicPtr<RawTable<T>>,
/// A lock acquired to allocate the next table.
pub allocating: Mutex<()>,
/// The number of entries that have been copied to the next table.
pub copied: AtomicUsize,
/// The number of entries that have been claimed by copiers,
/// but not necessarily copied.
pub claim: AtomicUsize,
/// The status of the resize.
pub status: AtomicU8,
/// A thread parker for blocking on copy operations.
pub parker: Parker,
/// Entries whose retirement has been deferred by later tables.
pub deferred: Stack<*mut T>,
}
impl<T> Default for State<T> {
fn default() -> State<T> {
State {
next: AtomicPtr::new(ptr::null_mut()),
allocating: Mutex::new(()),
copied: AtomicUsize::new(0),
claim: AtomicUsize::new(0),
status: AtomicU8::new(State::PENDING),
parker: Parker::default(),
deferred: Stack::new(),
}
}
}
impl State<()> {
/// A resize is in-progress.
pub const PENDING: u8 = 0;
/// The resize has been aborted, continue to the next table.
pub const ABORTED: u8 = 1;
/// The resize was complete and the table was promoted.
pub const PROMOTED: u8 = 2;
}
// The result of an insert operation.
pub enum InsertResult<'g, V> {
/// Inserted the given value.
Inserted(&'g V),
/// Replaced the given value.
Replaced(&'g V),
/// Error returned by `try_insert`.
Error { current: &'g V, not_inserted: V },
}
// The raw result of an insert operation.
pub enum RawInsertResult<'g, K, V> {
/// Inserted the given value.
Inserted(&'g V),
/// Replaced the given value.
Replaced(&'g V),
/// Error returned by `try_insert`.
Error {
current: &'g V,
not_inserted: *mut Entry<K, V>,
},
}
// An entry in the hash-table.
#[repr(C, align(8))] // Reserve the lower 3 bits for pointer tagging.
pub struct Entry<K, V> {
/// The key for this entry.
pub key: K,
/// The value for this entry.
pub value: V,
}
impl Entry<(), ()> {
/// The entry is being copied to the new table, no updates are allowed on the old table.
///
/// This bit is put down to initiate a copy, forcing all writers to complete the resize
/// before making progress.
const COPYING: usize = 0b001;
/// The entry has been copied to the new table.
///
/// This bit is put down after a copy completes. Both readers and writers must go to
/// the new table to see the new state of the entry.
///
/// In blocking mode this is unused.
const COPIED: usize = 0b010;
/// The entry was copied from a previous table.
///
/// This bit indicates that an entry may still be accessible from previous tables
/// because the resize is still in progress, and so it is unsafe to reclaim.
///
/// In blocking mode this is unused.
const BORROWED: usize = 0b100;
}
impl<K, V> utils::Unpack for Entry<K, V> {
/// Mask for an entry pointer, ignoring any tag bits.
const MASK: usize = !(Entry::COPYING | Entry::COPIED | Entry::BORROWED);
}
impl<K, V> Entry<K, V> {
/// A sentinel pointer for a deleted entry.
///
/// Null pointers are never copied to the new table, so this state is safe to use.
/// Note that tombstone entries may still be marked as `COPYING`, so this state
/// cannot be used for direct equality.
const TOMBSTONE: *mut Entry<K, V> = Entry::COPIED as _;
}
/// The status of an entry.
enum EntryStatus<K, V> {
/// The entry is a tombstone or null (potentially a null copy).
Null,
/// The entry is being copied.
Copied(Tagged<Entry<K, V>>),
/// A valid entry.
Value(Tagged<Entry<K, V>>),
}
impl<K, V> From<Tagged<Entry<K, V>>> for EntryStatus<K, V> {
/// Returns the status for this entry.
#[inline]
fn from(entry: Tagged<Entry<K, V>>) -> Self {
if entry.ptr.is_null() {
EntryStatus::Null
} else if entry.tag() & Entry::COPYING != 0 {
EntryStatus::Copied(entry)
} else {
EntryStatus::Value(entry)
}
}
}
/// The state of an entry we attempted to update.
enum UpdateStatus<K, V> {
/// Successfully replaced the given key and value.
Replaced(Tagged<Entry<K, V>>),
/// A new entry was written before we could update.
Found(EntryStatus<K, V>),
}
/// The state of an entry we attempted to insert into.
enum InsertStatus<K, V> {
/// Successfully inserted the value.
Inserted,
/// A new entry was written before we could update.
Found(EntryStatus<K, V>),
}
impl<K, V, S> HashMap<K, V, S> {
/// Creates new hash-table with the given options.
#[inline]
pub fn new(
capacity: usize,
hasher: S,
collector: Collector,
resize: ResizeMode,
) -> HashMap<K, V, S> {
// The table is lazily allocated.
if capacity == 0 {
return HashMap {
collector,
resize,
hasher,
initial_capacity: 1,
table: AtomicPtr::new(ptr::null_mut()),
count: Counter::default(),
};
}
let capacity = probe::entries_for(capacity);
// Initialize the table and mark it as the root.
let mut table = Table::alloc(capacity);
*table.state_mut().status.get_mut() = State::PROMOTED;
HashMap {
hasher,
resize,
collector,
initial_capacity: capacity,
table: AtomicPtr::new(table.raw),
count: Counter::default(),
}
}
/// Returns a guard for this collector
pub fn guard(&self) -> MapGuard<LocalGuard<'_>> {
// Safety: Created the guard from our collector.
unsafe { MapGuard::new(self.collector().enter()) }
}
/// Returns an owned guard for this collector
pub fn owned_guard(&self) -> MapGuard<OwnedGuard<'_>> {
// Safety: Created the guard from our collector.
unsafe { MapGuard::new(self.collector().enter_owned()) }
}
/// Verify a guard is valid to use with this map.
#[inline]
pub fn verify<'g, G>(&self, guard: &'g G) -> &'g MapGuard<G>
where
G: seize::Guard,
{
assert_eq!(
*guard.collector(),
self.collector,
"Attempted to access map with incorrect guard"
);
// Safety: Verified the guard above.
unsafe { MapGuard::from_ref(guard) }
}
/// Returns a reference to the root hash-table.
#[inline]
fn root(&self, guard: &impl VerifiedGuard) -> Table<Entry<K, V>> {
// Load the root table.
let raw = guard.protect(&self.table, Ordering::Acquire);
// Safety: The root table is either null or a valid table allocation.
unsafe { Table::from_raw(raw) }
}
/// Returns a reference to the collector.
#[inline]
pub fn collector(&self) -> &Collector {
&self.collector
}
/// Returns the number of entries in the table.
#[inline]
pub fn len(&self) -> usize {
self.count.sum()
}
/// Returns true if incremental resizing is enabled.
#[inline]
fn is_incremental(&self) -> bool {
matches!(self.resize, ResizeMode::Incremental(_))
}
}
impl<K, V, S> HashMap<K, V, S>
where
K: Hash + Eq,
S: BuildHasher,
{
/// Returns a reference to the entry corresponding to the key.
#[inline]
pub fn get<'g, Q>(&self, key: &Q, guard: &'g impl VerifiedGuard) -> Option<(&'g K, &'g V)>
where
Q: Equivalent<K> + Hash + ?Sized,
{
// Load the root table.
let mut table = self.root(guard);
// The table has not been initialized yet.
if table.raw.is_null() {
return None;
}
let (h1, h2) = self.hash(key);
loop {
// Initialize the probe state.
let mut probe = Probe::start(h1, table.mask);
// Probe until we reach the limit.
'probe: while probe.len <= table.limit {
// Load the entry metadata first for cheap searches.
//
// Safety: `probe.i` is always in-bounds for the table length.
let meta = unsafe { table.meta(probe.i) }.load(Ordering::Acquire);
if meta == h2 {
// Load the full entry.
//
// Safety: `probe.i` is always in-bounds for the table length.
let entry = guard
.protect(unsafe { table.entry(probe.i) }, Ordering::Acquire)
.unpack();
// The entry was deleted, keep probing.
if entry.ptr.is_null() {
probe.next(table.mask);
continue 'probe;
}
// Safety: We performed a protected load of the pointer using a verified guard with
// `Acquire` and ensured that it is non-null, meaning it is valid for reads as long
// as we hold the guard.
let entry_ref = unsafe { &(*entry.ptr) };
// Check for a full match.
if key.equivalent(&entry_ref.key) {
// The entry was copied to the new table.
//
// In blocking resize mode we do not need to perform self check as all writes block
// until any resizes are complete, making the root table the source of truth for readers.
if entry.tag() & Entry::COPIED != 0 {
break 'probe;
}
// Found the correct entry, return the key and value.
return Some((&entry_ref.key, &entry_ref.value));
}
}
// The key is not in the table.
//
// It also cannot be in the next table because we have not went over the probe limit.
if meta == meta::EMPTY {
return None;
}
probe.next(table.mask);
}
// In incremental resize mode, we have to check the next table if we found
// a copied entry or went over the probe limit.
if self.is_incremental() {
if let Some(next) = table.next_table() {
table = next;
continue;
}
}
// Otherwise, the key is not in the table.
return None;
}
}
/// Inserts a key-value pair into the table.
#[inline]
pub fn insert<'g>(
&self,
key: K,
value: V,
replace: bool,
guard: &'g impl VerifiedGuard,
) -> InsertResult<'g, V> {
// Perform the insert.
let raw_result = self.insert_inner(key, value, replace, guard);
let result = match raw_result {
// Updated an entry.
RawInsertResult::Replaced(value) => InsertResult::Replaced(value),
// Inserted a new entry.
RawInsertResult::Inserted(value) => {
// Increment the table length.
self.count.get(guard).fetch_add(1, Ordering::Relaxed);
InsertResult::Inserted(value)
}
// Failed to insert the entry.
RawInsertResult::Error {
current,
not_inserted,
} => {
// Safety: We allocated this box above and it was not inserted into the table.
let not_inserted = unsafe { Box::from_raw(not_inserted) };
InsertResult::Error {
current,
not_inserted: not_inserted.value,
}
}
};
result
}
/// Inserts an entry into the map.
#[inline]
fn insert_inner<'g>(
&self,
key: K,
value: V,
should_replace: bool,
guard: &'g impl VerifiedGuard,
) -> RawInsertResult<'g, K, V> {
// Allocate the entry to be inserted.
let new_entry = untagged(Box::into_raw(Box::new(Entry { key, value })));
// Safety: We just allocated the entry above.
let new_ref = unsafe { &(*new_entry.ptr) };
// Load the root table.
let mut table = self.root(guard);
// Allocate the table if it has not been initialized yet.
if table.raw.is_null() {
table = self.init(None);
}
let (h1, h2) = self.hash(&new_ref.key);
let mut help_copy = true;
loop {
// Initialize the probe state.
let mut probe = Probe::start(h1, table.mask);
// Probe until we reach the limit.
let copying = 'probe: loop {
if probe.len > table.limit {
break None;
}
// Load the entry metadata first for cheap searches.
//
// Safety: `probe.i` is always in-bounds for the table length.
let meta = unsafe { table.meta(probe.i) }.load(Ordering::Acquire);
// The entry is empty, try to insert.
let entry = if meta == meta::EMPTY {
// Perform the insertion.
//
// Safety: `probe.i` is always in-bounds for the table length. Additionally,
// `new_entry` was allocated above and never shared.
match unsafe { self.insert_at(probe.i, h2, new_entry.raw, table, guard) } {
// Successfully inserted.
InsertStatus::Inserted => return RawInsertResult::Inserted(&new_ref.value),
// Lost to a concurrent insert.
//
// If the key matches, we might be able to update the value.
InsertStatus::Found(EntryStatus::Value(found))
| InsertStatus::Found(EntryStatus::Copied(found)) => found,
// Otherwise, continue probing.
InsertStatus::Found(EntryStatus::Null) => {
probe.next(table.mask);
continue 'probe;
}
}
}
// Found a potential match.
else if meta == h2 {
// Load the full entry.
//
// Safety: `probe.i` is always in-bounds for the table length.
let entry = guard
.protect(unsafe { table.entry(probe.i) }, Ordering::Acquire)
.unpack();
// The entry was deleted, keep probing.
if entry.ptr.is_null() {
probe.next(table.mask);
continue 'probe;
}
// If the key matches, we might be able to update the value.
entry
}
// Otherwise, continue probing.
else {
probe.next(table.mask);
continue 'probe;
};
// Safety: We performed a protected load of the pointer using a verified guard with
// `Acquire` and ensured that it is non-null, meaning it is valid for reads as long
// as we hold the guard.
let entry_ref = unsafe { &(*entry.ptr) };
// Check for a full match.
if entry_ref.key != new_ref.key {
probe.next(table.mask);
continue 'probe;
}
// The entry is being copied to the new table.
if entry.tag() & Entry::COPYING != 0 {
break 'probe Some(probe.i);
}
// Return an error for calls to `try_insert`.
if !should_replace {
return RawInsertResult::Error {
current: &entry_ref.value,
not_inserted: new_entry.ptr,
};
}
// Try to update the value.
//
// Safety:
// - `probe.i` is always in-bounds for the table length
// - `entry` is a valid non-null entry that was inserted into the map.
match unsafe { self.insert_slow(probe.i, entry, new_entry.raw, table, guard) } {
// Successfully performed the update.
UpdateStatus::Replaced(entry) => {
// Safety: `entry` is a valid non-null entry that we found in the map
// before replacing it.
let value = unsafe { &(*entry.ptr).value };
return RawInsertResult::Replaced(value);
}
// The entry is being copied.
UpdateStatus::Found(EntryStatus::Copied(_)) => break 'probe Some(probe.i),
// The entry was deleted before we could update it, continue probing.
UpdateStatus::Found(EntryStatus::Null) => {
probe.next(table.mask);
continue 'probe;
}
UpdateStatus::Found(EntryStatus::Value(_)) => {}
}
};
// Prepare to retry in the next table.
table = self.prepare_retry_insert(copying, &mut help_copy, table, guard);
}
}
/// The slow-path for `insert`, updating the value.
///
/// The returned pointer is guaranteed to be non-null and valid for reads.
///
/// # Safety
///
/// The safety requirements of `HashMap::update_at` apply.
#[cold]
#[inline(never)]
unsafe fn insert_slow(
&self,
i: usize,
mut entry: Tagged<Entry<K, V>>,
new_entry: *mut Entry<K, V>,
table: Table<Entry<K, V>>,
guard: &impl VerifiedGuard,
) -> UpdateStatus<K, V> {
loop {
// Try to update the value.
//
// Safety: Guaranteed by caller.
match unsafe { self.update_at(i, entry, new_entry, table, guard) } {
// Someone else beat us to the update, retry.
//
// Note that the pointer we find here is a non-null entry that was inserted
// into the map.
UpdateStatus::Found(EntryStatus::Value(found)) => entry = found,
status => return status,
}
}
}
/// Prepare to retry an insert operation in the next table.
#[cold]
#[inline(never)]
fn prepare_retry_insert(
&self,
copying: Option<usize>,
help_copy: &mut bool,
table: Table<Entry<K, V>>,
guard: &impl VerifiedGuard,
) -> Table<Entry<K, V>> {
// If went over the probe limit or found a copied entry, trigger a resize.
let mut next_table = self.get_or_alloc_next(None, table);
let next_table = match self.resize {
// In blocking mode we must complete the resize before proceeding.
ResizeMode::Blocking => self.help_copy(true, &table, guard),
// In incremental mode we can perform more granular blocking.
ResizeMode::Incremental(_) => {
// Help out with the copy.
if *help_copy {
next_table = self.help_copy(false, &table, guard);
}
// The entry we want to update is being copied.
if let Some(i) = copying {
// Wait for the entry to be copied.
//
// We could race with the copy to insert into the table. However,
// this entire code path is very rare and likely to complete quickly,
// so blocking allows us to make copies faster.
self.wait_copied(i, &table);
}
next_table
}
};
// Limit incremental copying to once per operation, for more consistent latency.
*help_copy = false;
// Continue in the new table.
next_table
}
/// Removes a key from the map, returning the entry for the key if the key was previously in the map.
#[inline]
pub fn remove<'g, Q>(&self, key: &Q, guard: &'g impl VerifiedGuard) -> Option<(&'g K, &'g V)>
where
Q: Equivalent<K> + Hash + ?Sized,
{
#[inline(always)]
fn should_remove<K, V>(_key: &K, _value: &V) -> bool {
true
}
// Safety: `should_remove` unconditionally returns `true`.
unsafe { self.remove_if(key, should_remove, guard).unwrap_unchecked() }
}
/// Removes a key from the map, returning the entry for the key if the key was previously in the map
/// and the provided closure returns `true`
#[inline]
pub fn remove_if<'g, Q, F>(
&self,
key: &Q,
mut should_remove: F,
guard: &'g impl VerifiedGuard,
) -> Result<Option<(&'g K, &'g V)>, (&'g K, &'g V)>
where
Q: Equivalent<K> + Hash + ?Sized,
F: FnMut(&K, &V) -> bool,
{
// Load the root table.
let mut table = self.root(guard);
// The table has not been initialized yet.
if table.raw.is_null() {
return Ok(None);
}
let (h1, h2) = self.hash(key);
let mut help_copy = true;
loop {
// Initialize the probe state.
let mut probe = Probe::start(h1, table.mask);
// Probe until we reach the limit.
let copying = 'probe: loop {
if probe.len > table.limit {
break None;
}
// Load the entry metadata first for cheap searches.
//
// Safety: `probe.i` is always in-bounds for the table length.
let meta = unsafe { table.meta(probe.i).load(Ordering::Acquire) };
// The key is not in the table.
// It also cannot be in the next table because we have not went over the probe limit.
if meta == meta::EMPTY {
return Ok(None);
}
// Check for a potential match.
if meta != h2 {
probe.next(table.mask);
continue 'probe;
}
// Load the full entry.
//
// Safety: `probe.i` is always in-bounds for the table length.
let mut entry = guard
.protect(unsafe { table.entry(probe.i) }, Ordering::Acquire)
.unpack();
// The entry was deleted, keep probing.
if entry.ptr.is_null() {
probe.next(table.mask);
continue 'probe;
}
// Check for a full match.
//
// Safety: We performed a protected load of the pointer using a verified guard with
// `Acquire` and ensured that it is non-null, meaning it is valid for reads as long
// as we hold the guard.
if !key.equivalent(unsafe { &(*entry.ptr).key }) {
probe.next(table.mask);
continue 'probe;
}
// The entry is being copied to the new table, we have to complete the copy before
// we can remove it.
if entry.tag() & Entry::COPYING != 0 {
break 'probe Some(probe.i);
}
loop {
// Safety: `entry` is a valid, non-null, protected entry that we found in the map.
let entry_ref = unsafe { &(*entry.ptr) };
// Ensure that the entry should be removed.
if !should_remove(&entry_ref.key, &entry_ref.value) {
return Err((&entry_ref.key, &entry_ref.value));
}
// Safety:
// - `probe.i` is always in-bounds for the table length
// - `entry` is a valid non-null entry that we found in the map.
let status =
unsafe { self.update_at(probe.i, entry, Entry::TOMBSTONE, table, guard) };
match status {
// Successfully removed the entry.
UpdateStatus::Replaced(_entry) => {
// Mark the entry as a tombstone.
//
// Note that this might end up being overwritten by the metadata hash
// if the initial insertion is lagging behind, but we avoid the RMW
// and sacrifice reads in the extremely rare case.
//
// Safety: `probe.i` is always in-bounds for the table length.
unsafe {
table
.meta(probe.i)
.store(meta::TOMBSTONE, Ordering::Release)
};
// Decrement the table length.
self.count.get(guard).fetch_sub(1, Ordering::Relaxed);
// Note that `entry_ref` here is the entry that we just replaced.
return Ok(Some((&entry_ref.key, &entry_ref.value)));
}
// The entry is being copied to the new table, we have to complete the copy
// before we can remove.
UpdateStatus::Found(EntryStatus::Copied(_)) => break 'probe Some(probe.i),
// The entry was deleted.
//
// We know that at some point during our execution the key was not in the map.
UpdateStatus::Found(EntryStatus::Null) => return Ok(None),
// Lost to a concurrent update, retry.
UpdateStatus::Found(EntryStatus::Value(found)) => entry = found,
}
}
};
// Prepare to retry in the next table.
table = match self.prepare_retry(copying, &mut help_copy, table, guard) {
Some(table) => table,
// The search was exhausted.
None => return Ok(None),
}
}
}
/// Prepare to retry an operation on an existing key in the next table.
///
/// Returns `None` if the recursive search has been exhausted.
#[cold]
fn prepare_retry(
&self,
copying: Option<usize>,
help_copy: &mut bool,
table: Table<Entry<K, V>>,
guard: &impl VerifiedGuard,
) -> Option<Table<Entry<K, V>>> {
let next_table = match self.resize {
ResizeMode::Blocking => match copying {
// The entry we want to perform the operation on is being copied.
//
// In blocking mode we must complete the resize before proceeding.
Some(_) => self.help_copy(true, &table, guard),
// If we went over the probe limit, the key is not in the map.
None => return None,
},
ResizeMode::Incremental(_) => {
// In incremental resize mode, we always have to check the next table.
let next_table = table.next_table()?;
// Help out with the copy.
if *help_copy {
self.help_copy(false, &table, guard);
}
if let Some(i) = copying {
// Wait for the entry to be copied.
//
// We could race with the copy to insert into the table. However,
// this entire code path is very rare and likely to complete quickly,
// so blocking allows us to make copies faster.
self.wait_copied(i, &table);
}
next_table
}
};
// Limit incremental copying to once per operation, for more consistent latency.
*help_copy = false;
// Continue in the new table.
Some(next_table)
}
/// Attempts to insert an entry at the given index.
///
/// In the case of an error, the returned pointer is guaranteed to be
/// protected and valid for reads as long as the guard is held.
///
/// # Safety
///
/// The index must be in-bounds for the table. Additionally, `new_entry` must be a
/// valid owned pointer to insert into the map.
#[inline]
unsafe fn insert_at(
&self,
i: usize,
meta: u8,
new_entry: *mut Entry<K, V>,
table: Table<Entry<K, V>>,
guard: &impl VerifiedGuard,
) -> InsertStatus<K, V> {
// Safety: The caller guarantees that `i` is in-bounds.
let entry = unsafe { table.entry(i) };
let meta_entry = unsafe { table.meta(i) };
// Try to claim the empty entry.
let found = match guard.compare_exchange(
entry,
ptr::null_mut(),
new_entry,
Ordering::Release,
Ordering::Acquire,
) {
// Successfully claimed the entry.
Ok(_) => {
// Update the metadata table.
meta_entry.store(meta, Ordering::Release);
// Return the value we inserted.
return InsertStatus::Inserted;
}
// Lost to a concurrent update.
Err(found) => found.unpack(),
};
let (meta, status) = match EntryStatus::from(found) {
EntryStatus::Value(_) | EntryStatus::Copied(_) => {
// Safety: We performed a protected load of the pointer using a verified guard
// with `Acquire` and ensured that it is non-null, meaning it is valid for reads
// as long as we hold the guard.
let key = unsafe { &(*found.ptr).key };
// An entry was inserted, we have to hash it to get the metadata.
//
// The logic is the same for copied entries here as we have to
// check if the key matches and continue the update in the new table.
let hash = self.hasher.hash_one(key);
(meta::h2(hash), EntryStatus::Value(found))
}
// The entry was deleted or null copied.
EntryStatus::Null => (meta::TOMBSTONE, EntryStatus::Null),
};
// Ensure the meta table is updated to keep the probe chain alive for readers.
if meta_entry.load(Ordering::Relaxed) == meta::EMPTY {
meta_entry.store(meta, Ordering::Release);
}
InsertStatus::Found(status)
}
/// Attempts to replace the value of an existing entry at the given index.
///
/// In the case of an error, the returned pointer is guaranteed to be
/// protected and valid for reads.
///
/// # Safety
///
/// - The index must be in-bounds for the table.
/// - `current` must be a valid non-null entry that was inserted into the map.
/// - `new_entry` must be a valid sentinel or owned pointer to insert into the map.
#[inline]
unsafe fn update_at(
&self,
i: usize,
current: Tagged<Entry<K, V>>,
new_entry: *mut Entry<K, V>,
table: Table<Entry<K, V>>,
guard: &impl VerifiedGuard,
) -> UpdateStatus<K, V> {
// Safety: The caller guarantees that `i` is in-bounds.
let entry = unsafe { table.entry(i) };
// Try to perform the update.
let found = match guard.compare_exchange_weak(
entry,
current.raw,
new_entry,
Ordering::Release,
Ordering::Acquire,
) {
// Successfully updated.
Ok(_) => unsafe {
// Safety: The caller guarantees that `current` is a valid non-null entry that was
// inserted into the map. Additionally, it is now unreachable from this table due
// to the CAS above.
self.defer_retire(current, &table, guard);
return UpdateStatus::Replaced(current);
},
// Lost to a concurrent update.
Err(found) => found.unpack(),
};
UpdateStatus::Found(EntryStatus::from(found))
}
/// Reserve capacity for `additional` more elements.
#[inline]
pub fn reserve(&self, additional: usize, guard: &impl VerifiedGuard) {
let mut table = self.root(guard);
// The table has not yet been allocated, initialize it.
if table.raw.is_null() {
table = self.init(Some(probe::entries_for(additional)));
}
loop {
let capacity = probe::entries_for(self.count.sum().checked_add(additional).unwrap());
// We have enough capacity.
if table.len() >= capacity {
return;
}
// Race to allocate the new table.
self.get_or_alloc_next(Some(capacity), table);
// Force the copy to complete.
//
// Note that this is not strictly necessary for a `reserve` operation.
table = self.help_copy(true, &table, guard);
}
}
/// Remove all entries from this table.
#[inline]
pub fn clear(&self, guard: &impl VerifiedGuard) {
// Load the root table.
let mut table = self.root(guard);
// The table has not been initialized yet.
if table.raw.is_null() {
return;
}
loop {
// Get a clean copy of the table to delete from.
table = self.linearize(table, guard);
// Note that this method is not implemented in terms of `retain(|_, _| true)` to avoid
// loading entry metadata, as there is no need to provide consistency with `get`.
let mut copying = false;
'probe: for i in 0..table.len() {
// Load the entry to delete.
//
// Safety: `i` is in bounds for the table length.
let mut entry = guard
.protect(unsafe { table.entry(i) }, Ordering::Acquire)
.unpack();
loop {
// The entry is empty or already deleted.
if entry.ptr.is_null() {
continue 'probe;
}
// Found a non-empty entry being copied.
if entry.tag() & Entry::COPYING != 0 {
// Clear every entry in this table that we can, then deal with the copy.
copying = true;
continue 'probe;
}
// Try to delete the entry.
//
// Safety: `i` is in bounds for the table length.
let result = unsafe {
table.entry(i).compare_exchange(
entry.raw,
Entry::TOMBSTONE,
Ordering::Release,
Ordering::Acquire,
)
};
match result {
// Successfully deleted the entry.
Ok(_) => {
// Update the metadata table.
//
// Safety: `i` is in bounds for the table length.
unsafe { table.meta(i).store(meta::TOMBSTONE, Ordering::Release) };
// Decrement the table length.
self.count.get(guard).fetch_sub(1, Ordering::Relaxed);
// Safety: The caller guarantees that `current` is a valid non-null entry that was
// inserted into the map. Additionally, it is now unreachable from this table due
// to the CAS above.
unsafe { self.defer_retire(entry, &table, guard) };
continue 'probe;
}
// Lost to a concurrent update, retry.
Err(found) => entry = found.unpack(),
}
}
}
// We cleared every entry in this table.
if !copying {
break;
}
// A resize prevented us from deleting all the entries in this table.
//
// Complete the resize and retry in the new table.
table = self.help_copy(true, &table, guard);
}
}
/// Retains only the elements specified by the predicate.
#[inline]
pub fn retain<F>(&self, mut f: F, guard: &impl VerifiedGuard)
where
F: FnMut(&K, &V) -> bool,
{
// Load the root table.
let mut table = self.root(guard);
// The table has not been initialized yet.
if table.raw.is_null() {
return;
}
loop {
// Get a clean copy of the table to delete from.
table = self.linearize(table, guard);
let mut copying = false;
'probe: for i in 0..table.len() {
// Load the entry metadata first to ensure consistency with calls to `get`
// for entries that are retained.
//
// Safety: `i` is in bounds for the table length.
let meta = unsafe { table.meta(i) }.load(Ordering::Acquire);
// The entry is empty or deleted.
if matches!(meta, meta::EMPTY | meta::TOMBSTONE) {
continue 'probe;
}
// Load the entry to delete.
//
// Safety: `i` is in bounds for the table length.
let mut entry = guard
.protect(unsafe { table.entry(i) }, Ordering::Acquire)
.unpack();
loop {
// The entry is empty or already deleted.
if entry.ptr.is_null() {
continue 'probe;
}
// Found a non-empty entry being copied.
if entry.tag() & Entry::COPYING != 0 {
// Clear every entry in this table that we can, then deal with the copy.
copying = true;
continue 'probe;
}
// Safety: We performed a protected load of the pointer using a verified guard with
// `Acquire` and ensured that it is non-null, meaning it is valid for reads as long
// as we hold the guard.
let entry_ref = unsafe { &*entry.ptr };
// Should we retain this entry?
if f(&entry_ref.key, &entry_ref.value) {
continue 'probe;
}
// Try to delete the entry.
//
// Safety: `i` is in bounds for the table length.
let result = unsafe {
table.entry(i).compare_exchange(
entry.raw,
Entry::TOMBSTONE,
Ordering::Release,
Ordering::Acquire,
)
};
match result {
// Successfully deleted the entry.
Ok(_) => {
// Update the metadata table.
//
// Safety: `i` is in bounds for the table length.
unsafe { table.meta(i).store(meta::TOMBSTONE, Ordering::Release) };
// Decrement the table length.
self.count.get(guard).fetch_sub(1, Ordering::Relaxed);
// Safety: The caller guarantees that `current` is a valid non-null entry that was
// inserted into the map. Additionally, it is now unreachable from this table due
// to the CAS above.
unsafe { self.defer_retire(entry, &table, guard) };
continue 'probe;
}
// Lost to a concurrent update, retry.
Err(found) => entry = found.unpack(),
}
}
}
// We cleared every entry in this table.
if !copying {
break;
}
// A resize prevented us from deleting all the entries in this table.
//
// Complete the resize and retry in the new table.
table = self.help_copy(true, &table, guard);
}
}
/// Returns an iterator over the keys and values of this table.
#[inline]
pub fn iter<'g, G>(&self, guard: &'g G) -> Iter<'g, K, V, G>
where
G: VerifiedGuard,
{
// Load the root table.
let root = self.root(guard);
// The table has not been initialized yet, return a dummy iterator.
if root.raw.is_null() {
return Iter {
i: 0,
guard,
table: root,
};
}
// Get a clean copy of the table to iterate over.
let table = self.linearize(root, guard);
Iter { i: 0, guard, table }
}
/// Returns the h1 and h2 hash for the given key.
#[inline]
fn hash<Q>(&self, key: &Q) -> (usize, u8)
where
Q: Hash + ?Sized,
{
let hash = self.hasher.hash_one(key);
(meta::h1(hash), meta::h2(hash))
}
}
/// A wrapper around a CAS function that manages the computed state.
struct ComputeState<F, K, V, T> {
/// The CAS function.
compute: F,
/// A cached insert transition.
insert: Option<V>,
/// A cached update transition.
update: Option<CachedUpdate<K, V, T>>,
}
/// A cached update transition.
struct CachedUpdate<K, V, T> {
/// The entry that the CAS function was called with.
input: *mut Entry<K, V>,
/// The cached result.
output: Operation<V, T>,
}
impl<'g, F, K, V, T> ComputeState<F, K, V, T>
where
F: FnMut(Option<(&'g K, &'g V)>) -> Operation<V, T>,
K: 'g,
V: 'g,
{
/// Create a new `ComputeState` for the given function.
#[inline]
fn new(compute: F) -> ComputeState<F, K, V, T> {
ComputeState {
compute,
insert: None,
update: None,
}
}
/// Performs a state transition.
///
/// # Safety
///
/// The entry pointer must be valid for reads if provided.
#[inline]
unsafe fn next(&mut self, entry: Option<*mut Entry<K, V>>) -> Operation<V, T> {
let Some(entry) = entry else {
// If there is no current entry, perform a transition for the insert.
return match self.insert.take() {
// Use the cached insert.
Some(value) => Operation::Insert(value),
// Otherwise, compute the value to insert.
None => (self.compute)(None),
};
};
// Otherwise, perform an update transition.
match self.update.take() {
// Used the cached update if the entry has not changed.
Some(CachedUpdate { input, output }) if input == entry => output,
// Otherwise, compute the value to update.
_ => {
// Safety: The caller guarantees that `entry` is valid for reads.
let entry_ref = unsafe { &*entry };
(self.compute)(Some((&entry_ref.key, &entry_ref.value)))
}
}
}
/// Restores the state if an operation fails.
///
/// This allows the result of the compute closure with a given input to be cached.
/// This is useful at it avoids calling the closure multiple times if an update needs
/// to be retried in a new table.
///
/// Additionally, update and insert operations are cached separately, although this
/// is not guaranteed in the public API. This means that internal methods can rely on
/// `compute(None)` being called at most once.
#[inline]
fn restore(&mut self, input: Option<*mut Entry<K, V>>, output: Operation<V, T>) {
match input {
Some(input) => self.update = Some(CachedUpdate { input, output }),
None => match output {
Operation::Insert(value) => self.insert = Some(value),
_ => unreachable!(),
},
}
}
}
/// A lazy initialized `Entry` allocation.
enum LazyEntry<K, V> {
/// An uninitialized entry, containing just the owned key.
Uninit(K),
/// An allocated entry.
Init(*mut Entry<K, MaybeUninit<V>>),
}
impl<K, V> LazyEntry<K, V> {
/// Returns a reference to the entry's key.
#[inline]
fn key(&self) -> &K {
match self {
LazyEntry::Uninit(key) => key,
LazyEntry::Init(entry) => unsafe { &(**entry).key },
}
}
/// Initializes the entry if it has not already been initialized, returning the pointer
/// to the entry allocation.
#[inline]
fn init(&mut self) -> *mut Entry<K, MaybeUninit<V>> {
match self {
LazyEntry::Init(entry) => *entry,
LazyEntry::Uninit(key) => {
// Safety: we read the current key with `ptr::read` and overwrite the
// state with `ptr::write`. We also make sure to abort if the allocator
// panics, ensuring the current value is not dropped twice.
unsafe {
let key = ptr::read(key);
let entry = panic::catch_unwind(panic::AssertUnwindSafe(|| {
Box::into_raw(Box::new(Entry {
value: MaybeUninit::uninit(),
key,
}))
}))
.unwrap_or_else(|_| std::process::abort());
ptr::write(self, LazyEntry::Init(entry));
entry
}
}
}
}
}
/// RMW operations.
impl<K, V, S> HashMap<K, V, S>
where
K: Hash + Eq,
S: BuildHasher,
{
/// Tries to insert a key and value computed from a closure into the map,
/// and returns a reference to the value that was inserted.
#[inline]
pub fn try_insert_with<'g, F>(
&self,
key: K,
f: F,
guard: &'g impl VerifiedGuard,
) -> Result<&'g V, &'g V>
where
F: FnOnce() -> V,
K: 'g,
{
let mut f = Some(f);
let compute = |entry| match entry {
// There is already an existing value.
Some((_, current)) => Operation::Abort(current),
// Insert the initial value.
//
// Note that this case is guaranteed to be executed at most
// once as insert values are cached, so this can never panic.
None => Operation::Insert((f.take().unwrap())()),
};
match self.compute(key, compute, guard) {
// Failed to insert, return the existing value.
Compute::Aborted(current) => Err(current),
// Successfully inserted.
Compute::Inserted(_, value) => Ok(value),
_ => unreachable!(),
}
}
/// Returns a reference to the value corresponding to the key, or inserts a default value
/// computed from a closure.
#[inline]
pub fn get_or_insert_with<'g, F>(&self, key: K, f: F, guard: &'g impl VerifiedGuard) -> &'g V
where
F: FnOnce() -> V,
K: 'g,
{
match self.try_insert_with(key, f, guard) {
Ok(value) => value,
Err(value) => value,
}
}
/// Updates an existing entry atomically, returning the value that was inserted.
#[inline]
pub fn update<'g, F>(
&self,
key: K,
mut update: F,
guard: &'g impl VerifiedGuard,
) -> Option<&'g V>
where
F: FnMut(&V) -> V,
K: 'g,
{
let compute = |entry| match entry {
// There is nothing to update.
None => Operation::Abort(()),
// Perform the update.
Some((_, value)) => Operation::Insert(update(value)),
};
match self.compute(key, compute, guard) {
// Return the updated value.
Compute::Updated {
new: (_, value), ..
} => Some(value),
// There was nothing to update.
Compute::Aborted(_) => None,
_ => unreachable!(),
}
}
/// Updates an existing entry or inserts a default value computed from a closure.
#[inline]
pub fn update_or_insert_with<'g, U, F>(
&self,
key: K,
update: U,
f: F,
guard: &'g impl VerifiedGuard,
) -> &'g V
where
F: FnOnce() -> V,
U: Fn(&V) -> V,
K: 'g,
{
let mut f = Some(f);
let compute = |entry| match entry {
// Perform the update.
Some((_, value)) => Operation::Insert::<_, ()>(update(value)),
// Insert the initial value.
//
// Note that this case is guaranteed to be executed at most
// once as insert values are cached, so this can never panic.
None => Operation::Insert((f.take().unwrap())()),
};
match self.compute(key, compute, guard) {
// Return the updated value.
Compute::Updated {
new: (_, value), ..
} => value,
// Return the value we inserted.
Compute::Inserted(_, value) => value,
_ => unreachable!(),
}
}
/// Update an entry with a CAS function.
///
/// Note that `compute` closure is guaranteed to be called for a `None` input only once, allowing the
/// insertion of values that cannot be cloned or reconstructed.
#[inline]
pub fn compute<'g, F, T>(
&self,
key: K,
compute: F,
guard: &'g impl VerifiedGuard,
) -> Compute<'g, K, V, T>
where
F: FnMut(Option<(&'g K, &'g V)>) -> Operation<V, T>,
{
// Lazy initialize the entry allocation.
let mut entry = LazyEntry::Uninit(key);
// Perform the update.
//
// Safety: We just allocated the entry above.
let result = unsafe { self.compute_with(&mut entry, ComputeState::new(compute), guard) };
// Deallocate the entry if it was not inserted.
if matches!(result, Compute::Removed(..) | Compute::Aborted(_)) {
if let LazyEntry::Init(entry) = entry {
// Safety: The entry was allocated but not inserted into the map.
let _ = unsafe { Box::from_raw(entry) };
}
}
result
}
/// Update an entry with a CAS function.
///
/// # Safety
///
/// The new entry must be a valid owned pointer to insert into the map.
#[inline]
unsafe fn compute_with<'g, F, T>(
&self,
new_entry: &mut LazyEntry<K, V>,
mut state: ComputeState<F, K, V, T>,
guard: &'g impl VerifiedGuard,
) -> Compute<'g, K, V, T>
where
F: FnMut(Option<(&'g K, &'g V)>) -> Operation<V, T>,
{
// Load the root table.
let mut table = self.root(guard);
// The table has not yet been allocated.
if table.raw.is_null() {
// Compute the value to insert.
//
// Safety: Insert transitions are always sound.
match unsafe { state.next(None) } {
op @ Operation::Insert(_) => state.restore(None, op),
Operation::Remove => panic!("Cannot remove `None` entry."),
Operation::Abort(value) => return Compute::Aborted(value),
}
// Initialize the table.
table = self.init(None);
}
let (h1, h2) = self.hash(new_entry.key());
let mut help_copy = false;
loop {
// Initialize the probe state.
let mut probe = Probe::start(h1, table.mask);
// Probe until we reach the limit.
let copying = 'probe: loop {
if probe.len > table.limit {
break 'probe None;
}
// Load the entry metadata first for cheap searches.
//
// Safety: `probe.i` is always in-bounds for the table length.
let meta = unsafe { table.meta(probe.i) }.load(Ordering::Acquire);
// The entry is empty.
let mut entry = if meta == meta::EMPTY {
// Compute the value to insert.
//
// Safety: Insert transitions are always sound.
let value = match unsafe { state.next(None) } {
Operation::Insert(value) => value,
Operation::Remove => panic!("Cannot remove `None` entry."),
Operation::Abort(value) => return Compute::Aborted(value),
};
let new_entry = new_entry.init();
// Safety: `new_entry` was just allocated above and is valid for writes.
unsafe { (*new_entry).value = MaybeUninit::new(value) }
// Attempt to insert.
//
// Safety: `probe.i` is always in-bounds for the table length.Additionally,
// `new_entry` was allocated above and never shared.
match unsafe { self.insert_at(probe.i, h2, new_entry.cast(), table, guard) } {
// Successfully inserted.
InsertStatus::Inserted => {
// Increment the table length.
self.count.get(guard).fetch_add(1, Ordering::Relaxed);
// Safety: `new_entry` was initialized above.
let new_ref = unsafe { &*new_entry.cast::<Entry<K, V>>() };
return Compute::Inserted(&new_ref.key, &new_ref.value);
}
// Lost to a concurrent insert.
//
// If the key matches, we might be able to update the value.
InsertStatus::Found(EntryStatus::Value(found))
| InsertStatus::Found(EntryStatus::Copied(found)) => {
// Cache the previous value
//
// Safety: `new_entry` was initialized above and was not inserted
// into the map.
let value = unsafe { (*new_entry).value.assume_init_read() };
state.restore(None, Operation::Insert(value));
found
}
// The entry was removed or invalidated.
InsertStatus::Found(EntryStatus::Null) => {
// Cache the previous value.
//
// Safety: `new_entry` was initialized above and was not inserted
// into the map.
let value = unsafe { (*new_entry).value.assume_init_read() };
state.restore(None, Operation::Insert(value));
// Continue probing.
probe.next(table.mask);
continue 'probe;
}
}
}
// Found a potential match.
else if meta == h2 {
// Load the full entry.
//
// Safety: `probe.i` is always in-bounds for the table length.
let found = guard
.protect(unsafe { table.entry(probe.i) }, Ordering::Acquire)
.unpack();
// The entry was deleted, keep probing.
if found.ptr.is_null() {
probe.next(table.mask);
continue 'probe;
}
// If the key matches, we might be able to update the value.
found
}
// Otherwise, continue probing.
else {
probe.next(table.mask);
continue 'probe;
};
// Check for a full match.
//
// Safety: We performed a protected load of the pointer using a verified guard with
// `Acquire` and ensured that it is non-null, meaning it is valid for reads as long
// as we hold the guard.
if unsafe { (*entry.ptr).key != *new_entry.key() } {
probe.next(table.mask);
continue 'probe;
}
// The entry is being copied to the new table.
if entry.tag() & Entry::COPYING != 0 {
break 'probe Some(probe.i);
}
loop {
// Compute the value to insert.
//
// Safety: `entry` is valid for reads.
let failure = match unsafe { state.next(Some(entry.ptr)) } {
// The operation was aborted.
Operation::Abort(value) => return Compute::Aborted(value),
// Update the value.
Operation::Insert(value) => {
let new_entry = new_entry.init();
// Safety: `new_entry` was just allocated above and is valid for writes.
unsafe { (*new_entry).value = MaybeUninit::new(value) }
// Try to perform the update.
//
// Safety:
// - `probe.i` is always in-bounds for the table length
// - `entry` is a valid non-null entry that we found in the map.
// - `new_entry` was initialized above and never shared.
let status = unsafe {
self.update_at(probe.i, entry, new_entry.cast(), table, guard)
};
match status {
// Successfully updated.
UpdateStatus::Replaced(entry) => {
// Safety: `entry` is a valid non-null entry that we found in the map
// before replacing it.
let entry_ref = unsafe { &(*entry.ptr) };
// Safety: `new_entry` was initialized above.
let new_ref = unsafe { &*new_entry.cast::<Entry<K, V>>() };
return Compute::Updated {
old: (&entry_ref.key, &entry_ref.value),
new: (&new_ref.key, &new_ref.value),
};
}
// The update failed.
failure => {
// Save the previous value.
//
// Safety: `new_entry` was initialized above and was not inserted
// into the map.
let value = unsafe { (*new_entry).value.assume_init_read() };
state.restore(Some(entry.ptr), Operation::Insert(value));
failure
}
}
}
// Remove the key from the map.
Operation::Remove => {
// Try to perform the removal.
//
// Safety:
// - `probe.i` is always in-bounds for the table length
// - `entry` is a valid non-null entry that we found in the map.
let status = unsafe {
self.update_at(probe.i, entry, Entry::TOMBSTONE, table, guard)
};
match status {
// Successfully removed the entry.
UpdateStatus::Replaced(entry) => {
// Mark the entry as a tombstone.
//
// Note that this might end up being overwritten by the metadata hash
// if the initial insertion is lagging behind, but we avoid the RMW
// and sacrifice reads in the extremely rare case.
unsafe {
table
.meta(probe.i)
.store(meta::TOMBSTONE, Ordering::Release)
};
// Decrement the table length.
self.count.get(guard).fetch_sub(1, Ordering::Relaxed);
// Safety: `entry` is a valid non-null entry that we found in the map
// before replacing it.
let entry_ref = unsafe { &(*entry.ptr) };
return Compute::Removed(&entry_ref.key, &entry_ref.value);
}
// The remove failed.
failure => {
// Save the removal operation.
state.restore(Some(entry.ptr), Operation::Remove);
failure
}
}
}
};
match failure {
// The entry is being copied to the new table.
UpdateStatus::Found(EntryStatus::Copied(_)) => break 'probe Some(probe.i),
// The entry was deleted before we could update it.
//
// We know that at some point during our execution the key was not in the map.
UpdateStatus::Found(EntryStatus::Null) => {
// Compute the next operation.
//
// Safety: Insert transitions are always sound.
match unsafe { state.next(None) } {
Operation::Insert(value) => {
// Save the computed value.
state.restore(None, Operation::Insert(value));
// Continue probing to find an empty slot.
probe.next(table.mask);
continue 'probe;
}
Operation::Remove => panic!("Cannot remove `None` entry."),
Operation::Abort(value) => return Compute::Aborted(value),
}
}
// Someone else beat us to the update, retry.
UpdateStatus::Found(EntryStatus::Value(found)) => entry = found,
_ => unreachable!(),
}
}
};
// Prepare to retry in the next table.
if let Some(next_table) = self.prepare_retry(copying, &mut help_copy, table, guard) {
table = next_table;
continue;
}
// Otherwise, the key is not in the map.
//
// Safety: Insert transitions are always sound.
match unsafe { state.next(None) } {
// Need to insert into the new table.
op @ Operation::Insert(_) => {
table = self.prepare_retry_insert(None, &mut help_copy, table, guard);
state.restore(None, op);
}
// The operation was aborted.
Operation::Abort(value) => return Compute::Aborted(value),
Operation::Remove => panic!("Cannot remove `None` entry."),
}
}
}
}
/// Resize operations.
impl<K, V, S> HashMap<K, V, S>
where
K: Hash + Eq,
S: BuildHasher,
{
/// Allocate the initial table.
#[cold]
#[inline(never)]
fn init(&self, capacity: Option<usize>) -> Table<Entry<K, V>> {
const CAPACITY: usize = 32;
// Allocate the table and mark it as the root.
let mut new = Table::alloc(capacity.unwrap_or(CAPACITY));
*new.state_mut().status.get_mut() = State::PROMOTED;
// Race to write the initial table.
match self.table.compare_exchange(
ptr::null_mut(),
new.raw,
Ordering::Release,
Ordering::Acquire,
) {
// Successfully initialized the table.
Ok(_) => new,
// Someone beat us, deallocate our table and use the table that was written.
Err(found) => {
// Safety: We allocated the table above and never shared it.
unsafe { Table::dealloc(new) }
// Safety: The table was just initialized.
unsafe { Table::from_raw(found) }
}
}
}
/// Returns the next table, allocating it has not already been created.
#[cold]
#[inline(never)]
fn get_or_alloc_next(
&self,
capacity: Option<usize>,
table: Table<Entry<K, V>>,
) -> Table<Entry<K, V>> {
// Avoid spinning in tests, which can hide race conditions.
const SPIN_ALLOC: usize = if cfg!(any(test, debug_assertions)) {
1
} else {
7
};
// The next table is already allocated.
if let Some(next) = table.next_table() {
return next;
}
let state = table.state();
// Otherwise, try to acquire the allocation lock.
//
// Unlike in `init`, we do not race here to prevent unnecessary allocator pressure.
let _allocating = match state.allocating.try_lock() {
Ok(lock) => lock,
// Someone else is currently allocating.
Err(_) => {
let mut spun = 0;
// Spin for a bit, waiting for the table to be initialized.
while spun <= SPIN_ALLOC {
for _ in 0..(spun * spun) {
hint::spin_loop();
}
// The table was initialized.
if let Some(next) = table.next_table() {
return next;
}
spun += 1;
}
// Otherwise, we have to block.
state.allocating.lock().unwrap()
}
};
// The table was allocated while we were waiting for the lock.
if let Some(next) = table.next_table() {
return next;
}
let current_capacity = table.len();
// Loading the length here is quite expensive, we may want to consider
// a probabilistic counter to detect high-deletion workloads.
let active_entries = self.len();
let next_capacity = match cfg!(papaya_stress) {
// Never grow the table to stress the incremental resizing algorithm.
true => current_capacity,
// Double the table capacity if we are at least 50% full.
false if active_entries >= (current_capacity >> 1) => current_capacity << 1,
// Halve the table if we are at most 12.5% full.
//
// This heuristic is intentionally pessimistic as unnecessarily shrinking
// is an expensive operation, but it may change in the future. We also respect
// the initial capacity to give the user a way to retain a strict minimum table
// size.
false if active_entries <= (current_capacity >> 3) => {
self.initial_capacity.max(current_capacity >> 1)
}
// Otherwise keep the capacity the same.
//
// This can occur due to poor hash distribution or frequent cycling of
// insertions and deletions, in which case we want to avoid continuously
// growing the table.
false => current_capacity,
};
let next_capacity = capacity.unwrap_or(next_capacity);
assert!(
next_capacity <= isize::MAX as usize,
"`HashMap` exceeded maximum capacity"
);
// Allocate the new table while holding the lock.
let next = Table::alloc(next_capacity);
state.next.store(next.raw, Ordering::Release);
drop(_allocating);
next
}
/// Help along with an existing resize operation, returning the new root table.
///
/// If `copy_all` is `false` in incremental resize mode, this returns the current reference's next
/// table, not necessarily the new root.
#[cold]
#[inline(never)]
fn help_copy(
&self,
copy_all: bool,
table: &Table<Entry<K, V>>,
guard: &impl VerifiedGuard,
) -> Table<Entry<K, V>> {
match self.resize {
ResizeMode::Blocking => self.help_copy_blocking(table, guard),
ResizeMode::Incremental(chunk) => {
let copied_to = self.help_copy_incremental(chunk, copy_all, guard);
if !copy_all {
// If we weren't trying to linearize, we have to write to the next table
// even if the copy hasn't completed yet.
return table.next_table().unwrap();
}
copied_to
}
}
}
/// Help along the resize operation until it completes and the next table is promoted.
///
/// Should only be called on the root table.
fn help_copy_blocking(
&self,
table: &Table<Entry<K, V>>,
guard: &impl VerifiedGuard,
) -> Table<Entry<K, V>> {
// Load the next table.
let mut next = table.next_table().unwrap();
'copy: loop {
// Make sure we are copying to the correct table.
while next.state().status.load(Ordering::Relaxed) == State::ABORTED {
next = self.get_or_alloc_next(None, next);
}
// The copy already completed
if self.try_promote(table, &next, 0, guard) {
return next;
}
let copy_chunk = table.len().min(4096);
loop {
// Every entry has already been claimed.
if next.state().claim.load(Ordering::Relaxed) >= table.len() {
break;
}
// Claim a chunk to copy.
let copy_start = next.state().claim.fetch_add(copy_chunk, Ordering::Relaxed);
// Copy our chunk of entries.
let mut copied = 0;
for i in 0..copy_chunk {
let i = copy_start + i;
if i >= table.len() {
break;
}
// Copy the entry.
//
// Safety: We verified that `i` is in-bounds above.
if unsafe { !self.copy_at_blocking(i, table, &next, guard) } {
// This table doesn't have space for the next entry.
//
// Abort the current resize.
//
// Note that the `SeqCst` is necessary to make the store visible
// to threads that are unparked.
next.state().status.store(State::ABORTED, Ordering::SeqCst);
// Allocate the next table.
let allocated = self.get_or_alloc_next(None, next);
// Wake anyone waiting for us to finish.
let state = table.state();
state.parker.unpark(&state.status);
// Retry in a new table.
next = allocated;
continue 'copy;
}
copied += 1;
}
// Are we done?
if self.try_promote(table, &next, copied, guard) {
return next;
}
// If the resize was aborted while we were copying, continue in the new table.
if next.state().status.load(Ordering::Relaxed) == State::ABORTED {
continue 'copy;
}
}
let state = next.state();
// We copied all that we can, wait for the table to be promoted.
for spun in 0.. {
// Avoid spinning in tests, which can hide race conditions.
const SPIN_WAIT: usize = if cfg!(any(test, debug_assertions)) {
1
} else {
7
};
// Note that `Acquire` is necessary here to ensure we see the
// relevant modifications to the root table if see the updated
// state before parking.
//
// Otherwise, `Parker::park` will ensure the necessary synchronization
// when we are unparked.
let status = state.status.load(Ordering::Acquire);
// If this copy was aborted, we have to retry in the new table.
if status == State::ABORTED {
continue 'copy;
}
// The copy has completed.
if status == State::PROMOTED {
return next;
}
// Copy chunks are relatively small and we expect to finish quickly,
// so spin for a bit before resorting to parking.
if spun <= SPIN_WAIT {
for _ in 0..(spun * spun) {
hint::spin_loop();
}
continue;
}
// Park until the table is promoted.
state
.parker
.park(&state.status, |status| status == State::PENDING);
}
}
}
/// Copy the entry at the given index to the new table.
///
/// Returns `true` if the entry was copied into the table or `false` if the table was full.
///
/// # Safety
///
/// The index must be in-bounds for the table.
unsafe fn copy_at_blocking(
&self,
i: usize,
table: &Table<Entry<K, V>>,
next_table: &Table<Entry<K, V>>,
guard: &impl VerifiedGuard,
) -> bool {
// Mark the entry as copying.
//
// Safety: The caller guarantees that the index is in-bounds.
//
// Note that we don't need to protect the returned entry here, because
// no one is allowed to retire the entry once we put the `COPYING` bit
// down until it is inserted into the new table.
let entry = unsafe { table.entry(i) }
.fetch_or(Entry::COPYING, Ordering::AcqRel)
.unpack();
// The entry is a tombstone.
if entry.raw == Entry::TOMBSTONE {
return true;
}
// There is nothing to copy, we're done.
if entry.ptr.is_null() {
// Mark as a tombstone so readers avoid having to load the entry.
//
// Safety: The caller guarantees that the index is in-bounds.
unsafe { table.meta(i) }.store(meta::TOMBSTONE, Ordering::Release);
return true;
}
// Copy the value to the new table.
//
// Safety: We marked the entry as `COPYING`, ensuring that any updates
// or removals wait until we complete the copy, and allowing us to get
// away without a protected load. Additionally, we verified that the
// entry is non-null, meaning that it is valid for reads.
unsafe {
self.insert_copy(entry.ptr.unpack(), false, next_table, guard)
.is_some()
}
}
/// Help along an in-progress resize incrementally by copying a chunk of entries.
///
/// Returns the table that was copied to.
fn help_copy_incremental(
&self,
chunk: usize,
block: bool,
guard: &impl VerifiedGuard,
) -> Table<Entry<K, V>> {
// Always help the highest priority root resize.
let table = self.root(guard);
// Load the next table.
let Some(next) = table.next_table() else {
// The copy we tried to help was already promoted.
return table;
};
loop {
// The copy already completed.
if self.try_promote(&table, &next, 0, guard) {
return next;
}
loop {
// Every entry has already been claimed.
if next.state().claim.load(Ordering::Relaxed) >= table.len() {
break;
}
// Claim a chunk to copy.
let copy_start = next.state().claim.fetch_add(chunk, Ordering::Relaxed);
// Copy our chunk of entries.
let mut copied = 0;
for i in 0..chunk {
let i = copy_start + i;
if i >= table.len() {
break;
}
// Copy the entry.
//
// Safety: We verified that `i` is in-bounds above.
unsafe { self.copy_at_incremental(i, &table, &next, guard) };
copied += 1;
}
// Update the copy state, and try to promote the table.
//
// Only copy a single chunk if promotion fails, unless we are forced
// to complete the resize.
if self.try_promote(&table, &next, copied, guard) || !block {
return next;
}
}
// There are no entries that we can copy, block if necessary.
if !block {
return next;
}
let state = next.state();
for spun in 0.. {
// Avoid spinning in tests, which can hide race conditions.
const SPIN_WAIT: usize = if cfg!(any(test, debug_assertions)) {
1
} else {
7
};
// The copy has completed.
//
// Note that `Acquire` is necessary here to ensure we see the
// relevant modifications to the root table if see the updated
// state before parking.
//
// Otherwise, `Parker::park` will ensure the necessary synchronization
// when we are unparked.
let status = state.status.load(Ordering::Acquire);
if status == State::PROMOTED {
return next;
}
// Copy chunks are relatively small and we expect to finish quickly,
// so spin for a bit before resorting to parking.
if spun <= SPIN_WAIT {
for _ in 0..(spun * spun) {
hint::spin_loop();
}
continue;
}
// Park until the table is promoted.
state
.parker
.park(&state.status, |status| status == State::PENDING);
}
}
}
/// Copy the entry at the given index to the new table.
///
/// # Safety
///
/// The index must be in-bounds for the table.
unsafe fn copy_at_incremental(
&self,
i: usize,
table: &Table<Entry<K, V>>,
next_table: &Table<Entry<K, V>>,
guard: &impl VerifiedGuard,
) {
// Safety: The caller guarantees that the index is in-bounds.
let entry = unsafe { table.entry(i) };
// Mark the entry as copying.
let found = entry.fetch_or(Entry::COPYING, Ordering::AcqRel).unpack();
// The entry is a tombstone.
if found.raw == Entry::TOMBSTONE {
return;
}
// There is nothing to copy, we're done.
if found.ptr.is_null() {
// Mark as a tombstone so readers avoid having to load the entry.
//
// Safety: The caller guarantees that the index is in-bounds.
unsafe { table.meta(i) }.store(meta::TOMBSTONE, Ordering::Release);
return;
}
// Mark the entry as borrowed so writers in the new table know it was copied.
let new_entry = found.map_tag(|addr| addr | Entry::BORROWED);
// Copy the value to the new table.
//
// Safety: We marked the entry as `COPYING`, ensuring that any updates
// or removals wait until we complete the copy, and allowing us to get
// away without a protected load. Additionally, we verified that the
// entry is non-null, meaning that it is valid for reads.
unsafe {
self.insert_copy(new_entry, true, next_table, guard)
.unwrap();
}
// Mark the entry as copied.
let copied = found
.raw
.map_addr(|addr| addr | Entry::COPYING | Entry::COPIED);
// Note that we already wrote the COPYING bit, so no one is writing to the old
// entry except us.
//
// Note that the `SeqCst` is necessary to make the store visible to threads
// that are unparked.
entry.store(copied, Ordering::SeqCst);
// Notify any writers that the copy has completed.
table.state().parker.unpark(entry);
}
// Copy an entry into the table, returning the index it was inserted into.
//
// This is an optimized version of `insert_entry` where the caller is the only writer
// inserting the given key into the new table, as it has already been marked as copying.
//
// # Safety
//
// The new entry must be valid for reads.
unsafe fn insert_copy(
&self,
new_entry: Tagged<Entry<K, V>>,
resize: bool,
table: &Table<Entry<K, V>>,
guard: &impl VerifiedGuard,
) -> Option<(Table<Entry<K, V>>, usize)> {
// Safety: The new entry is guaranteed to be valid for reads.
let key = unsafe { &(*new_entry.ptr).key };
let mut table = *table;
let (h1, h2) = self.hash(key);
loop {
// Initialize the probe state.
let mut probe = Probe::start(h1, table.mask);
// Probe until we reach the limit.
while probe.len <= table.limit {
// Safety: `probe.i` is always in-bounds for the table length.
let meta_entry = unsafe { table.meta(probe.i) };
// Load the entry metadata first for cheap searches.
let meta = meta_entry.load(Ordering::Acquire);
// The entry is empty, try to insert.
if meta == meta::EMPTY {
// Safety: `probe.i` is always in-bounds for the table length.
let entry = unsafe { table.entry(probe.i) };
// Try to claim the entry.
match guard.compare_exchange(
entry,
ptr::null_mut(),
new_entry.raw,
Ordering::Release,
Ordering::Acquire,
) {
// Successfully inserted.
Ok(_) => {
// Update the metadata table.
meta_entry.store(h2, Ordering::Release);
return Some((table, probe.i));
}
Err(found) => {
let found = found.unpack();
// The entry was deleted or copied.
let meta = if found.ptr.is_null() {
meta::TOMBSTONE
} else {
// Safety: We performed a protected load of the pointer using a verified guard with
// `Acquire` and ensured that it is non-null, meaning it is valid for reads as long
// as we hold the guard.
let found_ref = unsafe { &(*found.ptr) };
// Ensure the meta table is updated to avoid breaking the probe chain.
let hash = self.hasher.hash_one(&found_ref.key);
meta::h2(hash)
};
if meta_entry.load(Ordering::Relaxed) == meta::EMPTY {
meta_entry.store(meta, Ordering::Release);
}
}
}
}
// Continue probing.
probe.next(table.mask);
}
if !resize {
return None;
}
// Insert into the next table.
table = self.get_or_alloc_next(None, table);
}
}
// Update the copy state and attempt to promote a table to the root.
//
// Returns `true` if the table was promoted.
fn try_promote(
&self,
table: &Table<Entry<K, V>>,
next: &Table<Entry<K, V>>,
copied: usize,
guard: &impl VerifiedGuard,
) -> bool {
let state = next.state();
// Update the copy count.
let copied = if copied > 0 {
state.copied.fetch_add(copied, Ordering::AcqRel) + copied
} else {
state.copied.load(Ordering::Acquire)
};
// If we copied all the entries in the table, we can try to promote.
if copied == table.len() {
let root = self.table.load(Ordering::Relaxed);
// Only promote root copies.
//
// We can't promote a nested copy before it's parent has finished, as
// it may not contain all the entries in the table.
if table.raw == root {
// Try to update the root.
if self
.table
.compare_exchange(table.raw, next.raw, Ordering::Release, Ordering::Acquire)
.is_ok()
{
// Successfully promoted the table.
//
// Note that the `SeqCst` is necessary to make the store visible to threads
// that are unparked.
state.status.store(State::PROMOTED, Ordering::SeqCst);
// Retire the old table.
//
// Safety: `table.raw` is a valid pointer to the table we just copied from.
// Additionally, the CAS above made the previous table unreachable from the
// root pointer, allowing it to be safely retired.
unsafe {
guard.defer_retire(table.raw, |table, collector| {
// Note that we do not drop entries because they have been copied to
// the new root.
drop_table(Table::from_raw(table), collector);
});
}
}
// Wake up any writers waiting for the resize to complete.
state.parker.unpark(&state.status);
return true;
}
}
// Not ready to promote yet.
false
}
// Completes all pending copies in incremental mode to get a clean copy of the table.
//
// This is necessary for operations like `iter` or `clear`, where entries in multiple tables
// can cause lead to incomplete results.
#[inline]
fn linearize(
&self,
mut table: Table<Entry<K, V>>,
guard: &impl VerifiedGuard,
) -> Table<Entry<K, V>> {
if self.is_incremental() {
// If we're in incremental resize mode, we need to complete any in-progress resizes to
// ensure we don't miss any entries in the next table. We can't iterate over both because
// we risk returning the same entry twice.
while table.next_table().is_some() {
table = self.help_copy(true, &table, guard);
}
}
table
}
// Wait for an incremental copy of a given entry to complete.
#[cold]
#[inline(never)]
fn wait_copied(&self, i: usize, table: &Table<Entry<K, V>>) {
// Avoid spinning in tests, which can hide race conditions.
const SPIN_WAIT: usize = if cfg!(any(test, debug_assertions)) {
1
} else {
5
};
let entry = unsafe { table.entry(i) };
// Spin for a short while, waiting for the entry to be copied.
for spun in 0..SPIN_WAIT {
// The entry was copied.
let entry = entry.load(Ordering::Acquire).unpack();
if entry.tag() & Entry::COPIED != 0 {
return;
}
for _ in 0..(spun * spun) {
hint::spin_loop();
}
}
// Park until the copy completes.
let parker = &table.state().parker;
parker.park(entry, |entry| entry.addr() & Entry::COPIED == 0);
}
/// Retire an entry that was removed from the current table, but may still be reachable from
/// previous tables.
///
/// # Safety
///
/// The entry must be a valid pointer that is unreachable from the current table. Additionally,
/// it is *undefined behavior* to call this method multiple times for the same entry.
#[inline]
unsafe fn defer_retire(
&self,
entry: Tagged<Entry<K, V>>,
table: &Table<Entry<K, V>>,
guard: &impl VerifiedGuard,
) {
match self.resize {
// Safety: In blocking resize mode, we only ever write to the root table, so the entry
// is inaccessible from all tables.
ResizeMode::Blocking => unsafe {
guard.defer_retire(entry.ptr, seize::reclaim::boxed);
},
// In incremental resize mode, the entry may be accessible in previous tables.
ResizeMode::Incremental(_) => {
if entry.tag() & Entry::BORROWED == 0 {
// Safety: If the entry is not borrowed, meaning it is not in any previous tables,
// it is inaccessible even if the current table is not root. Thus we can safely retire.
unsafe { guard.defer_retire(entry.ptr, seize::reclaim::boxed) };
return;
}
let root = self.root(guard);
// Check if our table, or any subsequent table, is the root.
let mut next = Some(*table);
while let Some(table) = next {
if table.raw == root.raw {
// Safety: The root table is our table or a table that succeeds ours.
// Thus any previous tables are unreachable from the root, so we can safely retire.
unsafe { guard.defer_retire(entry.ptr, seize::reclaim::boxed) };
return;
}
next = table.next_table();
}
// Otherwise, we have to wait for the table we are copying from to be reclaimed.
//
// Find the table we are copying from, searching from the root.
let mut prev = root;
loop {
let next = prev.next_table().unwrap();
// Defer the entry to be retired by the table we are copying from.
if next.raw == table.raw {
prev.state().deferred.push(entry.ptr);
return;
}
prev = next;
}
}
}
}
}
// An iterator over the keys and values of this table.
pub struct Iter<'g, K, V, G> {
i: usize,
table: Table<Entry<K, V>>,
guard: &'g G,
}
impl<'g, K: 'g, V: 'g, G> Iterator for Iter<'g, K, V, G>
where
G: VerifiedGuard,
{
type Item = (&'g K, &'g V);
#[inline]
fn next(&mut self) -> Option<Self::Item> {
// The table has not yet been allocated.
if self.table.raw.is_null() {
return None;
}
loop {
// Iterated over every entry in the table, we're done.
if self.i >= self.table.len() {
return None;
}
// Load the entry metadata first to ensure consistency with calls to `get`.
//
// Safety: We verified that `self.i` is in-bounds above.
let meta = unsafe { self.table.meta(self.i) }.load(Ordering::Acquire);
// The entry is empty or deleted.
if matches!(meta, meta::EMPTY | meta::TOMBSTONE) {
self.i += 1;
continue;
}
// Load the entry.
//
// Safety: We verified that `self.i` is in-bounds above.
let entry = self
.guard
.protect(unsafe { self.table.entry(self.i) }, Ordering::Acquire)
.unpack();
// The entry was deleted.
if entry.ptr.is_null() {
self.i += 1;
continue;
}
// Safety: We performed a protected load of the pointer using a verified guard with
// `Acquire` and ensured that it is non-null, meaning it is valid for reads as long
// as we hold the guard.
let entry_ref = unsafe { &(*entry.ptr) };
self.i += 1;
return Some((&entry_ref.key, &entry_ref.value));
}
}
}
// Safety: An iterator holds a shared reference to the HashMap
// and Guard, and outputs shared references to keys and values.
// Thus everything must be `Sync` for the iterator to be `Send`
// or `Sync`.
//
// It is not possible to obtain an owned key, value, or guard
// from an iterator, so `Send` is not a required bound.
unsafe impl<K, V, G> Send for Iter<'_, K, V, G>
where
K: Sync,
V: Sync,
G: Sync,
{
}
unsafe impl<K, V, G> Sync for Iter<'_, K, V, G>
where
K: Sync,
V: Sync,
G: Sync,
{
}
impl<K, V, G> Clone for Iter<'_, K, V, G> {
#[inline]
fn clone(&self) -> Self {
Iter {
i: self.i,
table: self.table,
guard: self.guard,
}
}
}
impl<K, V, S> Drop for HashMap<K, V, S> {
fn drop(&mut self) {
let mut raw = *self.table.get_mut();
// Make sure all objects are reclaimed before the collector is dropped.
//
// Dropping a table depends on accessing the collector for deferred retirement,
// using the shared collector pointer that is invalidated by drop.
//
// Safety: We have a unique reference to the collector.
unsafe { self.collector.reclaim_all() };
// Drop all nested tables and entries.
while !raw.is_null() {
// Safety: The root and next tables are always valid pointers to a
// table allocation, or null.
let mut table = unsafe { Table::from_raw(raw) };
// Read the next table pointer before dropping the current one.
let next = *table.state_mut().next.get_mut();
// Safety: We have unique access to the table and do
// not access the entries after this call.
unsafe { drop_entries(table) };
// Safety: We have unique access to the table and do
// not access it after this call.
unsafe { drop_table(table, &self.collector) };
// Continue for all nested tables.
raw = next;
}
}
}
// Drop all entries in this table.
//
// # Safety
//
// The table entries must not be accessed after this call.
unsafe fn drop_entries<K, V>(table: Table<Entry<K, V>>) {
for i in 0..table.len() {
// Safety: `i` is in-bounds and we have unique access to the table.
let entry = unsafe { (*table.entry(i).as_ptr()).unpack() };
// The entry was copied, or there is nothing to deallocate.
if entry.ptr.is_null() || entry.tag() & Entry::COPYING != 0 {
continue;
}
// Drop the entry.
//
// Safety: We verified that the table is non-null and will
// not be accessed after this call. Additionally, we ensured
// that the entry is not copied to avoid double freeing entries
// that may exist in multiple tables.
unsafe { drop(Box::from_raw(entry.ptr)) }
}
}
// Drop the table allocation.
//
// # Safety
//
// The table must not be accessed after this call.
unsafe fn drop_table<K, V>(mut table: Table<Entry<K, V>>, collector: &Collector) {
// Drop any entries that were deferred during an incremental resize.
//
// Safety: Entries are deferred after they are made unreachable from the
// next table during a resize from this table. This table must have been accessible
// from the root for any entry to have been deferred. Thus it is being retired now,
// *after* the entry was made inaccessible from the next table. Additionally, for
// this table to have been retired, it also must no longer be accessible from the root,
// meaning that the entry has been totally removed from the map, and can be safely
// retired.
table
.state_mut()
.deferred
.drain(|entry| unsafe { collector.retire(entry, seize::reclaim::boxed) });
// Deallocate the table.
//
// Safety: The caller guarantees that the table will not be accessed after this call.
unsafe { Table::dealloc(table) };
}
// Entry metadata, inspired by `hashbrown`.
mod meta {
use std::mem;
// Indicates an empty entry.
pub const EMPTY: u8 = 0x80;
// Indicates an entry that has been deleted.
pub const TOMBSTONE: u8 = u8::MAX;
// Returns the primary hash for an entry.
#[inline]
pub fn h1(hash: u64) -> usize {
hash as usize
}
/// Return a byte of hash metadata, used for cheap searches.
#[inline]
pub fn h2(hash: u64) -> u8 {
const MIN_HASH_LEN: usize = if mem::size_of::<usize>() < mem::size_of::<u64>() {
mem::size_of::<usize>()
} else {
mem::size_of::<u64>()
};
// Grab the top 7 bits of the hash.
//
// While the hash is normally a full 64-bit value, some hash functions
// (such as fxhash) produce a usize result instead, which means that the
// top 32 bits are 0 on 32-bit platforms.
let top7 = hash >> (MIN_HASH_LEN * 8 - 7);
(top7 & 0x7f) as u8
}
}