1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335
use crate::iter::{adapters::SourceIter, FusedIterator, TrustedLen};
use crate::ops::{ControlFlow, Try};
/// 带有 `peek()` 的迭代器,该迭代器将可选的引用返回到下一个元素。
///
///
/// 该 `struct` 是通过 [`Iterator`] 上的 [`peekable`] 方法创建的。
/// 有关更多信息,请参见其文档。
///
/// [`peekable`]: Iterator::peekable
/// [`Iterator`]: trait.Iterator.html
#[derive(Clone, Debug)]
#[must_use = "iterators are lazy and do nothing unless consumed"]
#[stable(feature = "rust1", since = "1.0.0")]
pub struct Peekable<I: Iterator> {
iter: I,
/// 记住一个 peeked 的值,即使它是 `None`。
peeked: Option<Option<I::Item>>,
}
impl<I: Iterator> Peekable<I> {
pub(in crate::iter) fn new(iter: I) -> Peekable<I> {
Peekable { iter, peeked: None }
}
}
// Peekable 必须记住是否在 `.peek()` 方法中看到 `None`。
// 它确保 `.peek(); .peek();` 或 `.peek(); .next();` 最多只推进底层迭代器一次。
// 这本身不会使迭代器融合。
//
#[stable(feature = "rust1", since = "1.0.0")]
impl<I: Iterator> Iterator for Peekable<I> {
type Item = I::Item;
#[inline]
fn next(&mut self) -> Option<I::Item> {
match self.peeked.take() {
Some(v) => v,
None => self.iter.next(),
}
}
#[inline]
#[rustc_inherit_overflow_checks]
fn count(mut self) -> usize {
match self.peeked.take() {
Some(None) => 0,
Some(Some(_)) => 1 + self.iter.count(),
None => self.iter.count(),
}
}
#[inline]
fn nth(&mut self, n: usize) -> Option<I::Item> {
match self.peeked.take() {
Some(None) => None,
Some(v @ Some(_)) if n == 0 => v,
Some(Some(_)) => self.iter.nth(n - 1),
None => self.iter.nth(n),
}
}
#[inline]
fn last(mut self) -> Option<I::Item> {
let peek_opt = match self.peeked.take() {
Some(None) => return None,
Some(v) => v,
None => None,
};
self.iter.last().or(peek_opt)
}
#[inline]
fn size_hint(&self) -> (usize, Option<usize>) {
let peek_len = match self.peeked {
Some(None) => return (0, Some(0)),
Some(Some(_)) => 1,
None => 0,
};
let (lo, hi) = self.iter.size_hint();
let lo = lo.saturating_add(peek_len);
let hi = match hi {
Some(x) => x.checked_add(peek_len),
None => None,
};
(lo, hi)
}
#[inline]
fn try_fold<B, F, R>(&mut self, init: B, mut f: F) -> R
where
Self: Sized,
F: FnMut(B, Self::Item) -> R,
R: Try<Output = B>,
{
let acc = match self.peeked.take() {
Some(None) => return try { init },
Some(Some(v)) => f(init, v)?,
None => init,
};
self.iter.try_fold(acc, f)
}
#[inline]
fn fold<Acc, Fold>(self, init: Acc, mut fold: Fold) -> Acc
where
Fold: FnMut(Acc, Self::Item) -> Acc,
{
let acc = match self.peeked {
Some(None) => return init,
Some(Some(v)) => fold(init, v),
None => init,
};
self.iter.fold(acc, fold)
}
}
#[stable(feature = "double_ended_peek_iterator", since = "1.38.0")]
impl<I> DoubleEndedIterator for Peekable<I>
where
I: DoubleEndedIterator,
{
#[inline]
fn next_back(&mut self) -> Option<Self::Item> {
match self.peeked.as_mut() {
Some(v @ Some(_)) => self.iter.next_back().or_else(|| v.take()),
Some(None) => None,
None => self.iter.next_back(),
}
}
#[inline]
fn try_rfold<B, F, R>(&mut self, init: B, mut f: F) -> R
where
Self: Sized,
F: FnMut(B, Self::Item) -> R,
R: Try<Output = B>,
{
match self.peeked.take() {
Some(None) => try { init },
Some(Some(v)) => match self.iter.try_rfold(init, &mut f).branch() {
ControlFlow::Continue(acc) => f(acc, v),
ControlFlow::Break(r) => {
self.peeked = Some(Some(v));
R::from_residual(r)
}
},
None => self.iter.try_rfold(init, f),
}
}
#[inline]
fn rfold<Acc, Fold>(self, init: Acc, mut fold: Fold) -> Acc
where
Fold: FnMut(Acc, Self::Item) -> Acc,
{
match self.peeked {
Some(None) => init,
Some(Some(v)) => {
let acc = self.iter.rfold(init, &mut fold);
fold(acc, v)
}
None => self.iter.rfold(init, fold),
}
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<I: ExactSizeIterator> ExactSizeIterator for Peekable<I> {}
#[stable(feature = "fused", since = "1.26.0")]
impl<I: FusedIterator> FusedIterator for Peekable<I> {}
impl<I: Iterator> Peekable<I> {
/// 在不推进迭代器的情况下,返回 next() 值的引用。
///
/// 与 [`next`] 一样,如果有值,则将其包装在 `Some(T)` 中。
/// 但是,如果迭代结束,则返回 `None`。
///
/// [`next`]: Iterator::next
///
/// 因为 `peek()` 返回一个引用,并且许多迭代器迭代引用,所以返回值是双引用的情况可能会令人困惑。
/// 您可以在下面的示例中看到这种效果。
///
/// # Examples
///
/// 基本用法:
///
/// ```
/// let xs = [1, 2, 3];
///
/// let mut iter = xs.iter().peekable();
///
/// // peek() 让我们能看到未来
/// assert_eq!(iter.peek(), Some(&&1));
/// assert_eq!(iter.next(), Some(&1));
///
/// assert_eq!(iter.next(), Some(&2));
///
/// // 即使我们多次 `peek`,迭代器也不会前进
/// assert_eq!(iter.peek(), Some(&&3));
/// assert_eq!(iter.peek(), Some(&&3));
///
/// assert_eq!(iter.next(), Some(&3));
///
/// // 迭代器完成后,`peek()` 也是如此
/// assert_eq!(iter.peek(), None);
/// assert_eq!(iter.next(), None);
/// ```
///
///
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
pub fn peek(&mut self) -> Option<&I::Item> {
let iter = &mut self.iter;
self.peeked.get_or_insert_with(|| iter.next()).as_ref()
}
/// 返回 next() 值的变量引用,而无需前进迭代器。
///
/// 与 [`next`] 一样,如果有值,则将其包装在 `Some(T)` 中。
/// 但是,如果迭代结束,则返回 `None`。
///
/// 因为 `peek_mut()` 返回一个,并且许多迭代器迭代引用,所以返回值是双引用的情况可能会令人困惑。
/// 您可以在下面的示例中看到这种效果。
///
/// [`next`]: Iterator::next
///
/// # Examples
///
/// 基本用法:
///
/// ```
/// let mut iter = [1, 2, 3].iter().peekable();
///
/// // 像 `peek()` 一样,我们可以在不推进迭代器的情况下查看 future。
/// assert_eq!(iter.peek_mut(), Some(&mut &1));
/// assert_eq!(iter.peek_mut(), Some(&mut &1));
/// assert_eq!(iter.next(), Some(&1));
///
/// // 查看迭代器并设置可变引用背后的值。
/// if let Some(p) = iter.peek_mut() {
/// assert_eq!(*p, &2);
/// *p = &5;
/// }
///
/// // 随着迭代器的继续,我们输入的值会重新出现。
/// assert_eq!(iter.collect::<Vec<_>>(), vec![&5, &3]);
/// ```
///
///
#[inline]
#[stable(feature = "peekable_peek_mut", since = "1.53.0")]
pub fn peek_mut(&mut self) -> Option<&mut I::Item> {
let iter = &mut self.iter;
self.peeked.get_or_insert_with(|| iter.next()).as_mut()
}
/// 如果条件为 true,则消费并返回此迭代器的下一个值。
///
/// 如果 `func` 返回 `true` 作为此迭代器的下一个值,请消耗并返回它。
/// 否则,返回 `None`。
///
/// # Examples
/// 消耗一个数字,如果它等于 0.
/// ```
/// let mut iter = (0..5).peekable();
/// // 迭代器的第一个项是 0; 消耗它。
/// assert_eq!(iter.next_if(|&x| x == 0), Some(0));
/// // 现在返回的下一个项为 1,因此 `consume` 将返回 `false`。
/// assert_eq!(iter.next_if(|&x| x == 0), None);
/// // 如果 `next_if` 不等于 `expected`,则保存下一个项的值。
/// assert_eq!(iter.next(), Some(1));
/// ```
///
/// 消费小于 10 的任何数字。
/// ```
/// let mut iter = (1..20).peekable();
/// // 消耗所有小于 10 的数字
/// while iter.next_if(|&x| x < 10).is_some() {}
/// // 返回的下一个值将是 10
/// assert_eq!(iter.next(), Some(10));
/// ```
#[stable(feature = "peekable_next_if", since = "1.51.0")]
pub fn next_if(&mut self, func: impl FnOnce(&I::Item) -> bool) -> Option<I::Item> {
match self.next() {
Some(matched) if func(&matched) => Some(matched),
other => {
// 因为我们叫 `self.next()`,所以我们消耗了 `self.peeked`。
assert!(self.peeked.is_none());
self.peeked = Some(other);
None
}
}
}
/// 消费并返回下一个等于 `expected` 的项。
///
/// # Example
/// 消耗一个数字,如果它等于 0.
/// ```
/// let mut iter = (0..5).peekable();
/// // 迭代器的第一个项是 0; 消耗它。
/// assert_eq!(iter.next_if_eq(&0), Some(0));
/// // 现在返回的下一个项为 1,因此 `consume` 将返回 `false`。
/// assert_eq!(iter.next_if_eq(&0), None);
/// // 如果 `next_if_eq` 不等于 `expected`,则保存下一个项的值。
/// assert_eq!(iter.next(), Some(1));
/// ```
#[stable(feature = "peekable_next_if", since = "1.51.0")]
pub fn next_if_eq<T>(&mut self, expected: &T) -> Option<I::Item>
where
T: ?Sized,
I::Item: PartialEq<T>,
{
self.next_if(|next| next == expected)
}
}
#[unstable(feature = "trusted_len", issue = "37572")]
unsafe impl<I> TrustedLen for Peekable<I> where I: TrustedLen {}
#[unstable(issue = "none", feature = "inplace_iteration")]
unsafe impl<I: Iterator> SourceIter for Peekable<I>
where
I: SourceIter,
{
type Source = I::Source;
#[inline]
unsafe fn as_inner(&mut self) -> &mut I::Source {
// SAFETY: 将不安全的函数转发到具有相同要求的不安全的函数
unsafe { SourceIter::as_inner(&mut self.iter) }
}
}