@@ -111,6 +111,18 @@ impl<K, V> BTreeMap<K, V> {
111
111
}
112
112
}
113
113
}
114
+
115
+ // Transform the tree to minimize wasted space, obtaining fewer nodes that
116
+ // are mostly filled up to their capacity. The same compact tree could have
117
+ // been obtained by inserting keys in a shrewd order.
118
+ fn compact ( & mut self )
119
+ where
120
+ K : Ord ,
121
+ {
122
+ let iter = mem:: take ( self ) . into_iter ( ) ;
123
+ let root = BTreeMap :: ensure_is_owned ( & mut self . root ) ;
124
+ root. bulk_push ( iter, & mut self . length ) ;
125
+ }
114
126
}
115
127
116
128
impl < ' a , K : ' a , V : ' a > NodeRef < marker:: Immut < ' a > , K , V , marker:: LeafOrInternal > {
@@ -1679,17 +1691,29 @@ fn test_first_last_entry() {
1679
1691
}
1680
1692
1681
1693
#[ test]
1682
- fn test_insert_into_full_left ( ) {
1683
- let mut map: BTreeMap < _ , _ > = ( 0 ..NODE_CAPACITY ) . map ( |i| ( i * 2 , ( ) ) ) . collect ( ) ;
1684
- assert ! ( map. insert( NODE_CAPACITY , ( ) ) . is_none( ) ) ;
1685
- map. check ( ) ;
1694
+ fn test_insert_into_full_height_0 ( ) {
1695
+ let size = NODE_CAPACITY ;
1696
+ for pos in 0 ..=size {
1697
+ let mut map: BTreeMap < _ , _ > = ( 0 ..size) . map ( |i| ( i * 2 + 1 , ( ) ) ) . collect ( ) ;
1698
+ assert ! ( map. insert( pos * 2 , ( ) ) . is_none( ) ) ;
1699
+ map. check ( ) ;
1700
+ }
1686
1701
}
1687
1702
1688
1703
#[ test]
1689
- fn test_insert_into_full_right ( ) {
1690
- let mut map: BTreeMap < _ , _ > = ( 0 ..NODE_CAPACITY ) . map ( |i| ( i * 2 , ( ) ) ) . collect ( ) ;
1691
- assert ! ( map. insert( NODE_CAPACITY + 2 , ( ) ) . is_none( ) ) ;
1692
- map. check ( ) ;
1704
+ fn test_insert_into_full_height_1 ( ) {
1705
+ let size = NODE_CAPACITY + 1 + NODE_CAPACITY ;
1706
+ for pos in 0 ..=size {
1707
+ let mut map: BTreeMap < _ , _ > = ( 0 ..size) . map ( |i| ( i * 2 + 1 , ( ) ) ) . collect ( ) ;
1708
+ map. compact ( ) ;
1709
+ let root_node = map. root . as_ref ( ) . unwrap ( ) . reborrow ( ) ;
1710
+ assert_eq ! ( root_node. len( ) , 1 ) ;
1711
+ assert_eq ! ( root_node. first_leaf_edge( ) . into_node( ) . len( ) , NODE_CAPACITY ) ;
1712
+ assert_eq ! ( root_node. last_leaf_edge( ) . into_node( ) . len( ) , NODE_CAPACITY ) ;
1713
+
1714
+ assert ! ( map. insert( pos * 2 , ( ) ) . is_none( ) ) ;
1715
+ map. check ( ) ;
1716
+ }
1693
1717
}
1694
1718
1695
1719
macro_rules! create_append_test {
0 commit comments