1 // helper struct for keeping track of which values are exact 2 3 use std::fmt; 4 use std::ops::Neg; 5 6 #[derive(Copy, Clone)] 7 pub(crate) struct Exact<T: fmt::Debug> { 8 pub(crate) value: T, 9 pub(crate) exact: bool, 10 } 11 12 impl<T: fmt::Debug> fmt::Debug for Exact<T> { fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result13 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 14 if self.exact { 15 write!(f, "exactly ")?; 16 } else { 17 write!(f, "approx. ")?; 18 } 19 write!(f, "{:?}", self.value)?; 20 Ok(()) 21 } 22 } 23 24 impl<T: fmt::Debug> Exact<T> { new(value: T, exact: bool) -> Self25 pub(crate) fn new(value: T, exact: bool) -> Self { 26 Self { value, exact } 27 } 28 apply<R: fmt::Debug, F: FnOnce(T) -> R>(self, f: F) -> Exact<R>29 pub(crate) fn apply<R: fmt::Debug, F: FnOnce(T) -> R>(self, f: F) -> Exact<R> { 30 Exact::<R> { 31 value: f(self.value), 32 exact: self.exact, 33 } 34 } 35 try_and_then< R: fmt::Debug, E: fmt::Debug, F: FnOnce(T) -> Result<Exact<R>, E>, >( self, f: F, ) -> Result<Exact<R>, E>36 pub(crate) fn try_and_then< 37 R: fmt::Debug, 38 E: fmt::Debug, 39 F: FnOnce(T) -> Result<Exact<R>, E>, 40 >( 41 self, 42 f: F, 43 ) -> Result<Exact<R>, E> { 44 Ok(f(self.value)?.combine(self.exact)) 45 } 46 combine(self, x: bool) -> Self47 pub(crate) fn combine(self, x: bool) -> Self { 48 Self { 49 value: self.value, 50 exact: self.exact && x, 51 } 52 } 53 re<'a>(&'a self) -> Exact<&'a T>54 pub(crate) fn re<'a>(&'a self) -> Exact<&'a T> { 55 Exact::<&'a T> { 56 value: &self.value, 57 exact: self.exact, 58 } 59 } 60 } 61 62 impl<A: fmt::Debug, B: fmt::Debug> Exact<(A, B)> { pair(self) -> (Exact<A>, Exact<B>)63 pub(crate) fn pair(self) -> (Exact<A>, Exact<B>) { 64 ( 65 Exact { 66 value: self.value.0, 67 exact: self.exact, 68 }, 69 Exact { 70 value: self.value.1, 71 exact: self.exact, 72 }, 73 ) 74 } 75 } 76 77 impl<T: fmt::Debug + Neg<Output = T>> Neg for Exact<T> { 78 type Output = Self; neg(self) -> Self79 fn neg(self) -> Self { 80 Self { 81 value: -self.value, 82 exact: self.exact, 83 } 84 } 85 } 86