Gather the first N items, and provide the count of the remaining items. The max count cannot be zero as that's a pathological case.
(it: I, max: NonZeroUsize)
| 16 | /// Gather the first N items, and provide the count of the remaining items. |
| 17 | /// The max count cannot be zero as that's a pathological case. |
| 18 | pub fn collect_until<I>(it: I, max: NonZeroUsize) -> Option<(Vec<I::Item>, usize)> |
| 19 | where |
| 20 | I: Iterator, |
| 21 | { |
| 22 | let mut items = Vec::with_capacity(max.get()); |
| 23 | |
| 24 | let mut it = it.peekable(); |
| 25 | // If there's nothing, just return |
| 26 | let _ = it.peek()?; |
| 27 | |
| 28 | for next in it.by_ref() { |
| 29 | items.push(next); |
| 30 | |
| 31 | // If we've reached max items, stop collecting |
| 32 | if items.len() == max.get() { |
| 33 | break; |
| 34 | } |
| 35 | } |
| 36 | // Count remaining items |
| 37 | let remaining = it.count(); |
| 38 | items.shrink_to_fit(); |
| 39 | Some((items, remaining)) |
| 40 | } |
| 41 | |
| 42 | #[cfg(test)] |
| 43 | mod tests { |
no outgoing calls