Skip to content

Commit

Permalink
btree_map: Cursor{,Mut}::peek_prev must agree
Browse files Browse the repository at this point in the history
Our `Cursor::peek_prev` and `CursorMut::peek_prev` must agree
on how to behave when they are called on the "null element".
  • Loading branch information
workingjubilee committed May 5, 2023
1 parent 74c4821 commit 00cb59b
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 2 deletions.
4 changes: 2 additions & 2 deletions library/alloc/src/collections/btree/map.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3079,8 +3079,8 @@ impl<'a, K, V, A> CursorMut<'a, K, V, A> {
unsafe { self.root.reborrow() }
.as_mut()?
.borrow_mut()
.first_leaf_edge()
.next_kv()
.last_leaf_edge()
.next_back_kv()
.ok()?
.into_kv_valmut()
}
Expand Down
19 changes: 19 additions & 0 deletions library/alloc/src/collections/btree/map/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ use crate::testing::crash_test::{CrashTestDummy, Panic};
use crate::testing::ord_chaos::{Cyclic3, Governed, Governor};
use crate::testing::rng::DeterministicRng;
use crate::vec::Vec;
use core::assert_matches::assert_matches;
use std::cmp::Ordering;
use std::iter;
use std::mem;
Expand Down Expand Up @@ -2448,3 +2449,21 @@ fn test_cursor_mut_insert_after_4() {
let mut cur = map.upper_bound_mut(Bound::Included(&2));
cur.insert_after(4, 'd');
}

#[test]
fn cursor_peek_prev_agrees_with_cursor_mut() {
let mut map = BTreeMap::from([(1, 1), (2, 2), (3, 3)]);

let cursor = map.lower_bound(Bound::Excluded(&3));
assert!(cursor.key().is_none());

let prev = cursor.peek_prev();
assert_matches!(prev, Some((&3, _)));

// Shadow names so the two parts of this test match.
let mut cursor = map.lower_bound_mut(Bound::Excluded(&3));
assert!(cursor.key().is_none());

let prev = cursor.peek_prev();
assert_matches!(prev, Some((&3, _)));
}

0 comments on commit 00cb59b

Please sign in to comment.