Improve TokenStreamIter.

It's simpler if it's just a wrapper around `slice::Iter`.

Also, we might as well implement `size_hint`. It doesn't have any effect
on perf but it's trivial and might help one day.
This commit is contained in:
Nicholas Nethercote
2026-07-09 09:25:17 +10:00
parent 47e62ee30c
commit fa43a69051
2 changed files with 9 additions and 11 deletions

View File

@@ -836,21 +836,18 @@ impl StableHash for TokenStream {
}
#[derive(Clone)]
pub struct TokenStreamIter<'t> {
stream: &'t TokenStream,
index: usize,
}
pub struct TokenStreamIter<'t>(std::slice::Iter<'t, TokenTree>);
impl<'t> TokenStreamIter<'t> {
fn new(stream: &'t TokenStream) -> Self {
TokenStreamIter { stream, index: 0 }
TokenStreamIter(stream.0.as_slice().iter())
}
// Peeking could be done via `Peekable`, but most iterators need peeking,
// and this is simple and avoids the need to use `peekable` and `Peekable`
// at all the use sites.
pub fn peek(&self) -> Option<&'t TokenTree> {
self.stream.0.get(self.index)
self.0.as_slice().first()
}
}
@@ -858,10 +855,11 @@ impl<'t> Iterator for TokenStreamIter<'t> {
type Item = &'t TokenTree;
fn next(&mut self) -> Option<&'t TokenTree> {
self.stream.0.get(self.index).map(|tree| {
self.index += 1;
tree
})
self.0.next()
}
fn size_hint(&self) -> (usize, Option<usize>) {
self.0.size_hint()
}
}

View File

@@ -9,5 +9,5 @@ fn test_token_stream_iter() {
assert_eq!(ts.len(), 1);
let iter = ts.iter();
assert_eq!(iter.size_hint(), (0, None));
assert_eq!(iter.size_hint(), (1, Some(1)));
}