use crate::Pred;
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)]
pub struct PetRef<'a, T: ?Sized, P>(&'a T, P);
impl<'a, T: ?Sized, P: Pred<T>> PetRef<'a, T, P> {
pub fn new(t: &'a T) -> Option<Self> {
if P::accept(t) {
Some(Self(t, P::default()))
} else {
None
}
}
pub unsafe fn new_unchecked(t: &'a T) -> Self {
Self(t, P::default())
}
pub fn value(&self) -> &'a T {
self.0
}
}
impl<'a, T: ?Sized, P> AsRef<T> for PetRef<'a, T, P> {
fn as_ref(&self) -> &T {
self.0
}
}
impl<'a, T: ?Sized, P> Borrow<T> for PetRef<'a, T, P> {
fn borrow(&self) -> &T {
self.0
}
}
impl<'a, 'b, T: ?Sized, P, Q> PartialEq<PetRef<'b, T, Q>> for PetRef<'a, T, P>
where
T: PartialEq,
{
fn eq(&self, o: &PetRef<'b, T, Q>) -> bool {
self.0.eq(&o.0)
}
fn ne(&self, o: &PetRef<'b, T, Q>) -> bool {
self.0.ne(&o.0)
}
}
impl<'a, 'b, T: ?Sized, P, Q> PartialOrd<PetRef<'b, T, Q>> for PetRef<'a, T, P>
where
T: PartialOrd,
{
fn partial_cmp(&self, o: &PetRef<'b, T, Q>) -> Option<Ordering> {
self.0.partial_cmp(&o.0)
}
fn lt(&self, o: &PetRef<'b, T, Q>) -> bool {
self.0.lt(&o.0)
}
fn le(&self, o: &PetRef<'b, T, Q>) -> bool {
self.0.le(&o.0)
}
fn gt(&self, o: &PetRef<'b, T, Q>) -> bool {
self.0.gt(&o.0)
}
fn ge(&self, o: &PetRef<'b, T, Q>) -> bool {
self.0.ge(&o.0)
}
}
impl<'a, T: ?Sized, P> Eq for PetRef<'a, T, P> where T: Eq {}
impl<'a, T: ?Sized, P> Ord for PetRef<'a, T, P>
where
T: Ord,
{
fn cmp(&self, o: &Self) -> Ordering {
self.0.cmp(&o.0)
}
}
impl<'a, T, P> Hash for PetRef<'a, T, P>
where
T: Hash,
{
fn hash<H>(&self, state: &mut H)
where
H: Hasher,
{
self.0.hash(state)
}
}
impl<'a, T: ?Sized, P> Debug for PetRef<'a, T, P>
where
T: Debug,
P: Debug,
{
fn fmt(&self, f: &mut Formatter) -> FmtResult {
write!(f, "PetRef<{:?}>({:?})", self.1, self.0)
}
}
impl<'a, T, P> Display for PetRef<'a, T, P>
where
T: Display,
{
fn fmt(&self, f: &mut Formatter) -> FmtResult {
self.0.fmt(f)
}
}