Skip to main content

nil_util/
iter.rs

1// Copyright (C) Call of Nil contributors
2// SPDX-License-Identifier: AGPL-3.0-only
3
4use std::collections::{HashMap, HashSet, VecDeque};
5use std::hash::Hash;
6use std::ops::{ControlFlow, Try};
7
8pub trait IterExt: Iterator {
9  fn collect_deque(self) -> VecDeque<Self::Item>
10  where
11    Self: Sized,
12  {
13    self.collect()
14  }
15
16  fn collect_map<K, V>(self) -> HashMap<K, V>
17  where
18    Self: Sized + Iterator<Item = (K, V)>,
19    K: Hash + Eq,
20  {
21    self.collect()
22  }
23
24  fn collect_set(self) -> HashSet<Self::Item>
25  where
26    Self: Sized,
27    Self::Item: Hash + Eq,
28  {
29    self.collect()
30  }
31
32  fn try_each<R>(self) -> R
33  where
34    Self: Iterator<Item = R> + Sized,
35    R: Try<Output = ()>,
36  {
37    for item in self {
38      if let ControlFlow::Break(e) = item.branch() {
39        return R::from_residual(e);
40      }
41    }
42
43    R::from_output(())
44  }
45}
46
47impl<T: Iterator> IterExt for T {}