rust-lang / rust-lang/rfcs

Consider adding `BinaryHeap::peek_mut` like API for `Vec` and `VecDeque`

Open
#3,082 3 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

T-libs
Dominant language
Markdown
Stars
6.6k
Forks
1.7k
Avg merge
16h 14m
Merged PRs (30d)
1

Description

There are times when I want to remove an element from a collection only if it meets some conditions. For example, I want to remove the last item from a Vec<i32> if it exists and is less than 10. Currently I can think of two ways to do this:

fn pop_if_less_than_10(values: &mut Vec<i32>) -> Option<i32> {
    values.pop().and_then(|value| {
        if value < 10 {
            Some(value)
        } else {
            values.push(value);

            None
        }
    })
}

Or I can write:

fn pop_if_less_than_10(values: &mut Vec<i32>) -> Option<i32> {
    if values.last().map_or(false, |value| *value < 10) {
        Some(values.pop().unwrap())
    } else {
        None
    }
}

The first one may pop and push the same element which is the same as doing nothing, and the second one has a infallible unwrap. I think the idea of BinaryHeap::peek_mut may be applied here:

fn pop_if_less_than_10(values: &mut Vec<i32>) -> Option<i32> {
    values.peek_last_mut().and_then(|last| {
        if *last < 10 {
            Some(PeekLastMut::pop(last))
        } else {
            None
        }
    })
}

Where peek_last_mut is an imaginary method like BinaryHeap::peek_mut and PeekLastMut is an imaginary type is like std::collections::binary_heap::PeekMut.

The entry methods from HashMap and BTreeMap are similar, but we have no way of doing this in Vec and VecDeque. It would be nice to have something like this.

Contributor guide

No contributing guide indexed for this repository

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start by comparing the proposed Vec and VecDeque operation with BinaryHeap::peek_mut and the existing collection APIs mentioned in the issue. Work out the intended API and ownership or drop semantics, then define what a complete proposal would need to specify; the issue does not name files or tests.

Written by the indexing model from the issue text.

Assessment

Tech stack
rust
Domain
api
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
25/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.