[no description]
option?
| -rw-r--r-- | src/iterator.rs | 2 | ||||
| -rw-r--r-- | src/lib.rs | 4 | ||||
| -rw-r--r-- | src/option.rs | 76 |
3 files changed, 81 insertions, 1 deletions
diff --git a/src/iterator.rs b/src/iterator.rs index 56a441a..e2ed432 100644 --- a/src/iterator.rs +++ b/src/iterator.rs @@ -6,7 +6,7 @@ pub trait IteratorOfTuplesWithF<retval>: /// Map the item at: (|(x, y)| (f(x), y)) fn map_at<const N: usize>( self, - mut f: impl FnMut(<Self::Item as Pick<N>>::At) -> retval, + f: impl FnMut(<Self::Item as Pick<N>>::At) -> retval, ) -> core::iter::Map< Self, impl FnMut(<Self>::Item) -> <<Self>::Item as RePick<N, retval>>::New, @@ -20,6 +20,10 @@ pub use iterator::{ IteratorOfTuplesWithF, }; pub mod fns; +mod option; +pub use option::{ + OptionOfMutRefToTuple, OptionOfRefToTuple, OptionOfTuple, +}; /// Reverse a tuple. pub trait Reverse: Tupl { type Reversed: Tupl; diff --git a/src/option.rs b/src/option.rs new file mode 100644 index 0000000..0ab0cd8 --- /dev/null +++ b/src/option.rs @@ -0,0 +1,76 @@ +use crate::{Pick, Tupl}; + +pub trait OptionOfTuple<T: Tupl> { + fn on<const N: usize>(self) -> Option<T::At> + where + T: Pick<N>; +} + +impl<T: Tupl> OptionOfTuple<T> for Option<T> { + fn on<const N: usize>(self) -> Option<<T>::At> + where + T: Pick<N>, + { + self.map(T::pick) + } +} +macro_rules! option_of_ref_to_tuple { + ($name1:ident, $name2:ident, $as_ref:ident, $AsRef:ident $(, $mut:tt)?) => { + pub trait $name1<'a, T: Tupl> { + fn on<const N: usize>( + self, + ) -> Option<<T::$AsRef<'a> as Pick<N>>::At> + where + T::$AsRef<'a>: Pick<N>; + } + impl<'a, T: Tupl> $name1<'a, T> for Option<&'a $($mut)? T> { + fn on<const N: usize>( + self, + ) -> Option<<T::$AsRef<'a> as Pick<N>>::At> + where + T::$AsRef<'a>: Pick<N>, + { + match self { + Some(x) => Some(x.$as_ref().pick()), + None => None, + } + } + } + impl<'a, T: Tupl> $name1<'a, T> for &'a $($mut)? Option< T> { + fn on<const N: usize>( + self, + ) -> Option<<T::$AsRef<'a> as Pick<N>>::At> + where + T::$AsRef<'a>: Pick<N>, + { + match self { + Some(x) => Some(x.$as_ref().pick()), + None => None, + } + } + } + }; +} + +option_of_ref_to_tuple!( + OptionOfRefToTuple, + OptionOfRefToTupleWithF, + as_ref, + AsRef +); + +option_of_ref_to_tuple!( + OptionOfMutRefToTuple, + OptionOfMutRefToTupleWithF, + as_mut, + AsMut, + mut +); +#[test] +fn x() { + struct Y; + let x = Some(&mut (Y, 2)); + let x = x.on::<1>(); + let x = &mut Some((Y, 2)); + let x = x.on::<1>(); +} |