summaryrefslogtreecommitdiffstats
path: root/mfbt/HashTable.h
blob: 9f3f42b40ec79ae00d4d38c613801204320d01f4 (plain)
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
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=8 sts=2 et sw=2 tw=80: */
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

//---------------------------------------------------------------------------
// Overview
//---------------------------------------------------------------------------
//
// This file defines HashMap<Key, Value> and HashSet<T>, hash tables that are
// fast and have a nice API.
//
// Both hash tables have two optional template parameters.
//
// - HashPolicy. This defines the operations for hashing and matching keys. The
//   default HashPolicy is appropriate when both of the following two
//   conditions are true.
//
//   - The key type stored in the table (|Key| for |HashMap<Key, Value>|, |T|
//     for |HashSet<T>|) is an integer, pointer, UniquePtr, float, or double.
//
//   - The type used for lookups (|Lookup|) is the same as the key type. This
//     is usually the case, but not always.
//
//   There is also a |CStringHasher| policy for |char*| keys. If your keys
//   don't match any of the above cases, you must provide your own hash policy;
//   see the "Hash Policy" section below.
//
// - AllocPolicy. This defines how allocations are done by the table.
//
//   - |MallocAllocPolicy| is the default and is usually appropriate; note that
//     operations (such as insertions) that might cause allocations are
//     fallible and must be checked for OOM. These checks are enforced by the
//     use of [[nodiscard]].
//
//   - |InfallibleAllocPolicy| is another possibility; it allows the
//     abovementioned OOM checks to be done with MOZ_ALWAYS_TRUE().
//
//   Note that entry storage allocation is lazy, and not done until the first
//   lookupForAdd(), put(), or putNew() is performed.
//
//  See AllocPolicy.h for more details.
//
// Documentation on how to use HashMap and HashSet, including examples, is
// present within those classes. Search for "class HashMap" and "class
// HashSet".
//
// Both HashMap and HashSet are implemented on top of a third class, HashTable.
// You only need to look at HashTable if you want to understand the
// implementation.
//
// How does mozilla::HashTable (this file) compare with PLDHashTable (and its
// subclasses, such as nsTHashtable)?
//
// - mozilla::HashTable is a lot faster, largely because it uses templates
//   throughout *and* inlines everything. PLDHashTable inlines operations much
//   less aggressively, and also uses "virtual ops" for operations like hashing
//   and matching entries that require function calls.
//
// - Correspondingly, mozilla::HashTable use is likely to increase executable
//   size much more than PLDHashTable.
//
// - mozilla::HashTable has a nicer API, with a proper HashSet vs. HashMap
//   distinction.
//
// - mozilla::HashTable requires more explicit OOM checking. As mentioned
//   above, the use of |InfallibleAllocPolicy| can simplify things.
//
// - mozilla::HashTable has a default capacity on creation of 32 and a minimum
//   capacity of 4. PLDHashTable has a default capacity on creation of 8 and a
//   minimum capacity of 8.

#ifndef mozilla_HashTable_h
#define mozilla_HashTable_h

#include <utility>
#include <type_traits>

#include "mozilla/AllocPolicy.h"
#include "mozilla/Assertions.h"
#include "mozilla/Attributes.h"
#include "mozilla/Casting.h"
#include "mozilla/HashFunctions.h"
#include "mozilla/MathAlgorithms.h"
#include "mozilla/Maybe.h"
#include "mozilla/MemoryChecking.h"
#include "mozilla/MemoryReporting.h"
#include "mozilla/Opaque.h"
#include "mozilla/OperatorNewExtensions.h"
#include "mozilla/ReentrancyGuard.h"
#include "mozilla/UniquePtr.h"
#include "mozilla/WrappingOperations.h"

namespace mozilla {

template <class, class = void>
struct DefaultHasher;

template <class, class>
class HashMapEntry;

namespace detail {

template <typename T>
class HashTableEntry;

template <class T, class HashPolicy, class AllocPolicy>
class HashTable;

}  // namespace detail

// The "generation" of a hash table is an opaque value indicating the state of
// modification of the hash table through its lifetime.  If the generation of
// a hash table compares equal at times T1 and T2, then lookups in the hash
// table, pointers to (or into) hash table entries, etc. at time T1 are valid
// at time T2.  If the generation compares unequal, these computations are all
// invalid and must be performed again to be used.
//
// Generations are meaningfully comparable only with respect to a single hash
// table.  It's always nonsensical to compare the generation of distinct hash
// tables H1 and H2.
using Generation = Opaque<uint64_t>;

//---------------------------------------------------------------------------
// HashMap
//---------------------------------------------------------------------------

// HashMap is a fast hash-based map from keys to values.
//
// Template parameter requirements:
// - Key/Value: movable, destructible, assignable.
// - HashPolicy: see the "Hash Policy" section below.
// - AllocPolicy: see AllocPolicy.h.
//
// Note:
// - HashMap is not reentrant: Key/Value/HashPolicy/AllocPolicy members
//   called by HashMap must not call back into the same HashMap object.
//
template <class Key, class Value, class HashPolicy = DefaultHasher<Key>,
          class AllocPolicy = MallocAllocPolicy>
class HashMap {
  // -- Implementation details -----------------------------------------------

  // HashMap is not copyable or assignable.
  HashMap(const HashMap& hm) = delete;
  HashMap& operator=(const HashMap& hm) = delete;

  using TableEntry = HashMapEntry<Key, Value>;

  struct MapHashPolicy : HashPolicy {
    using Base = HashPolicy;
    using KeyType = Key;

    static const Key& getKey(TableEntry& aEntry) { return aEntry.key(); }

    static void setKey(TableEntry& aEntry, Key& aKey) {
      HashPolicy::rekey(aEntry.mutableKey(), aKey);
    }
  };

  using Impl = detail::HashTable<TableEntry, MapHashPolicy, AllocPolicy>;
  Impl mImpl;

  friend class Impl::Enum;

 public:
  using Lookup = typename HashPolicy::Lookup;
  using Entry = TableEntry;

  // -- Initialization -------------------------------------------------------

  explicit HashMap(AllocPolicy aAllocPolicy = AllocPolicy(),
                   uint32_t aLen = Impl::sDefaultLen)
      : mImpl(std::move(aAllocPolicy), aLen) {}

  explicit HashMap(uint32_t aLen) : mImpl(AllocPolicy(), aLen) {}

  // HashMap is movable.
  HashMap(HashMap&& aRhs) = default;
  HashMap& operator=(HashMap&& aRhs) = default;

  // -- Status and sizing ----------------------------------------------------

  // The map's current generation.
  Generation generation() const { return mImpl.generation(); }

  // Is the map empty?
  bool empty() const { return mImpl.empty(); }

  // Number of keys/values in the map.
  uint32_t count() const { return mImpl.count(); }

  // Number of key/value slots in the map. Note: resize will happen well before
  // count() == capacity().
  uint32_t capacity() const { return mImpl.capacity(); }

  // The size of the map's entry storage, in bytes. If the keys/values contain
  // pointers to other heap blocks, you must iterate over the map and measure
  // them separately; hence the "shallow" prefix.
  size_t shallowSizeOfExcludingThis(MallocSizeOf aMallocSizeOf) const {
    return mImpl.shallowSizeOfExcludingThis(aMallocSizeOf);
  }
  size_t shallowSizeOfIncludingThis(MallocSizeOf aMallocSizeOf) const {
    return aMallocSizeOf(this) +
           mImpl.shallowSizeOfExcludingThis(aMallocSizeOf);
  }

  // Attempt to minimize the capacity(). If the table is empty, this will free
  // the empty storage and upon regrowth it will be given the minimum capacity.
  void compact() { mImpl.compact(); }

  // Attempt to reserve enough space to fit at least |aLen| elements. This is
  // total capacity, including elements already present. Does nothing if the
  // map already has sufficient capacity.
  [[nodiscard]] bool reserve(uint32_t aLen) { return mImpl.reserve(aLen); }

  // -- Lookups --------------------------------------------------------------

  // Does the map contain a key/value matching |aLookup|?
  bool has(const Lookup& aLookup) const {
    return mImpl.lookup(aLookup).found();
  }

  // Return a Ptr indicating whether a key/value matching |aLookup| is
  // present in the map. E.g.:
  //
  //   using HM = HashMap<int,char>;
  //   HM h;
  //   if (HM::Ptr p = h.lookup(3)) {
  //     assert(p->key() == 3);
  //     char val = p->value();
  //   }
  //
  using Ptr = typename Impl::Ptr;
  MOZ_ALWAYS_INLINE Ptr lookup(const Lookup& aLookup) const {
    return mImpl.lookup(aLookup);
  }

  // Like lookup(), but does not assert if two threads call it at the same
  // time. Only use this method when none of the threads will modify the map.
  MOZ_ALWAYS_INLINE Ptr readonlyThreadsafeLookup(const Lookup& aLookup) const {
    return mImpl.readonlyThreadsafeLookup(aLookup);
  }

  // -- Insertions -----------------------------------------------------------

  // Overwrite existing value with |aValue|, or add it if not present. Returns
  // false on OOM.
  template <typename KeyInput, typename ValueInput>
  [[nodiscard]] bool put(KeyInput&& aKey, ValueInput&& aValue) {
    return put(aKey, std::forward<KeyInput>(aKey),
               std::forward<ValueInput>(aValue));
  }

  template <typename KeyInput, typename ValueInput>
  [[nodiscard]] bool put(const Lookup& aLookup, KeyInput&& aKey,
                         ValueInput&& aValue) {
    AddPtr p = lookupForAdd(aLookup);
    if (p) {
      p->value() = std::forward<ValueInput>(aValue);
      return true;
    }
    return add(p, std::forward<KeyInput>(aKey),
               std::forward<ValueInput>(aValue));
  }

  // Like put(), but slightly faster. Must only be used when the given key is
  // not already present. (In debug builds, assertions check this.)
  template <typename KeyInput, typename ValueInput>
  [[nodiscard]] bool putNew(KeyInput&& aKey, ValueInput&& aValue) {
    return mImpl.putNew(aKey, std::forward<KeyInput>(aKey),
                        std::forward<ValueInput>(aValue));
  }

  template <typename KeyInput, typename ValueInput>
  [[nodiscard]] bool putNew(const Lookup& aLookup, KeyInput&& aKey,
                            ValueInput&& aValue) {
    return mImpl.putNew(aLookup, std::forward<KeyInput>(aKey),
                        std::forward<ValueInput>(aValue));
  }

  // Like putNew(), but should be only used when the table is known to be big
  // enough for the insertion, and hashing cannot fail. Typically this is used
  // to populate an empty map with known-unique keys after reserving space with
  // reserve(), e.g.
  //
  //   using HM = HashMap<int,char>;
  //   HM h;
  //   if (!h.reserve(3)) {
  //     MOZ_CRASH("OOM");
  //   }
  //   h.putNewInfallible(1, 'a');    // unique key
  //   h.putNewInfallible(2, 'b');    // unique key
  //   h.putNewInfallible(3, 'c');    // unique key
  //
  template <typename KeyInput, typename ValueInput>
  void putNewInfallible(KeyInput&& aKey, ValueInput&& aValue) {
    mImpl.putNewInfallible(aKey, std::forward<KeyInput>(aKey),
                           std::forward<ValueInput>(aValue));
  }

  // Like |lookup(l)|, but on miss, |p = lookupForAdd(l)| allows efficient
  // insertion of Key |k| (where |HashPolicy::match(k,l) == true|) using
  // |add(p,k,v)|. After |add(p,k,v)|, |p| points to the new key/value. E.g.:
  //
  //   using HM = HashMap<int,char>;
  //   HM h;
  //   HM::AddPtr p = h.lookupForAdd(3);
  //   if (!p) {
  //     if (!h.add(p, 3, 'a')) {
  //       return false;
  //     }
  //   }
  //   assert(p->key() == 3);
  //   char val = p->value();
  //
  // N.B. The caller must ensure that no mutating hash table operations occur
  // between a pair of lookupForAdd() and add() calls. To avoid looking up the
  // key a second time, the caller may use the more efficient relookupOrAdd()
  // method. This method reuses part of the hashing computation to more
  // efficiently insert the key if it has not been added. For example, a
  // mutation-handling version of the previous example:
  //
  //    HM::AddPtr p = h.lookupForAdd(3);
  //    if (!p) {
  //      call_that_may_mutate_h();
  //      if (!h.relookupOrAdd(p, 3, 'a')) {
  //        return false;
  //      }
  //    }
  //    assert(p->key() == 3);
  //    char val = p->value();
  //
  using AddPtr = typename Impl::AddPtr;
  MOZ_ALWAYS_INLINE AddPtr lookupForAdd(const Lookup& aLookup) {
    return mImpl.lookupForAdd(aLookup);
  }

  // Add a key/value. Returns false on OOM.
  template <typename KeyInput, typename ValueInput>
  [[nodiscard]] bool add(AddPtr& aPtr, KeyInput&& aKey, ValueInput&& aValue) {
    return mImpl.add(aPtr, std::forward<KeyInput>(aKey),
                     std::forward<ValueInput>(aValue));
  }

  // See the comment above lookupForAdd() for details.
  template <typename KeyInput, typename ValueInput>
  [[nodiscard]] bool relookupOrAdd(AddPtr& aPtr, KeyInput&& aKey,
                                   ValueInput&& aValue) {
    return mImpl.relookupOrAdd(aPtr, aKey, std::forward<KeyInput>(aKey),
                               std::forward<ValueInput>(aValue));
  }

  // -- Removal --------------------------------------------------------------

  // Lookup and remove the key/value matching |aLookup|, if present.
  void remove(const Lookup& aLookup) {
    if (Ptr p = lookup(aLookup)) {
      remove(p);
    }
  }

  // Remove a previously found key/value (assuming aPtr.found()). The map must
  // not have been mutated in the interim.
  void remove(Ptr aPtr) { mImpl.remove(aPtr); }

  // Remove all keys/values without changing the capacity.
  void clear() { mImpl.clear(); }

  // Like clear() followed by compact().
  void clearAndCompact() { mImpl.clearAndCompact(); }

  // -- Rekeying -------------------------------------------------------------

  // Infallibly rekey one entry, if necessary. Requires that template
  // parameters Key and HashPolicy::Lookup are the same type.
  void rekeyIfMoved(const Key& aOldKey, const Key& aNewKey) {
    if (aOldKey != aNewKey) {
      rekeyAs(aOldKey, aNewKey, aNewKey);
    }
  }

  // Infallibly rekey one entry if present, and return whether that happened.
  bool rekeyAs(const Lookup& aOldLookup, const Lookup& aNewLookup,
               const Key& aNewKey) {
    if (Ptr p = lookup(aOldLookup)) {
      mImpl.rekeyAndMaybeRehash(p, aNewLookup, aNewKey);
      return true;
    }
    return false;
  }

  // -- Iteration ------------------------------------------------------------

  // |iter()| returns an Iterator:
  //
  //   HashMap<int, char> h;
  //   for (auto iter = h.iter(); !iter.done(); iter.next()) {
  //     char c = iter.get().value();
  //   }
  //
  using Iterator = typename Impl::Iterator;
  Iterator iter() const { return mImpl.iter(); }

  // |modIter()| returns a ModIterator:
  //
  //   HashMap<int, char> h;
  //   for (auto iter = h.modIter(); !iter.done(); iter.next()) {
  //     if (iter.get().value() == 'l') {
  //       iter.remove();
  //     }
  //   }
  //
  // Table resize may occur in ModIterator's destructor.
  using ModIterator = typename Impl::ModIterator;
  ModIterator modIter() { return mImpl.modIter(); }

  // These are similar to Iterator/ModIterator/iter(), but use different
  // terminology.
  using Range = typename Impl::Range;
  using Enum = typename Impl::Enum;
  Range all() const { return mImpl.all(); }
};

//---------------------------------------------------------------------------
// HashSet
//---------------------------------------------------------------------------

// HashSet is a fast hash-based set of values.
//
// Template parameter requirements:
// - T: movable, destructible, assignable.
// - HashPolicy: see the "Hash Policy" section below.
// - AllocPolicy: see AllocPolicy.h
//
// Note:
// - HashSet is not reentrant: T/HashPolicy/AllocPolicy members called by
//   HashSet must not call back into the same HashSet object.
//
template <class T, class HashPolicy = DefaultHasher<T>,
          class AllocPolicy = MallocAllocPolicy>
class HashSet {
  // -- Implementation details -----------------------------------------------

  // HashSet is not copyable or assignable.
  HashSet(const HashSet& hs) = delete;
  HashSet& operator=(const HashSet& hs) = delete;

  struct SetHashPolicy : HashPolicy {
    using Base = HashPolicy;
    using KeyType = T;

    static const KeyType& getKey(const T& aT) { return aT; }

    static void setKey(T& aT, KeyType& aKey) { HashPolicy::rekey(aT, aKey); }
  };

  using Impl = detail::HashTable<const T, SetHashPolicy, AllocPolicy>;
  Impl mImpl;

  friend class Impl::Enum;

 public:
  using Lookup = typename HashPolicy::Lookup;
  using Entry = T;

  // -- Initialization -------------------------------------------------------

  explicit HashSet(AllocPolicy aAllocPolicy = AllocPolicy(),
                   uint32_t aLen = Impl::sDefaultLen)
      : mImpl(std::move(aAllocPolicy), aLen) {}

  explicit HashSet(uint32_t aLen) : mImpl(AllocPolicy(), aLen) {}

  // HashSet is movable.
  HashSet(HashSet&& aRhs) = default;
  HashSet& operator=(HashSet&& aRhs) = default;

  // -- Status and sizing ----------------------------------------------------

  // The set's current generation.
  Generation generation() const { return mImpl.generation(); }

  // Is the set empty?
  bool empty() const { return mImpl.empty(); }

  // Number of elements in the set.
  uint32_t count() const { return mImpl.count(); }

  // Number of element slots in the set. Note: resize will happen well before
  // count() == capacity().
  uint32_t capacity() const { return mImpl.capacity(); }

  // The size of the set's entry storage, in bytes. If the elements contain
  // pointers to other heap blocks, you must iterate over the set and measure
  // them separately; hence the "shallow" prefix.
  size_t shallowSizeOfExcludingThis(MallocSizeOf aMallocSizeOf) const {
    return mImpl.shallowSizeOfExcludingThis(aMallocSizeOf);
  }
  size_t shallowSizeOfIncludingThis(MallocSizeOf aMallocSizeOf) const {
    return aMallocSizeOf(this) +
           mImpl.shallowSizeOfExcludingThis(aMallocSizeOf);
  }

  // Attempt to minimize the capacity(). If the table is empty, this will free
  // the empty storage and upon regrowth it will be given the minimum capacity.
  void compact() { mImpl.compact(); }

  // Attempt to reserve enough space to fit at least |aLen| elements. This is
  // total capacity, including elements already present. Does nothing if the
  // map already has sufficient capacity.
  [[nodiscard]] bool reserve(uint32_t aLen) { return mImpl.reserve(aLen); }

  // -- Lookups --------------------------------------------------------------

  // Does the set contain an element matching |aLookup|?
  bool has(const Lookup& aLookup) const {
    return mImpl.lookup(aLookup).found();
  }

  // Return a Ptr indicating whether an element matching |aLookup| is present
  // in the set. E.g.:
  //
  //   using HS = HashSet<int>;
  //   HS h;
  //   if (HS::Ptr p = h.lookup(3)) {
  //     assert(*p == 3);   // p acts like a pointer to int
  //   }
  //
  using Ptr = typename Impl::Ptr;
  MOZ_ALWAYS_INLINE Ptr lookup(const Lookup& aLookup) const {
    return mImpl.lookup(aLookup);
  }

  // Like lookup(), but does not assert if two threads call it at the same
  // time. Only use this method when none of the threads will modify the set.
  MOZ_ALWAYS_INLINE Ptr readonlyThreadsafeLookup(const Lookup& aLookup) const {
    return mImpl.readonlyThreadsafeLookup(aLookup);
  }

  // -- Insertions -----------------------------------------------------------

  // Add |aU| if it is not present already. Returns false on OOM.
  template <typename U>
  [[nodiscard]] bool put(U&& aU) {
    AddPtr p = lookupForAdd(aU);
    return p ? true : add(p, std::forward<U>(aU));
  }

  // Like put(), but slightly faster. Must only be used when the given element
  // is not already present. (In debug builds, assertions check this.)
  template <typename U>
  [[nodiscard]] bool putNew(U&& aU) {
    return mImpl.putNew(aU, std::forward<U>(aU));
  }

  // Like the other putNew(), but for when |Lookup| is different to |T|.
  template <typename U>
  [[nodiscard]] bool putNew(const Lookup& aLookup, U&& aU) {
    return mImpl.putNew(aLookup, std::forward<U>(aU));
  }

  // Like putNew(), but should be only used when the table is known to be big
  // enough for the insertion, and hashing cannot fail. Typically this is used
  // to populate an empty set with known-unique elements after reserving space
  // with reserve(), e.g.
  //
  //   using HS = HashMap<int>;
  //   HS h;
  //   if (!h.reserve(3)) {
  //     MOZ_CRASH("OOM");
  //   }
  //   h.putNewInfallible(1);     // unique element
  //   h.putNewInfallible(2);     // unique element
  //   h.putNewInfallible(3);     // unique element
  //
  template <typename U>
  void putNewInfallible(const Lookup& aLookup, U&& aU) {
    mImpl.putNewInfallible(aLookup, std::forward<U>(aU));
  }

  // Like |lookup(l)|, but on miss, |p = lookupForAdd(l)| allows efficient
  // insertion of T value |t| (where |HashPolicy::match(t,l) == true|) using
  // |add(p,t)|. After |add(p,t)|, |p| points to the new element. E.g.:
  //
  //   using HS = HashSet<int>;
  //   HS h;
  //   HS::AddPtr p = h.lookupForAdd(3);
  //   if (!p) {
  //     if (!h.add(p, 3)) {
  //       return false;
  //     }
  //   }
  //   assert(*p == 3);   // p acts like a pointer to int
  //
  // N.B. The caller must ensure that no mutating hash table operations occur
  // between a pair of lookupForAdd() and add() calls. To avoid looking up the
  // key a second time, the caller may use the more efficient relookupOrAdd()
  // method. This method reuses part of the hashing computation to more
  // efficiently insert the key if it has not been added. For example, a
  // mutation-handling version of the previous example:
  //
  //    HS::AddPtr p = h.lookupForAdd(3);
  //    if (!p) {
  //      call_that_may_mutate_h();
  //      if (!h.relookupOrAdd(p, 3, 3)) {
  //        return false;
  //      }
  //    }
  //    assert(*p == 3);
  //
  // Note that relookupOrAdd(p,l,t) performs Lookup using |l| and adds the
  // entry |t|, where the caller ensures match(l,t).
  using AddPtr = typename Impl::AddPtr;
  MOZ_ALWAYS_INLINE AddPtr lookupForAdd(const Lookup& aLookup) {
    return mImpl.lookupForAdd(aLookup);
  }

  // Add an element. Returns false on OOM.
  template <typename U>
  [[nodiscard]] bool add(AddPtr& aPtr, U&& aU) {
    return mImpl.add(aPtr, std::forward<U>(aU));
  }

  // See the comment above lookupForAdd() for details.
  template <typename U>
  [[nodiscard]] bool relookupOrAdd(AddPtr& aPtr, const Lookup& aLookup,
                                   U&& aU) {
    return mImpl.relookupOrAdd(aPtr, aLookup, std::forward<U>(aU));
  }

  // -- Removal --------------------------------------------------------------

  // Lookup and remove the element matching |aLookup|, if present.
  void remove(const Lookup& aLookup) {
    if (Ptr p = lookup(aLookup)) {
      remove(p);
    }
  }

  // Remove a previously found element (assuming aPtr.found()). The set must
  // not have been mutated in the interim.
  void remove(Ptr aPtr) { mImpl.remove(aPtr); }

  // Remove all keys/values without changing the capacity.
  void clear() { mImpl.clear(); }

  // Like clear() followed by compact().
  void clearAndCompact() { mImpl.clearAndCompact(); }

  // -- Rekeying -------------------------------------------------------------

  // Infallibly rekey one entry, if present. Requires that template parameters
  // T and HashPolicy::Lookup are the same type.
  void rekeyIfMoved(const Lookup& aOldValue, const T& aNewValue) {
    if (aOldValue != aNewValue) {
      rekeyAs(aOldValue, aNewValue, aNewValue);
    }
  }

  // Infallibly rekey one entry if present, and return whether that happened.
  bool rekeyAs(const Lookup& aOldLookup, const Lookup& aNewLookup,
               const T& aNewValue) {
    if (Ptr p = lookup(aOldLookup)) {
      mImpl.rekeyAndMaybeRehash(p, aNewLookup, aNewValue);
      return true;
    }
    return false;
  }

  // Infallibly replace the current key at |aPtr| with an equivalent key.
  // Specifically, both HashPolicy::hash and HashPolicy::match must return
  // identical results for the new and old key when applied against all
  // possible matching values.
  void replaceKey(Ptr aPtr, const Lookup& aLookup, const T& aNewValue) {
    MOZ_ASSERT(aPtr.found());
    MOZ_ASSERT(*aPtr != aNewValue);
    MOZ_ASSERT(HashPolicy::match(*aPtr, aLookup));
    MOZ_ASSERT(HashPolicy::match(aNewValue, aLookup));
    const_cast<T&>(*aPtr) = aNewValue;
    MOZ_ASSERT(*lookup(aLookup) == aNewValue);
  }
  void replaceKey(Ptr aPtr, const T& aNewValue) {
    replaceKey(aPtr, aNewValue, aNewValue);
  }

  // -- Iteration ------------------------------------------------------------

  // |iter()| returns an Iterator:
  //
  //   HashSet<int> h;
  //   for (auto iter = h.iter(); !iter.done(); iter.next()) {
  //     int i = iter.get();
  //   }
  //
  using Iterator = typename Impl::Iterator;
  Iterator iter() const { return mImpl.iter(); }

  // |modIter()| returns a ModIterator:
  //
  //   HashSet<int> h;
  //   for (auto iter = h.modIter(); !iter.done(); iter.next()) {
  //     if (iter.get() == 42) {
  //       iter.remove();
  //     }
  //   }
  //
  // Table resize may occur in ModIterator's destructor.
  using ModIterator = typename Impl::ModIterator;
  ModIterator modIter() { return mImpl.modIter(); }

  // These are similar to Iterator/ModIterator/iter(), but use different
  // terminology.
  using Range = typename Impl::Range;
  using Enum = typename Impl::Enum;
  Range all() const { return mImpl.all(); }
};

//---------------------------------------------------------------------------
// Hash Policy
//---------------------------------------------------------------------------

// A hash policy |HP| for a hash table with key-type |Key| must provide:
//
//  - a type |HP::Lookup| to use to lookup table entries;
//
//  - a static member function |HP::hash| that hashes lookup values:
//
//      static mozilla::HashNumber hash(const Lookup&);
//
//  - a static member function |HP::match| that tests equality of key and
//    lookup values:
//
//      static bool match(const Key& aKey, const Lookup& aLookup);
//
//    |aKey| and |aLookup| can have different hash numbers, only when a
//    collision happens with |prepareHash| operation, which is less frequent.
//    Thus, |HP::match| shouldn't assume the hash equality in the comparison,
//    even if the hash numbers are almost always same between them.
//
// Normally, Lookup = Key. In general, though, different values and types of
// values can be used to lookup and store. If a Lookup value |l| is not equal
// to the added Key value |k|, the user must ensure that |HP::match(k,l)| is
// true. E.g.:
//
//   mozilla::HashSet<Key, HP>::AddPtr p = h.lookup(l);
//   if (!p) {
//     assert(HP::match(k, l));  // must hold
//     h.add(p, k);
//   }

// A pointer hashing policy that uses HashGeneric() to create good hashes for
// pointers. Note that we don't shift out the lowest k bits because we don't
// want to assume anything about the alignment of the pointers.
template <typename Key>
struct PointerHasher {
  using Lookup = Key;

  static HashNumber hash(const Lookup& aLookup) { return HashGeneric(aLookup); }

  static bool match(const Key& aKey, const Lookup& aLookup) {
    return aKey == aLookup;
  }

  static void rekey(Key& aKey, const Key& aNewKey) { aKey = aNewKey; }
};

// The default hash policy, which only works with integers.
template <class Key, typename>
struct DefaultHasher {
  using Lookup = Key;

  static HashNumber hash(const Lookup& aLookup) {
    // Just convert the integer to a HashNumber and use that as is. (This
    // discards the high 32-bits of 64-bit integers!) ScrambleHashCode() is
    // subsequently called on the value to improve the distribution.
    return aLookup;
  }

  static bool match(const Key& aKey, const Lookup& aLookup) {
    // Use builtin or overloaded operator==.
    return aKey == aLookup;
  }

  static void rekey(Key& aKey, const Key& aNewKey) { aKey = aNewKey; }
};

// A DefaultHasher specialization for enums.
template <class T>
struct DefaultHasher<T, std::enable_if_t<std::is_enum_v<T>>> {
  using Key = T;
  using Lookup = Key;

  static HashNumber hash(const Lookup& aLookup) { return HashGeneric(aLookup); }

  static bool match(const Key& aKey, const Lookup& aLookup) {
    // Use builtin or overloaded operator==.
    return aKey == static_cast<Key>(aLookup);
  }

  static void rekey(Key& aKey, const Key& aNewKey) { aKey = aNewKey; }
};

// A DefaultHasher specialization for pointers.
template <class T>
struct DefaultHasher<T*> : PointerHasher<T*> {};

// A DefaultHasher specialization for mozilla::UniquePtr.
template <class T, class D>
struct DefaultHasher<UniquePtr<T, D>> {
  using Key = UniquePtr<T, D>;
  using Lookup = Key;
  using PtrHasher = PointerHasher<T*>;

  static HashNumber hash(const Lookup& aLookup) {
    return PtrHasher::hash(aLookup.get());
  }

  static bool match(const Key& aKey, const Lookup& aLookup) {
    return PtrHasher::match(aKey.get(), aLookup.get());
  }

  static void rekey(UniquePtr<T, D>& aKey, UniquePtr<T, D>&& aNewKey) {
    aKey = std::move(aNewKey);
  }
};

// A DefaultHasher specialization for doubles.
template <>
struct DefaultHasher<double> {
  using Key = double;
  using Lookup = Key;

  static HashNumber hash(const Lookup& aLookup) {
    // Just xor the high bits with the low bits, and then treat the bits of the
    // result as a uint32_t.
    static_assert(sizeof(HashNumber) == 4,
                  "subsequent code assumes a four-byte hash");
    uint64_t u = BitwiseCast<uint64_t>(aLookup);
    return HashNumber(u ^ (u >> 32));
  }

  static bool match(const Key& aKey, const Lookup& aLookup) {
    return BitwiseCast<uint64_t>(aKey) == BitwiseCast<uint64_t>(aLookup);
  }
};

// A DefaultHasher specialization for floats.
template <>
struct DefaultHasher<float> {
  using Key = float;
  using Lookup = Key;

  static HashNumber hash(const Lookup& aLookup) {
    // Just use the value as if its bits form an integer. ScrambleHashCode() is
    // subsequently called on the value to improve the distribution.
    static_assert(sizeof(HashNumber) == 4,
                  "subsequent code assumes a four-byte hash");
    return HashNumber(BitwiseCast<uint32_t>(aLookup));
  }

  static bool match(const Key& aKey, const Lookup& aLookup) {
    return BitwiseCast<uint32_t>(aKey) == BitwiseCast<uint32_t>(aLookup);
  }
};

// A hash policy for C strings.
struct CStringHasher {
  using Key = const char*;
  using Lookup = const char*;

  static HashNumber hash(const Lookup& aLookup) { return HashString(aLookup); }

  static bool match(const Key& aKey, const Lookup& aLookup) {
    return strcmp(aKey, aLookup) == 0;
  }
};

//---------------------------------------------------------------------------
// Fallible Hashing Interface
//---------------------------------------------------------------------------

// Most of the time generating a hash code is infallible, but sometimes it is
// necessary to generate hash codes on demand in a way that can fail. Specialize
// this class for your own hash policy to provide fallible hashing.
//
// This is used by MovableCellHasher to handle the fact that generating a unique
// ID for cell pointer may fail due to OOM.
//
// The default implementations of these methods delegate to the usual HashPolicy
// implementation and always succeed.
template <typename HashPolicy>
struct FallibleHashMethods {
  // Return true if a hashcode is already available for its argument, and
  // sets |aHashOut|. Once this succeeds for a specific argument it
  // must continue to do so.
  //
  // Return false if a hashcode is not already available. This implies that any
  // lookup must fail, as the hash code would have to have been successfully
  // created on insertion.
  template <typename Lookup>
  static bool maybeGetHash(Lookup&& aLookup, HashNumber* aHashOut) {
    *aHashOut = HashPolicy::hash(aLookup);
    return true;
  }

  // Fallible method to ensure a hashcode exists for its argument and create one
  // if not. Sets |aHashOut| to the hashcode and retuns true on success. Returns
  // false on error, e.g. out of memory.
  template <typename Lookup>
  static bool ensureHash(Lookup&& aLookup, HashNumber* aHashOut) {
    *aHashOut = HashPolicy::hash(aLookup);
    return true;
  }
};

template <typename HashPolicy, typename Lookup>
static bool MaybeGetHash(Lookup&& aLookup, HashNumber* aHashOut) {
  return FallibleHashMethods<typename HashPolicy::Base>::maybeGetHash(
      std::forward<Lookup>(aLookup), aHashOut);
}

template <typename HashPolicy, typename Lookup>
static bool EnsureHash(Lookup&& aLookup, HashNumber* aHashOut) {
  return FallibleHashMethods<typename HashPolicy::Base>::ensureHash(
      std::forward<Lookup>(aLookup), aHashOut);
}

//---------------------------------------------------------------------------
// Implementation Details (HashMapEntry, HashTableEntry, HashTable)
//---------------------------------------------------------------------------

// Both HashMap and HashSet are implemented by a single HashTable that is even
// more heavily parameterized than the other two. This leaves HashTable gnarly
// and extremely coupled to HashMap and HashSet; thus code should not use
// HashTable directly.

template <class Key, class Value>
class HashMapEntry {
  Key key_;
  Value value_;

  template <class, class, class>
  friend class detail::HashTable;
  template <class>
  friend class detail::HashTableEntry;
  template <class, class, class, class>
  friend class HashMap;

 public:
  template <typename KeyInput, typename ValueInput>
  HashMapEntry(KeyInput&& aKey, ValueInput&& aValue)
      : key_(std::forward<KeyInput>(aKey)),
        value_(std::forward<ValueInput>(aValue)) {}

  HashMapEntry(HashMapEntry&& aRhs) = default;
  HashMapEntry& operator=(HashMapEntry&& aRhs) = default;

  using KeyType = Key;
  using ValueType = Value;

  const Key& key() const { return key_; }

  // Use this method with caution! If the key is changed such that its hash
  // value also changes, the map will be left in an invalid state.
  Key& mutableKey() { return key_; }

  const Value& value() const { return value_; }
  Value& value() { return value_; }

 private:
  HashMapEntry(const HashMapEntry&) = delete;
  void operator=(const HashMapEntry&) = delete;
};

namespace detail {

template <class T, class HashPolicy, class AllocPolicy>
class HashTable;

template <typename T>
class EntrySlot;

template <typename T>
class HashTableEntry {
 private:
  using NonConstT = std::remove_const_t<T>;

  // Instead of having a hash table entry store that looks like this:
  //
  // +--------+--------+--------+--------+
  // | entry0 | entry1 |  ....  | entryN |
  // +--------+--------+--------+--------+
  //
  // where the entries contained their cached hash code, we're going to lay out
  // the entry store thusly:
  //
  // +-------+-------+-------+-------+--------+--------+--------+--------+
  // | hash0 | hash1 |  ...  | hashN | entry0 | entry1 |  ....  | entryN |
  // +-------+-------+-------+-------+--------+--------+--------+--------+
  //
  // with all the cached hashes prior to the actual entries themselves.
  //
  // We do this because implementing the first strategy requires us to make
  // HashTableEntry look roughly like:
  //
  // template <typename T>
  // class HashTableEntry {
  //   HashNumber mKeyHash;
  //   T mValue;
  // };
  //
  // The problem with this setup is that, depending on the layout of `T`, there
  // may be platform ABI-mandated padding between `mKeyHash` and the first
  // member of `T`. This ABI-mandated padding is wasted space, and can be
  // surprisingly common, e.g. when `T` is a single pointer on 64-bit platforms.
  // In such cases, we're throwing away a quarter of our entry store on padding,
  // which is undesirable.
  //
  // The second layout above, namely:
  //
  // +-------+-------+-------+-------+--------+--------+--------+--------+
  // | hash0 | hash1 |  ...  | hashN | entry0 | entry1 |  ....  | entryN |
  // +-------+-------+-------+-------+--------+--------+--------+--------+
  //
  // means there is no wasted space between the hashes themselves, and no wasted
  // space between the entries themselves.  However, we would also like there to
  // be no gap between the last hash and the first entry. The memory allocator
  // guarantees the alignment of the start of the hashes. The use of a
  // power-of-two capacity of at least 4 guarantees that the alignment of the
  // *end* of the hash array is no less than the alignment of the start.
  // Finally, the static_asserts here guarantee that the entries themselves
  // don't need to be any more aligned than the alignment of the entry store
  // itself.
  //
  // This assertion is safe for 32-bit builds because on both Windows and Linux
  // (including Android), the minimum alignment for allocations larger than 8
  // bytes is 8 bytes, and the actual data for entries in our entry store is
  // guaranteed to have that alignment as well, thanks to the power-of-two
  // number of cached hash values stored prior to the entry data.

  // The allocation policy must allocate a table with at least this much
  // alignment.
  static constexpr size_t kMinimumAlignment = 8;

  static_assert(alignof(HashNumber) <= kMinimumAlignment,
                "[N*2 hashes, N*2 T values] allocation's alignment must be "
                "enough to align each hash");
  static_assert(alignof(NonConstT) <= 2 * sizeof(HashNumber),
                "subsequent N*2 T values must not require more than an even "
                "number of HashNumbers provides");

  static const HashNumber sFreeKey = 0;
  static const HashNumber sRemovedKey = 1;
  static const HashNumber sCollisionBit = 1;

  alignas(NonConstT) unsigned char mValueData[sizeof(NonConstT)];

 private:
  template <class, class, class>
  friend class HashTable;
  template <typename>
  friend class EntrySlot;

  // Some versions of GCC treat it as a -Wstrict-aliasing violation (ergo a
  // -Werror compile error) to reinterpret_cast<> |mValueData| to |T*|, even
  // through |void*|.  Placing the latter cast in these separate functions
  // breaks the chain such that affected GCC versions no longer warn/error.
  void* rawValuePtr() { return mValueData; }

  static bool isLiveHash(HashNumber hash) { return hash > sRemovedKey; }

  HashTableEntry(const HashTableEntry&) = delete;
  void operator=(const HashTableEntry&) = delete;

  NonConstT* valuePtr() { return reinterpret_cast<NonConstT*>(rawValuePtr()); }

  void destroyStoredT() {
    NonConstT* ptr = valuePtr();
    ptr->~T();
    MOZ_MAKE_MEM_UNDEFINED(ptr, sizeof(*ptr));
  }

 public:
  HashTableEntry() = default;

  ~HashTableEntry() { MOZ_MAKE_MEM_UNDEFINED(this, sizeof(*this)); }

  void destroy() { destroyStoredT(); }

  void swap(HashTableEntry* aOther, bool aIsLive) {
    // This allows types to use Argument-Dependent-Lookup, and thus use a custom
    // std::swap, which is needed by types like JS::Heap and such.
    using std::swap;

    if (this == aOther) {
      return;
    }
    if (aIsLive) {
      swap(*valuePtr(), *aOther->valuePtr());
    } else {
      *aOther->valuePtr() = std::move(*valuePtr());
      destroy();
    }
  }

  T& get() { return *valuePtr(); }

  NonConstT& getMutable() { return *valuePtr(); }
};

// A slot represents a cached hash value and its associated entry stored
// in the hash table. These two things are not stored in contiguous memory.
template <class T>
class EntrySlot {
  using NonConstT = std::remove_const_t<T>;

  using Entry = HashTableEntry<T>;

  Entry* mEntry;
  HashNumber* mKeyHash;

  template <class, class, class>
  friend class HashTable;

  EntrySlot(Entry* aEntry, HashNumber* aKeyHash)
      : mEntry(aEntry), mKeyHash(aKeyHash) {}

 public:
  static bool isLiveHash(HashNumber hash) { return hash > Entry::sRemovedKey; }

  EntrySlot(const EntrySlot&) = default;
  EntrySlot(EntrySlot&& aOther) = default;

  EntrySlot& operator=(const EntrySlot&) = default;
  EntrySlot& operator=(EntrySlot&&) = default;

  bool operator==(const EntrySlot& aRhs) const { return mEntry == aRhs.mEntry; }

  bool operator<(const EntrySlot& aRhs) const { return mEntry < aRhs.mEntry; }

  EntrySlot& operator++() {
    ++mEntry;
    ++mKeyHash;
    return *this;
  }

  void destroy() { mEntry->destroy(); }

  void swap(EntrySlot& aOther) {
    mEntry->swap(aOther.mEntry, aOther.isLive());
    std::swap(*mKeyHash, *aOther.mKeyHash);
  }

  T& get() const { return mEntry->get(); }

  NonConstT& getMutable() { return mEntry->getMutable(); }

  bool isFree() const { return *mKeyHash == Entry::sFreeKey; }

  void clearLive() {
    MOZ_ASSERT(isLive());
    *mKeyHash = Entry::sFreeKey;
    mEntry->destroyStoredT();
  }

  void clear() {
    if (isLive()) {
      mEntry->destroyStoredT();
    }
    MOZ_MAKE_MEM_UNDEFINED(mEntry, sizeof(*mEntry));
    *mKeyHash = Entry::sFreeKey;
  }

  bool isRemoved() const { return *mKeyHash == Entry::sRemovedKey; }

  void removeLive() {
    MOZ_ASSERT(isLive());
    *mKeyHash = Entry::sRemovedKey;
    mEntry->destroyStoredT();
  }

  bool isLive() const { return isLiveHash(*mKeyHash); }

  void setCollision() {
    MOZ_ASSERT(isLive());
    *mKeyHash |= Entry::sCollisionBit;
  }
  void unsetCollision() { *mKeyHash &= ~Entry::sCollisionBit; }
  bool hasCollision() const { return *mKeyHash & Entry::sCollisionBit; }
  bool matchHash(HashNumber hn) {
    return (*mKeyHash & ~Entry::sCollisionBit) == hn;
  }
  HashNumber getKeyHash() const { return *mKeyHash & ~Entry::sCollisionBit; }

  template <typename... Args>
  void setLive(HashNumber aHashNumber, Args&&... aArgs) {
    MOZ_ASSERT(!isLive());
    *mKeyHash = aHashNumber;
    new (KnownNotNull, mEntry->valuePtr()) T(std::forward<Args>(aArgs)...);
    MOZ_ASSERT(isLive());
  }

  Entry* toEntry() const { return mEntry; }
};

template <class T, class HashPolicy, class AllocPolicy>
class HashTable : private AllocPolicy {
  friend class mozilla::ReentrancyGuard;

  using NonConstT = std::remove_const_t<T>;
  using Key = typename HashPolicy::KeyType;
  using Lookup = typename HashPolicy::Lookup;

 public:
  using Entry = HashTableEntry<T>;
  using Slot = EntrySlot<T>;

  template <typename F>
  static void forEachSlot(char* aTable, uint32_t aCapacity, F&& f) {
    auto hashes = reinterpret_cast<HashNumber*>(aTable);
    auto entries = reinterpret_cast<Entry*>(&hashes[aCapacity]);
    Slot slot(entries, hashes);
    for (size_t i = 0; i < size_t(aCapacity); ++i) {
      f(slot);
      ++slot;
    }
  }

  // A nullable pointer to a hash table element. A Ptr |p| can be tested
  // either explicitly |if (p.found()) p->...| or using boolean conversion
  // |if (p) p->...|. Ptr objects must not be used after any mutating hash
  // table operations unless |generation()| is tested.
  class Ptr {
    friend class HashTable;

    Slot mSlot;
#ifdef DEBUG
    const HashTable* mTable;
    Generation mGeneration;
#endif

   protected:
    Ptr(Slot aSlot, const HashTable& aTable)
        : mSlot(aSlot)
#ifdef DEBUG
          ,
          mTable(&aTable),
          mGeneration(aTable.generation())
#endif
    {
    }

    // This constructor is used only by AddPtr() within lookupForAdd().
    explicit Ptr(const HashTable& aTable)
        : mSlot(nullptr, nullptr)
#ifdef DEBUG
          ,
          mTable(&aTable),
          mGeneration(aTable.generation())
#endif
    {
    }

    bool isValid() const { return !!mSlot.toEntry(); }

   public:
    Ptr()
        : mSlot(nullptr, nullptr)
#ifdef DEBUG
          ,
          mTable(nullptr),
          mGeneration(0)
#endif
    {
    }

    bool found() const {
      if (!isValid()) {
        return false;
      }
#ifdef DEBUG
      MOZ_ASSERT(mGeneration == mTable->generation());
#endif
      return mSlot.isLive();
    }

    explicit operator bool() const { return found(); }

    bool operator==(const Ptr& aRhs) const {
      MOZ_ASSERT(found() && aRhs.found());
      return mSlot == aRhs.mSlot;
    }

    bool operator!=(const Ptr& aRhs) const {
#ifdef DEBUG
      MOZ_ASSERT(mGeneration == mTable->generation());
#endif
      return !(*this == aRhs);
    }

    T& operator*() const {
#ifdef DEBUG
      MOZ_ASSERT(found());
      MOZ_ASSERT(mGeneration == mTable->generation());
#endif
      return mSlot.get();
    }

    T* operator->() const {
#ifdef DEBUG
      MOZ_ASSERT(found());
      MOZ_ASSERT(mGeneration == mTable->generation());
#endif
      return &mSlot.get();
    }
  };

  // A Ptr that can be used to add a key after a failed lookup.
  class AddPtr : public Ptr {
    friend class HashTable;

    HashNumber mKeyHash;
#ifdef DEBUG
    uint64_t mMutationCount;
#endif

    AddPtr(Slot aSlot, const HashTable& aTable, HashNumber aHashNumber)
        : Ptr(aSlot, aTable),
          mKeyHash(aHashNumber)
#ifdef DEBUG
          ,
          mMutationCount(aTable.mMutationCount)
#endif
    {
    }

    // This constructor is used when lookupForAdd() is performed on a table
    // lacking entry storage; it leaves mSlot null but initializes everything
    // else.
    AddPtr(const HashTable& aTable, HashNumber aHashNumber)
        : Ptr(aTable),
          mKeyHash(aHashNumber)
#ifdef DEBUG
          ,
          mMutationCount(aTable.mMutationCount)
#endif
    {
      MOZ_ASSERT(isLive());
    }

    bool isLive() const { return isLiveHash(mKeyHash); }

   public:
    AddPtr() : mKeyHash(0) {}
  };

  // A hash table iterator that (mostly) doesn't allow table modifications.
  // As with Ptr/AddPtr, Iterator objects must not be used after any mutating
  // hash table operation unless the |generation()| is tested.
  class Iterator {
    void moveToNextLiveEntry() {
      while (++mCur < mEnd && !mCur.isLive()) {
        continue;
      }
    }

   protected:
    friend class HashTable;

    explicit Iterator(const HashTable& aTable)
        : mCur(aTable.slotForIndex(0)),
          mEnd(aTable.slotForIndex(aTable.capacity()))
#ifdef DEBUG
          ,
          mTable(aTable),
          mMutationCount(aTable.mMutationCount),
          mGeneration(aTable.generation()),
          mValidEntry(true)
#endif
    {
      if (!done() && !mCur.isLive()) {
        moveToNextLiveEntry();
      }
    }

    Slot mCur;
    Slot mEnd;
#ifdef DEBUG
    const HashTable& mTable;
    uint64_t mMutationCount;
    Generation mGeneration;
    bool mValidEntry;
#endif

   public:
    bool done() const {
      MOZ_ASSERT(mGeneration == mTable.generation());
      MOZ_ASSERT(mMutationCount == mTable.mMutationCount);
      return mCur == mEnd;
    }

    T& get() const {
      MOZ_ASSERT(!done());
      MOZ_ASSERT(mValidEntry);
      MOZ_ASSERT(mGeneration == mTable.generation());
      MOZ_ASSERT(mMutationCount == mTable.mMutationCount);
      return mCur.get();
    }

    void next() {
      MOZ_ASSERT(!done());
      MOZ_ASSERT(mGeneration == mTable.generation());
      MOZ_ASSERT(mMutationCount == mTable.mMutationCount);
      moveToNextLiveEntry();
#ifdef DEBUG
      mValidEntry = true;
#endif
    }
  };

  // A hash table iterator that permits modification, removal and rekeying.
  // Since rehashing when elements were removed during enumeration would be
  // bad, it is postponed until the ModIterator is destructed. Since the
  // ModIterator's destructor touches the hash table, the user must ensure
  // that the hash table is still alive when the destructor runs.
  class ModIterator : public Iterator {
    friend class HashTable;

    HashTable& mTable;
    bool mRekeyed;
    bool mRemoved;

    // ModIterator is movable but not copyable.
    ModIterator(const ModIterator&) = delete;
    void operator=(const ModIterator&) = delete;

   protected:
    explicit ModIterator(HashTable& aTable)
        : Iterator(aTable), mTable(aTable), mRekeyed(false), mRemoved(false) {}

   public:
    MOZ_IMPLICIT ModIterator(ModIterator&& aOther)
        : Iterator(aOther),
          mTable(aOther.mTable),
          mRekeyed(aOther.mRekeyed),
          mRemoved(aOther.mRemoved) {
      aOther.mRekeyed = false;
      aOther.mRemoved = false;
    }

    // Removes the current element from the table, leaving |get()|
    // invalid until the next call to |next()|.
    void remove() {
      mTable.remove(this->mCur);
      mRemoved = true;
#ifdef DEBUG
      this->mValidEntry = false;
      this->mMutationCount = mTable.mMutationCount;
#endif
    }

    NonConstT& getMutable() {
      MOZ_ASSERT(!this->done());
      MOZ_ASSERT(this->mValidEntry);
      MOZ_ASSERT(this->mGeneration == this->Iterator::mTable.generation());
      MOZ_ASSERT(this->mMutationCount == this->Iterator::mTable.mMutationCount);
      return this->mCur.getMutable();
    }

    // Removes the current element and re-inserts it into the table with
    // a new key at the new Lookup position.  |get()| is invalid after
    // this operation until the next call to |next()|.
    void rekey(const Lookup& l, const Key& k) {
      MOZ_ASSERT(&k != &HashPolicy::getKey(this->mCur.get()));
      Ptr p(this->mCur, mTable);
      mTable.rekeyWithoutRehash(p, l, k);
      mRekeyed = true;
#ifdef DEBUG
      this->mValidEntry = false;
      this->mMutationCount = mTable.mMutationCount;
#endif
    }

    void rekey(const Key& k) { rekey(k, k); }

    // Potentially rehashes the table.
    ~ModIterator() {
      if (mRekeyed) {
        mTable.mGen++;
        mTable.infallibleRehashIfOverloaded();
      }

      if (mRemoved) {
        mTable.compact();
      }
    }
  };

  // Range is similar to Iterator, but uses different terminology.
  class Range {
    friend class HashTable;

    Iterator mIter;

   protected:
    explicit Range(const HashTable& table) : mIter(table) {}

   public:
    bool empty() const { return mIter.done(); }

    T& front() const { return mIter.get(); }

    void popFront() { return mIter.next(); }
  };

  // Enum is similar to ModIterator, but uses different terminology.
  class Enum {
    ModIterator mIter;

    // Enum is movable but not copyable.
    Enum(const Enum&) = delete;
    void operator=(const Enum&) = delete;

   public:
    template <class Map>
    explicit Enum(Map& map) : mIter(map.mImpl) {}

    MOZ_IMPLICIT Enum(Enum&& other) : mIter(std::move(other.mIter)) {}

    bool empty() const { return mIter.done(); }

    T& front() const { return mIter.get(); }

    void popFront() { return mIter.next(); }

    void removeFront() { mIter.remove(); }

    NonConstT& mutableFront() { return mIter.getMutable(); }

    void rekeyFront(const Lookup& aLookup, const Key& aKey) {
      mIter.rekey(aLookup, aKey);
    }

    void rekeyFront(const Key& aKey) { mIter.rekey(aKey); }
  };

  // HashTable is movable
  HashTable(HashTable&& aRhs) : AllocPolicy(std::move(aRhs)) { moveFrom(aRhs); }
  HashTable& operator=(HashTable&& aRhs) {
    MOZ_ASSERT(this != &aRhs, "self-move assignment is prohibited");
    if (mTable) {
      destroyTable(*this, mTable, capacity());
    }
    AllocPolicy::operator=(std::move(aRhs));
    moveFrom(aRhs);
    return *this;
  }

 private:
  void moveFrom(HashTable& aRhs) {
    mGen = aRhs.mGen;
    mHashShift = aRhs.mHashShift;
    mTable = aRhs.mTable;
    mEntryCount = aRhs.mEntryCount;
    mRemovedCount = aRhs.mRemovedCount;
#ifdef DEBUG
    mMutationCount = aRhs.mMutationCount;
    mEntered = aRhs.mEntered;
#endif
    aRhs.mTable = nullptr;
    aRhs.clearAndCompact();
  }

  // HashTable is not copyable or assignable
  HashTable(const HashTable&) = delete;
  void operator=(const HashTable&) = delete;

  static const uint32_t CAP_BITS = 30;

 public:
  uint64_t mGen : 56;       // entry storage generation number
  uint64_t mHashShift : 8;  // multiplicative hash shift
  char* mTable;             // entry storage
  uint32_t mEntryCount;     // number of entries in mTable
  uint32_t mRemovedCount;   // removed entry sentinels in mTable

#ifdef DEBUG
  uint64_t mMutationCount;
  mutable bool mEntered;
#endif

  // The default initial capacity is 32 (enough to hold 16 elements), but it
  // can be as low as 4.
  static const uint32_t sDefaultLen = 16;
  static const uint32_t sMinCapacity = 4;
  // See the comments in HashTableEntry about this value.
  static_assert(sMinCapacity >= 4, "too-small sMinCapacity breaks assumptions");
  static const uint32_t sMaxInit = 1u << (CAP_BITS - 1);
  static const uint32_t sMaxCapacity = 1u << CAP_BITS;

  // Hash-table alpha is conceptually a fraction, but to avoid floating-point
  // math we implement it as a ratio of integers.
  static const uint8_t sAlphaDenominator = 4;
  static const uint8_t sMinAlphaNumerator = 1;  // min alpha: 1/4
  static const uint8_t sMaxAlphaNumerator = 3;  // max alpha: 3/4

  static const HashNumber sFreeKey = Entry::sFreeKey;
  static const HashNumber sRemovedKey = Entry::sRemovedKey;
  static const HashNumber sCollisionBit = Entry::sCollisionBit;

  static uint32_t bestCapacity(uint32_t aLen) {
    static_assert(
        (sMaxInit * sAlphaDenominator) / sAlphaDenominator == sMaxInit,
        "multiplication in numerator below could overflow");
    static_assert(
        sMaxInit * sAlphaDenominator <= UINT32_MAX - sMaxAlphaNumerator,
        "numerator calculation below could potentially overflow");

    // Callers should ensure this is true.
    MOZ_ASSERT(aLen <= sMaxInit);

    // Compute the smallest capacity allowing |aLen| elements to be
    // inserted without rehashing: ceil(aLen / max-alpha).  (Ceiling
    // integral division: <http://stackoverflow.com/a/2745086>.)
    uint32_t capacity = (aLen * sAlphaDenominator + sMaxAlphaNumerator - 1) /
                        sMaxAlphaNumerator;
    capacity = (capacity < sMinCapacity) ? sMinCapacity : RoundUpPow2(capacity);

    MOZ_ASSERT(capacity >= aLen);
    MOZ_ASSERT(capacity <= sMaxCapacity);

    return capacity;
  }

  static uint32_t hashShift(uint32_t aLen) {
    // Reject all lengths whose initial computed capacity would exceed
    // sMaxCapacity. Round that maximum aLen down to the nearest power of two
    // for speedier code.
    if (MOZ_UNLIKELY(aLen > sMaxInit)) {
      MOZ_CRASH("initial length is too large");
    }

    return kHashNumberBits - mozilla::CeilingLog2(bestCapacity(aLen));
  }

  static bool isLiveHash(HashNumber aHash) { return Entry::isLiveHash(aHash); }

  static HashNumber prepareHash(HashNumber aInputHash) {
    HashNumber keyHash = ScrambleHashCode(aInputHash);

    // Avoid reserved hash codes.
    if (!isLiveHash(keyHash)) {
      keyHash -= (sRemovedKey + 1);
    }
    return keyHash & ~sCollisionBit;
  }

  enum FailureBehavior { DontReportFailure = false, ReportFailure = true };

  // Fake a struct that we're going to alloc. See the comments in
  // HashTableEntry about how the table is laid out, and why it's safe.
  struct FakeSlot {
    unsigned char c[sizeof(HashNumber) + sizeof(typename Entry::NonConstT)];
  };

  static char* createTable(AllocPolicy& aAllocPolicy, uint32_t aCapacity,
                           FailureBehavior aReportFailure = ReportFailure) {
    FakeSlot* fake =
        aReportFailure
            ? aAllocPolicy.template pod_malloc<FakeSlot>(aCapacity)
            : aAllocPolicy.template maybe_pod_malloc<FakeSlot>(aCapacity);

    MOZ_ASSERT((reinterpret_cast<uintptr_t>(fake) % Entry::kMinimumAlignment) ==
               0);

    char* table = reinterpret_cast<char*>(fake);
    if (table) {
      forEachSlot(table, aCapacity, [&](Slot& slot) {
        *slot.mKeyHash = sFreeKey;
        new (KnownNotNull, slot.toEntry()) Entry();
      });
    }
    return table;
  }

  static void destroyTable(AllocPolicy& aAllocPolicy, char* aOldTable,
                           uint32_t aCapacity) {
    forEachSlot(aOldTable, aCapacity, [&](const Slot& slot) {
      if (slot.isLive()) {
        slot.toEntry()->destroyStoredT();
      }
    });
    freeTable(aAllocPolicy, aOldTable, aCapacity);
  }

  static void freeTable(AllocPolicy& aAllocPolicy, char* aOldTable,
                        uint32_t aCapacity) {
    FakeSlot* fake = reinterpret_cast<FakeSlot*>(aOldTable);
    aAllocPolicy.free_(fake, aCapacity);
  }

 public:
  HashTable(AllocPolicy aAllocPolicy, uint32_t aLen)
      : AllocPolicy(std::move(aAllocPolicy)),
        mGen(0),
        mHashShift(hashShift(aLen)),
        mTable(nullptr),
        mEntryCount(0),
        mRemovedCount(0)
#ifdef DEBUG
        ,
        mMutationCount(0),
        mEntered(false)
#endif
  {
  }

  explicit HashTable(AllocPolicy aAllocPolicy)
      : HashTable(aAllocPolicy, sDefaultLen) {}

  ~HashTable() {
    if (mTable) {
      destroyTable(*this, mTable, capacity());
    }
  }

 private:
  HashNumber hash1(HashNumber aHash0) const { return aHash0 >> mHashShift; }

  struct DoubleHash {
    HashNumber mHash2;
    HashNumber mSizeMask;
  };

  DoubleHash hash2(HashNumber aCurKeyHash) const {
    uint32_t sizeLog2 = kHashNumberBits - mHashShift;
    DoubleHash dh = {((aCurKeyHash << sizeLog2) >> mHashShift) | 1,
                     (HashNumber(1) << sizeLog2) - 1};
    return dh;
  }

  static HashNumber applyDoubleHash(HashNumber aHash1,
                                    const DoubleHash& aDoubleHash) {
    return WrappingSubtract(aHash1, aDoubleHash.mHash2) & aDoubleHash.mSizeMask;
  }

  static MOZ_ALWAYS_INLINE bool match(T& aEntry, const Lookup& aLookup) {
    return HashPolicy::match(HashPolicy::getKey(aEntry), aLookup);
  }

  enum LookupReason { ForNonAdd, ForAdd };

  Slot slotForIndex(HashNumber aIndex) const {
    auto hashes = reinterpret_cast<HashNumber*>(mTable);
    auto entries = reinterpret_cast<Entry*>(&hashes[capacity()]);
    return Slot(&entries[aIndex], &hashes[aIndex]);
  }

  // Warning: in order for readonlyThreadsafeLookup() to be safe this
  // function must not modify the table in any way when Reason==ForNonAdd.
  template <LookupReason Reason>
  MOZ_ALWAYS_INLINE Slot lookup(const Lookup& aLookup,
                                HashNumber aKeyHash) const {
    MOZ_ASSERT(isLiveHash(aKeyHash));
    MOZ_ASSERT(!(aKeyHash & sCollisionBit));
    MOZ_ASSERT(mTable);

    // Compute the primary hash address.
    HashNumber h1 = hash1(aKeyHash);
    Slot slot = slotForIndex(h1);

    // Miss: return space for a new entry.
    if (slot.isFree()) {
      return slot;
    }

    // Hit: return entry.
    if (slot.matchHash(aKeyHash) && match(slot.get(), aLookup)) {
      return slot;
    }

    // Collision: double hash.
    DoubleHash dh = hash2(aKeyHash);

    // Save the first removed entry pointer so we can recycle later.
    Maybe<Slot> firstRemoved;

    while (true) {
      if (Reason == ForAdd && !firstRemoved) {
        if (MOZ_UNLIKELY(slot.isRemoved())) {
          firstRemoved.emplace(slot);
        } else {
          slot.setCollision();
        }
      }

      h1 = applyDoubleHash(h1, dh);

      slot = slotForIndex(h1);
      if (slot.isFree()) {
        return firstRemoved.refOr(slot);
      }

      if (slot.matchHash(aKeyHash) && match(slot.get(), aLookup)) {
        return slot;
      }
    }
  }

  // This is a copy of lookup() hardcoded to the assumptions:
  //   1. the lookup is for an add;
  //   2. the key, whose |keyHash| has been passed, is not in the table.
  Slot findNonLiveSlot(HashNumber aKeyHash) {
    MOZ_ASSERT(!(aKeyHash & sCollisionBit));
    MOZ_ASSERT(mTable);

    // We assume 'aKeyHash' has already been distributed.

    // Compute the primary hash address.
    HashNumber h1 = hash1(aKeyHash);
    Slot slot = slotForIndex(h1);

    // Miss: return space for a new entry.
    if (!slot.isLive()) {
      return slot;
    }

    // Collision: double hash.
    DoubleHash dh = hash2(aKeyHash);

    while (true) {
      slot.setCollision();

      h1 = applyDoubleHash(h1, dh);

      slot = slotForIndex(h1);
      if (!slot.isLive()) {
        return slot;
      }
    }
  }

  enum RebuildStatus { NotOverloaded, Rehashed, RehashFailed };

  RebuildStatus changeTableSize(
      uint32_t newCapacity, FailureBehavior aReportFailure = ReportFailure) {
    MOZ_ASSERT(IsPowerOfTwo(newCapacity));
    MOZ_ASSERT(!!mTable == !!capacity());

    // Look, but don't touch, until we succeed in getting new entry store.
    char* oldTable = mTable;
    uint32_t oldCapacity = capacity();
    uint32_t newLog2 = mozilla::CeilingLog2(newCapacity);

    if (MOZ_UNLIKELY(newCapacity > sMaxCapacity)) {
      if (aReportFailure) {
        this->reportAllocOverflow();
      }
      return RehashFailed;
    }

    char* newTable = createTable(*this, newCapacity, aReportFailure);
    if (!newTable) {
      return RehashFailed;
    }

    // We can't fail from here on, so update table parameters.
    mHashShift = kHashNumberBits - newLog2;
    mRemovedCount = 0;
    mGen++;
    mTable = newTable;

    // Copy only live entries, leaving removed ones behind.
    forEachSlot(oldTable, oldCapacity, [&](Slot& slot) {
      if (slot.isLive()) {
        HashNumber hn = slot.getKeyHash();
        findNonLiveSlot(hn).setLive(
            hn, std::move(const_cast<typename Entry::NonConstT&>(slot.get())));
      }

      slot.clear();
    });

    // All entries have been destroyed, no need to destroyTable.
    freeTable(*this, oldTable, oldCapacity);
    return Rehashed;
  }

  RebuildStatus rehashIfOverloaded(
      FailureBehavior aReportFailure = ReportFailure) {
    static_assert(sMaxCapacity <= UINT32_MAX / sMaxAlphaNumerator,
                  "multiplication below could overflow");

    // Note: if capacity() is zero, this will always succeed, which is
    // what we want.
    bool overloaded = mEntryCount + mRemovedCount >=
                      capacity() * sMaxAlphaNumerator / sAlphaDenominator;

    if (!overloaded) {
      return NotOverloaded;
    }

    // Succeed if a quarter or more of all entries are removed. Note that this
    // always succeeds if capacity() == 0 (i.e. entry storage has not been
    // allocated), which is what we want, because it means changeTableSize()
    // will allocate the requested capacity rather than doubling it.
    bool manyRemoved = mRemovedCount >= (capacity() >> 2);
    uint32_t newCapacity = manyRemoved ? rawCapacity() : rawCapacity() * 2;
    return changeTableSize(newCapacity, aReportFailure);
  }

  void infallibleRehashIfOverloaded() {
    if (rehashIfOverloaded(DontReportFailure) == RehashFailed) {
      rehashTableInPlace();
    }
  }

  void remove(Slot& aSlot) {
    MOZ_ASSERT(mTable);

    if (aSlot.hasCollision()) {
      aSlot.removeLive();
      mRemovedCount++;
    } else {
      aSlot.clearLive();
    }
    mEntryCount--;
#ifdef DEBUG
    mMutationCount++;
#endif
  }

  void shrinkIfUnderloaded() {
    static_assert(sMaxCapacity <= UINT32_MAX / sMinAlphaNumerator,
                  "multiplication below could overflow");
    bool underloaded =
        capacity() > sMinCapacity &&
        mEntryCount <= capacity() * sMinAlphaNumerator / sAlphaDenominator;

    if (underloaded) {
      (void)changeTableSize(capacity() / 2, DontReportFailure);
    }
  }

  // This is identical to changeTableSize(currentSize), but without requiring
  // a second table.  We do this by recycling the collision bits to tell us if
  // the element is already inserted or still waiting to be inserted.  Since
  // already-inserted elements win any conflicts, we get the same table as we
  // would have gotten through random insertion order.
  void rehashTableInPlace() {
    mRemovedCount = 0;
    mGen++;
    forEachSlot(mTable, capacity(), [&](Slot& slot) { slot.unsetCollision(); });
    for (uint32_t i = 0; i < capacity();) {
      Slot src = slotForIndex(i);

      if (!src.isLive() || src.hasCollision()) {
        ++i;
        continue;
      }

      HashNumber keyHash = src.getKeyHash();
      HashNumber h1 = hash1(keyHash);
      DoubleHash dh = hash2(keyHash);
      Slot tgt = slotForIndex(h1);
      while (true) {
        if (!tgt.hasCollision()) {
          src.swap(tgt);
          tgt.setCollision();
          break;
        }

        h1 = applyDoubleHash(h1, dh);
        tgt = slotForIndex(h1);
      }
    }

    // TODO: this algorithm leaves collision bits on *all* elements, even if
    // they are on no collision path. We have the option of setting the
    // collision bits correctly on a subsequent pass or skipping the rehash
    // unless we are totally filled with tombstones: benchmark to find out
    // which approach is best.
  }

  // Prefer to use putNewInfallible; this function does not check
  // invariants.
  template <typename... Args>
  void putNewInfallibleInternal(HashNumber aKeyHash, Args&&... aArgs) {
    MOZ_ASSERT(mTable);

    Slot slot = findNonLiveSlot(aKeyHash);

    if (slot.isRemoved()) {
      mRemovedCount--;
      aKeyHash |= sCollisionBit;
    }

    slot.setLive(aKeyHash, std::forward<Args>(aArgs)...);
    mEntryCount++;
#ifdef DEBUG
    mMutationCount++;
#endif
  }

 public:
  void clear() {
    forEachSlot(mTable, capacity(), [&](Slot& slot) { slot.clear(); });
    mRemovedCount = 0;
    mEntryCount = 0;
#ifdef DEBUG
    mMutationCount++;
#endif
  }

  // Resize the table down to the smallest capacity that doesn't overload the
  // table. Since we call shrinkIfUnderloaded() on every remove, you only need
  // to call this after a bulk removal of items done without calling remove().
  void compact() {
    if (empty()) {
      // Free the entry storage.
      freeTable(*this, mTable, capacity());
      mGen++;
      mHashShift = hashShift(0);  // gives minimum capacity on regrowth
      mTable = nullptr;
      mRemovedCount = 0;
      return;
    }

    uint32_t bestCapacity = this->bestCapacity(mEntryCount);
    MOZ_ASSERT(bestCapacity <= capacity());

    if (bestCapacity < capacity()) {
      (void)changeTableSize(bestCapacity, DontReportFailure);
    }
  }

  void clearAndCompact() {
    clear();
    compact();
  }

  [[nodiscard]] bool reserve(uint32_t aLen) {
    if (aLen == 0) {
      return true;
    }

    if (MOZ_UNLIKELY(aLen > sMaxInit)) {
      this->reportAllocOverflow();
      return false;
    }

    uint32_t bestCapacity = this->bestCapacity(aLen);
    if (bestCapacity <= capacity()) {
      return true;  // Capacity is already sufficient.
    }

    RebuildStatus status = changeTableSize(bestCapacity, ReportFailure);
    MOZ_ASSERT(status != NotOverloaded);
    return status != RehashFailed;
  }

  Iterator iter() const { return Iterator(*this); }

  ModIterator modIter() { return ModIterator(*this); }

  Range all() const { return Range(*this); }

  bool empty() const { return mEntryCount == 0; }

  uint32_t count() const { return mEntryCount; }

  uint32_t rawCapacity() const { return 1u << (kHashNumberBits - mHashShift); }

  uint32_t capacity() const { return mTable ? rawCapacity() : 0; }

  Generation generation() const { return Generation(mGen); }

  size_t shallowSizeOfExcludingThis(MallocSizeOf aMallocSizeOf) const {
    return aMallocSizeOf(mTable);
  }

  size_t shallowSizeOfIncludingThis(MallocSizeOf aMallocSizeOf) const {
    return aMallocSizeOf(this) + shallowSizeOfExcludingThis(aMallocSizeOf);
  }

  MOZ_ALWAYS_INLINE Ptr readonlyThreadsafeLookup(const Lookup& aLookup) const {
    if (empty()) {
      return Ptr();
    }

    HashNumber inputHash;
    if (!MaybeGetHash<HashPolicy>(aLookup, &inputHash)) {
      return Ptr();
    }

    HashNumber keyHash = prepareHash(inputHash);
    return Ptr(lookup<ForNonAdd>(aLookup, keyHash), *this);
  }

  MOZ_ALWAYS_INLINE Ptr lookup(const Lookup& aLookup) const {
    ReentrancyGuard g(*this);
    return readonlyThreadsafeLookup(aLookup);
  }

  MOZ_ALWAYS_INLINE AddPtr lookupForAdd(const Lookup& aLookup) {
    ReentrancyGuard g(*this);

    HashNumber inputHash;
    if (!EnsureHash<HashPolicy>(aLookup, &inputHash)) {
      return AddPtr();
    }

    HashNumber keyHash = prepareHash(inputHash);

    if (!mTable) {
      return AddPtr(*this, keyHash);
    }

    // Directly call the constructor in the return statement to avoid
    // excess copying when building with Visual Studio 2017.
    // See bug 1385181.
    return AddPtr(lookup<ForAdd>(aLookup, keyHash), *this, keyHash);
  }

  template <typename... Args>
  [[nodiscard]] bool add(AddPtr& aPtr, Args&&... aArgs) {
    ReentrancyGuard g(*this);
    MOZ_ASSERT_IF(aPtr.isValid(), mTable);
    MOZ_ASSERT_IF(aPtr.isValid(), aPtr.mTable == this);
    MOZ_ASSERT(!aPtr.found());
    MOZ_ASSERT(!(aPtr.mKeyHash & sCollisionBit));

    // Check for error from ensureHash() here.
    if (!aPtr.isLive()) {
      return false;
    }

    MOZ_ASSERT(aPtr.mGeneration == generation());
#ifdef DEBUG
    MOZ_ASSERT(aPtr.mMutationCount == mMutationCount);
#endif

    if (!aPtr.isValid()) {
      MOZ_ASSERT(!mTable && mEntryCount == 0);
      uint32_t newCapacity = rawCapacity();
      RebuildStatus status = changeTableSize(newCapacity, ReportFailure);
      MOZ_ASSERT(status != NotOverloaded);
      if (status == RehashFailed) {
        return false;
      }
      aPtr.mSlot = findNonLiveSlot(aPtr.mKeyHash);

    } else if (aPtr.mSlot.isRemoved()) {
      // Changing an entry from removed to live does not affect whether we are
      // overloaded and can be handled separately.
      if (!this->checkSimulatedOOM()) {
        return false;
      }
      mRemovedCount--;
      aPtr.mKeyHash |= sCollisionBit;

    } else {
      // Preserve the validity of |aPtr.mSlot|.
      RebuildStatus status = rehashIfOverloaded();
      if (status == RehashFailed) {
        return false;
      }
      if (status == NotOverloaded && !this->checkSimulatedOOM()) {
        return false;
      }
      if (status == Rehashed) {
        aPtr.mSlot = findNonLiveSlot(aPtr.mKeyHash);
      }
    }

    aPtr.mSlot.setLive(aPtr.mKeyHash, std::forward<Args>(aArgs)...);
    mEntryCount++;
#ifdef DEBUG
    mMutationCount++;
    aPtr.mGeneration = generation();
    aPtr.mMutationCount = mMutationCount;
#endif
    return true;
  }

  // Note: |aLookup| may reference pieces of arguments in |aArgs|, so this
  // function must take care not to use |aLookup| after moving |aArgs|.
  template <typename... Args>
  void putNewInfallible(const Lookup& aLookup, Args&&... aArgs) {
    MOZ_ASSERT(!lookup(aLookup).found());
    ReentrancyGuard g(*this);
    HashNumber keyHash = prepareHash(HashPolicy::hash(aLookup));
    putNewInfallibleInternal(keyHash, std::forward<Args>(aArgs)...);
  }

  // Note: |aLookup| may alias arguments in |aArgs|, so this function must take
  // care not to use |aLookup| after moving |aArgs|.
  template <typename... Args>
  [[nodiscard]] bool putNew(const Lookup& aLookup, Args&&... aArgs) {
    MOZ_ASSERT(!lookup(aLookup).found());
    ReentrancyGuard g(*this);
    if (!this->checkSimulatedOOM()) {
      return false;
    }
    HashNumber inputHash;
    if (!EnsureHash<HashPolicy>(aLookup, &inputHash)) {
      return false;
    }
    HashNumber keyHash = prepareHash(inputHash);
    if (rehashIfOverloaded() == RehashFailed) {
      return false;
    }
    putNewInfallibleInternal(keyHash, std::forward<Args>(aArgs)...);
    return true;
  }

  // Note: |aLookup| may be a reference pieces of arguments in |aArgs|, so this
  // function must take care not to use |aLookup| after moving |aArgs|.
  template <typename... Args>
  [[nodiscard]] bool relookupOrAdd(AddPtr& aPtr, const Lookup& aLookup,
                                   Args&&... aArgs) {
    // Check for error from ensureHash() here.
    if (!aPtr.isLive()) {
      return false;
    }
#ifdef DEBUG
    aPtr.mGeneration = generation();
    aPtr.mMutationCount = mMutationCount;
#endif
    if (mTable) {
      ReentrancyGuard g(*this);
      // Check that aLookup has not been destroyed.
      MOZ_ASSERT(prepareHash(HashPolicy::hash(aLookup)) == aPtr.mKeyHash);
      aPtr.mSlot = lookup<ForAdd>(aLookup, aPtr.mKeyHash);
      if (aPtr.found()) {
        return true;
      }
    } else {
      // Clear aPtr so it's invalid; add() will allocate storage and redo the
      // lookup.
      aPtr.mSlot = Slot(nullptr, nullptr);
    }
    return add(aPtr, std::forward<Args>(aArgs)...);
  }

  void remove(Ptr aPtr) {
    MOZ_ASSERT(mTable);
    ReentrancyGuard g(*this);
    MOZ_ASSERT(aPtr.found());
    MOZ_ASSERT(aPtr.mGeneration == generation());
    remove(aPtr.mSlot);
    shrinkIfUnderloaded();
  }

  void rekeyWithoutRehash(Ptr aPtr, const Lookup& aLookup, const Key& aKey) {
    MOZ_ASSERT(mTable);
    ReentrancyGuard g(*this);
    MOZ_ASSERT(aPtr.found());
    MOZ_ASSERT(aPtr.mGeneration == generation());
    typename HashTableEntry<T>::NonConstT t(std::move(*aPtr));
    HashPolicy::setKey(t, const_cast<Key&>(aKey));
    remove(aPtr.mSlot);
    HashNumber keyHash = prepareHash(HashPolicy::hash(aLookup));
    putNewInfallibleInternal(keyHash, std::move(t));
  }

  void rekeyAndMaybeRehash(Ptr aPtr, const Lookup& aLookup, const Key& aKey) {
    rekeyWithoutRehash(aPtr, aLookup, aKey);
    infallibleRehashIfOverloaded();
  }
};

}  // namespace detail
}  // namespace mozilla

#endif /* mozilla_HashTable_h */