diff --git a/Cargo.toml b/Cargo.toml index 83cb83c..8ef892a 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "ad-hoc-iter" -version = "0.2.0" +version = "0.2.1" description = "Ad-hoc exact size owning iterator macro and other optional utils" repository = "https://git.flanchan.moe/flanchan/ad-hoc-iter" keywords = ["iterator", "macro", "iter"] diff --git a/src/maybe.rs b/src/maybe.rs index 7bfe10e..ce27d84 100644 --- a/src/maybe.rs +++ b/src/maybe.rs @@ -21,6 +21,30 @@ impl MaybeMany> { Self::One(value) } + + /// Map an infallibly `One` into the `Many` variant. + /// + /// # `None` variants are preserved. + pub fn map_single_into_many(self, trans: F) -> MaybeMany + where F: FnOnce(T) -> W, + W: IntoIterator, + { + match self { + Self::One(one) => MaybeMany::Many(trans(one)), + _ => MaybeMany::None, + } + } + + /// Convert `Many(Empty)` into `None` of any type. + pub fn map_none(self) -> MaybeMany + where V: IntoIterator + { + match self + { + Self::None | Self::Many(_) => MaybeMany::None, + Self::One(o) => MaybeMany::One(o), + } + } } impl MaybeMany> @@ -31,7 +55,6 @@ impl MaybeMany MaybeMany where U: IntoIterator @@ -42,6 +65,20 @@ where U: IntoIterator MaybeMany::Many(self) } + /// Map into the `Many` variant. + /// + /// # `None` variants are preserved. + pub fn map_into_many(self, trans: F) -> MaybeMany + where F: FnOnce(T) -> W, + W: IntoIterator + From, + { + 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 pub fn chain(self, iter: I) -> MaybeMany::IntoIter, I::IntoIter>> where I: IntoIterator @@ -196,11 +233,11 @@ mod tests #[test] fn into_many() { - let mut mayb = MaybeMany::one("hello").boxed(); - mayb = mayb.chain(vec!["world", "!"]).boxed(); + let mayb = MaybeMany::one("hello"); + let mayb = mayb.map_single_into_many(|x| vec![x, " "]).chain(vec!["world", "!"]); let output: Vec<_> = mayb.into_iter().collect(); - assert_eq!(&output[..], &["hello", "world", "!"]); + assert_eq!(&output[..], &["hello", " ", "world", "!"]); } }