pets 0.1.2

Predicate existential types.
Documentation
use crate::Pred;
#[cfg(feature = "serde")]
use serde::{de::Error as DeError, Deserialize, Deserializer, Serialize, Serializer};
use std::borrow::Borrow;
use std::cmp::Ordering;
use std::fmt::{Debug, Display, Formatter, Result as FmtResult};
use std::hash::Hash;
use std::hash::Hasher;
std_prelude!();

#[derive(Clone, Copy)]
/// A value that is accepted by a given predicate.
pub struct Pet<T, P>(T, P);

impl<T, P: Pred<T>> Pet<T, P> {
    /// Attempts to create a new `Pet<T, P>` from a value `t`.
    ///
    /// If `P` accepts `t`, then the result is a `Some(..)` containing the value `t`.
    /// Otherwise, `None` is returned.
    pub fn new(t: T) -> Option<Self> {
        if P::accept(&t) {
            Some(Self(t, P::default()))
        } else {
            None
        }
    }

    /// Creates a new `Pet<T, P>` from a value `t` without checking if `P` accepts `t`.
    pub unsafe fn new_unchecked(t: T) -> Self {
        Self(t, P::default())
    }

    /// Retrieves the value contained in this `Pet<T, P>`.
    pub fn value(self) -> T {
        self.0
    }
}

impl<T, P> AsRef<T> for Pet<T, P> {
    fn as_ref(&self) -> &T {
        &self.0
    }
}
impl<T, P> Borrow<T> for Pet<T, P> {
    fn borrow(&self) -> &T {
        &self.0
    }
}

impl<T, P> Debug for Pet<T, P>
where
    T: Debug,
    P: Debug,
{
    fn fmt(&self, f: &mut Formatter) -> FmtResult {
        write!(f, "Pet<{:?}>({:?})", self.1, self.0)
    }
}

impl<T, P> Display for Pet<T, P>
where
    T: Display,
{
    fn fmt(&self, f: &mut Formatter) -> FmtResult {
        self.0.fmt(f)
    }
}

impl<T, P, Q> PartialEq<Pet<T, Q>> for Pet<T, P>
where
    T: PartialEq,
{
    fn eq(&self, o: &Pet<T, Q>) -> bool {
        self.0.eq(&o.0)
    }
    fn ne(&self, o: &Pet<T, Q>) -> bool {
        self.0.ne(&o.0)
    }
}
impl<T, P> Eq for Pet<T, P> where T: Eq {}

impl<T, P, Q> PartialOrd<Pet<T, Q>> for Pet<T, P>
where
    T: PartialOrd,
{
    fn partial_cmp(&self, o: &Pet<T, Q>) -> Option<Ordering> {
        self.0.partial_cmp(&o.0)
    }
    fn lt(&self, o: &Pet<T, Q>) -> bool {
        self.0.lt(&o.0)
    }
    fn le(&self, o: &Pet<T, Q>) -> bool {
        self.0.le(&o.0)
    }
    fn gt(&self, o: &Pet<T, Q>) -> bool {
        self.0.gt(&o.0)
    }
    fn ge(&self, o: &Pet<T, Q>) -> bool {
        self.0.ge(&o.0)
    }
}
impl<T, P> Ord for Pet<T, P>
where
    T: Ord,
{
    fn cmp(&self, o: &Self) -> Ordering {
        self.0.cmp(&o.0)
    }
}

impl<T, P> Hash for Pet<T, P>
where
    T: Hash,
{
    fn hash<H>(&self, state: &mut H)
    where
        H: Hasher,
    {
        self.0.hash(state)
    }
}

#[cfg(feature = "serde")]
impl<T, P: Pred<T>> Serialize for Pet<T, P>
where
    T: Serialize,
{
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        self.0.serialize(serializer)
    }
}

#[cfg(feature = "serde")]
impl<'de, T, P: Pred<T>> Deserialize<'de> for Pet<T, P>
where
    T: Deserialize<'de>,
{
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        Self::new(T::deserialize(deserializer)?).ok_or_else(|| {
            D::Error::custom(format_args!(
                "Value did not pass predicate {:?}",
                P::default()
            ))
        })
    }
}