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
//! Summation loops

mod unroll;
#[cfg(feature = "use_nightly")]
mod specialization;

use num_traits::Zero;

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

/// Compute the sum of the values in `xs`
///
/// With `"use_nightly"`, this is special cased for `f32, f64`.
pub fn sum<A>(xs: &[A]) -> A
    where A: Clone + Add<Output=A> + Zero,
{
    Sum::sum(xs)
}

/// Compute the dot product.
///
/// `xs` and `ys` should be the same length and there *may* be a panic if they
/// are not.
///
/// With `"use_nightly"`, this is special cased for `f32, f64`.
pub fn dot<A>(xs: &[A], ys: &[A]) -> A
    where A: Add<Output=A> + Mul<Output=A> + Zero + Copy,
{
    debug_assert_eq!(xs.len(), ys.len());
    Dot::dot(xs, ys)
}

trait Sum : Sized {
    fn sum(lhs: &[Self]) -> Self;
}

trait Dot : Sized {
    fn dot(lhs: &[Self], rhs: &[Self]) -> Self;
}

impl<A> Sum for A
    where A: Clone + Add<Output=A> + Zero,
{
    #[cfg(feature = "use_nightly")]
    default fn sum(lhs: &[A]) -> A {
        unroll::sum(lhs)
    }
    #[cfg(not(feature = "use_nightly"))]
    fn sum(lhs: &[A]) -> A {
        unroll::sum(lhs)
    }
}

impl<A> Dot for A
    where A: Add<Output=A> + Mul<Output=A> + Zero + Copy,
{
    #[cfg(feature = "use_nightly")]
    default fn dot(lhs: &[A], rhs: &[A]) -> A {
        unroll::dot(lhs, rhs)
    }
    #[cfg(not(feature = "use_nightly"))]
    fn dot(lhs: &[A], rhs: &[A]) -> A {
        unroll::dot(lhs, rhs)
    }
}