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
use crate::dim::Dim;
use crate::expr::Producer;
use crate::expression::Expression;

/// Trait for applying a closure and returning a new or an existing array.
pub trait Apply<T>: IntoExpression {
    /// The resulting type after applying a closure.
    type Output: IntoExpression<Item = T, Dim = Self::Dim>;

    /// The resulting type after zipping elements and applying a closure.
    type ZippedWith<I: IntoExpression>: IntoExpression<Item = T>;

    /// Returns a new or an existing array with the given closure applied to each element.
    fn apply<F: FnMut(Self::Item) -> T>(self, f: F) -> Self::Output;

    /// Returns a new or an existing array with the given closure applied to zipped element pairs.
    fn zip_with<I: IntoExpression, F>(self, expr: I, f: F) -> Self::ZippedWith<I>
    where
        F: FnMut(Self::Item, I::Item) -> T;
}

/// Trait for generalization of `Clone` that can reuse an existing object.
pub trait IntoCloned<T> {
    /// Moves an existing object or clones from a reference to the target object.
    fn clone_to(self, target: &mut T);

    /// Returns an existing object or a new clone from a reference.
    fn into_cloned(self) -> T;
}

/// Conversion trait into an expression.
pub trait IntoExpression {
    /// Array element type.
    type Item;

    /// Array dimension type.
    type Dim: Dim;

    /// Which kind of expression producer are we turning this into?
    type Producer: Producer<Item = Self::Item, Dim = Self::Dim>;

    /// Creates an expression from a value.
    fn into_expr(self) -> Expression<Self::Producer>;
}

impl<T: Clone> IntoCloned<T> for &T {
    fn clone_to(self, target: &mut T) {
        target.clone_from(self);
    }

    fn into_cloned(self) -> T {
        self.clone()
    }
}

impl<T> IntoCloned<T> for T {
    fn clone_to(self, target: &mut T) {
        *target = self;
    }

    fn into_cloned(self) -> T {
        self
    }
}