maybe-many into many

master
Avril 4 years ago
parent c37cb6c3bb
commit 7dc820317e
Signed by: flanchan
GPG Key ID: 284488987C31F630

@ -1,6 +1,6 @@
[package] [package]
name = "ad-hoc-iter" name = "ad-hoc-iter"
version = "0.2.0" version = "0.2.1"
description = "Ad-hoc exact size owning iterator macro and other optional utils" description = "Ad-hoc exact size owning iterator macro and other optional utils"
repository = "https://git.flanchan.moe/flanchan/ad-hoc-iter" repository = "https://git.flanchan.moe/flanchan/ad-hoc-iter"
keywords = ["iterator", "macro", "iter"] keywords = ["iterator", "macro", "iter"]

@ -21,6 +21,30 @@ impl<T> MaybeMany<T, std::iter::Empty<T>>
{ {
Self::One(value) Self::One(value)
} }
/// Map an infallibly `One` into the `Many` variant.
///
/// # `None` variants are preserved.
pub fn map_single_into_many<F, V, W>(self, trans: F) -> MaybeMany<V, W>
where F: FnOnce(T) -> W,
W: IntoIterator<Item=V>,
{
match self {
Self::One(one) => MaybeMany::Many(trans(one)),
_ => MaybeMany::None,
}
}
/// Convert `Many(Empty)` into `None` of any type.
pub fn map_none<V>(self) -> MaybeMany<T, V>
where V: IntoIterator<Item=T>
{
match self
{
Self::None | Self::Many(_) => MaybeMany::None,
Self::One(o) => MaybeMany::One(o),
}
}
} }
impl MaybeMany<std::convert::Infallible, std::iter::Empty<std::convert::Infallible>> impl MaybeMany<std::convert::Infallible, std::iter::Empty<std::convert::Infallible>>
@ -31,7 +55,6 @@ impl MaybeMany<std::convert::Infallible, std::iter::Empty<std::convert::Infallib
Self::None Self::None
} }
} }
impl<T,U> MaybeMany<T,U> impl<T,U> MaybeMany<T,U>
where U: IntoIterator<Item = T> where U: IntoIterator<Item = T>
@ -42,6 +65,20 @@ where U: IntoIterator<Item = T>
MaybeMany::Many(self) MaybeMany::Many(self)
} }
/// Map into the `Many` variant.
///
/// # `None` variants are preserved.
pub fn map_into_many<F, V, W>(self, trans: F) -> MaybeMany<V, W>
where F: FnOnce(T) -> W,
W: IntoIterator<Item=V> + From<U>,
{
match self {
Self::None => MaybeMany::None,
Self::One(one) => MaybeMany::Many(trans(one)),
Self::Many(many) => MaybeMany::Many(W::from(many)),
}
}
/// Chain another iterator to this one /// Chain another iterator to this one
pub fn chain<I>(self, iter: I) -> MaybeMany<T, std::iter::Chain<<Self as IntoIterator>::IntoIter, I::IntoIter>> pub fn chain<I>(self, iter: I) -> MaybeMany<T, std::iter::Chain<<Self as IntoIterator>::IntoIter, I::IntoIter>>
where I: IntoIterator<Item=T> where I: IntoIterator<Item=T>
@ -196,11 +233,11 @@ mod tests
#[test] #[test]
fn into_many() fn into_many()
{ {
let mut mayb = MaybeMany::one("hello").boxed(); let mayb = MaybeMany::one("hello");
mayb = mayb.chain(vec!["world", "!"]).boxed(); let mayb = mayb.map_single_into_many(|x| vec![x, " "]).chain(vec!["world", "!"]);
let output: Vec<_> = mayb.into_iter().collect(); let output: Vec<_> = mayb.into_iter().collect();
assert_eq!(&output[..], &["hello", "world", "!"]); assert_eq!(&output[..], &["hello", " ", "world", "!"]);
} }
} }

Loading…
Cancel
Save