vec-collections 0.4.3

Rust collections that are newtype wrappers around smallvec
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
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
#![allow(dead_code)]
//! A radix tree
//!
//! The advantage of a radix tree over a collection like a [BTreeMap](std::collections::BTreeMap) or a [HashMap](std::collections::HashMap)
//! is that keys are not stored in full. So when keys are very long and commonly have a common prefix,
//! a radix tree is a good choice.
//!
//! Radix trees allow very quick (O(log n)) filtering by prefix, as well as very fast (O(1)) prepending a prefix.
//!
//! Radix trees in this crate come in three flavours:
//! - [RadixTree](RadixTree) is the most straightforward flavour. It does not contain any indirection.
//!   use this for short lived objects.
//! - [ArcRadixTree](ArcRadixTree) allows cheap snapshots and has copy on write semantics.
//!   use this for a longer lived in memory tree that evolves over time
//! - [LazyRadixTree](LazyRadixTree) allows cheap snapshots, copy on write semantics, and lazy loading.
//!   use this for e.g. memory mapping a giant radix tree from a large file, that does not fit in memory.
//!
//! No attempt is made to hide the internal structure. E.g. if you want to use a RadixTree as a set,
//! this is possible by using unit as value type, but probably not very convenient.
use std::{borrow::Borrow, cmp::Ordering, fmt::Debug, marker::PhantomData, ops::Deref, sync::Arc};

/// Trait for everything that is needed for a component to be a radix tree key component
pub trait TKey: Debug + Ord + Copy + Archive<Archived = Self> + Send + Sync + 'static {}

impl<T: Debug + Ord + Copy + Archive<Archived = T> + Send + Sync + 'static> TKey for T {}

/// Trait for everything that is needed for a component to be a radix tree value
pub trait TValue: Debug + Clone + Archive + Send + Sync + 'static {}

impl<T: Debug + Clone + Archive + Send + Sync + 'static> TValue for T {}

use rkyv::Archive;
#[cfg(feature = "lazy_radixtree")]
mod lazy_radix_tree;
#[cfg(feature = "lazy_radixtree")]
pub use lazy_radix_tree::LazyRadixTree;
#[cfg(feature = "rkyv")]
mod arc_radix_tree;
#[cfg(feature = "rkyv")]
pub use arc_radix_tree::ArcRadixTree;
use smallvec::SmallVec;
use sorted_iter::sorted_pair_iterator::SortedByKey;
mod flat_radix_tree;
use crate::merge_state::{
    BoolOpMergeState, Converter, InPlaceVecMergeStateRef, MergeStateMut, MutateInput, NoConverter,
    VecMergeState,
};
use binary_merge::MergeOperation;
pub use flat_radix_tree::RadixTree;

// common prefix of two slices.
fn common_prefix<'a, T: Eq>(a: &'a [T], b: &'a [T]) -> usize {
    a.iter().zip(b).take_while(|(a, b)| a == b).count()
}

pub(crate) mod internals {
    use super::*;

    /// A path fragment
    #[derive(Debug, Clone, PartialEq, Eq)]
    pub struct Fragment<T>(SmallVec<[T; 16]>);

    impl<T> AsRef<[T]> for Fragment<T> {
        fn as_ref(&self) -> &[T] {
            self.0.as_ref()
        }
    }

    impl<T> Borrow<[T]> for Fragment<T> {
        fn borrow(&self) -> &[T] {
            self.0.as_ref()
        }
    }

    impl<T> Deref for Fragment<T> {
        type Target = [T];

        fn deref(&self) -> &[T] {
            self.as_ref()
        }
    }

    impl<'a, T: Clone> From<&'a [T]> for Fragment<T> {
        fn from(value: &'a [T]) -> Self {
            Self(value.into())
        }
    }

    impl<T> From<SmallVec<[T; 16]>> for Fragment<T> {
        fn from(value: SmallVec<[T; 16]>) -> Self {
            Self(value)
        }
    }

    impl<T: Ord> Ord for Fragment<T> {
        fn cmp(&self, other: &Self) -> std::cmp::Ordering {
            self.0[0].cmp(&other.0[0])
        }
    }

    impl<T: Ord> PartialOrd for Fragment<T> {
        fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
            Some(self.cmp(other))
        }
    }

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

    /// implement this trait for a new flavour of radix tree. The public AbstractRadixTreeMut will be implemented for you.
    ///
    /// this is in a private module since it allows you to break the invariants of the tree.
    pub trait AbstractRadixTreeMut<K: TKey, V: TValue>:
        AbstractRadixTree<K, V, Materialized = Self> + Clone + Default
    {
        /// Creates a new, possibly non-canonical node
        ///
        /// because this allows the creation of a non-canonical node, which is sometimes necessary
        /// for intermediate states, it must not be publicly exposed.
        fn new(prefix: Fragment<K>, value: Option<V>, children: Vec<Self>) -> Self;
        fn value_mut(&mut self) -> &mut Option<V>;
        fn children_mut(&mut self) -> &mut Vec<Self>;
        fn prefix_mut(&mut self) -> &mut Fragment<K>;

        /// create an artificial split at offset n
        /// splitting at n >= prefix.len() is an error
        fn split(&mut self, n: usize) {
            assert!(n < self.prefix().len());
            let first = self.prefix()[..n].into();
            let rest = self.prefix()[n..].into();
            let mut split = Self::new(first, None, Vec::new());
            std::mem::swap(self, &mut split);
            let mut child = split;
            *child.prefix_mut() = rest;
            self.children_mut().push(child);
        }

        /// removes degenerate node again
        fn unsplit(&mut self) {
            // remove all empty children
            // this might sometimes not be necessary, but it is tricky to find out when.
            self.children_mut().retain(|x| !x.is_empty());
            // a single child and no own value is degenerate
            if self.children().len() == 1 && self.value().is_none() {
                let mut child = self.children_mut().pop().unwrap();
                child.prepend0(self.prefix());
                *self = child;
            }
            // canonicalize prefix for empty node
            // this might sometimes not be necessary, but it is tricky to find out when.
            if self.is_empty() {
                *self.prefix_mut() = Fragment::default();
            }
        }

        fn prepend0(&mut self, prefix: &[K]) {
            if !prefix.is_empty() && !self.is_empty() {
                let mut prefix1 = SmallVec::new();
                prefix1.extend_from_slice(prefix);
                prefix1.extend_from_slice(self.prefix());
                *self.prefix_mut() = prefix1.into();
            }
        }

        fn outer_combine_children_with<R, F>(&mut self, rhs: &[R], f: F)
        where
            R: AbstractRadixTree<K, V, Materialized = Self::Materialized>,
            F: Fn(&mut V, &V) -> bool + Copy,
        {
            InPlaceVecMergeStateRef::merge(
                self.children_mut(),
                &rhs,
                OuterCombineOp(f, PhantomData),
                RadixTreeConverter(PhantomData),
            );
        }

        fn inner_combine_children_with<W, R, F>(&mut self, rhs: &[R], f: F)
        where
            W: TValue,
            R: AbstractRadixTree<K, W>,
            F: Fn(&mut V, &W) -> bool + Copy,
        {
            InPlaceVecMergeStateRef::merge(
                self.children_mut(),
                &rhs,
                InnerCombineOp(f, PhantomData),
                NoConverter,
            );
        }

        fn left_combine_children_with<W, R, F>(&mut self, rhs: &[R], f: F)
        where
            W: TValue,
            R: AbstractRadixTree<K, W>,
            F: Fn(&mut V, &W) -> bool + Copy,
        {
            InPlaceVecMergeStateRef::merge(
                self.children_mut(),
                &rhs,
                LeftCombineOp(f, PhantomData),
                NoConverter,
            );
        }

        fn retain_prefix_children_with<W, R>(&mut self, rhs: &[R], f: impl Fn(&W) -> bool + Copy)
        where
            W: TValue,
            R: AbstractRadixTree<K, W>,
        {
            InPlaceVecMergeStateRef::merge(
                self.children_mut(),
                &rhs,
                RetainPrefixOp(f, PhantomData),
                NoConverter,
            );
        }

        fn remove_prefix_children_with<W, R, F>(&mut self, rhs: &[R], f: F)
        where
            W: TValue,
            R: AbstractRadixTree<K, W>,
            F: Fn(&W) -> bool + Copy,
        {
            InPlaceVecMergeStateRef::merge(
                self.children_mut(),
                &rhs,
                RemovePrefixOp(f, PhantomData),
                NoConverter,
            );
        }
    }
}

use internals::{AbstractRadixTreeMut as _, Fragment};

/// Interface to a mutable abstract radix tree that allows mutation.
///
/// Most operations are meant to be generically useful. E.g.
pub trait AbstractRadixTreeMut<K: TKey, V: TValue>: internals::AbstractRadixTreeMut<K, V> {
    /// Create an empty tree
    fn empty() -> Self {
        Self::default()
    }

    /// Create a leaf tree - with just a value, but no prefix and no children
    fn leaf(value: V) -> Self {
        Self::new(Fragment::default(), Some(value), Default::default())
    }

    /// Create a tree containing a single key/value pair
    fn single(key: &[K], value: V) -> Self {
        Self::new(key.into(), Some(value), Vec::new())
    }

    /// Insert a mapping. Will replace existing mapping.
    fn insert(&mut self, key: &[K], value: V) {
        self.outer_combine_with(&Self::single(key, value), |a, b| {
            *a = b.clone();
            true
        })
    }

    /// Return the subtree with the given prefix. Will return an empty tree in case there is no match.
    fn filter_prefix(&self, prefix: &[K]) -> Self {
        match find(self, prefix) {
            FindResult::Found(tree) => {
                let mut res = tree.clone();
                *res.prefix_mut() = prefix.into();
                res
            }
            FindResult::Prefix { tree, rt } => {
                let mut res = tree.clone();
                let p = res.prefix();
                *res.prefix_mut() = Fragment::from(&p[p.len() - rt..]);
                res.prepend(prefix);
                res
            }
            FindResult::NotFound { .. } => Self::default(),
        }
    }

    /// Prepend a prefix to the tree
    fn prepend(&mut self, prefix: &[K]) {
        if !prefix.is_empty() && !self.is_empty() {
            let mut prefix1 = SmallVec::new();
            prefix1.extend_from_slice(prefix);
            prefix1.extend_from_slice(self.prefix());
            *self.prefix_mut() = prefix1.into();
        }
    }

    /// Left biased union with another tree of the same key and value type
    ///
    /// If you want a right biased union, you can implement it with [outer_combine](AbstractRadixTree::outer_combine).
    fn union(
        &self,
        that: &impl AbstractRadixTree<K, V, Materialized = Self::Materialized>,
    ) -> Self::Materialized {
        self.outer_combine(that, |a, _| Some(a.clone()))
    }

    /// In place left biased union with another tree of the same key and value type
    ///
    /// If you want a right biased union, you can implement it with [outer_combine_with](AbstractRadixTreeMut::outer_combine_with).
    fn union_with(
        &mut self,
        that: &impl AbstractRadixTree<K, V, Materialized = Self::Materialized>,
    ) {
        self.outer_combine_with(that, |_, _| true)
    }

    /// Intersection with another tree of the same key type
    fn intersection<W: TValue>(&self, that: &impl AbstractRadixTree<K, W>) -> Self::Materialized {
        self.inner_combine(that, |a, _| Some(a.clone()))
    }

    /// In place intersection with another tree of the same key type
    fn intersection_with<W: TValue>(&mut self, that: &impl AbstractRadixTree<K, W>) {
        self.inner_combine_with(that, |_, _| true)
    }

    /// Difference with another tree of the same key type
    fn difference<W: TValue>(&self, that: &impl AbstractRadixTree<K, W>) -> Self::Materialized {
        self.left_combine(
            that,
            |a, b| if b.is_none() { Some(a.clone()) } else { None },
        )
    }

    /// In place difference with another tree of the same key type
    fn difference_with<W: TValue>(&mut self, that: &impl AbstractRadixTree<K, W>) {
        self.left_combine_with(that, |_, _| false)
    }

    /// outer combine of `self` tree with `that` tree
    ///
    /// outer means that elements that are in `self` but not in `that` or vice versa are copied.
    /// for elements that are in both trees, it is possible to customize how they are combined.
    /// `f` can mutate the value of `self` in place, or return false to remove the value.
    fn outer_combine_with(
        &mut self,
        that: &impl AbstractRadixTree<K, V, Materialized = Self::Materialized>,
        f: impl Fn(&mut V, &V) -> bool + Copy,
    ) {
        let n = common_prefix(self.prefix(), that.prefix());
        if n == self.prefix().len() && n == that.prefix().len() {
            // prefixes are identical
            if let Some(w) = that.value() {
                if let Some(v) = &mut self.value_mut() {
                    if !f(v, w) {
                        *self.value_mut() = None;
                    }
                } else {
                    *self.value_mut() = Some(w.clone())
                }
            }
            self.outer_combine_children_with(that.children(), f);
        } else if n == self.prefix().len() {
            // self is a prefix of that
            let that = that.materialize_shortened(n);
            self.outer_combine_children_with(&[that], f);
        } else if n == that.prefix().len() {
            // that is a prefix of self
            // split at the offset, then merge in that
            // we must not swap sides!
            self.split(n);
            // self now has the same prefix as that, so just repeat the code
            // from where prefixes are identical
            if let Some(w) = that.value() {
                if let Some(v) = &mut self.value_mut() {
                    if !f(v, w) {
                        *self.value_mut() = None;
                    }
                } else {
                    *self.value_mut() = Some(w.clone())
                }
            }
            self.outer_combine_children_with(that.children(), f);
        } else {
            // disjoint
            self.split(n);
            self.children_mut().push(that.materialize_shortened(n));
            self.children_mut().sort_by_key(|x| x.prefix()[0]);
        }
        self.unsplit();
    }

    /// inner combine of `self` tree with `that` tree
    ///
    /// inner means that elements that are in `self` but not in `that` or vice versa are removed.
    /// for elements that are in both trees, it is possible to customize how they are combined.
    /// `f` can mutate the value of `self` in place, or return false to remove the value.
    fn inner_combine_with<W: TValue>(
        &mut self,
        that: &impl AbstractRadixTree<K, W>,
        f: impl Fn(&mut V, &W) -> bool + Copy,
    ) {
        let n = common_prefix(self.prefix(), that.prefix());
        if n == self.prefix().len() && n == that.prefix().len() {
            // prefixes are identical
            if let (Some(v), Some(w)) = (self.value_mut(), that.value()) {
                if !f(v, w) {
                    *self.value_mut() = None;
                }
            } else {
                *self.value_mut() = None;
            }
            self.inner_combine_children_with(that.children(), f);
        } else if n == self.prefix().len() {
            // self is a prefix of that
            *self.value_mut() = None;
            let that = that.materialize_shortened(n);
            self.inner_combine_children_with(&[that], f);
        } else if n == that.prefix().len() {
            // that is a prefix of self
            // split at the offset, then merge in that
            // we must not swap sides!
            self.split(n);
            self.inner_combine_children_with(that.children(), f);
        } else {
            // disjoint
            *self.value_mut() = None;
            self.children_mut().clear();
        }
        self.unsplit();
    }

    /// Left combine of `self` tree with `that` tree
    ///
    /// Left means that elements that are in `self` but not in `that` are kept, but elements that
    /// are in `that` but not in `self` are dropped.
    ///
    /// For elements that are in both trees, it is possible to customize how they are combined.
    /// `f` can mutate the value of `self` in place, or return false to remove the value.
    fn left_combine_with<W: TValue>(
        &mut self,
        that: &impl AbstractRadixTree<K, W>,
        f: impl Fn(&mut V, &W) -> bool + Copy,
    ) {
        let n = common_prefix(self.prefix(), that.prefix());
        if n == self.prefix().len() && n == that.prefix().len() {
            // prefixes are identical
            if let Some(w) = that.value() {
                if let Some(v) = self.value_mut() {
                    if !f(v, w) {
                        *self.value_mut() = None;
                    }
                }
            }
            self.left_combine_children_with(that.children(), f);
        } else if n == self.prefix().len() {
            // self is a prefix of that
            let that = that.materialize_shortened(n);
            self.left_combine_children_with(&[that], f);
        } else if n == that.prefix().len() {
            // that is a prefix of self
            self.split(n);
            self.left_combine_children_with(that.children(), f);
        } else {
            // disjoint, nothing to do
        }
        self.unsplit();
    }

    /// Remove all parts of the tree for which that contains a prefix.
    ///
    /// The predicate `f` is used to filter the tree `that` before applying it.
    /// If the predicate returns always false, this will be a noop.
    fn remove_prefix_with<W: TValue>(
        &mut self,
        that: &impl AbstractRadixTree<K, W>,
        f: impl Fn(&W) -> bool + Copy,
    ) {
        let n = common_prefix(self.prefix(), that.prefix());
        if n == self.prefix().len() && n == that.prefix().len() {
            // prefixes are identical
            match that.value() {
                Some(value) if f(value) => {
                    *self.value_mut() = None;
                    self.children_mut().clear();
                }
                _ => {
                    self.remove_prefix_children_with(that.children(), f);
                }
            }
        } else if n == that.prefix().len() {
            // that is a prefix of self
            match that.value() {
                Some(value) if f(value) => {
                    *self.value_mut() = None;
                    self.children_mut().clear();
                }
                _ => {
                    self.split(n);
                    self.remove_prefix_children_with(that.children(), f);
                }
            }
        } else if n == self.prefix().len() {
            // self is a prefix of that
            let that = that.materialize_shortened(n);
            self.remove_prefix_children_with(&[that], f);
        } else {
            // disjoint, nothing to do
        }
        self.unsplit();
    }

    /// Retain all parts of the tree for which that contains a prefix.
    ///
    /// The predicate `f` is used to filter the tree `that` before applying it.
    /// If the predicate returns always false, this will result in the empty tree.
    fn retain_prefix_with<W: TValue>(
        &mut self,
        that: &impl AbstractRadixTree<K, W>,
        f: impl Fn(&W) -> bool + Copy,
    ) {
        let n = common_prefix(self.prefix(), that.prefix());
        if n == self.prefix().len() && n == that.prefix().len() {
            // prefixes are identical
            if that.value().is_none() || !f(that.value().unwrap()) {
                *self.value_mut() = None;
                self.retain_prefix_children_with(that.children(), f);
            }
        } else if n == that.prefix().len() {
            // that is a prefix of self
            if that.value().is_none() || !f(that.value().unwrap()) {
                self.split(n);
                self.retain_prefix_children_with(that.children(), f);
            } // otherwise, keep it all
        } else if n == self.prefix().len() {
            // self is a prefix of that
            *self.value_mut() = None;
            let that = that.materialize_shortened(n);
            self.retain_prefix_children_with(&[that], f);
        } else {
            // disjoint, nuke it
            *self.value_mut() = None;
            self.children_mut().clear();
        }
        self.unsplit();
    }
}

/// Implement the public AbstractRadixTreeMut for everything that has internals::AbstractRadixTreeMut implemented,
/// which can only be in this crate.
impl<K: TKey, V: TValue, T: internals::AbstractRadixTreeMut<K, V>> AbstractRadixTreeMut<K, V>
    for T
{
}

/// Trait to abstract over radix trees.
///
/// This is mostly for DRYing the various flavours of radix trees in this crate as well as their rkyved versions.
pub trait AbstractRadixTree<K: TKey, V: TValue>: Sized {
    /// The prefix of this node. May only be empty for the top level node of a tree
    fn prefix(&self) -> &[K];

    /// The optional value
    fn value(&self) -> Option<&V>;

    /// The children
    fn children(&self) -> &[Self];

    /// Type of a materialized, mutable version of this tree
    type Materialized: AbstractRadixTreeMut<K, V, Materialized = Self::Materialized>;

    /// True if the tree is empty
    fn is_empty(&self) -> bool {
        self.value().is_none() && self.children().is_empty()
    }

    /// true if two maps have values at the same keys
    fn intersects<W: TValue>(&self, that: &impl AbstractRadixTree<K, W>) -> bool {
        intersects(self, that)
    }

    /// true if two maps have no values at the same keys
    fn is_disjoint<W: TValue>(&self, that: &impl AbstractRadixTree<K, W>) -> bool {
        !intersects(self, that)
    }

    /// iterate over all elements
    fn iter<'a>(&'a self) -> Iter<'a, K, V, Self>
    where
        K: 'a,
    {
        Iter::new(self, IterKey::new(self.prefix()))
    }

    /// iterate over all elements
    fn into_iter(self) -> ObjAndIter<Self, Iter<'static, K, V, Self>> {
        ObjAndIter::new(Box::new(self), |x| x.iter())
    }

    /// iterate over all values - this is cheaper than iterating over elements, since it does not have to build the keys from fragments
    fn values<'a>(&'a self) -> Values<'a, K, V, Self>
    where
        K: 'a,
    {
        Values::new(self)
    }

    /// True if key is contained in this set
    fn contains_key(&self, key: &[K]) -> bool {
        // if we find a tree at exactly the location, and it has a value, we have a hit
        if let FindResult::Found(tree) = find(self, key) {
            tree.value().is_some()
        } else {
            false
        }
    }

    /// Get an optional reference to the value for the given key
    fn get(&self, key: &[K]) -> Option<&V> {
        // if we find a tree at exactly the location, and it has a value, we have a hit
        if let FindResult::Found(tree) = find(self, key) {
            tree.value()
        } else {
            None
        }
    }

    /// true if the keys of self are a subset of the keys of that.
    ///
    /// a set is considered to be a subset of itself.
    fn is_subset<W: TValue>(&self, that: &impl AbstractRadixTree<K, W>) -> bool {
        is_subset(self, that)
    }

    /// true if the keys of self are a superset of the keys of that.
    ///
    /// a set is considered to be a subset of itself.
    fn is_superset<W: TValue>(&self, that: &impl AbstractRadixTree<K, W>) -> bool {
        is_subset(that, self)
    }

    fn materialize_shortened(&self, n: usize) -> Self::Materialized {
        assert!(n < self.prefix().len());
        Self::Materialized::new(
            self.prefix()[n..].into(),
            self.value().cloned(),
            self.children()
                .iter()
                .map(|x| x.materialize_shortened(0))
                .collect(),
        )
    }

    /// Outer combine this tree with another tree, using the given combine function
    fn outer_combine(
        &self,
        that: &impl AbstractRadixTree<K, V, Materialized = Self::Materialized>,
        f: impl Fn(&V, &V) -> Option<V> + Copy,
    ) -> Self::Materialized {
        outer_combine(self, that, f)
    }

    /// Inner combine this tree with another tree, using the given combine function
    fn inner_combine<W: TValue>(
        &self,
        that: &impl AbstractRadixTree<K, W>,
        f: impl Fn(&V, &W) -> Option<V> + Copy,
    ) -> Self::Materialized {
        inner_combine(self, that, f)
    }

    /// Left combine this tree with another tree, using the given combine function
    fn left_combine<W: TValue>(
        &self,
        that: &impl AbstractRadixTree<K, W>,
        f: impl Fn(&V, Option<&W>) -> Option<V> + Copy,
    ) -> Self::Materialized {
        left_combine(self, that, f)
    }

    /// An iterator for all pairs with a certain prefix
    fn scan_prefix<'a>(&'a self, prefix: &'a [K]) -> Iter<'a, K, V, Self> {
        match find(self, prefix) {
            FindResult::Found(tree) => {
                let prefix = IterKey::new(prefix);
                Iter::new(tree, prefix)
            }
            FindResult::Prefix { tree, rt } => {
                let mut prefix = IterKey::new(prefix);
                let remaining = &tree.prefix()[tree.prefix().len() - rt..];
                prefix.append(remaining);
                Iter::new(tree, prefix)
            }
            FindResult::NotFound { .. } => Iter::empty(),
        }
    }
}

enum FindResult<T> {
    // Found an exact match
    Found(T),
    // found a tree for which the path is a prefix, with n remaining chars in the prefix of T
    Prefix {
        // a tree of which the searched path is a prefix
        tree: T,
        // number of remaining elements in the prefix of the tree
        rt: usize,
    },
    // did not find anything, T is the closest match, with n remaining (unmatched) in the prefix of T
    NotFound {
        // the closest match
        closest: T,
        // number of remaining elements in the prefix of the tree
        rt: usize,
        // number of remaining elements in the search prefix
        rp: usize,
    },
}

/// find a prefix in a tree. Will either return
/// - Found(tree) if we found the tree exactly,
/// - Prefix if we found a tree of which prefix is a prefix
/// - NotFound if there is no tree
fn find<'a, K: TKey, V: TValue, T: AbstractRadixTree<K, V>>(
    tree: &'a T,
    prefix: &[K],
) -> FindResult<&'a T> {
    let n = common_prefix(tree.prefix(), prefix);
    // remaining in prefix
    let rp = prefix.len() - n;
    // remaining in tree prefix
    let rt = tree.prefix().len() - n;
    if rp == 0 && rt == 0 {
        // direct hit
        FindResult::Found(tree)
    } else if rp == 0 {
        // tree is a subtree of prefix
        FindResult::Prefix { tree, rt }
    } else if rt == 0 {
        // prefix is a subtree of tree
        let c = &prefix[n];
        if let Ok(index) = tree.children().binary_search_by(|e| e.prefix()[0].cmp(c)) {
            let child = &tree.children()[index];
            find(child, &prefix[n..])
        } else {
            FindResult::NotFound {
                closest: tree,
                rp,
                rt,
            }
        }
    } else {
        // disjoint, but we still need to store how far we matched
        FindResult::NotFound {
            closest: tree,
            rp,
            rt,
        }
    }
}

fn materialize<T, K: TKey, V: TValue>(tree: &T) -> T::Materialized
where
    K: Clone,
    V: Clone,
    T: AbstractRadixTree<K, V>,
{
    materialize_shortened(tree, 0)
}

fn materialize_shortened<T, K: TKey, V: TValue>(tree: &T, n: usize) -> T::Materialized
where
    K: Clone,
    V: Clone,
    T: AbstractRadixTree<K, V>,
{
    assert!(n < tree.prefix().len());
    T::Materialized::new(
        tree.prefix()[n..].into(),
        tree.value().cloned(),
        tree.children().iter().map(materialize).collect(),
    )
}

/// Key for iteration
///
/// This refers to a temporary key that is being constructed during iteration. Cloning it will make a copy.
#[derive(Debug, Clone)]
pub struct IterKey<K>(Arc<Vec<K>>);

impl<K: Clone> IterKey<K> {
    fn new(root: &[K]) -> Self {
        Self(Arc::new(root.to_vec()))
    }

    fn append(&mut self, data: &[K]) {
        // for typical iterator use, a reference is not kept for a long time, so this will be very cheap
        //
        // in the case a reference is kept, this will make a copy.
        let elems = Arc::make_mut(&mut self.0);
        elems.extend_from_slice(data);
    }

    fn pop(&mut self, n: usize) {
        let elems = Arc::make_mut(&mut self.0);
        elems.truncate(elems.len().saturating_sub(n));
    }
}

impl<T> AsRef<[T]> for IterKey<T> {
    fn as_ref(&self) -> &[T] {
        self.0.as_ref()
    }
}

impl<T> Borrow<[T]> for IterKey<T> {
    fn borrow(&self) -> &[T] {
        self.0.as_ref()
    }
}

impl<T> core::ops::Deref for IterKey<T> {
    type Target = [T];

    fn deref(&self) -> &Self::Target {
        self.0.as_ref()
    }
}

/// An iterator over the values of a radix tree.
///
/// This is more efficient than taking the value part of an entry iteration, because the keys
/// do not have to be constructed.
pub struct Values<'a, K, V, T> {
    stack: Vec<(&'a T, usize)>,
    _p: PhantomData<(K, V)>,
}

impl<'a, K, V, T> Values<'a, K, V, T> {
    fn new(tree: &'a T) -> Self {
        Self {
            stack: vec![(tree, 0)],
            _p: PhantomData,
        }
    }

    fn tree(&self) -> &'a T {
        self.stack.last().unwrap().0
    }

    fn inc(&mut self) -> Option<usize> {
        let pos = &mut self.stack.last_mut().unwrap().1;
        let res = if *pos == 0 { None } else { Some(*pos - 1) };
        *pos += 1;
        res
    }
}

impl<'a, K: TKey, V: TValue, T> Iterator for Values<'a, K, V, T>
where
    T: AbstractRadixTree<K, V>,
{
    type Item = &'a V;

    fn next(&mut self) -> Option<Self::Item> {
        while !self.stack.is_empty() {
            if let Some(pos) = self.inc() {
                if pos < self.tree().children().len() {
                    self.stack.push((&self.tree().children()[pos], 0));
                } else {
                    self.stack.pop();
                }
            } else if let Some(value) = self.tree().value() {
                return Some(value);
            }
        }
        None
    }
}

/// An iterator over the elements (key and value) of a radix tree
///
/// A complication of this compared to an iterator for a normal collection is that the keys do
/// not acutally exist, but are constructed on demand during iteration.
pub struct Iter<'a, K, V, T> {
    path: IterKey<K>,
    stack: Vec<(&'a T, usize)>,
    _v: PhantomData<V>,
}

impl<'a, K: TKey, V: TValue, T: AbstractRadixTree<K, V>> Iter<'a, K, V, T> {
    fn empty() -> Self {
        Self {
            stack: Vec::new(),
            path: IterKey::new(&[]),
            _v: PhantomData,
        }
    }

    fn new(tree: &'a T, prefix: IterKey<K>) -> Self {
        Self {
            stack: vec![(tree, 0)],
            path: prefix,
            _v: PhantomData,
        }
    }

    fn tree(&self) -> &'a T {
        self.stack.last().unwrap().0
    }

    fn inc(&mut self) -> Option<usize> {
        let pos = &mut self.stack.last_mut().unwrap().1;
        let res = if *pos == 0 { None } else { Some(*pos - 1) };
        *pos += 1;
        res
    }
}

impl<'a, K: TKey, V: TValue, T: AbstractRadixTree<K, V>> SortedByKey for Iter<'a, K, V, T> {}

impl<'a, K: TKey, V: 'a + TValue, T: AbstractRadixTree<K, V>> Iterator for Iter<'a, K, V, T> {
    type Item = (IterKey<K>, &'a V);

    fn next(&mut self) -> Option<Self::Item> {
        while !self.stack.is_empty() {
            if let Some(pos) = self.inc() {
                if pos < self.tree().children().len() {
                    let child = &self.tree().children()[pos];
                    self.path.append(child.prefix());
                    self.stack.push((child, 0));
                } else {
                    self.path.pop(self.tree().prefix().len());
                    self.stack.pop();
                }
            } else if let Some(value) = self.tree().value().as_ref() {
                return Some((self.path.clone(), value));
            }
        }
        None
    }
}

struct RadixTreeConverter<K, V>(PhantomData<(K, V)>);

impl<T: AbstractRadixTree<K, V>, K: TKey, V: TValue> Converter<&T, T::Materialized>
    for RadixTreeConverter<K, V>
{
    fn convert(value: &T) -> T::Materialized {
        materialize(value)
    }
}

fn is_subset<K: TKey, V: TValue, W: TValue>(
    l: &impl AbstractRadixTree<K, V>,
    r: &impl AbstractRadixTree<K, W>,
) -> bool {
    is_subset0(l, l.prefix(), r, r.prefix())
}

fn is_subset0<K: TKey, V: TValue, W: TValue>(
    l: &impl AbstractRadixTree<K, V>,
    l_prefix: &[K],
    r: &impl AbstractRadixTree<K, W>,
    r_prefix: &[K],
) -> bool {
    let n = common_prefix(l_prefix, r_prefix);
    if n == l_prefix.len() && n == r_prefix.len() {
        // prefixes are identical
        (l.value().is_none() || r.value().is_some())
            && !BoolOpMergeState::merge(l.children(), r.children(), NonSubsetOp(PhantomData))
    } else if n == l_prefix.len() {
        // l is a prefix of r - shorten r_prefix
        let r_prefix = &r_prefix[n..];
        // if l has a value but not r, we found one
        // if one or more of lc are not a subset of r, we are done
        l.value().is_none()
            && l.children()
                .iter()
                .all(|lc| is_subset0(lc, lc.prefix(), r, r_prefix))
    } else if n == r_prefix.len() {
        // r is a prefix of l - shorten L_prefix
        let l_prefix = &l_prefix[n..];
        // if l is a subset of none of rc, we are done
        r.children()
            .iter()
            .any(|rc| is_subset0(l, l_prefix, rc, rc.prefix()))
    } else {
        // disjoint
        false
    }
}

fn intersects<K: TKey, V: TValue, W: TValue>(
    l: &impl AbstractRadixTree<K, V>,
    r: &impl AbstractRadixTree<K, W>,
) -> bool {
    intersects0(l, l.prefix(), r, r.prefix())
}

fn intersects0<K: TKey, V: TValue, W: TValue>(
    l: &impl AbstractRadixTree<K, V>,
    l_prefix: &[K],
    r: &impl AbstractRadixTree<K, W>,
    r_prefix: &[K],
) -> bool {
    let n = common_prefix(l_prefix, r_prefix);
    if n == l_prefix.len() && n == r_prefix.len() {
        // prefixes are identical
        (l.value().is_some() && r.value().is_some())
            || BoolOpMergeState::merge(l.children(), r.children(), IntersectOp(PhantomData))
    } else if n == l_prefix.len() {
        // l is a prefix of r
        let r_prefix = &r_prefix[n..];
        l.children()
            .iter()
            .any(|lc| intersects0(lc, lc.prefix(), r, r_prefix))
    } else if n == r_prefix.len() {
        // r is a prefix of l
        let l_prefix = &l_prefix[n..];
        r.children()
            .iter()
            .any(|rc| intersects0(l, l_prefix, rc, rc.prefix()))
    } else {
        // disjoint
        false
    }
}

/// Outer combine two trees with a function f
fn outer_combine<
    K: TKey,
    V: TValue,
    R: AbstractRadixTreeMut<K, V, Materialized = R>,
    A: AbstractRadixTree<K, V, Materialized = R>,
    B: AbstractRadixTree<K, V, Materialized = R>,
>(
    a: &A,
    b: &B,
    f: impl Fn(&V, &V) -> Option<V> + Copy,
) -> R {
    let n = common_prefix(a.prefix(), b.prefix());
    let prefix = a.prefix()[..n].into();
    let mut children = Vec::new();
    let mut value = None;
    if n == a.prefix().len() && n == b.prefix().len() {
        // prefixes are identical
        value = match (a.value(), b.value()) {
            (Some(a), Some(b)) => f(a, b),
            (Some(a), None) => Some(a.clone()),
            (None, Some(b)) => Some(b.clone()),
            (None, None) => None,
        };
        children = VecMergeState::merge(
            a.children(),
            b.children(),
            OuterCombineOp(f, PhantomData),
            RadixTreeConverter(PhantomData),
            RadixTreeConverter(PhantomData),
        );
    } else if n == a.prefix().len() {
        // a is a prefix of b
        let b = b.materialize_shortened(n);
        value = a.value().cloned();
        children = VecMergeState::merge(
            a.children(),
            &[b],
            OuterCombineOp(f, PhantomData),
            RadixTreeConverter(PhantomData),
            RadixTreeConverter(PhantomData),
        );
    } else if n == b.prefix().len() {
        // b is a prefix of a
        let a = a.materialize_shortened(n);
        value = b.value().cloned();
        children = VecMergeState::merge(
            &[a],
            b.children(),
            OuterCombineOp(f, PhantomData),
            RadixTreeConverter(PhantomData),
            RadixTreeConverter(PhantomData),
        );
    } else {
        // disjoint
        children.push(a.materialize_shortened(n));
        children.push(b.materialize_shortened(n));
        children.sort_by_key(|x| x.prefix()[0]);
    }
    let mut res = R::new(prefix, value, children);
    res.unsplit();
    res
}

/// Inner combine two trees with a function f
fn inner_combine<K: TKey, V: TValue, W: TValue, R: AbstractRadixTreeMut<K, V, Materialized = R>>(
    a: &impl AbstractRadixTree<K, V, Materialized = R>,
    b: &impl AbstractRadixTree<K, W>,
    f: impl Fn(&V, &W) -> Option<V> + Copy,
) -> R {
    let n = common_prefix(a.prefix(), b.prefix());
    let prefix = a.prefix()[..n].into();
    let mut children = Vec::<R>::new();
    let mut value = None;
    if n == a.prefix().len() && n == b.prefix().len() {
        // prefixes are identical
        value = match (a.value(), b.value()) {
            (Some(a), Some(b)) => f(a, b),
            _ => None,
        };
        children = VecMergeState::merge(
            a.children(),
            b.children(),
            InnerCombineOp(f, PhantomData),
            RadixTreeConverter(PhantomData),
            NoConverter,
        );
    } else if n == a.prefix().len() {
        // a is a prefix of b
        let b = b.materialize_shortened(n);
        children = VecMergeState::merge(
            a.children(),
            &[b],
            InnerCombineOp(f, PhantomData),
            RadixTreeConverter(PhantomData),
            NoConverter,
        );
    } else if n == b.prefix().len() {
        // b is a prefix of a
        let a = a.materialize_shortened(n);
        children = VecMergeState::merge(
            &[a],
            b.children(),
            InnerCombineOp(f, PhantomData),
            RadixTreeConverter(PhantomData),
            NoConverter,
        );
    } else {
        // disjoint
    }
    let mut res = R::new(prefix, value, children);
    res.unsplit();
    res
}

/// Left combine two trees with a function f
fn left_combine<K: TKey, V: TValue, W: TValue, R: AbstractRadixTreeMut<K, V, Materialized = R>>(
    a: &impl AbstractRadixTree<K, V, Materialized = R>,
    b: &impl AbstractRadixTree<K, W>,
    f: impl Fn(&V, Option<&W>) -> Option<V> + Copy,
) -> R {
    let n = common_prefix(a.prefix(), b.prefix());
    let mut prefix = a.prefix()[..n].into();
    let children;
    let mut value = None;
    if n == a.prefix().len() && n == b.prefix().len() {
        // prefixes are identical
        value = match (a.value(), b.value()) {
            (Some(a), b) => f(a, b),
            _ => None,
        };
        children = VecMergeState::merge(
            a.children(),
            b.children(),
            LeftCombineOp(f, PhantomData),
            RadixTreeConverter(PhantomData),
            NoConverter,
        );
    } else if n == a.prefix().len() {
        // a is a prefix of b
        let b = b.materialize_shortened(n);
        value = a.value().cloned();
        children = VecMergeState::merge(
            a.children(),
            &[b],
            LeftCombineOp(f, PhantomData),
            RadixTreeConverter(PhantomData),
            NoConverter,
        );
    } else if n == b.prefix().len() {
        // b is a prefix of a
        let a = a.materialize_shortened(n);
        children = VecMergeState::merge(
            &[a],
            b.children(),
            LeftCombineOp(f, PhantomData),
            RadixTreeConverter(PhantomData),
            NoConverter,
        );
    } else {
        // disjoint
        prefix = a.prefix().into();
        value = a.value().cloned();
        children = a
            .children()
            .iter()
            .map(|x| x.materialize_shortened(0))
            .collect();
    }
    let mut res = R::new(prefix, value, children);
    res.unsplit();
    res
}

struct IntersectOp<T>(PhantomData<T>);

impl<'a, K, V, W, I> MergeOperation<I> for IntersectOp<(K, V, W)>
where
    K: TKey,
    V: TValue,
    W: TValue,
    I: MergeStateMut,
    I::A: AbstractRadixTree<K, V>,
    I::B: AbstractRadixTree<K, W>,
{
    fn cmp(&self, a: &I::A, b: &I::B) -> Ordering {
        a.prefix()[0].cmp(&b.prefix()[0])
    }
    fn from_a(&self, m: &mut I, n: usize) -> bool {
        m.advance_a(n, false)
    }
    fn from_b(&self, m: &mut I, n: usize) -> bool {
        m.advance_b(n, false)
    }
    fn collision(&self, m: &mut I) -> bool {
        let a = &m.a_slice()[0];
        let b = &m.b_slice()[0];
        // if this is true, we have found an intersection and can abort.
        let take = intersects(a, b);
        m.advance_a(1, take) && m.advance_b(1, false)
    }
}
struct NonSubsetOp<V>(PhantomData<V>);

impl<'a, K, V, W, I> MergeOperation<I> for NonSubsetOp<(K, V, W)>
where
    K: TKey,
    V: TValue,
    W: TValue,
    I: MergeStateMut,
    I::A: AbstractRadixTree<K, V>,
    I::B: AbstractRadixTree<K, W>,
{
    fn cmp(&self, a: &I::A, b: &I::B) -> Ordering {
        a.prefix()[0].cmp(&b.prefix()[0])
    }
    fn from_a(&self, m: &mut I, n: usize) -> bool {
        m.advance_a(n, true)
    }
    fn from_b(&self, m: &mut I, n: usize) -> bool {
        m.advance_b(n, false)
    }
    fn collision(&self, m: &mut I) -> bool {
        let a = &m.a_slice()[0];
        let b = &m.b_slice()[0];
        // if this is true, we have found a value of a that is not in b, and we can abort
        let take = !a.is_subset(b);
        m.advance_a(1, take) && m.advance_b(1, false)
    }
}

/// In place merge operation
struct OuterCombineOp<F, P>(F, PhantomData<P>);

impl<'a, F, K, V, A, B, C> MergeOperation<InPlaceVecMergeStateRef<'a, A, B, C>>
    for OuterCombineOp<F, (K, V)>
where
    K: TKey,
    V: TValue,
    F: Fn(&mut V, &V) -> bool + Copy,
    B: AbstractRadixTree<K, V, Materialized = A>,
    C: Converter<&'a B, A>,
    A: AbstractRadixTreeMut<K, V, Materialized = A>,
{
    fn cmp(&self, a: &A, b: &B) -> Ordering {
        a.prefix()[0].cmp(&b.prefix()[0])
    }
    fn from_a(&self, m: &mut InPlaceVecMergeStateRef<'a, A, B, C>, n: usize) -> bool {
        m.advance_a(n, true)
    }
    fn from_b(&self, m: &mut InPlaceVecMergeStateRef<'a, A, B, C>, n: usize) -> bool {
        m.advance_b(n, true)
    }
    fn collision(&self, m: &mut InPlaceVecMergeStateRef<'a, A, B, C>) -> bool {
        let (a, b) = m.source_slices_mut();
        let av = &mut a[0];
        let bv = &b[0];
        av.outer_combine_with(bv, self.0);
        // we have modified av in place. We are only going to take it over if it
        // is non-empty, otherwise we skip it.
        let take = !av.is_empty();
        m.advance_a(1, take) && m.advance_b(1, false)
    }
}

impl<'a, F, K, V, A, B, R>
    MergeOperation<VecMergeState<'a, A, B, R, RadixTreeConverter<K, V>, RadixTreeConverter<K, V>>>
    for OuterCombineOp<F, ()>
where
    K: TKey,
    V: TValue,
    A: AbstractRadixTree<K, V, Materialized = R>,
    B: AbstractRadixTree<K, V, Materialized = R>,
    F: Fn(&V, &V) -> Option<V> + Copy,
    R: AbstractRadixTreeMut<K, V, Materialized = R>,
{
    fn cmp(&self, a: &A, b: &B) -> Ordering {
        a.prefix()[0].cmp(&b.prefix()[0])
    }
    fn from_a(
        &self,
        m: &mut VecMergeState<'a, A, B, R, RadixTreeConverter<K, V>, RadixTreeConverter<K, V>>,
        n: usize,
    ) -> bool {
        m.advance_a(n, true)
    }
    fn from_b(
        &self,
        m: &mut VecMergeState<'a, A, B, R, RadixTreeConverter<K, V>, RadixTreeConverter<K, V>>,
        n: usize,
    ) -> bool {
        m.advance_b(n, true)
    }
    fn collision(
        &self,
        m: &mut VecMergeState<'a, A, B, R, RadixTreeConverter<K, V>, RadixTreeConverter<K, V>>,
    ) -> bool {
        let a = m.a.next().unwrap();
        let b = m.b.next().unwrap();
        let res: R = outer_combine(a, b, self.0);
        if !res.is_empty() {
            m.r.push(res);
        }
        true
    }
}

/// In place intersection operation
struct InnerCombineOp<F, P>(F, PhantomData<P>);

impl<'a, K, V, W, F, I, R> MergeOperation<I> for InnerCombineOp<F, (K, V, W)>
where
    K: TKey,
    V: TValue,
    W: TValue,
    F: Fn(&mut V, &W) -> bool + Copy,
    I: MutateInput<A = R>,
    I::B: AbstractRadixTree<K, W>,
    R: AbstractRadixTreeMut<K, V, Materialized = R>,
{
    fn cmp(&self, a: &I::A, b: &I::B) -> Ordering {
        a.prefix()[0].cmp(&b.prefix()[0])
    }
    fn from_a(&self, m: &mut I, n: usize) -> bool {
        m.advance_a(n, false)
    }
    fn from_b(&self, m: &mut I, n: usize) -> bool {
        m.advance_b(n, false)
    }
    fn collision(&self, m: &mut I) -> bool {
        let (a, b) = m.source_slices_mut();
        let av = &mut a[0];
        let bv = &b[0];
        av.inner_combine_with(bv, self.0);
        // we have modified av in place. We are only going to take it over if it
        // is non-empty, otherwise we skip it.
        let take = !av.is_empty();
        m.advance_a(1, take) && m.advance_b(1, false)
    }
}

impl<'a, F, K, V, W, A, B, R>
    MergeOperation<VecMergeState<'a, A, B, R, RadixTreeConverter<K, V>, NoConverter>>
    for InnerCombineOp<F, W>
where
    K: TKey,
    V: TValue,
    W: TValue,
    A: AbstractRadixTree<K, V, Materialized = R>,
    B: AbstractRadixTree<K, W>,
    R: AbstractRadixTreeMut<K, V, Materialized = R>,
    F: Fn(&V, &W) -> Option<V> + Copy,
{
    fn cmp(&self, a: &A, b: &B) -> Ordering {
        a.prefix()[0].cmp(&b.prefix()[0])
    }
    fn from_a(
        &self,
        m: &mut VecMergeState<'a, A, B, R, RadixTreeConverter<K, V>, NoConverter>,
        n: usize,
    ) -> bool {
        m.advance_a(n, false)
    }
    fn from_b(
        &self,
        m: &mut VecMergeState<'a, A, B, R, RadixTreeConverter<K, V>, NoConverter>,
        n: usize,
    ) -> bool {
        m.advance_b(n, false)
    }
    fn collision(
        &self,
        m: &mut VecMergeState<'a, A, B, R, RadixTreeConverter<K, V>, NoConverter>,
    ) -> bool {
        let a = m.a.next().unwrap();
        let b = m.b.next().unwrap();
        let res = inner_combine(a, b, self.0);
        if !res.is_empty() {
            m.r.push(res);
        }
        true
    }
}

/// In place intersection operation
struct LeftCombineOp<F, P>(F, PhantomData<P>);

impl<'a, K, V, W, F, I, R> MergeOperation<I> for LeftCombineOp<F, (K, V, W)>
where
    K: TKey,
    V: TValue,
    W: TValue,
    F: Fn(&mut V, &W) -> bool + Copy,
    I: MutateInput<A = R>,
    I::B: AbstractRadixTree<K, W>,
    R: AbstractRadixTreeMut<K, V, Materialized = R>,
{
    fn cmp(&self, a: &I::A, b: &I::B) -> Ordering {
        a.prefix()[0].cmp(&b.prefix()[0])
    }
    fn from_a(&self, m: &mut I, n: usize) -> bool {
        m.advance_a(n, true)
    }
    fn from_b(&self, m: &mut I, n: usize) -> bool {
        m.advance_b(n, false)
    }
    fn collision(&self, m: &mut I) -> bool {
        let (a, b) = m.source_slices_mut();
        let av = &mut a[0];
        let bv = &b[0];
        av.left_combine_with(bv, self.0);
        // we have modified av in place. We are only going to take it over if it
        // is non-empty, otherwise we skip it.
        let take = !av.is_empty();
        m.advance_a(1, take) && m.advance_b(1, false)
    }
}

impl<'a, F, K, V, W, A, B, R>
    MergeOperation<VecMergeState<'a, A, B, R, RadixTreeConverter<K, V>, NoConverter>>
    for LeftCombineOp<F, W>
where
    K: TKey,
    V: TValue,
    W: TValue,
    A: AbstractRadixTree<K, V, Materialized = R>,
    B: AbstractRadixTree<K, W>,
    R: AbstractRadixTreeMut<K, V, Materialized = R>,
    F: Fn(&V, Option<&W>) -> Option<V> + Copy,
{
    fn cmp(&self, a: &A, b: &B) -> Ordering {
        a.prefix()[0].cmp(&b.prefix()[0])
    }
    fn from_a(
        &self,
        m: &mut VecMergeState<'a, A, B, R, RadixTreeConverter<K, V>, NoConverter>,
        n: usize,
    ) -> bool {
        m.advance_a(n, true)
    }
    fn from_b(
        &self,
        m: &mut VecMergeState<'a, A, B, R, RadixTreeConverter<K, V>, NoConverter>,
        n: usize,
    ) -> bool {
        m.advance_b(n, false)
    }
    fn collision(
        &self,
        m: &mut VecMergeState<'a, A, B, R, RadixTreeConverter<K, V>, NoConverter>,
    ) -> bool {
        let a = m.a.next().unwrap();
        let b = m.b.next().unwrap();
        let res = left_combine(a, b, self.0);
        if !res.is_empty() {
            m.r.push(res);
        }
        true
    }
}

/// Remove prefixes of b in a
struct RemovePrefixOp<F, P>(F, PhantomData<P>);

impl<'a, K, V, W, F, I, R> MergeOperation<I> for RemovePrefixOp<F, (K, V, W)>
where
    K: TKey,
    V: TValue,
    W: TValue,
    F: Fn(&W) -> bool + Copy,
    I: MutateInput<A = R>,
    I::B: AbstractRadixTree<K, W>,
    R: AbstractRadixTreeMut<K, V, Materialized = R>,
{
    fn cmp(&self, a: &I::A, b: &I::B) -> Ordering {
        a.prefix()[0].cmp(&b.prefix()[0])
    }
    fn from_a(&self, m: &mut I, n: usize) -> bool {
        m.advance_a(n, true)
    }
    fn from_b(&self, m: &mut I, n: usize) -> bool {
        m.advance_b(n, false)
    }
    fn collision(&self, m: &mut I) -> bool {
        let (a, b) = m.source_slices_mut();
        let av = &mut a[0];
        let bv = &b[0];
        av.remove_prefix_with(bv, self.0);
        // we have modified av in place. We are only going to take it over if it
        // is non-empty, otherwise we skip it.
        let take = !av.is_empty();
        m.advance_a(1, take) && m.advance_b(1, false)
    }
}

/// Retain prefixes of b in a
struct RetainPrefixOp<F, P>(F, PhantomData<P>);

impl<'a, K, V, W, F, I, R> MergeOperation<I> for RetainPrefixOp<F, (K, V, W)>
where
    K: TKey,
    V: TValue,
    W: TValue,
    F: Fn(&W) -> bool + Copy,
    I: MutateInput<A = R>,
    I::B: AbstractRadixTree<K, W>,
    R: AbstractRadixTreeMut<K, V, Materialized = R>,
{
    fn cmp(&self, a: &I::A, b: &I::B) -> Ordering {
        a.prefix()[0].cmp(&b.prefix()[0])
    }
    fn from_a(&self, m: &mut I, n: usize) -> bool {
        m.advance_a(n, false)
    }
    fn from_b(&self, m: &mut I, n: usize) -> bool {
        m.advance_b(n, false)
    }
    fn collision(&self, m: &mut I) -> bool {
        let (a, b) = m.source_slices_mut();
        let av = &mut a[0];
        let bv = &b[0];
        av.retain_prefix_with(bv, self.0);
        // we have modified av in place. We are only going to take it over if it
        // is non-empty, otherwise we skip it.
        let take = !av.is_empty();
        m.advance_a(1, take) && m.advance_b(1, false)
    }
}

#[cfg(test)]
mod test {
    use std::collections::BTreeSet;

    use super::*;
    use maplit::btreeset;
    use obey::*;
    use quickcheck::*;

    impl Arbitrary for RadixTree<u8, ()> {
        fn arbitrary<G: Gen>(g: &mut G) -> Self {
            let t: Vec<String> = Arbitrary::arbitrary(g);
            t.iter()
                .take(2)
                .map(|x| (x.as_bytes().to_vec(), ()))
                .collect()
        }
    }

    impl TestSamples<Vec<u8>, bool> for RadixTree<u8, ()> {
        fn samples(&self, res: &mut BTreeSet<Vec<u8>>) {
            res.insert(vec![]);
            for (k, _) in self.iter() {
                let a = k.as_ref().to_vec();
                let mut b = a.clone();
                let mut c = a.clone();
                b.push(0);
                c.pop();
                res.insert(a);
                res.insert(b);
                res.insert(c);
            }
        }

        fn at(&self, elem: Vec<u8>) -> bool {
            self.contains_key(&elem)
        }
    }

    type Test = RadixTree<u8, ()>;
    type Reference = BTreeSet<Vec<u8>>;

    fn r2t(r: &Reference) -> Test {
        r.iter().map(|t| (t.to_vec(), ())).collect()
    }

    quickcheck! {

        fn is_disjoint_sample(a: Test, b: Test) -> bool {
            binary_property_test(&a, &b, a.is_disjoint(&b), |a, b| !(a & b))
        }

        fn is_subset_sample(a: Reference, b: Reference) -> bool {
            let a = r2t(&a);
            let b = r2t(&b);
            binary_property_test(&a, &b, a.is_subset(&b), |a, b| !a | b)
        }

        fn union_sample(a: Test, b: Test) -> bool {
            let r = a.union(&b);
            binary_element_test(&a, &b, r, |a, b| a | b)
        }

        fn union_with_sample(a: Test, b: Test) -> bool {
            let mut r = a.clone();
            r.union_with(&b);
            binary_element_test(&a, &b, r, |a, b| a | b)
        }

        fn intersection_sample(a: Test, b: Test) -> bool {
            let r = a.intersection(&b);
            binary_element_test(&a, &b, r, |a, b| a & b)
        }

        fn intersection_with_sample(a: Test, b: Test) -> bool {
            let mut r = a.clone();
            r.intersection_with(&b);
            binary_element_test(&a, &b, r, |a, b| a & b)
        }

        fn difference_with_sample(a: Test, b: Test) -> bool {
            let mut r = a.clone();
            r.difference_with(&b);
            binary_element_test(&a, &b, r, |a, b| a & !b)
        }

        fn difference_sample(a: Test, b: Test) -> bool {
            let r = a.difference(&b);
            binary_element_test(&a, &b, r, |a, b| a & !b)
        }

        fn union(a: Reference, b: Reference) -> bool {
            let a1: Test = r2t(&a);
            let b1: Test = r2t(&b);
            let r1 = a1.union(&b1);
            let expected = r2t(&a.union(&b).cloned().collect());
            expected == r1
        }

        fn union_with(a: Reference, b: Reference) -> bool {
            let a1: Test = r2t(&a);
            let b1: Test = r2t(&b);
            let mut r1 = a1;
            r1.union_with(&b1);
            let expected = r2t(&a.union(&b).cloned().collect());
            expected == r1
        }

        fn intersection(a: Reference, b: Reference) -> bool {
            let a1: Test = r2t(&a);
            let b1: Test = r2t(&b);
            let r1 = a1.intersection(&b1);
            let expected = r2t(&a.intersection(&b).cloned().collect());
            expected == r1
        }

        fn intersection_with(a: Reference, b: Reference) -> bool {
            let a1: Test = r2t(&a);
            let b1: Test = r2t(&b);
            let mut r1 = a1;
            r1.intersection_with(&b1);
            let expected = r2t(&a.intersection(&b).cloned().collect());
            expected == r1
        }

        fn difference(a: Reference, b: Reference) -> bool {
            let a = a.into_iter().collect();
            let b = b.into_iter().collect();
            let a1: Test = r2t(&a);
            let b1: Test = r2t(&b);
            let r1 = a1.difference(&b1);
            let expected = r2t(&a.difference(&b).cloned().collect());
            if expected != r1 {
                println!("a:{:#?}\nb:{:#?}", a1, b1);
                println!("expected:{:#?}\nvalue:{:#?}", expected, r1);
            }
            expected == r1
        }

        fn difference_with(a: Reference, b: Reference) -> bool {
            let a = a.into_iter().collect();
            let b = b.into_iter().collect();
            let a1: Test = r2t(&a);
            let b1: Test = r2t(&b);
            let mut r1 = a1;
            r1.difference_with(&b1);
            let expected = r2t(&a.difference(&b).cloned().collect());
            if expected != r1 {
                println!("expected:{:#?}\nvalue:{:#?}", expected, r1);
            }
            expected == r1
        }

        fn remove_prefix(a: Reference, b: Reference) -> bool {
            let a = a.into_iter().collect();
            let b = b.into_iter().collect();
            let a1: Test = r2t(&a);
            let b1: Test = r2t(&b);
            let mut r1 = a1.clone();
            r1.remove_prefix_with(&b1, |_| true);
            let mut r = a;
            // keep all elements of a for which no element in b is a prefix
            r.retain(|re| !b.iter().any(|x| re.starts_with(x)));
            let expected = r2t(&r);
            if expected != r1 {
                println!("a:{:#?}\nb:{:#?}", a1, b1);
                println!("expected:{:#?}\nvalue:{:#?}", expected, r1);
            }
            expected == r1
        }

        fn retain_prefix(a: Reference, b: Reference) -> bool {
            let a = a.into_iter().collect();
            let b = b.into_iter().collect();
            let a1: Test = r2t(&a);
            let b1: Test = r2t(&b);
            let mut r1 = a1.clone();
            r1.retain_prefix_with(&b1, |_| true);
            let mut r = a;
            // keep all elements of a for which no element in b is a prefix
            r.retain(|re| b.iter().any(|x| re.starts_with(x)));
            let expected = r2t(&r);
            if expected != r1 {
                println!("a:{:#?}\nb:{:#?}", a1, b1);
                println!("expected:{:#?}\nvalue:{:#?}", expected, r1);
            }
            expected == r1
        }

        fn is_disjoint(a: Reference, b: Reference) -> bool {
            let a1: Test = r2t(&a);
            let b1: Test = r2t(&b);
            let actual = a1.is_disjoint(&b1);
            let expected = a.is_disjoint(&b);
            expected == actual
        }

        fn is_subset(a: Reference, b: Reference) -> bool {
            let a1: Test = r2t(&a);
            let b1: Test = r2t(&b);
            let actual = a1.is_subset(&b1);
            let expected = a.is_subset(&b);
            expected == actual
        }

        fn contains(a: Reference, b: Vec<u8>) -> bool {
            let a1: Test = r2t(&a);
            let expected = a.contains(&b);
            let actual = a1.contains_key(&b);
            expected == actual
        }
    }

    // bitop_assign_consistent!(Test);
    // set_predicate_consistent!(Test);
    // bitop_symmetry!(Test);
    // bitop_empty!(Test);

    // #[test]
    // fn values_iter() {
    //     let elems = &["abc", "ab", "a", "ba"];
    //     let tree = elems
    //         .iter()
    //         .map(|x| (x.as_bytes(), (*x).to_owned()))
    //         .collect::<RadixTree<_, _>>();
    //     for x in tree.values() {
    //         println!("{}", x);
    //     }
    //     for (k, v) in tree.iter() {
    //         println!("{:?} {}", k, v);
    //     }
    // }

    fn test_tree(strings: &[&str]) -> RadixTree<u8, ()> {
        let mut res = RadixTree::default();
        for key in strings {
            res.insert(key.as_bytes(), ());
        }
        res
    }

    #[test]
    fn smoke_test() {
        let mut res = RadixTree::default();
        let keys = ["aabbcc", "aabb", "aabbee"];
        let nope = ["xaabbcc", "aabbx", "aabbx", "aabbeex"];
        for key in keys {
            let x = RadixTree::single(key.as_bytes(), ());
            res.union_with(&x);
            // any set is subset of itself
            assert!(res.is_subset(&res));
        }
        for (key, _) in res.scan_prefix("aa".as_bytes()) {
            println!("{:?}", std::str::from_utf8(key.as_ref()).unwrap());
        }
        for key in nope {
            assert!(!res.contains_key(key.as_bytes()));
            // keys not contained in the set must not be a subset
            let mut t = RadixTree::single(key.as_bytes(), ());
            assert!(!t.is_subset(&res));
            t.intersection_with(&res);
            assert!(t.is_empty());
            let mut dif = res.clone();
            dif.difference_with(&RadixTree::single(key.as_bytes(), ()));
            assert_eq!(dif, res);
        }
        for key in keys {
            assert!(res.contains_key(key.as_bytes()));
            // keys contained in the set must be a subset
            assert!(RadixTree::single(key.as_bytes(), ()).is_subset(&res));
            let mut t = RadixTree::single(key.as_bytes(), ());
            assert!(t.is_subset(&res));
            t.intersection_with(&res);
            assert!(t == RadixTree::single(key.as_bytes(), ()));
            let mut dif = res.clone();
            dif.difference_with(&RadixTree::single(key.as_bytes(), ()));
            assert!(!dif.contains_key(key.as_bytes()));
        }
    }

    #[test]
    fn is_subset_sample1() {
        let a = r2t(&btreeset! { vec![1]});
        let b = r2t(&btreeset! {});
        println!("a.is_subset(b): {}", a.is_subset(&b));
        assert!(binary_property_test(&a, &b, a.is_subset(&b), |a, b| !a | b));
    }

    #[test]
    fn difference_sample1() {
        let a = r2t(&btreeset! { vec![]});
        let b = r2t(&btreeset! { vec![0] });
        println!("a.difference(b): {:#?}", a.difference(&b));
        assert!(binary_element_test(&a, &b, a.difference(&b), |a, b| a & !b));
    }

    #[test]
    fn difference_sample2() {
        let a = r2t(&btreeset! { vec![0]});
        let b = r2t(&btreeset! { vec![1] });
        println!("a.difference(b): {:#?}", a.difference(&b));
        assert!(binary_element_test(&a, &b, a.difference(&b), |a, b| a & !b));
    }

    #[test]
    fn remove_prefix_sample1() {
        let mut test = test_tree(&["a", "aa", "aaa", "ab", "b", "bc", "bc", "eeeee", "eeeef"]);
        let exclude = test_tree(&["aa", "bc", "ee"]);
        test.remove_prefix_with(&exclude, |_| true);
        let expected = test_tree(&["a", "ab", "b"]);
        assert_eq!(test, expected);
    }

    #[test]
    fn retain_prefix_sample1() {
        let a = r2t(&btreeset! { vec![0]});
        let b = r2t(&btreeset! { vec![0], vec![1] });
        let mut r = a.clone();
        r.retain_prefix_with(&b, |_| true);
        assert_eq!(r, a);
    }

    #[test]
    fn retain_prefix_sample() {
        let mut test = test_tree(&["a", "aa", "aaa", "ab", "b", "bc", "bcd", "eeeee", "eeeef"]);
        let exclude = test_tree(&["aa", "bc", "ee"]);
        test.retain_prefix_with(&exclude, |_| true);
        let expected = test_tree(&["aa", "aaa", "bc", "bcd", "eeeee", "eeeef"]);
        assert_eq!(test, expected);
    }
}

fn offset_from<T, U>(base: *const T, p: *const U) -> usize {
    let base = base as usize;
    let p = p as usize;
    assert!(p >= base);
    p - base
}

fn location<T>(x: &T) -> usize {
    (x as *const T) as usize
}

/// Helper to contain an object and an interator that takes the object by reference
///
/// This is a quick way to implement into_iter in terms of iter.
pub struct ObjAndIter<K, V> {
    k: Box<K>,
    v: V,
}

impl<K: 'static, V> ObjAndIter<K, V> {
    fn new(k: Box<K>, f: impl Fn(&'static K) -> V) -> Self {
        let kr = unsafe { std::mem::transmute(k.as_ref()) };
        let v = f(kr);
        Self { k, v }
    }
}

impl<K: 'static, V: Iterator> Iterator for ObjAndIter<K, V> {
    type Item = V::Item;

    fn next(&mut self) -> Option<Self::Item> {
        self.v.next()
    }
}