summaryrefslogtreecommitdiffstats
path: root/src/coords.rs
blob: cee89eebb3c054cbcda2690517b60e4a9dd0f982 (plain)
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
//! [Coordinate spaces](https://en.wikipedia.org/wiki/Cartesian_coordinate_system).

use crate::distance::Value;

/// A coordinate space.
pub trait Coordinates {
    /// The type of individual coordinates.
    type Value: Value;

    /// Get the number of dims this point has.
    fn dims(&self) -> usize;

    /// Get the `i`th coordinate of this point.
    fn coord(&self, i: usize) -> Self::Value;

    /// Create a vector with this point's coordinates as values.
    fn as_vec(&self) -> Vec<Self::Value> {
        let len = self.dims();
        let mut vec = Vec::with_capacity(len);
        for i in 0..len {
            vec.push(self.coord(i));
        }
        vec
    }
}

/// [`Coordinates`] implementation for slices.
impl<T: Value> Coordinates for [T] {
    type Value = T;

    fn dims(&self) -> usize {
        self.len()
    }

    fn coord(&self, i: usize) -> T {
        self[i]
    }
}

/// [`Coordinates`] implementation for arrays.
impl<T: Value, const N: usize> Coordinates for [T; N] {
    type Value = T;

    fn dims(&self) -> usize {
        N
    }

    fn coord(&self, i: usize) -> T {
        self[i]
    }
}

/// [`Coordinates`] implemention for vectors.
impl<T: Value> Coordinates for Vec<T> {
    type Value = T;

    fn dims(&self) -> usize {
        self.len()
    }

    fn coord(&self, i: usize) -> T {
        self[i]
    }
}

/// Blanket [`Coordinates`] implementation for references.
impl<T: ?Sized + Coordinates> Coordinates for &T {
    type Value = T::Value;

    fn dims(&self) -> usize {
        (*self).dims()
    }

    fn coord(&self, i: usize) -> Self::Value {
        (*self).coord(i)
    }
}