Skip to content

Commit f327a35

Browse files
committed
BTreeMap: test full nodes a little more
1 parent c34c015 commit f327a35

File tree

2 files changed

+33
-9
lines changed

2 files changed

+33
-9
lines changed

library/alloc/src/collections/btree/append.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@ impl<K, V> Root<K, V> {
3030
/// Pushes all key-value pairs to the end of the tree, incrementing a
3131
/// `length` variable along the way. The latter makes it easier for the
3232
/// caller to avoid a leak when the iterator panicks.
33-
fn bulk_push<I>(&mut self, iter: I, length: &mut usize)
33+
pub fn bulk_push<I>(&mut self, iter: I, length: &mut usize)
3434
where
3535
I: Iterator<Item = (K, V)>,
3636
{

library/alloc/src/collections/btree/map/tests.rs

+32-8
Original file line numberDiff line numberDiff line change
@@ -111,6 +111,18 @@ impl<K, V> BTreeMap<K, V> {
111111
}
112112
}
113113
}
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+
}
114126
}
115127

116128
impl<'a, K: 'a, V: 'a> NodeRef<marker::Immut<'a>, K, V, marker::LeafOrInternal> {
@@ -1679,17 +1691,29 @@ fn test_first_last_entry() {
16791691
}
16801692

16811693
#[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+
}
16861701
}
16871702

16881703
#[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+
}
16931717
}
16941718

16951719
macro_rules! create_append_test {

0 commit comments

Comments
 (0)