pub trait OptionBoost<T>: Sized {
fn inspect_none(self, none_handler: impl FnOnce()) -> Self;
fn none(self) -> Self;
fn map_unwrap_or<U>(self, f: impl FnOnce(T) -> U, default: U) -> U;
fn coalesce<F>(&mut self, other: &Self, f: F)
where
F: FnOnce(&T) -> T;
fn coalesce_clone(&mut self, other: &Self)
where
T: Clone,
{
self.coalesce(other, T::clone)
}
}
impl<T> OptionBoost<T> for Option<T> {
fn inspect_none(self, none_handler: impl FnOnce()) -> Self {
if self.is_none() {
none_handler()
}
self
}
fn none(self) -> Self
where
Self: Sized,
{
None
}
#[inline]
#[must_use]
fn map_unwrap_or<U>(self, f: impl FnOnce(T) -> U, default: U) -> U {
match self {
Some(t) => f(t),
None => default,
}
}
#[inline]
fn coalesce<F>(&mut self, other: &Self, f_value_gen: F)
where
F: FnOnce(&T) -> T,
{
if let (None, Some(v)) = (&self, other) {
*self = Some(f_value_gen(v))
}
}
}
pub trait BoostWithOption: Sized {
#[inline]
fn option<C>(self, criterion: C) -> Option<Self>
where
C: FnOnce(&Self) -> bool,
{
Some(self).filter(criterion)
}
#[inline]
fn some(self) -> Option<Self> {
Some(self)
}
#[inline]
fn none(self) -> Option<Self> {
None
}
}
impl<T: Sized> BoostWithOption for T {}