Skip to content

Commit

Permalink
Merge #643
Browse files Browse the repository at this point in the history
643: Implement `PeekingNext` transitively over mutable references. r=jswrenn a=olson-sean-k

This PR allows `PeekingNext` to be used as a trait object just like `Iterator`, allowing code to accept types like `&mut dyn PeekingNext<Item = T>` for some item type `T`. To accomplish this, generic methods now require that `Self: Sized` and `PeekingNext` now has a transitive implementation over mutable references to types that implement `PeekingNext`.

This mirrors the design of the `Iterator` trait ([here](https://doc.rust-lang.org/nightly/src/core/iter/traits/iterator.rs.html#776-782) and [here](https://doc.rust-lang.org/nightly/src/core/iter/traits/iterator.rs.html), for example). See also [this discussion on the Rust internals forum](https://internals.rust-lang.org/t/generic-methods-over-object-safe-traits/6774).

Co-authored-by: Sean Olson <[email protected]>
  • Loading branch information
bors[bot] and olson-sean-k authored Jun 15, 2023
2 parents 8184e4c + 590fdef commit 3e92550
Showing 1 changed file with 12 additions and 1 deletion.
13 changes: 12 additions & 1 deletion src/peeking_take_while.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,18 @@ pub trait PeekingNext : Iterator {
/// if `accept` returns true, return it as the next element,
/// else None.
fn peeking_next<F>(&mut self, accept: F) -> Option<Self::Item>
where F: FnOnce(&Self::Item) -> bool;
where Self: Sized,
F: FnOnce(&Self::Item) -> bool;
}

impl<'a, I> PeekingNext for &'a mut I
where I: PeekingNext,
{
fn peeking_next<F>(&mut self, accept: F) -> Option<Self::Item>
where F: FnOnce(&Self::Item) -> bool
{
(*self).peeking_next(accept)
}
}

impl<I> PeekingNext for Peekable<I>
Expand Down

0 comments on commit 3e92550

Please sign in to comment.