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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
macro_rules! define_ty {
    ($id:ident, $($elem_tys:ident),+) => {
        #[derive(Copy, Clone, PartialEq, Debug)]
        #[allow(non_camel_case_types)]
        pub struct $id($($elem_tys),*);
    }
}

macro_rules! impl_minimal {
    ($id:ident, $elem_ty:ident, $elem_count:expr, $($elem_name:ident),+) => {
        impl $id {
            #[allow(clippy::complexity)]
            #[inline]
            pub const fn new($($elem_name: $elem_ty),*) -> Self {
                $id($($elem_name),*)
            }

            #[inline]
            pub const fn lanes() -> usize {
                $elem_count
            }

             pub const fn splat(value: $elem_ty) -> Self {
                $id($({
                    // this just allows us to repeat over the elements
                    #[allow(non_camel_case_types, dead_code)]
                    struct $elem_name;
                    value
                }),*)
            }
        }
    };
}

macro_rules! impl_op2 {
    ($trait:ident, $fn:ident, $typ:ty, $op:tt) => {
        impl $trait for $typ {
            type Output = $typ;
            fn $fn(self, rhs: Self) -> Self::Output {
                Self(
                    self.0 $op rhs.0,
                    self.1 $op rhs.1,
                )
            }
        }
    };
    (assn $trait:ident, $fn:ident, $typ:ty, $op:tt) => {
        impl $trait for $typ {
            fn $fn(&mut self, rhs: Self) {
                    self.0 $op rhs.0;
                    self.1 $op rhs.1;
            }
        }
    };
}

macro_rules! impl_op4 {
    ($trait:ident, $fn:ident, $typ:ty, $op:tt) => {
        impl $trait for $typ {
            type Output = $typ;
            fn $fn(self, rhs: Self) -> Self::Output {
                Self(
                    self.0 $op rhs.0,
                    self.1 $op rhs.1,
                    self.2 $op rhs.2,
                    self.3 $op rhs.3,
                )
            }
        }
    };
    (assn $trait:ident, $fn:ident, $typ:ty, $op:tt) => {
        impl $trait for $typ {
            fn $fn(&mut self, rhs: Self) {
                    self.0 $op rhs.0;
                    self.1 $op rhs.1;
                    self.2 $op rhs.2;
                    self.3 $op rhs.3;
            }
        }
    };
}

macro_rules! impl_op8 {
    ($trait:ident, $fn:ident, $typ:ty, $op:tt) => {
        impl $trait for $typ {
            type Output = $typ;
            fn $fn(self, rhs: Self) -> Self::Output {
                Self(
                    self.0 $op rhs.0,
                    self.1 $op rhs.1,
                    self.2 $op rhs.2,
                    self.3 $op rhs.3,
                    self.4 $op rhs.4,
                    self.5 $op rhs.5,
                    self.6 $op rhs.6,
                    self.7 $op rhs.7,
                )
            }
        }
    };
    (assn $trait:ident, $fn:ident, $typ:ty, $op:tt) => {
        impl $trait for $typ {
            fn $fn(&mut self, rhs: Self) {
                    self.0 $op rhs.0;
                    self.1 $op rhs.1;
                    self.2 $op rhs.2;
                    self.3 $op rhs.3;
                    self.4 $op rhs.4;
                    self.5 $op rhs.5;
                    self.6 $op rhs.6;
                    self.7 $op rhs.7;
            }
        }
    };
}

macro_rules! impl_op16 {
    ($trait:ident, $fn:ident, $typ:ty, $op:tt) => {
        impl $trait for $typ {
            type Output = $typ;
            fn $fn(self, rhs: Self) -> Self::Output {
                Self(
                    self.0 $op rhs.0,
                    self.1 $op rhs.1,
                    self.2 $op rhs.2,
                    self.3 $op rhs.3,
                    self.4 $op rhs.4,
                    self.5 $op rhs.5,
                    self.6 $op rhs.6,
                    self.7 $op rhs.7,
                    self.8 $op rhs.8,
                    self.9 $op rhs.9,
                    self.10 $op rhs.10,
                    self.11 $op rhs.11,
                    self.12 $op rhs.12,
                    self.13 $op rhs.13,
                    self.14 $op rhs.14,
                    self.15 $op rhs.15,
                )
            }
        }
    };
    (assn $trait:ident, $fn:ident, $typ:ty, $op:tt) => {
        impl $trait for $typ {
            fn $fn(&mut self, rhs: Self) {
                    self.0 $op rhs.0;
                    self.1 $op rhs.1;
                    self.2 $op rhs.2;
                    self.3 $op rhs.3;
                    self.4 $op rhs.4;
                    self.5 $op rhs.5;
                    self.6 $op rhs.6;
                    self.7 $op rhs.7;
                    self.8 $op rhs.8;
                    self.9 $op rhs.9;
                    self.10 $op rhs.10;
                    self.11 $op rhs.11;
                    self.12 $op rhs.12;
                    self.13 $op rhs.13;
                    self.14 $op rhs.14;
                    self.15 $op rhs.15;
            }
        }
    };
}

macro_rules! impl_distances {
    ($name:ident, $ty:ty) => {
        use super::Naive;
        impl $name {
            /// Calculate the squared distance between two SIMD lane-slices
            pub fn euclidean_inner(a: &[$ty], b: &[$ty]) -> $name {
                let i = $name::from_slice(a);
                let j = $name::from_slice(b);
                let u = i - j;
                u * u
            }

            /// Calculate the cosine accumulators (3) between two SIMD lane-slices
            pub fn cosine_inner(a: &[$ty], b: &[$ty]) -> [$name; 3] {
                let i = $name::from_slice(a);
                let j = $name::from_slice(b);
                [i * i, j * j, i * j]
            }

            /// Calculate euclidean distance between two slices of equal length,
            /// using auto-vectorized SIMD primitives
            pub fn squared_euclidean(a: &[$ty], b: &[$ty]) -> $ty {
                assert_eq!(a.len(), b.len());
                if a.len() < $name::lanes() {
                    return Naive::squared_euclidean(a, b);
                }

                let mut i = 0;
                let mut sum = $name::splat(0 as $ty);
                while a.len() - $name::lanes() >= i {
                    sum += $name::euclidean_inner(
                        &a[i..i + $name::lanes()],
                        &b[i..i + $name::lanes()],
                    );
                    i += $name::lanes();
                }

                let mut sum = sum.horizontal_add();
                if i < a.len() {
                    sum += Naive::squared_euclidean(&a[i..], &b[i..]);
                }
                sum
            }

            pub fn euclidean(a: &[$ty], b: &[$ty]) -> $ty {
                $name::squared_euclidean(a, b).sqrt()
            }

            pub fn cosine_acc(a: &[$ty], b: &[$ty]) -> [$ty; 3] {
                assert_eq!(a.len(), b.len());
                if a.len() < $name::lanes() {
                    return Naive::cosine_acc(a, b);
                }
                let mut i = 0;
                let [mut xx, mut yy, mut xy] = [
                    $name::splat(0 as $ty),
                    $name::splat(0 as $ty),
                    $name::splat(0 as $ty),
                ];
                while a.len() - $name::lanes() >= i {
                    let [xxs, yys, xys] =
                        $name::cosine_inner(&a[i..i + $name::lanes()], &b[i..i + $name::lanes()]);
                    xx += xxs;
                    yy += yys;
                    xy += xys;
                    i += $name::lanes();
                }
                let mut xxsum = xx.horizontal_add();
                let mut yysum = yy.horizontal_add();
                let mut xysum = xy.horizontal_add();
                if i < a.len() {
                    let [xxs, yys, xys] = Naive::cosine_acc(&a[i..], &b[i..]);
                    xxsum += xxs;
                    yysum += yys;
                    xysum += xys;
                }
                [xxsum, yysum, xysum]
            }
            pub fn cosine(a: &[$ty], b: &[$ty]) -> $ty {
                let [xx, yy, xy] = $name::cosine_acc(a, b);
                let eps = <$ty>::EPSILON;
                if xx < eps || yy < eps || xy < eps {
                    1 as $ty
                } else {
                    let d = 1 as $ty - xy / (xx * yy).sqrt();
                    if d < eps {
                        0 as $ty
                    } else {
                        d
                    }
                }
            }
        }
    };
}

macro_rules! impl_naive {
    ($ty1:ty, $ty2:ty) => {
        impl Naive for &[$ty1] {
            type Output = $ty2;
            type Ty = $ty1;
            fn squared_euclidean(self, other: Self) -> Self::Output {
                assert_eq!(self.len(), other.len());

                let mut sum = 0 as Self::Output;
                for i in 0..self.len() {
                    let d = self[i] - other[i];
                    sum += (d * d) as Self::Output;
                }
                sum
            }

            fn euclidean(self, other: Self) -> Self::Output {
                Naive::squared_euclidean(self, other).sqrt()
            }

            fn cosine_acc(self, other: Self) -> [Self::Output; 3] {
                self.iter()
                    .zip(other.iter())
                    .fold([0 as Self::Output; 3], |[xx, yy, xy], (&a, &b)| {
                        [a.mul_add(a, xx), b.mul_add(b, yy), a.mul_add(b, xy)]
                    })
            }

            fn cosine(self, other: Self) -> Self::Output {
                let [xx, yy, xy] = Naive::cosine_acc(self, other);
                let eps = Self::Output::EPSILON;
                if xx < eps || yy < eps || xy < eps {
                    1 as Self::Output
                } else {
                    let d = 1 as Self::Output - xy / (xx * yy).sqrt();
                    if d < eps {
                        0 as Self::Output
                    } else {
                        d
                    }
                }
            }
        }
        impl Naive for &Vec<$ty1> {
            type Output = $ty2;
            type Ty = $ty1;
            fn squared_euclidean(self, other: Self) -> $ty2 {
                assert_eq!(self.len(), other.len());

                let mut sum = 0 as $ty2;
                for i in 0..self.len() {
                    let d = self[i] - other[i];
                    sum += (d * d) as $ty2;
                }
                sum
            }

            fn euclidean(self, other: Self) -> $ty2 {
                Naive::squared_euclidean(self, other).sqrt()
            }

            fn cosine_acc(self, other: Self) -> [Self::Output; 3] {
                self.iter()
                    .zip(other.iter())
                    .fold([0 as Self::Output; 3], |[xx, yy, xy], (&a, &b)| {
                        [a.mul_add(a, xx), b.mul_add(b, yy), a.mul_add(b, xy)]
                    })
            }

            fn cosine(self, other: Self) -> Self::Output {
                let [xx, yy, xy] = Naive::cosine_acc(self, other);
                let eps = Self::Output::EPSILON;
                if xx < eps || yy < eps || xy < eps {
                    1 as Self::Output
                } else {
                    let d = 1 as Self::Output - xy / (xx * yy).sqrt();
                    if d < eps {
                        0 as Self::Output
                    } else {
                        d
                    }
                }
            }
        }
    };
}