Skip to content

Experimental feature "BTreeMap cursors": CursorMut.peek_prev() broken #111228

Closed
@theandi667

Description

@theandi667

While using the experimental new API "BTreeMap cursors" (tracking issue: #107540) I noticed that the CursorMut.peek_prev() API, which is documented to return the last element of the map if the cursor is pointing to the "ghost" non-element, returns the first element of the map instead. Not only does this disagree with the documentation, the immutable Cursor.peek_prev() API does the right thing. Here's a small testcase:

#![feature(btree_cursors)]

fn main() {}

#[cfg(test)]
mod tests {

    use std::collections::BTreeMap;
    use std::ops::Bound;

    #[test]
    fn test_cursor() {
        let 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, _))));
    }

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

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

        let prev = cursor.peek_prev();
        // FAILS, prev is Some((&1, &1)) instead.
        assert!(matches!(prev, Some((&3, _))));
    }
}

The CursorMut.peek_prev() API should, as documented, return the last element of the map if the cursor points at the "ghost" non-element.

Instead, this happened: It currently returns the first element of the map.

Meta

rustc --version --verbose:

rustc 1.71.0-nightly (39c6804b9 2023-04-19)
binary: rustc
commit-hash: 39c6804b92aa202369e402525cee329556bc1db0
commit-date: 2023-04-19
host: aarch64-apple-darwin
release: 1.71.0-nightly
LLVM version: 16.0.2

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-collectionsArea: `std::collections`C-bugCategory: This is a bug.T-libs-apiRelevant to the library API team, which will review and decide on the PR/issue.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions