Skip to content

Add iter::Peekable::next_unpeek #557

Open
@SabrinaJewson

Description

@SabrinaJewson

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    ACP-acceptedAPI Change Proposal is accepted (seconded with no objections)T-libs-apiapi-change-proposalA proposal to add or alter unstable APIs in the standard libraries

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions