Skip to content

Commit ec565f6

Browse files
committed
Implement PeekableIterator for Chars
1 parent 5892463 commit ec565f6

File tree

1 file changed

+14
-2
lines changed

1 file changed

+14
-2
lines changed

library/core/src/str/iter.rs

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,8 +8,8 @@ use super::{
88
};
99
use crate::fmt::{self, Write};
1010
use crate::iter::{
11-
Chain, Copied, Filter, FlatMap, Flatten, FusedIterator, Map, TrustedLen, TrustedRandomAccess,
12-
TrustedRandomAccessNoCoerce,
11+
Chain, Copied, Filter, FlatMap, Flatten, FusedIterator, Map, PeekableIterator, TrustedLen,
12+
TrustedRandomAccess, TrustedRandomAccessNoCoerce,
1313
};
1414
use crate::num::NonZero;
1515
use crate::ops::Try;
@@ -132,6 +132,18 @@ impl<'a> DoubleEndedIterator for Chars<'a> {
132132
}
133133
}
134134

135+
#[unstable(feature = "peekable_iterator", issue = "132973")]
136+
impl<'a> PeekableIterator for Chars<'a> {
137+
fn peek_with<T>(&mut self, func: impl for<'b> FnOnce(Option<&'b Self::Item>) -> T) -> T {
138+
// SAFETY: `str` invariant says `self.iter` is a valid UTF-8 string and
139+
// the resulting `ch` is a valid Unicode Scalar Value.
140+
let tmp = unsafe {
141+
next_code_point(&mut self.iter.clone()).map(|ch| char::from_u32_unchecked(ch))
142+
};
143+
func(&tmp)
144+
}
145+
}
146+
135147
#[stable(feature = "fused", since = "1.26.0")]
136148
impl FusedIterator for Chars<'_> {}
137149

0 commit comments

Comments
 (0)