use crate::dupe::Dupe;
pub trait OptionRefExt {
type Item;
fn duped(self) -> Option<Self::Item>
where
Self::Item: Dupe;
}
pub trait OptionExt {
type Item;
fn into_try_map<U, E, F: FnOnce(Self::Item) -> Result<U, E>>(
self,
f: F,
) -> Result<Option<U>, E>;
fn try_map<U, E, F: FnOnce(&Self::Item) -> Result<U, E>>(self, f: F) -> Result<Option<U>, E>;
}
impl<'a, T> OptionRefExt for Option<&'a T> {
type Item = T;
fn duped(self) -> Option<T>
where
T: Dupe,
{
self.map(|x| x.dupe())
}
}
impl<T> OptionExt for Option<T> {
type Item = T;
fn into_try_map<U, E, F: FnOnce(Self::Item) -> Result<U, E>>(
self,
f: F,
) -> Result<Option<U>, E> {
Ok(match self {
None => None,
Some(x) => Some(f(x)?),
})
}
fn try_map<U, E, F: FnOnce(&Self::Item) -> Result<U, E>>(self, f: F) -> Result<Option<U>, E> {
Ok(match &self {
None => None,
Some(x) => Some(f(x)?),
})
}
}