1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
//! Trait definitions for approximated values

/// Represent an calculation result with a possible error.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Approximation<T, E> {
    /// The result is exact, contains the result value
    Exact(T),

    /// The result is inexact, contains the result value and error
    Inexact(T, E),
}

impl<T, E> Approximation<T, E> {
    /// Get the value of the calculation regardless of error
    #[inline]
    pub fn value(self) -> T {
        match self {
            Self::Exact(v) => v,
            Self::Inexact(v, _) => v,
        }
    }

    /// Get a reference to the calculation result
    #[inline]
    pub fn value_ref(&self) -> &T {
        match self {
            Self::Exact(v) => v,
            Self::Inexact(v, _) => v,
        }
    }

    #[inline]
    pub fn error(&self) -> Option<&E> {
        match self {
            Self::Exact(_) => None,
            Self::Inexact(_, e) => Some(e),
        }
    }

    #[inline]
    pub fn map<U, F>(self, f: F) -> Approximation<U, E>
    where
        F: FnOnce(T) -> U,
    {
        match self {
            Self::Exact(v) => Approximation::Exact(f(v)),
            Self::Inexact(v, e) => Approximation::Inexact(f(v), e),
        }
    }

    #[inline]
    pub fn and_then<U, F>(self, f: F) -> Approximation<U, E>
    where
        F: FnOnce(T) -> Approximation<U, E>,
    {
        match self {
            Self::Exact(v) => match f(v) {
                Approximation::Exact(v2) => Approximation::Exact(v2),
                Approximation::Inexact(v2, e) => Approximation::Inexact(v2, e),
            },
            Self::Inexact(v, e) => match f(v) {
                Approximation::Exact(v2) => Approximation::Inexact(v2, e),
                Approximation::Inexact(v2, e2) => Approximation::Inexact(v2, e2),
            },
        }
    }
}