Skip to content

Instantly share code, notes, and snippets.

@mkmik
Created October 1, 2020 07:34
Show Gist options
  • Save mkmik/110e66a9a3b7ad4742161136cf9dd8f8 to your computer and use it in GitHub Desktop.
Save mkmik/110e66a9a3b7ad4742161136cf9dd8f8 to your computer and use it in GitHub Desktop.
// Turns out that this iterator is unnecessary since the std::option::Option type
// itself implements this exact semantics
/// An iterator that yields an element once or never.
///
/// This `struct` is created by the [`once_if_ever`] function. See its documentation for more.
pub struct OnceIfEver<T> {
value: Option<T>,
}
impl<T> Iterator for OnceIfEver<T> {
type Item = T;
fn next(&mut self) -> Option<Self::Item> {
mem::replace(&mut self.value, None)
}
}
/// Creates an iterator that yields an element once or never.
fn once_if_ever<T>(v: Option<T>) -> OnceIfEver<T> {
OnceIfEver { value: v }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment