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
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
use crate::traits::*;
#[cfg(feature = "serde")]
use serde::{Deserialize, Serialize};
use std::ops::{Add, Div, Mul, Neg, Sub};

#[cfg(feature = "serde")]
mod serde_conversion;

/// A type with a value and uncertainties.
#[derive(Debug, Clone, Copy, Eq, PartialEq, Ord, PartialOrd, Hash, Default)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(
    feature = "serde",
    serde(
        into = "serde_conversion::ValUncTuple<V, U>",
        from = "serde_conversion::ValUncTuple<V, U>",
        bound(
            serialize = "V: Clone + Serialize, U: Clone + Serialize + UncZero",
            deserialize = "V: Deserialize<'de>, U: Deserialize<'de> + Default"
        )
    )
)]
pub struct ValUnc<V, U> {
    pub val: V,
    pub unc: U,
}

impl<V, U> ValUnc<V, U> {
    pub fn new(val: V, unc: U) -> Self {
        Self { val, unc }
    }
}

impl<V, U> From<V> for ValUnc<V, U>
where
    U: Default,
{
    fn from(val: V) -> Self {
        Self {
            val,
            unc: Default::default(),
        }
    }
}

impl<V, U> Add for ValUnc<V, U>
where
    V: Add<V, Output = V> + Copy,
    U: UncAdd<V>,
{
    type Output = Self;

    fn add(self, other: Self) -> Self {
        Self {
            val: self.val.add(other.val),
            unc: self.unc.unc_add(self.val, other.unc, other.val),
        }
    }
}

impl<V, U> Div for ValUnc<V, U>
where
    V: Div<V, Output = V> + Copy,
    U: UncDiv<V>,
{
    type Output = Self;

    fn div(self, other: Self) -> Self {
        Self {
            val: self.val.div(other.val),
            unc: self.unc.unc_div(self.val, other.unc, other.val),
        }
    }
}

impl<V, U> Mul for ValUnc<V, U>
where
    V: Mul<V, Output = V> + Copy,
    U: UncMul<V>,
{
    type Output = Self;

    fn mul(self, other: Self) -> Self {
        Self {
            val: self.val.mul(other.val),
            unc: self.unc.unc_mul(self.val, other.unc, other.val),
        }
    }
}

impl<V, U> Neg for ValUnc<V, U>
where
    V: Neg<Output = V> + Copy,
    U: UncNeg<V>,
{
    type Output = Self;

    fn neg(self) -> Self {
        Self {
            val: self.val.neg(),
            unc: self.unc.unc_neg(self.val),
        }
    }
}

impl<V, U> Sub for ValUnc<V, U>
where
    V: Sub<V, Output = V> + Copy,
    U: UncSub<V>,
{
    type Output = Self;

    fn sub(self, other: Self) -> Self {
        Self {
            val: self.val.sub(other.val),
            unc: self.unc.unc_sub(self.val, other.unc, other.val),
        }
    }
}