Skip to content

Instantly share code, notes, and snippets.

@sjkillen
Created March 22, 2021 22:08
Show Gist options
  • Save sjkillen/53e286791c791ab9a40e1f85ab6aa2df to your computer and use it in GitHub Desktop.
Save sjkillen/53e286791c791ab9a40e1f85ab6aa2df to your computer and use it in GitHub Desktop.
Unnecessary iterator abstraction
use std::iter::once;
#[derive(Debug)]
pub enum IterNum<T, I: Iterator<Item = T>> {
Zero,
One(T),
More(I),
}
pub fn inum<T, I: Iterator<Item = T>>(mut items: I) -> IterNum<T, impl Iterator<Item = T>> {
if let Some(first) = items.next() {
if let Some(second) = items.next() {
IterNum::More(once(first).chain(once(second)).chain(items))
} else {
IterNum::One(first)
}
} else {
IterNum::Zero
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn check() {
let zero = Vec::<i64>::new();
match inum(zero.into_iter()) {
IterNum::Zero => {},
_ => panic!(),
};
let one = vec![42i64];
match inum(one.into_iter()) {
IterNum::One(n) => assert!(n == 42),
_ => panic!(),
};
let more = vec![42i64, 43, 44];
match inum(more.into_iter()) {
IterNum::More(i) => {
let k: Vec<i64> = i.collect();
assert!(k == vec![42i64, 43, 44])
},
_ => panic!(),
};
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment