rust-lang / rust-lang/libs-team

Add `iter::Peekable::next_unpeek`

Open
#557 22 comments 8 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

ACP-accepted api-change-proposal
Dominant language
Rust
Stars
178
Forks
28
Avg merge
15m
Merged PRs (30d)
1

Description

Proposal

Problem statement

Working with iter::Peekable is often annoying because of two reasons:

  1. The peeked value is only a reference, which means one can’t make use of ownership, and sometimes ends up with a double reference.
  2. If the peeked value is considered good, one has to call .next() and discard the value, which looks a little strange – worse, one will need to match on it to take ownership of the contents within, with the other branches being forced to panic.

Some of these problems are alleviated by the addition of .next_if – however, this isn’t applicable in all situations.

Motivating examples or use cases

One example is the following code, which consumes all Text elements from a pulldown_cmark::Parser:

loop {
    match parser.peek() {
        Some(pulldown_cmark::Event::Text(_)) => {
            let pulldown_cmark::Event::Text(s) = parser.next().unwrap() else { unreachable!() };
            do_something(s);
        }
        _ => break,
    }
}

Solution sketch

impl<I: Iterator> Peekable<I> {
    pub fn next_unpeek(&mut self) -> (Option<I::Item>, Unpeeker<'a, I>) {
        (self.next(), Unpeeker(&mut self.peeked))
    }
}

pub struct Unpeeker<'a, I: Iterator>(&'a mut Option<Option<I::Item>>);

impl<'a, I: Iterator> Unpeeker<'a, I> {
    pub fn unpeek(self, item: Option<I::Item>) {
        *self.0 = Some(item);
    }
}

With this solution, the above code is made simpler:

loop {
    match parser.next_unpeek() {
        (Some(pulldown_cmark::Event::Text(s)), _) => do_something(s),
        (other, unpeeker) => {
            unpeeker.unpeek(other);
            break;
        }
    }
}

Alternatives

  • Instead of using a dedicated type Unpeeker<'a, I>, use an impl FnOnce. The disadvantage of impl FnOnce is that borrowck can’t see that it has no Drop implementation, meaning that less code compiles (see this comment).
  • Provide direct access to the underlying peeked field, or fn unpeek(&mut self, peeked: Option<I::Item>). The disadvantage of this is that one is able to replace an existing peeked value that is not None, which is a footgun. The unpeek method could panic in this case, but that’s also not great.

Links and related work

None.

What happens now?

This issue contains an API change proposal (or ACP) and is part of the libs-api team feature lifecycle. Once this issue is filed, the libs-api team will review open proposals as capability becomes available. Current response times do not have a clear estimate, but may be up to several months.

Possible responses

The libs team may respond in various different ways. First, the team will consider the problem (this doesn't require any concrete solution or alternatives to have been proposed):

  • We think this problem seems worth solving, and the standard library might be the right place to solve it.
  • We think that this probably doesn't belong in the standard library.

Second, if there's a concrete solution:

  • We think this specific solution looks roughly right, approved, you or someone else should implement this. (Further review will still happen on the subsequent implementation PR.)
  • We're not sure this is the right solution, and the alternatives or other materials don't give us enough information to be sure about that. Here are some questions we have that aren't answered, or rough ideas about alternatives we'd want to see discussed.

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 with the proposed Peekable::next_unpeek and Unpeeker API in the issue, then compare the listed impl FnOnce and direct-access alternatives. Read the linked feature lifecycle guidance and the discussion before doing implementation work; done currently means a libs-api decision on the proposal, not a named code or test change.

Written by the indexing model from the issue text.

Assessment

Tech stack
rust
Domain
backend-api-design
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Quiet
Clarity
Clearly specified
Newbie friendliness
25/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.