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
//! Naive floating point summation

use std::ops::{Add, AddAssign};

use num::Float;

use super::traits::SumAccumulator;

/// Naive floating point summation
///
/// ![](https://rockshrub.de/accurate/NaiveSum.svg)
///
/// # Examples
///
/// ```
/// use accurate::traits::*;
/// use accurate::sum::NaiveSum;
///
/// let s = NaiveSum::zero() + 1.0 + 2.0 + 3.0;
/// assert_eq!(6.0f64, s.sum());
/// ```
#[derive(Copy, Clone, Debug)]
pub struct NaiveSum<F>(F);

impl<F> SumAccumulator<F> for NaiveSum<F>
where
    F: Float,
{
    #[inline]
    fn sum(self) -> F {
        self.0
    }
}

impl<F> Add<F> for NaiveSum<F>
where
    NaiveSum<F>: AddAssign<F>,
{
    type Output = Self;

    #[inline]
    fn add(mut self, rhs: F) -> Self::Output {
        self += rhs;
        self
    }
}

impl<F> From<F> for NaiveSum<F>
where
    F: Float,
{
    fn from(x: F) -> Self {
        NaiveSum(x)
    }
}

impl<F> Add for NaiveSum<F>
where
    F: Float,
{
    type Output = Self;

    #[inline]
    fn add(self, rhs: Self) -> Self::Output {
        NaiveSum(self.0 + rhs.0)
    }
}

unsafe impl<F> Send for NaiveSum<F>
where
    F: Send,
{
}

impl<F> AddAssign<F> for NaiveSum<F>
where
    F: Float,
{
    #[inline]
    fn add_assign(&mut self, rhs: F) {
        self.0 = self.0 + rhs;
    }
}