hashed-array-tree 1.3.0

Hashed Array Trees
Documentation
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
//
// Copyright (c) 2025 Nathan Fiedler
//

//! An implementation of Hashed Array Trees by Edward Sitarski.
//!
//! From the original article:
//!
//! > To overcome the limitations of variable-length arrays, I created a data
//! > structure that has fast constant access time like an array, but mostly
//! > avoids copying elements when it grows. I call this new structure a
//! > "Hashed-Array Tree" (HAT) because it combines some of the features of hash
//! > tables, arrays, and trees.
//!
//! To achieve this, the data structure uses a standard growable vector to
//! reference separate data blocks which hold the array elements. The index and
//! the blocks are at most O(√N) in size. As more elements are added, the size
//! of the index and blocks will grow by powers of two (4, 8, 16, 32, etc).
//!
//! # Memory Usage
//!
//! An empty hased array tree is approximately 72 bytes in size, and while
//! holding elements it will have a space overhead on the order of O(√N). As
//! elements are added the array will grow by allocating additional data blocks.
//! Likewise, as elements are removed from the end of the array, data blocks
//! will be deallocated as they become empty.
//!
//! # Performance
//!
//! The get and set operations are O(1) while the push and pop may take O(N) in
//! the worst case, if the array needs to be grown or shrunk.
//!
//! # Safety
//!
//! Because this data structure is allocating memory, copying bytes using
//! pointers, and de-allocating memory as needed, there are many `unsafe` blocks
//! throughout the code.

use std::alloc::{Layout, alloc, dealloc, handle_alloc_error};
use std::cmp::Ordering;
use std::fmt;
use std::ops::{Index, IndexMut};

/// Hashed Array Tree (HAT) described by Edward Sitarski.
pub struct HashedArrayTree<T> {
    /// top array that holds pointers to data blocks ("leaves")
    index: Vec<*mut T>,
    /// number of elements in the array
    count: usize,
    /// index and leaves are 2^k in length
    k: usize,
    /// bit-mask to get the index into a leaf array
    k_mask: usize,
    /// the number of slots in the top array and leaves
    l: usize,
    /// when size increases to upper_limit, an expand is required
    upper_limit: usize,
    /// when size decreases to lower_limit, a compress is required
    lower_limit: usize,
}

impl<T> HashedArrayTree<T> {
    /// Returns a hashed array tree with zero capacity.
    pub fn new() -> Self {
        let index: Vec<*mut T> = vec![];
        Self {
            index,
            count: 0,
            k: 2,
            k_mask: 3,
            l: 4,
            upper_limit: 16,
            lower_limit: 0,
        }
    }

    /// Double the capacity of this array by combining its leaves into new
    /// leaves of double the capacity.
    fn expand(&mut self) {
        let l_prime = 1 << (self.k + 1);
        let old_index: Vec<*mut T> = std::mem::take(&mut self.index);
        let mut iter = old_index.into_iter();
        while let Some(a) = iter.next() {
            let layout = Layout::array::<T>(l_prime).expect("unexpected overflow");
            let buffer = unsafe {
                let ptr = alloc(layout).cast::<T>();
                if ptr.is_null() {
                    handle_alloc_error(layout);
                }
                ptr
            };
            if let Some(b) = iter.next() {
                let b_dst = unsafe { buffer.add(self.l) };
                let old_layout = Layout::array::<T>(self.l).expect("unexpected overflow");
                unsafe {
                    std::ptr::copy(a, buffer, self.l);
                    std::ptr::copy(b, b_dst, self.l);
                    dealloc(a as *mut u8, old_layout);
                    dealloc(b as *mut u8, old_layout);
                }
            } else {
                let old_layout = Layout::array::<T>(self.l).expect("unexpected overflow");
                unsafe {
                    std::ptr::copy(a, buffer, self.l);
                    dealloc(a as *mut u8, old_layout);
                }
            }
            self.index.push(buffer);
        }
        self.k += 1;
        self.k_mask = (1 << self.k) - 1;
        self.l = 1 << self.k;
        self.upper_limit = self.l * self.l;
        self.lower_limit = self.upper_limit / 8;
    }

    /// Appends an element to the back of a collection.
    ///
    /// # Panics
    ///
    /// Panics if a new block is allocated that would exceed `isize::MAX` _bytes_.
    ///
    /// # Time complexity
    ///
    /// O(N) in the worst case (expand).
    pub fn push(&mut self, value: T) {
        let len = self.count;
        if len >= self.upper_limit {
            self.expand();
        }
        if len >= self.capacity() {
            let layout = Layout::array::<T>(self.l).expect("unexpected overflow");
            let buffer = unsafe {
                let ptr = alloc(layout).cast::<T>();
                if ptr.is_null() {
                    handle_alloc_error(layout);
                }
                ptr
            };
            self.index.push(buffer);
        }
        let block = len >> self.k;
        let slot = len & self.k_mask;
        unsafe { self.index[block].add(slot).write(value) }
        self.count += 1;
    }

    /// Appends an element if there is sufficient spare capacity, otherwise an
    /// error is returned with the element.
    ///
    /// # Time complexity
    ///
    /// O(N) in the worst case (expand).
    pub fn push_within_capacity(&mut self, value: T) -> Result<(), T> {
        if self.capacity() <= self.count {
            Err(value)
        } else {
            self.push(value);
            Ok(())
        }
    }

    /// Like [`Self::get()`] but without the `Option` wrapper.
    ///
    /// Will panic if the index is out of bounds.
    fn raw_get(&self, index: usize) -> &T {
        let block = index >> self.k;
        let slot = index & self.k_mask;
        unsafe { &*self.index[block].add(slot) }
    }

    /// Retrieve a reference to the element at the given offset.
    ///
    /// # Time complexity
    ///
    /// Constant time.
    pub fn get(&self, index: usize) -> Option<&T> {
        if index >= self.count {
            None
        } else {
            Some(self.raw_get(index))
        }
    }

    /// Returns a mutable reference to an element.
    ///
    /// # Time complexity
    ///
    /// Constant time.
    pub fn get_mut(&mut self, index: usize) -> Option<&mut T> {
        if index >= self.count {
            None
        } else {
            let block = index >> self.k;
            let slot = index & self.k_mask;
            unsafe { (self.index[block].add(slot)).as_mut() }
        }
    }

    /// Shrink the capacity of this array by splitting its leaves into new
    /// leaves of half the capacity.
    fn compress(&mut self) {
        let old_index: Vec<*mut T> = std::mem::take(&mut self.index);
        for old_buffer in old_index.into_iter() {
            let half = self.l / 2;
            let layout = Layout::array::<T>(half).expect("unexpected overflow");
            let a = unsafe {
                let ptr = alloc(layout).cast::<T>();
                if ptr.is_null() {
                    handle_alloc_error(layout);
                }
                ptr
            };
            let b = unsafe {
                let ptr = alloc(layout).cast::<T>();
                if ptr.is_null() {
                    handle_alloc_error(layout);
                }
                ptr
            };
            unsafe {
                std::ptr::copy(old_buffer, a, half);
                std::ptr::copy(old_buffer.add(half), b, half);
            };
            let layout = Layout::array::<T>(self.l).expect("unexpected overflow");
            unsafe {
                dealloc(old_buffer as *mut u8, layout);
            }
            self.index.push(a);
            self.index.push(b);
        }
        self.k -= 1;
        self.k_mask = (1 << self.k) - 1;
        self.l = 1 << self.k;
        self.upper_limit = self.l * self.l;
        self.lower_limit = self.upper_limit / 8;
    }

    /// Like [`Self::pop()`] but without the `Option` wrapper.
    ///
    /// Will panic if the array is empty.
    pub fn raw_pop(&mut self) -> T {
        let index = self.count - 1;
        // avoid compressing the leaves smaller than 4
        if index < self.lower_limit && self.k > 2 {
            self.compress();
        }
        let block = index >> self.k;
        let slot = index & self.k_mask;
        let ret = unsafe { self.index[block].add(slot).read() };
        if slot == 0 {
            // prune leaves as they become empty
            let ptr = self.index.pop().unwrap();
            let layout = Layout::array::<T>(self.l).expect("unexpected overflow");
            unsafe {
                dealloc(ptr as *mut u8, layout);
            }
        }
        self.count -= 1;
        ret
    }

    /// Removes the last element from the array and returns it, or `None` if the
    /// array is empty.
    ///
    /// # Time complexity
    ///
    /// O(N) in the worst case (shrink).
    pub fn pop(&mut self) -> Option<T> {
        if self.count > 0 {
            Some(self.raw_pop())
        } else {
            None
        }
    }

    /// Removes and returns the last element from an array if the predicate
    /// returns true, or `None`` if the predicate returns `false`` or the array
    /// is empty (the predicate will not be called in that case).
    ///
    /// # Time complexity
    ///
    /// O(N) in the worst case (shrink).
    pub fn pop_if(&mut self, predicate: impl FnOnce(&mut T) -> bool) -> Option<T> {
        if self.count == 0 {
            None
        } else if let Some(last) = self.get_mut(self.count - 1) {
            if predicate(last) { self.pop() } else { None }
        } else {
            None
        }
    }

    /// Removes an element from the array and returns it.
    ///
    /// The removed element is replaced by the last element of the array.
    ///
    /// This does not preserve ordering of the remaining elements.
    ///
    /// # Panics
    ///
    /// Panics if the index is out of bounds.
    ///
    /// # Time complexity
    ///
    /// O(N) in the worst case (shrink).
    pub fn swap_remove(&mut self, index: usize) -> T {
        if index >= self.count {
            panic!(
                "swap_remove index (is {index}) should be < len (is {})",
                self.count
            );
        }
        // retreive the value at index before overwriting
        let block = index >> self.k;
        let slot = index & self.k_mask;
        unsafe {
            let index_ptr = self.index[block].add(slot);
            let value = index_ptr.read();
            // find the pointer of the last element and copy to index pointer
            let block = (self.count - 1) >> self.k;
            let slot = (self.count - 1) & self.k_mask;
            let last_ptr = self.index[block].add(slot);
            std::ptr::copy(last_ptr, index_ptr, 1);
            if slot == 0 {
                // prune leaves as they become empty
                let ptr = self.index.pop().unwrap();
                let layout = Layout::array::<T>(self.l).expect("unexpected overflow");
                dealloc(ptr as *mut u8, layout);
            }
            self.count -= 1;
            value
        }
    }

    /// Returns an iterator over the array.
    ///
    /// The iterator yields all items from start to end.
    pub fn iter(&self) -> ArrayIter<'_, T> {
        ArrayIter {
            array: self,
            index: 0,
            count: self.count,
        }
    }

    /// Returns an iterator that allows modifying each value.
    ///
    /// The iterator yields all items from start to end.
    pub fn iter_mut(&mut self) -> ArrayIterMut<'_, T> {
        ArrayIterMut {
            dope: self.index.as_mut_ptr(),
            index: 0,
            count: self.count,
            k: self.k,
            k_mask: self.k_mask,
            _marker: std::marker::PhantomData,
        }
    }

    /// Return the number of elements in the array.
    ///
    /// # Time complexity
    ///
    /// Constant time.
    pub fn len(&self) -> usize {
        self.count
    }

    /// Returns the total number of elements the array can hold without
    /// reallocating.
    ///
    /// # Time complexity
    ///
    /// Constant time.
    pub fn capacity(&self) -> usize {
        (1 << self.k) * self.index.len()
    }

    /// Returns true if the array has a length of 0.
    ///
    /// # Time complexity
    ///
    /// Constant time.
    pub fn is_empty(&self) -> bool {
        self.count == 0
    }

    /// Clears the array, removing all values and deallocating all leaves.
    ///
    /// # Time complexity
    ///
    /// O(N) if elements are droppable, otherwise O(√N)
    pub fn clear(&mut self) {
        use std::ptr::{drop_in_place, slice_from_raw_parts_mut};

        if self.count > 0 && std::mem::needs_drop::<T>() {
            // find the last leaf that contains values and drop them
            let last_index = self.count - 1;
            let last_block = last_index >> self.k;
            let last_slot = last_index & self.k_mask;
            unsafe {
                // last_slot is pointing at the last element, need to add
                // one to include it in the slice
                drop_in_place(slice_from_raw_parts_mut(
                    self.index[last_block],
                    last_slot + 1,
                ));
            }

            // drop the values in all of the preceding leaves
            for block in 0..last_block {
                unsafe {
                    drop_in_place(slice_from_raw_parts_mut(self.index[block], self.l));
                }
            }
        }

        // deallocate all leaves using the index as the source of truth
        let layout = Layout::array::<T>(self.l).expect("unexpected overflow");
        for block in 0..self.index.len() {
            unsafe {
                dealloc(self.index[block] as *mut u8, layout);
            }
        }
        self.index.clear();

        self.count = 0;
        self.k = 2;
        self.k_mask = 3;
        self.l = 1 << self.k;
        self.upper_limit = self.l * self.l;
        self.lower_limit = 0;
    }

    /// Swap two elements in the array.
    ///
    /// # Panics
    ///
    /// Panics if either index is out of bounds.
    pub fn swap(&mut self, a: usize, b: usize) {
        if a >= self.count {
            panic!("swap a (is {a}) should be < len (is {})", self.count);
        }
        if b >= self.count {
            panic!("swap b (is {b}) should be < len (is {})", self.count);
        }
        // save the value in slot a before overwriting with value from slot b,
        // then write the saved value to slot b
        let a_block = a >> self.k;
        let a_slot = a & self.k_mask;
        let b_block = b >> self.k;
        let b_slot = b & self.k_mask;
        unsafe {
            let a_ptr = self.index[a_block].add(a_slot);
            let value = a_ptr.read();
            let b_ptr = self.index[b_block].add(b_slot);
            std::ptr::copy(b_ptr, a_ptr, 1);
            b_ptr.write(value);
        }
    }

    /// Sorts the slice in ascending order with a comparison function,
    /// **without** preserving the initial order of equal elements.
    ///
    /// This sort is unstable (i.e., may reorder equal elements), in-place
    /// (i.e., does not allocate), and *O*(*n* \* log(*n*)) worst-case.
    ///
    /// Implements the standard heapsort algorithm.
    pub fn sort_unstable_by<F>(&mut self, mut compare: F)
    where
        F: FnMut(&T, &T) -> Ordering,
    {
        if self.count < 2 {
            return;
        }
        let mut start = self.count / 2;
        let mut end = self.count;
        while end > 1 {
            if start > 0 {
                start -= 1;
            } else {
                end -= 1;
                self.swap(end, 0);
            }
            let mut root = start;
            let mut child = 2 * root + 1;
            while child < end {
                if child + 1 < end && compare(&self[child], &self[child + 1]) == Ordering::Less {
                    child += 1;
                }
                if compare(&self[root], &self[child]) == Ordering::Less {
                    self.swap(root, child);
                    root = child;
                    child = 2 * root + 1;
                } else {
                    break;
                }
            }
        }
    }

    /// Removes all but the first of consecutive elements in the array
    /// satisfying a given equality relation.
    ///
    /// The `same_bucket` function is passed references to two elements from the
    /// array and must determine if the elements compare equal. The elements are
    /// passed in reverse order from their order in the array, so if
    /// `same_bucket(a, b)` returns `true`, `a` is removed.
    ///
    /// If the array is sorted, this removes all duplicates.
    pub fn dedup_by<F>(&mut self, mut same_bucket: F)
    where
        F: FnMut(&T, &T) -> bool,
    {
        let len = self.len();
        if len <= 1 {
            return;
        }

        // Check if any duplicates exist to avoid allocating, copying, and
        // deallocating memory if nothing needs to be removed.
        let mut first_duplicate_idx: usize = 1;
        while first_duplicate_idx != len {
            let found_duplicate = {
                let prev = self.raw_get(first_duplicate_idx - 1);
                let current = self.raw_get(first_duplicate_idx);
                same_bucket(current, prev)
            };
            if found_duplicate {
                break;
            }
            first_duplicate_idx += 1;
        }
        if first_duplicate_idx == len {
            return;
        }

        // duplicates exist, build a new array of only unique values; steal the
        // old index and sizes, then clear the rest of the properties in order
        // to start over
        let index = std::mem::take(&mut self.index);
        let old_l = self.l;
        let mut remaining = self.count - 1;
        self.count = 0;
        self.clear();
        let layout = Layout::array::<T>(old_l).expect("unexpected overflow");

        // read the first value (we know there are at least two) to get the
        // process started
        let mut prev = unsafe { index[0].read() };
        let mut slot = 1;
        for buffer in index.into_iter() {
            while slot < old_l {
                let current = unsafe { buffer.add(slot).read() };
                if same_bucket(&current, &prev) {
                    drop(current);
                } else {
                    self.push(prev);
                    prev = current;
                }
                remaining -= 1;
                if remaining == 0 {
                    break;
                }
                slot += 1;
            }
            unsafe {
                dealloc(buffer as *mut u8, layout);
            }
            slot = 0;
        }
        // the last element always gets saved
        self.push(prev);
    }

    /// Moves all the elements of `other` into `self`, leaving `other` empty.
    pub fn append(&mut self, other: &mut Self) {
        let index = std::mem::take(&mut other.index);
        let mut remaining = other.count;
        // prevent other from performing any dropping
        other.count = 0;
        let layout = Layout::array::<T>(other.l).expect("unexpected overflow");
        for buffer in index.into_iter() {
            for slot in 0..other.l {
                let value = unsafe { buffer.add(slot).read() };
                self.push(value);
                remaining -= 1;
                if remaining == 0 {
                    break;
                }
            }
            unsafe {
                dealloc(buffer as *mut u8, layout);
            }
        }
    }

    /// Splits the collection into two at the given index.
    ///
    /// Returns a newly allocated array containing the elements in the range
    /// `[at, len)`. After the call, the original array will be left containing
    /// the elements `[0, at)`.
    ///
    /// # Panics
    ///
    /// Panics if `at > len`.
    ///
    /// # Time complexity
    ///
    /// O(N)
    pub fn split_off(&mut self, at: usize) -> Self {
        if at >= self.count {
            panic!("index out of bounds: {at}");
        }
        // Unlike Vec, cannot simply cut the array into two parts, the structure
        // is built around the number of elements in the array, and that changes
        // no matter what the value of `at` might be.
        //
        // As such, pop elements from self and push onto other, maintaining the
        // correct structure of both arrays, then reverse the elements in the
        // other array to correct the order.
        let mut other = Self::new();
        while self.count > at {
            other.push(self.raw_pop());
        }
        let mut low = 0;
        let mut high = other.count - 1;
        while low < high {
            unsafe {
                let lp = other.index[low >> other.k].add(low & other.k_mask);
                let value = lp.read();
                let hp = other.index[high >> other.k].add(high & other.k_mask);
                std::ptr::copy(hp, lp, 1);
                hp.write(value);
            }
            low += 1;
            high -= 1;
        }
        other
    }

    /// Shortens the array, keeping the first `len` elements and dropping the
    /// rest.
    ///
    /// If `len` is greater or equal to the array's current length, this has no
    /// effect.
    ///
    /// # Time complexity
    ///
    /// O(N)
    pub fn truncate(&mut self, len: usize) {
        while self.count > len {
            self.raw_pop();
            // intentionally dropping the value
        }
    }
}

impl<T> Default for HashedArrayTree<T> {
    fn default() -> Self {
        Self::new()
    }
}

impl<T> fmt::Display for HashedArrayTree<T> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "HashedArrayTree(k: {}, count: {}, dope: {})",
            self.k,
            self.count,
            self.index.len(),
        )
    }
}

impl<T> Index<usize> for HashedArrayTree<T> {
    type Output = T;

    fn index(&self, index: usize) -> &Self::Output {
        let Some(item) = self.get(index) else {
            panic!("index out of bounds: {}", index);
        };
        item
    }
}

impl<T> IndexMut<usize> for HashedArrayTree<T> {
    fn index_mut(&mut self, index: usize) -> &mut Self::Output {
        let Some(item) = self.get_mut(index) else {
            panic!("index out of bounds: {}", index);
        };
        item
    }
}

impl<T> Drop for HashedArrayTree<T> {
    fn drop(&mut self) {
        self.clear();
    }
}

impl<T: Clone> Clone for HashedArrayTree<T> {
    fn clone(&self) -> Self {
        let mut result = HashedArrayTree::<T>::new();
        for value in self.iter() {
            result.push(value.clone());
        }
        result
    }
}

unsafe impl<T: Send> Send for HashedArrayTree<T> {}

impl<A> FromIterator<A> for HashedArrayTree<A> {
    fn from_iter<T: IntoIterator<Item = A>>(iter: T) -> Self {
        let mut arr: HashedArrayTree<A> = HashedArrayTree::new();
        for value in iter {
            arr.push(value)
        }
        arr
    }
}

/// Immutable hashed array tree iterator.
pub struct ArrayIter<'a, T> {
    array: &'a HashedArrayTree<T>,
    index: usize,
    count: usize,
}

impl<'a, T> Iterator for ArrayIter<'a, T> {
    type Item = &'a T;

    fn next(&mut self) -> Option<Self::Item> {
        if self.index < self.count {
            let value = self.array.get(self.index);
            self.index += 1;
            value
        } else {
            None
        }
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        let remaining = self.count - self.index;
        (remaining, Some(remaining))
    }
}

impl<'a, T> ExactSizeIterator for ArrayIter<'a, T> {}

/// Mutable hashed array tree iterator.
pub struct ArrayIterMut<'a, T> {
    dope: *mut *mut T, // pointer into the dope vector's backing array
    index: usize,
    count: usize,
    k: usize,
    k_mask: usize,
    _marker: std::marker::PhantomData<&'a mut T>,
}

impl<'a, T> Iterator for ArrayIterMut<'a, T> {
    type Item = &'a mut T;

    fn next(&mut self) -> Option<Self::Item> {
        if self.index < self.count {
            let block = self.index >> self.k;
            let slot = self.index & self.k_mask;
            self.index += 1;
            // SAFETY: `dope` points into the HAT's index vec, which is valid
            // for `'a`. Each successive call increments `self.index`, so no two
            // live references ever alias the same slot.
            unsafe {
                let block_ptr = *self.dope.add(block);
                Some(&mut *block_ptr.add(slot))
            }
        } else {
            None
        }
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        let remaining = self.count - self.index;
        (remaining, Some(remaining))
    }
}

impl<'a, T> ExactSizeIterator for ArrayIterMut<'a, T> {}

/// An iterator that moves out of a hashed array tree.
pub struct ArrayIntoIter<T> {
    index: usize,
    k: usize,
    k_mask: usize,
    count: usize,
    dope: Vec<*mut T>,
}

impl<T> Iterator for ArrayIntoIter<T> {
    type Item = T;

    fn next(&mut self) -> Option<Self::Item> {
        if self.index < self.count {
            let block = self.index >> self.k;
            let slot = self.index & self.k_mask;
            self.index += 1;
            unsafe { Some((self.dope[block].add(slot)).read()) }
        } else {
            None
        }
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        let remaining = self.count - self.index;
        (remaining, Some(remaining))
    }
}

impl<T> IntoIterator for HashedArrayTree<T> {
    type Item = T;
    type IntoIter = ArrayIntoIter<Self::Item>;

    fn into_iter(self) -> Self::IntoIter {
        let mut me = std::mem::ManuallyDrop::new(self);
        let dope = std::mem::take(&mut me.index);
        ArrayIntoIter {
            index: 0,
            count: me.count,
            k: me.k,
            k_mask: me.k_mask,
            dope,
        }
    }
}

impl<T> ExactSizeIterator for ArrayIntoIter<T> {}

impl<T> Drop for ArrayIntoIter<T> {
    fn drop(&mut self) {
        use std::ptr::{drop_in_place, slice_from_raw_parts_mut};
        let block_len = 1 << self.k;

        if self.count > 0 && std::mem::needs_drop::<T>() {
            // if completely exhausted, the first block/slot will be past the
            // end of the array and thus skip all drops below
            let first_block = self.index >> self.k;
            let first_slot = self.index & self.k_mask;
            let last_block = (self.count - 1) >> self.k;
            let last_slot = (self.count - 1) & self.k_mask;
            if first_block == last_block {
                // special-case, remaining values are in only one leaf
                if first_slot <= last_slot {
                    unsafe {
                        // last_slot is pointing at the last element, need to
                        // add one to include it in the slice
                        drop_in_place(slice_from_raw_parts_mut(
                            self.dope[first_block].add(first_slot),
                            last_slot - first_slot + 1,
                        ));
                    }
                }
            } else if first_block < last_block {
                // drop the remaining values in the first leaf
                if block_len < self.count {
                    unsafe {
                        drop_in_place(slice_from_raw_parts_mut(
                            self.dope[first_block].add(first_slot),
                            block_len - first_slot,
                        ));
                    }
                }

                // drop the values in the last leaf
                unsafe {
                    drop_in_place(slice_from_raw_parts_mut(
                        self.dope[last_block],
                        last_slot + 1,
                    ));
                }

                // drop the values in all of the other leaves
                for block in first_block + 1..last_block {
                    unsafe {
                        drop_in_place(slice_from_raw_parts_mut(self.dope[block], block_len));
                    }
                }
            }
        }

        // deallocate all of the leaves
        for block in 0..self.dope.len() {
            let layout = Layout::array::<T>(block_len).expect("unexpected overflow");
            unsafe {
                dealloc(self.dope[block] as *mut u8, layout);
            }
        }
    }
}

/// Creates a [`HashedArrayTree`] containing the arguments.
///
/// `hat!` allows `HashedArrayTree`s to be defined with the same syntax as array
/// expressions, much like the `vec!` mocro from the standard library.
#[macro_export]
macro_rules! hat {
    () => {
        HashedArrayTree::new()
    };
    // Takes a comma-separated list of expressions
    ( $($item:expr),* $(,)? ) => {
        {
            let mut result = HashedArrayTree::new();
            $(
                result.push($item);
            )*
            result
        }
    };
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_hat_macro() {
        let sut: HashedArrayTree<usize> = hat![];
        assert_eq!(sut.len(), 0);
        assert_eq!(sut.capacity(), 0);

        let sut: HashedArrayTree<usize> = hat![1];
        assert_eq!(sut.len(), 1);
        assert_eq!(sut.capacity(), 4);

        let sut = hat![1, 2, 3, 4, 5, 6, 7, 8, 9,];
        assert_eq!(sut.len(), 9);
        assert_eq!(sut.capacity(), 12);
        assert_eq!(sut[0], 1);
        assert_eq!(sut[1], 2);
        assert_eq!(sut[2], 3);
        assert_eq!(sut[3], 4);
        assert_eq!(sut[4], 5);
        assert_eq!(sut[5], 6);
        assert_eq!(sut[6], 7);
        assert_eq!(sut[7], 8);
        assert_eq!(sut[8], 9);
    }

    #[test]
    fn test_empty() {
        let sut = HashedArrayTree::<usize>::new();
        assert!(sut.get(0).is_none());
    }

    #[test]
    #[should_panic(expected = "index out of bounds:")]
    fn test_index_out_of_bounds() {
        let mut sut: HashedArrayTree<i32> = HashedArrayTree::new();
        sut.push(10);
        sut.push(20);
        let _ = sut[2];
    }

    #[test]
    #[should_panic(expected = "index out of bounds:")]
    fn test_index_mut_out_of_bounds() {
        let mut sut: HashedArrayTree<i32> = HashedArrayTree::new();
        sut.push(10);
        sut.push(20);
        sut[2] = 30;
    }

    #[test]
    fn test_push_no_expand() {
        // push few enough elements to avoid an expansion
        let mut sut = HashedArrayTree::<usize>::new();
        for value in 0..13 {
            sut.push(value);
        }
        assert_eq!(sut.len(), 13);
        assert_eq!(sut.capacity(), 16);
        for value in 0..13 {
            assert_eq!(sut[value], value);
        }
        // pop enough to cause the last leaf to be freed
        sut.pop();
        assert_eq!(sut.len(), 12);
        assert_eq!(sut.capacity(), 12);
    }

    #[test]
    fn test_push_with_expand() {
        // push few enough elements to cause an expansion
        let mut sut = HashedArrayTree::<usize>::new();
        for value in 0..64 {
            sut.push(value);
        }
        assert_eq!(sut.len(), 64);
        assert_eq!(sut.capacity(), 64);
        for value in 0..64 {
            assert_eq!(sut[value], value);
        }
    }

    #[test]
    fn test_expand_and_compress() {
        // add enough to cause multiple expansions
        let mut sut = HashedArrayTree::<usize>::new();
        for value in 0..1024 {
            sut.push(value);
        }
        assert_eq!(sut.len(), 1024);
        assert_eq!(sut.capacity(), 1024);
        // remove enough to cause multiple compressions
        for _ in 0..960 {
            sut.pop();
        }
        // ensure the correct elements remain
        assert_eq!(sut.len(), 64);
        assert_eq!(sut.capacity(), 64);
        for value in 0..64 {
            assert_eq!(sut[value], value);
        }
    }

    #[test]
    fn test_push_get_get_mut() {
        let mut sut = HashedArrayTree::<usize>::new();
        for value in 0..12 {
            sut.push(value);
        }
        assert_eq!(sut.get(2), Some(&2));
        if let Some(value) = sut.get_mut(1) {
            *value = 11;
        } else {
            panic!("get_mut() returned None")
        }
        assert_eq!(sut[0], 0);
        assert_eq!(sut[1], 11);
        assert_eq!(sut[2], 2);
    }

    #[test]
    fn test_push_within_capacity() {
        // empty array has no allocated space
        let mut sut = HashedArrayTree::<u32>::new();
        assert_eq!(sut.push_within_capacity(101), Err(101));
        // will have 4 slots after a single allocation
        sut.push(1);
        sut.push(2);
        assert_eq!(sut.push_within_capacity(3), Ok(()));
        assert_eq!(sut.push_within_capacity(4), Ok(()));
        assert_eq!(sut.push_within_capacity(5), Err(5));
    }

    #[test]
    fn test_pop_small() {
        let mut sut = HashedArrayTree::<usize>::new();
        assert!(sut.is_empty());
        assert_eq!(sut.len(), 0);
        for value in 0..15 {
            sut.push(value);
        }
        assert!(!sut.is_empty());
        assert_eq!(sut.len(), 15);
        for value in (0..15).rev() {
            assert_eq!(sut.pop(), Some(value));
        }
        assert!(sut.is_empty());
        assert_eq!(sut.len(), 0);
        assert_eq!(sut.capacity(), 0);
    }

    #[test]
    fn test_pop_if() {
        let mut sut = HashedArrayTree::<u32>::new();
        assert!(sut.pop_if(|_| panic!("should not be called")).is_none());
        for value in 0..10 {
            sut.push(value);
        }
        assert!(sut.pop_if(|_| false).is_none());
        let maybe = sut.pop_if(|v| *v == 9);
        assert_eq!(maybe.unwrap(), 9);
        assert!(sut.pop_if(|v| *v == 9).is_none());
    }

    #[test]
    fn test_clear_and_reuse_ints() {
        let mut sut: HashedArrayTree<i32> = HashedArrayTree::new();
        for value in 0..512 {
            sut.push(value);
        }
        assert_eq!(sut.len(), 512);
        sut.clear();
        assert_eq!(sut.len(), 0);
        for value in 0..512 {
            sut.push(value);
        }
        for idx in 0..512 {
            let maybe = sut.get(idx);
            assert!(maybe.is_some(), "{idx} is none");
            let actual = maybe.unwrap();
            assert_eq!(idx, *actual as usize);
        }
    }

    #[test]
    fn test_clear_and_reuse_strings() {
        let mut sut: HashedArrayTree<String> = HashedArrayTree::new();
        for _ in 0..512 {
            let value = ulid::Ulid::new().to_string();
            sut.push(value);
        }
        assert_eq!(sut.len(), 512);
        sut.clear();
        assert_eq!(sut.len(), 0);
        for _ in 0..512 {
            let value = ulid::Ulid::new().to_string();
            sut.push(value);
        }
        assert_eq!(sut.len(), 512);
        // implicitly drop()
    }

    #[test]
    fn test_clone_ints() {
        let mut sut = HashedArrayTree::<usize>::new();
        for value in 0..512 {
            sut.push(value);
        }
        let cloned = sut.clone();
        let ai = sut.iter();
        let bi = cloned.iter();
        for (a, b) in ai.zip(bi) {
            assert_eq!(a, b);
        }
    }

    #[test]
    fn test_clone_strings() {
        let mut sut = HashedArrayTree::<String>::new();
        for _ in 0..64 {
            let value = ulid::Ulid::new().to_string();
            sut.push(value);
        }
        let cloned = sut.clone();
        let ai = sut.iter();
        let bi = cloned.iter();
        for (a, b) in ai.zip(bi) {
            assert_eq!(a, b);
        }
    }

    #[test]
    fn test_swap() {
        let mut sut = HashedArrayTree::<usize>::new();
        sut.push(1);
        sut.push(2);
        sut.push(3);
        sut.push(4);
        sut.swap(1, 3);
        assert_eq!(sut[0], 1);
        assert_eq!(sut[1], 4);
        assert_eq!(sut[2], 3);
        assert_eq!(sut[3], 2);
    }

    #[test]
    #[should_panic(expected = "swap a (is 1) should be < len (is 1)")]
    fn test_swap_panic_a() {
        let mut sut = HashedArrayTree::<usize>::new();
        sut.push(1);
        sut.swap(1, 2);
    }

    #[test]
    #[should_panic(expected = "swap b (is 1) should be < len (is 1)")]
    fn test_swap_panic_b() {
        let mut sut = HashedArrayTree::<usize>::new();
        sut.push(1);
        sut.swap(0, 1);
    }

    #[test]
    fn test_sort_unstable_by_ints() {
        let mut sut = HashedArrayTree::<usize>::new();
        sut.push(10);
        sut.push(1);
        sut.push(100);
        sut.push(20);
        sut.push(2);
        sut.push(99);
        sut.push(88);
        sut.push(77);
        sut.push(66);
        sut.sort_unstable_by(|a, b| a.cmp(b));
        assert_eq!(sut[0], 1);
        assert_eq!(sut[1], 2);
        assert_eq!(sut[2], 10);
        assert_eq!(sut[3], 20);
        assert_eq!(sut[4], 66);
        assert_eq!(sut[5], 77);
        assert_eq!(sut[6], 88);
        assert_eq!(sut[7], 99);
        assert_eq!(sut[8], 100);
    }

    #[test]
    fn test_sort_unstable_by_strings() {
        let mut sut = HashedArrayTree::<String>::new();
        sut.push("cat".into());
        sut.push("ape".into());
        sut.push("zebra".into());
        sut.push("dog".into());
        sut.push("bird".into());
        sut.push("tapir".into());
        sut.push("monkey".into());
        sut.push("giraffe".into());
        sut.push("frog".into());
        sut.sort_unstable_by(|a, b| a.cmp(b));
        assert_eq!(sut[0], "ape");
        assert_eq!(sut[1], "bird");
        assert_eq!(sut[2], "cat");
        assert_eq!(sut[3], "dog");
        assert_eq!(sut[4], "frog");
        assert_eq!(sut[5], "giraffe");
        assert_eq!(sut[6], "monkey");
        assert_eq!(sut[7], "tapir");
        assert_eq!(sut[8], "zebra");
    }

    #[test]
    fn test_append() {
        let odds = ["one", "three", "five", "seven", "nine"];
        let mut sut = HashedArrayTree::<String>::new();
        for item in odds {
            sut.push(item.to_owned());
        }
        let evens = ["two", "four", "six", "eight", "ten"];
        let mut other = HashedArrayTree::<String>::new();
        for item in evens {
            other.push(item.to_owned());
        }
        sut.append(&mut other);
        assert_eq!(sut.len(), 10);
        assert_eq!(sut.capacity(), 12);
        assert_eq!(other.len(), 0);
        assert_eq!(other.capacity(), 0);
        sut.sort_unstable_by(|a, b| a.cmp(b));
        assert_eq!(sut[0], "eight");
        assert_eq!(sut[1], "five");
        assert_eq!(sut[2], "four");
        assert_eq!(sut[3], "nine");
        assert_eq!(sut[4], "one");
        assert_eq!(sut[5], "seven");
        assert_eq!(sut[6], "six");
        assert_eq!(sut[7], "ten");
        assert_eq!(sut[8], "three");
        assert_eq!(sut[9], "two");
    }

    #[test]
    fn test_dedup_by_tiny() {
        let mut sut = HashedArrayTree::<String>::new();
        sut.push("one".into());
        sut.dedup_by(|a, b| a == b);
        assert_eq!(sut.len(), 1);
        assert_eq!(sut[0], "one");
    }

    #[test]
    fn test_dedup_by_2_dupes() {
        let mut sut = HashedArrayTree::<String>::new();
        sut.push("one".into());
        sut.push("one".into());
        sut.dedup_by(|a, b| a == b);
        assert_eq!(sut.len(), 1);
        assert_eq!(sut[0], "one");
    }

    #[test]
    fn test_dedup_by_2_unique() {
        let mut sut = HashedArrayTree::<String>::new();
        sut.push("one".into());
        sut.push("two".into());
        sut.dedup_by(|a, b| a == b);
        assert_eq!(sut.len(), 2);
        assert_eq!(sut[0], "one");
        assert_eq!(sut[1], "two");
    }

    #[test]
    fn test_dedup_by_all_unique() {
        let inputs = [
            "one", "two", "three", "four", "five", "six", "seven", "eight", "nine",
        ];
        let mut sut = HashedArrayTree::<String>::new();
        for item in inputs {
            sut.push(item.to_owned());
        }
        sut.dedup_by(|a, b| a == b);
        assert_eq!(sut.len(), 9);
        for (idx, elem) in sut.into_iter().enumerate() {
            assert_eq!(inputs[idx], elem);
        }
    }

    #[test]
    fn test_dedup_by_all_dupes() {
        let inputs = [
            "one", "one", "one", "one", "one", "one", "one", "one", "one", "one",
        ];
        let mut sut = HashedArrayTree::<String>::new();
        for item in inputs {
            sut.push(item.to_owned());
        }
        assert_eq!(sut.len(), 10);
        sut.dedup_by(|a, b| a == b);
        assert_eq!(sut.len(), 1);
        assert_eq!(inputs[0], "one");
    }

    #[test]
    fn test_dedup_by_some_dupes_ints() {
        let inputs = [1, 2, 2, 3, 2];
        let mut sut = HashedArrayTree::<usize>::new();
        for item in inputs {
            sut.push(item.to_owned());
        }
        assert_eq!(sut.len(), 5);
        sut.dedup_by(|a, b| a == b);
        assert_eq!(sut.len(), 4);
        assert_eq!(sut[0], 1);
        assert_eq!(sut[1], 2);
        assert_eq!(sut[2], 3);
        assert_eq!(sut[3], 2);
    }

    #[test]
    fn test_dedup_by_some_dupes_strings() {
        let inputs = ["foo", "bar", "Bar", "baz", "bar"];
        let mut sut = HashedArrayTree::<String>::new();
        for item in inputs {
            sut.push(item.to_owned());
        }
        assert_eq!(sut.len(), 5);
        sut.dedup_by(|a, b| a.eq_ignore_ascii_case(b));
        assert_eq!(sut.len(), 4);
        assert_eq!(sut[0], "foo");
        assert_eq!(sut[1], "bar");
        assert_eq!(sut[2], "baz");
        assert_eq!(sut[3], "bar");
    }

    #[test]
    #[should_panic(expected = "index out of bounds: 10")]
    fn test_split_off_bounds_panic() {
        let mut sut = HashedArrayTree::<usize>::new();
        sut.split_off(10);
    }

    #[test]
    fn test_split_off_middle() {
        let mut sut = HashedArrayTree::<usize>::new();
        for value in 0..16 {
            sut.push(value);
        }
        assert_eq!(sut.len(), 16);
        assert_eq!(sut.capacity(), 16);
        let other = sut.split_off(8);
        assert_eq!(sut.len(), 8);
        assert_eq!(sut.capacity(), 8);
        for value in 0..8 {
            assert_eq!(sut[value], value);
        }
        assert_eq!(other.len(), 8);
        assert_eq!(other.capacity(), 8);
        for (index, value) in (8..16).enumerate() {
            assert_eq!(other[index], value);
        }
    }

    #[test]
    fn test_split_off_almost_start() {
        let mut sut = HashedArrayTree::<usize>::new();
        for value in 0..16 {
            sut.push(value);
        }
        assert_eq!(sut.len(), 16);
        assert_eq!(sut.capacity(), 16);
        let other = sut.split_off(1);
        assert_eq!(sut.len(), 1);
        assert_eq!(sut.capacity(), 4);
        for value in 0..1 {
            assert_eq!(sut[value], value);
        }
        assert_eq!(other.len(), 15);
        assert_eq!(other.capacity(), 16);
        for (index, value) in (1..16).enumerate() {
            assert_eq!(other[index], value);
        }
    }

    #[test]
    fn test_split_off_almost_end() {
        let mut sut = HashedArrayTree::<usize>::new();
        for value in 0..16 {
            sut.push(value);
        }
        assert_eq!(sut.len(), 16);
        assert_eq!(sut.capacity(), 16);
        let other = sut.split_off(15);
        assert_eq!(sut.len(), 15);
        assert_eq!(sut.capacity(), 16);
        for value in 0..15 {
            assert_eq!(sut[value], value);
        }
        assert_eq!(other.len(), 1);
        assert_eq!(other.capacity(), 4);
        assert_eq!(other[0], 15);
    }

    #[test]
    fn test_split_off_odd_other() {
        let mut sut = HashedArrayTree::<usize>::new();
        for value in 0..16 {
            sut.push(value);
        }
        assert_eq!(sut.len(), 16);
        assert_eq!(sut.capacity(), 16);
        let other = sut.split_off(11);
        assert_eq!(sut.len(), 11);
        assert_eq!(sut.capacity(), 12);
        for value in 0..11 {
            assert_eq!(sut[value], value);
        }
        assert_eq!(other.len(), 5);
        assert_eq!(other.capacity(), 8);
        for (index, value) in (11..16).enumerate() {
            assert_eq!(other[index], value);
        }
    }

    #[test]
    fn test_truncate_typical() {
        let mut sut = hat![1, 2, 3, 4, 5, 6, 7, 8];
        assert_eq!(sut.len(), 8);
        assert_eq!(sut.capacity(), 8);
        sut.truncate(5);
        assert_eq!(sut.len(), 5);
        assert_eq!(sut.capacity(), 8);
        for (index, value) in (1..6).enumerate() {
            assert_eq!(sut[index], value);
        }
    }

    #[test]
    fn test_truncate_out_of_bounds() {
        let mut sut = hat![1, 2, 3, 4, 5,];
        assert_eq!(sut.len(), 5);
        assert_eq!(sut.capacity(), 8);
        sut.truncate(8);
        assert_eq!(sut.len(), 5);
        assert_eq!(sut.capacity(), 8);
        for (index, value) in (1..6).enumerate() {
            assert_eq!(sut[index], value);
        }
    }

    #[test]
    fn test_truncate_to_empty() {
        let mut sut = hat![1, 2, 3, 4, 5,];
        assert_eq!(sut.len(), 5);
        assert_eq!(sut.capacity(), 8);
        sut.truncate(0);
        assert_eq!(sut.len(), 0);
        assert_eq!(sut.capacity(), 0);
    }

    #[test]
    fn test_from_iterator() {
        let mut inputs: Vec<i32> = Vec::new();
        for value in 0..10_000 {
            inputs.push(value);
        }
        let sut: HashedArrayTree<i32> = inputs.into_iter().collect();
        assert_eq!(sut.len(), 10_000);
        for idx in 0..10_000i32 {
            let maybe = sut.get(idx as usize);
            assert!(maybe.is_some(), "{idx} is none");
            let actual = maybe.unwrap();
            assert_eq!(idx, *actual);
        }
    }

    #[test]
    fn test_iterator() {
        let mut sut = HashedArrayTree::<usize>::new();
        for value in 0..512 {
            sut.push(value);
        }
        assert_eq!(sut.len(), 512);
        for (idx, elem) in sut.iter().enumerate() {
            assert_eq!(sut[idx], *elem);
        }
    }

    #[test]
    fn test_iter_mut() {
        let mut sut = HashedArrayTree::<usize>::new();
        for value in 0..512 {
            sut.push(value);
        }
        // double every element through the mutable iterator
        for elem in sut.iter_mut() {
            *elem *= 2;
        }
        for idx in 0..512 {
            assert_eq!(sut[idx], idx * 2);
        }
    }

    #[test]
    fn test_iter_mut_empty() {
        let mut sut = HashedArrayTree::<usize>::new();
        assert_eq!(sut.iter_mut().count(), 0);
    }

    #[test]
    fn test_into_iterator_edge_case() {
        // iterate to the end (of the last data block)
        let inputs = [
            "one", "two", "three", "four", "five", "six", "seven", "eight",
        ];
        let mut sut: HashedArrayTree<String> = HashedArrayTree::new();
        for item in inputs {
            sut.push(item.to_owned());
        }
        for (idx, elem) in sut.into_iter().enumerate() {
            assert_eq!(inputs[idx], elem);
        }
        // sut.len(); // error: ownership of sut was moved
    }

    #[test]
    fn test_into_iterator_multiple_leaves() {
        let inputs = [
            "one", "two", "three", "four", "five", "six", "seven", "eight", "nine",
        ];
        let mut sut: HashedArrayTree<String> = HashedArrayTree::new();
        for item in inputs {
            sut.push(item.to_owned());
        }
        for (idx, elem) in sut.into_iter().enumerate() {
            assert_eq!(inputs[idx], elem);
        }
        // sut.len(); // error: ownership of sut was moved
    }

    #[test]
    fn test_into_iterator_drop_empty() {
        let sut: HashedArrayTree<String> = HashedArrayTree::new();
        assert_eq!(sut.into_iter().count(), 0);
    }

    #[test]
    fn test_into_iterator_drop_single_leaf() {
        // an array that only requires a single segment and only some need to be
        // dropped after partially iterating the values
        let inputs = ["one", "two", "three", "four"];
        let mut sut: HashedArrayTree<String> = HashedArrayTree::new();
        for item in inputs {
            sut.push(item.to_owned());
        }
        for (idx, _) in sut.into_iter().enumerate() {
            if idx > 1 {
                break;
            }
        }
        // implicitly drop()
    }

    #[test]
    fn test_into_iterator_drop_large() {
        // by adding 512 values and iterating less than 32 times, there will be
        // values in the first segment and some in the last segment, and two
        // segments inbetween that all need to be dropped
        let mut sut: HashedArrayTree<String> = HashedArrayTree::new();
        for _ in 0..512 {
            let value = ulid::Ulid::new().to_string();
            sut.push(value);
        }
        for (idx, _) in sut.into_iter().enumerate() {
            if idx >= 28 {
                break;
            }
        }
        // implicitly drop()
    }

    #[test]
    fn test_swap_remove_single_segment() {
        let mut sut: HashedArrayTree<u32> = HashedArrayTree::new();
        sut.push(1);
        sut.push(2);
        assert_eq!(sut.len(), 2);
        let one = sut.swap_remove(0);
        assert_eq!(one, 1);
        assert_eq!(sut[0], 2);
    }

    #[test]
    fn test_swap_remove_prune_empty() {
        let mut sut: HashedArrayTree<u32> = HashedArrayTree::new();
        for value in 0..13 {
            sut.push(value);
        }
        assert_eq!(sut.len(), 13);
        assert_eq!(sut.capacity(), 16);
        let value = sut.swap_remove(8);
        assert_eq!(value, 8);
        assert_eq!(sut[8], 12);
        assert_eq!(sut.len(), 12);
        assert_eq!(sut.capacity(), 12);
    }

    #[test]
    fn test_swap_remove_multiple_segments() {
        let mut sut: HashedArrayTree<u32> = HashedArrayTree::new();
        for value in 0..512 {
            sut.push(value);
        }
        assert_eq!(sut.len(), 512);
        let eighty = sut.swap_remove(80);
        assert_eq!(eighty, 80);
        assert_eq!(sut.pop(), Some(510));
        assert_eq!(sut[80], 511);
    }

    #[test]
    #[should_panic(expected = "swap_remove index (is 0) should be < len (is 0)")]
    fn test_swap_remove_panic_empty() {
        let mut sut: HashedArrayTree<u32> = HashedArrayTree::new();
        sut.swap_remove(0);
    }

    #[test]
    #[should_panic(expected = "swap_remove index (is 1) should be < len (is 1)")]
    fn test_swap_remove_panic_range_edge() {
        let mut sut: HashedArrayTree<u32> = HashedArrayTree::new();
        sut.push(1);
        sut.swap_remove(1);
    }

    #[test]
    #[should_panic(expected = "swap_remove index (is 2) should be < len (is 1)")]
    fn test_swap_remove_panic_range_exceed() {
        let mut sut: HashedArrayTree<u32> = HashedArrayTree::new();
        sut.push(1);
        sut.swap_remove(2);
    }

    #[test]
    fn test_push_get_many_instances_ints() {
        // test allocating, filling, and then dropping many instances
        for _ in 0..1_000 {
            let mut sut: HashedArrayTree<usize> = HashedArrayTree::new();
            for value in 0..10_000 {
                sut.push(value);
            }
            assert_eq!(sut.len(), 10_000);
        }
    }

    #[test]
    fn test_push_get_many_instances_strings() {
        // test allocating, filling, and then dropping many instances
        for _ in 0..1_000 {
            let mut sut: HashedArrayTree<String> = HashedArrayTree::new();
            for _ in 0..1_000 {
                let value = ulid::Ulid::new().to_string();
                sut.push(value);
            }
            assert_eq!(sut.len(), 1_000);
        }
    }
}