blob: 7c839467b6540c20d795610638298ef00db201ea (
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
78
79
80
81
82
83
84
85
86
87
88
89
90
|
//! [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.
macro_rules! array_coordinates {
($n:expr) => {
impl<T: Value> Coordinates for [T; $n] {
type Value = T;
fn dims(&self) -> usize {
$n
}
fn coord(&self, i: usize) -> T {
self[i]
}
}
};
}
array_coordinates!(1);
array_coordinates!(2);
array_coordinates!(3);
array_coordinates!(4);
array_coordinates!(5);
array_coordinates!(6);
array_coordinates!(7);
array_coordinates!(8);
/// [`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)
}
}
|