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
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
use std::{
    fmt::Debug,
    iter::{Product, Sum},
    ops::{Add, AddAssign, Div, DivAssign, Index, IndexMut, Mul, MulAssign, Neg, Sub, SubAssign},
};

/// Base trait for fixed-size vector types.
pub trait SIMDBase<const N: usize>
where
    Self: Into<Self::Underlying> + From<Self::Underlying>,
    Self::Element: Copy,
{
    /// Underlying intrinsic type or tuple of types.
    type Underlying;

    /// Type of a single element of packed vector.
    type Element;

    /// Number of elements in vector.
    const N: usize = N;

    /// Initializes all values of returned vector with a given value.
    ///
    /// # Examples
    /// ```
    /// # use vrl::prelude::*;
    /// assert_eq!(
    ///     Vec4f::broadcast(42.0),
    ///     [42.0; 4].into()
    /// );
    /// ```
    ///
    /// # Note
    /// Prefer using [`default`](Default::default) instead of [`broadcast`]-ing zero.
    ///
    /// [`broadcast`]: SIMDBase::broadcast
    fn broadcast(value: Self::Element) -> Self;

    /// Loads vector from an array pointed by `addr`.
    /// `addr` is not required to be aligned.
    ///
    /// # Safety
    /// `addr` must be a valid pointer to an [`N`](Self::N)-sized array.
    ///
    /// # Example
    /// ```
    /// # use vrl::prelude::*;
    /// let array = [42.0; 4];
    /// let vec = unsafe { Vec4f::load_ptr(array.as_ptr()) };
    /// ```
    unsafe fn load_ptr(addr: *const Self::Element) -> Self;

    /// Loads vector from a given array.
    ///
    /// # Exmaples
    /// ```
    /// # use vrl::prelude::*;
    /// assert_eq!(
    ///     Vec4f::new(1.0, 2.0, 3.0, 4.0),
    ///     Vec4f::load(&[1.0, 2.0, 3.0, 4.0])
    /// );
    /// ```
    #[inline]
    fn load(data: &[Self::Element; N]) -> Self {
        // SAFETY: data contains exactly N elements hence it's safe to load them
        unsafe { Self::load_ptr(data.as_ptr()) }
    }

    /// Checks that `data` contains exactly [`N`] elements and loads them into vector.
    ///
    /// # Panics
    /// Panics if `data.len()` doesn't equal [`N`].
    ///
    /// # Examples
    /// ```
    /// # use vrl::prelude::*;
    /// assert_eq!(
    ///     Vec4f::load_checked(&[1.0, 2.0, 3.0, 4.0]),
    ///     Vec4f::new(1.0, 2.0, 3.0, 4.0)
    /// );
    /// ```
    /// ```should_panic
    /// # use vrl::prelude::*;
    /// Vec4f::load_checked(&[1.0, 2.0, 3.0]);
    /// ```
    /// ```should_panic
    /// # use vrl::prelude::*;
    /// Vec4f::load_checked(&[1.0, 2.0, 3.0, 4.0, 5.0]);
    /// ```
    ///
    /// [`N`]: Self::N
    #[inline]
    fn load_checked(data: &[Self::Element]) -> Self {
        if data.len() != Self::N {
            panic!("data must contain exactly {} elements", Self::N);
        }
        // SAFETY: data contains exactly N elements hence it's safe to load them
        unsafe { Self::load_ptr(data.as_ptr()) }
    }

    /// Loads first [`N`] elements of `data` into vector.
    ///
    /// # Panics
    /// Panics if `data` contains less than [`N`] elements.
    ///
    /// # Exmaples
    /// ```
    /// # use vrl::prelude::*;
    /// assert_eq!(
    ///     Vec4f::load_prefix(&[1.0, 2.0, 3.0, 4.0, 5.0]),
    ///     Vec4f::new(1.0, 2.0, 3.0, 4.0)
    /// );
    /// ```
    ///
    /// ```should_panic
    /// # use vrl::prelude::*;
    /// Vec4f::load_prefix(&[1.0, 2.0, 3.0]);
    /// ```
    ///
    /// [`N`]: Self::N
    #[inline]
    fn load_prefix(data: &[Self::Element]) -> Self {
        if data.len() < Self::N {
            panic!("data must contain at least {} elements", Self::N);
        }
        // SAFETY: data contains at least N elements hence it's safe to load the first N
        unsafe { Self::load_ptr(data.as_ptr()) }
    }

    /// Stores vector into array at given address.
    ///
    /// # Safety
    /// `addr` must be a valid pointer.
    unsafe fn store_ptr(self, addr: *mut Self::Element);

    /// Stores vector into given `array`.
    #[inline]
    fn store(self, array: &mut [Self::Element; N]) {
        // SAFETY: array has size of N elements hence it's safe to store the vector there
        unsafe { self.store_ptr(array.as_mut_ptr()) }
    }

    /// Checks that `slice` contains exactly [`N`] elements and stores elements of vector there.
    ///
    /// # Panics
    /// Panics if `slice.len()` doesn't equal [`N`].
    ///
    /// # Examples
    /// ```
    /// # use vrl::prelude::*;
    /// let mut data = [-1.0; 4];
    /// Vec4f::default().store_checked(&mut data);
    /// assert_eq!(data, [0.0; 4]);
    /// ```
    /// ```should_panic
    /// # use vrl::prelude::*;
    /// let mut data = [-1.0; 3];
    /// Vec4f::default().store_checked(&mut data);
    /// ```
    /// ```should_panic
    /// # use vrl::prelude::*;
    /// let mut data = [-1.0; 5];
    /// Vec4f::default().store_checked(&mut data);
    /// ```
    ///
    /// [`N`]: Self::N
    #[inline]
    fn store_checked(self, slice: &mut [Self::Element]) {
        if slice.len() != Self::N {
            panic!("slice must contain exactly {} elements", Self::N);
        }
        // SAFETY: slice has size of N elements hence it's safe to store the vector there
        unsafe { self.store_ptr(slice.as_mut_ptr()) };
    }

    /// Stores elements of the vector into prefix of `slice`.
    ///
    /// # Panics
    /// Panics if `slice.len()` is less than [`N`](Self::N).
    ///
    /// # Exmaples
    /// ```
    /// # use vrl::prelude::*;
    /// let mut data = [-1.0; 5];
    /// Vec4f::broadcast(2.0).store_prefix(&mut data);
    /// assert_eq!(data, [2.0, 2.0, 2.0, 2.0, -1.0]);
    /// ```
    /// ```should_panic
    /// # use vrl::prelude::*;
    /// let mut data = [-1.0; 3];
    /// Vec4f::default().store_prefix(&mut data);
    /// ```
    #[inline]
    fn store_prefix(self, slice: &mut [Self::Element]) {
        if slice.len() < Self::N {
            panic!("slice must contain at least {} elements", Self::N);
        }
        // SAFETY: slice has size of at least N elements hence it's safe to store the vector there
        unsafe { self.store_ptr(slice.as_mut_ptr()) };
    }

    /// Extracts `index`-th element of the vector. Index `0` corresponds to the "most left"
    /// element.
    ///
    /// # Panic
    /// Panics if `index` is invalid, i.e. isn't less than [`N`](Self::N).
    ///
    /// # Examples
    /// ```
    /// # use vrl::prelude::*;
    /// let vec = Vec4f::new(1.0, 2.0, 3.0, 4.0);
    /// assert_eq!(vec.extract(2), 3.0);
    /// ```
    /// ```should_panic
    /// # use vrl::prelude::*;
    /// Vec4f::default().extract(5);
    ///
    /// ```
    ///
    /// # Note
    /// If `index` is known at compile time consider using [`extract_const`](Self::extract_const).
    #[inline]
    fn extract(self, index: usize) -> Self::Element {
        if index >= Self::N {
            panic!("invalid index");
        }
        let mut stored = std::mem::MaybeUninit::<[Self::Element; N]>::uninit();
        // SAFETY: `stored` has size of N hence it's safe to store the vector there
        unsafe {
            self.store_ptr(stored.as_mut_ptr() as *mut Self::Element);
            stored.assume_init()[index]
        }
    }

    /// Extracts `index % N`-th element of the vector. This corresponds to the original [`extract`]
    /// function from VCL.
    ///
    /// # Examples
    /// ```
    /// # use vrl::prelude::*;
    /// assert_eq!(Vec4f::new(1.0, 2.0, 3.0, 4.0).extract_wrapping(6), 3.0);
    /// ```
    ///
    /// [`extract`]: https://github.com/vectorclass/version2/blob/f4617df57e17efcd754f5bbe0ec87883e0ed9ce6/vectorf128.h#L616
    #[inline]
    fn extract_wrapping(self, index: usize) -> Self::Element {
        self.extract(index % Self::N)
    }

    /// Extracts `INDEX`-th element of the vector. Does same as [`extract`](Self::extract) with compile-time
    /// known index.
    ///
    /// # Examples
    /// ```
    /// # use vrl::prelude::*;
    /// let vec = Vec4f::new(1.0, 2.0, 3.0, 4.0);
    /// assert_eq!(vec.extract_const::<2>(), 3.0);
    /// ```
    /// ```compile_fail
    /// # use vrl::prelude::*;
    /// Vec4f::default().extract_const::<5>();
    /// # compile_error!("out-of-range index for extract_const")
    /// ```
    ///
    /// # Note
    /// Currently not all implementations assures that `INDEX` is valid at compile time.
    #[inline]
    fn extract_const<const INDEX: i32>(self) -> Self::Element {
        self.extract(INDEX as usize)
    }

    /// Calculates the sum of all elements of vector.
    ///
    /// # Exmaples
    /// ```
    /// # use vrl::prelude::*;
    /// assert_eq!(Vec4f::new(1.0, 2.0, 3.0, 4.0).sum(), 10.0);
    /// ```
    fn sum(self) -> Self::Element;
}

pub trait SIMDPartialLoad<T> {
    /// Loads first `min(N, data.len())` elements of `data` into vector.
    ///
    /// # Example
    /// ```
    /// # use vrl::prelude::*;
    /// let values = [1.0, 2.0, 3.0, 4.0, 5.0];
    /// assert_eq!(
    ///     Vec4f::load_partial(&values),
    ///     Vec4f::from(&values[..4].try_into().unwrap())
    /// );
    /// assert_eq!(
    ///     Vec4f::load_partial(&values[..2]),
    ///     Vec4f::new(1.0, 2.0, 0.0, 0.0)  // note zeros here
    /// );
    /// ```
    fn load_partial(data: &[T]) -> Self;
}

pub trait SIMDPartialStore<T> {
    /// Stores `min(N, slice.len())` elements of vector into prefix of `slice`.
    ///
    /// # Exmaples
    /// ```
    /// # use vrl::prelude::*;
    /// let mut data = [0.0; 3];
    /// Vec4f::broadcast(1.0).store_partial(&mut data);
    /// assert_eq!(data, [1.0; 3]);
    /// ```
    /// ```
    /// # use vrl::prelude::*;
    /// let mut data = [0.0; 5];
    /// Vec4f::broadcast(1.0).store_partial(&mut data);
    /// assert_eq!(data, [1.0, 1.0, 1.0, 1.0, 0.0]);  // note last zero
    /// ```
    fn store_partial(&self, slice: &mut [T]);
}

pub trait SIMDFusedCalc {
    /// Multiplies vector by `b` and adds `c` to the product.
    ///
    /// # Exmaples
    /// ```
    /// # use vrl::prelude::*;
    /// let a = Vec4f::new(1.0, 2.0, 0.5, 2.0);
    /// let b = Vec4f::new(1.0, 0.5, 2.0, 3.0);
    /// let c = Vec4f::new(4.0, 2.0, 3.0, 1.0);
    /// assert_eq!(a.mul_add(b, c), a * b + c);
    /// ```
    fn mul_add(self, b: Self, c: Self) -> Self;

    /// Multiplies vector by `b` ans substracts `c` from the procuct.
    ///
    /// # Exmaples
    /// ```
    /// # use vrl::prelude::*;
    /// let a = Vec4f::new(1.0, 2.0, 0.5, 2.0);
    /// let b = Vec4f::new(1.0, 0.5, 2.0, 3.0);
    /// let c = Vec4f::new(4.0, 2.0, 3.0, 1.0);
    /// assert_eq!(a.mul_sub(b, c), a * b - c);
    /// ```
    fn mul_sub(self, b: Self, c: Self) -> Self;

    /// Multiplies vector by `b` and substracts the product from `c`.
    ///
    /// # Exmaples
    /// ```
    /// # use vrl::prelude::*;
    /// let a = Vec4f::new(1.0, 2.0, 0.5, 2.0);
    /// let b = Vec4f::new(1.0, 0.5, 2.0, 3.0);
    /// let c = Vec4f::new(4.0, 2.0, 3.0, 1.0);
    /// assert_eq!(a.nmul_add(b, c), c - a * b);
    /// ```
    fn nmul_add(self, b: Self, c: Self) -> Self;

    /// Multiplies vector by `b` and substracts the product from `-c`.
    ///
    /// # Exmaples
    /// ```
    /// # use vrl::prelude::*;
    /// let a = Vec4f::new(1.0, 2.0, 0.5, 2.0);
    /// let b = Vec4f::new(1.0, 0.5, 2.0, 3.0);
    /// let c = Vec4f::new(4.0, 2.0, 3.0, 1.0);
    /// assert_eq!(a.nmul_sub(b, c), -(a * b + c));
    /// ```
    fn nmul_sub(self, b: Self, c: Self) -> Self;
}

pub(crate) trait SIMDFusedCalcFallback {}

impl<T: SIMDFusedCalcFallback + Arithmetic + Neg<Output = Self>> SIMDFusedCalc for T {
    #[inline]
    fn mul_add(self, b: Self, c: Self) -> Self {
        self * b + c
    }

    #[inline]
    fn mul_sub(self, b: Self, c: Self) -> Self {
        self * b - c
    }

    #[inline]
    fn nmul_add(self, b: Self, c: Self) -> Self {
        c - self * b
    }

    #[inline]
    fn nmul_sub(self, b: Self, c: Self) -> Self {
        -(self * b + c)
    }
}

/// Commont floating-point functions.
pub trait SIMDFloat {
    /// Rounds values of the vector to the nearest integers. In case of two integers are equally
    /// close (i.e. fractional part of a number equals `0.5`) the behavior depends on platform.
    ///
    /// # Exmaples
    /// ```
    /// # use vrl::prelude::*;
    /// let vec = Vec4f::new(1.3, -3.7, 0.7, -0.3);
    /// assert_eq!(vec.round(), Vec4f::new(1.0, -4.0, 1.0, 0.0));
    /// ```
    fn round(self) -> Self;
}

pub trait Arithmetic<Rhs = Self, Output = Self>:
    Add<Rhs, Output = Output>
    + Sub<Rhs, Output = Output>
    + Mul<Rhs, Output = Output>
    + Div<Rhs, Output = Output>
{
}
impl<T, Rhs, Output> Arithmetic<Rhs, Output> for T where
    T: Add<Rhs, Output = Output>
        + Sub<Rhs, Output = Output>
        + Mul<Rhs, Output = Output>
        + Div<Rhs, Output = Output>
{
}

pub trait ArithmeticAssign<Rhs = Self>:
    AddAssign<Rhs> + SubAssign<Rhs> + MulAssign<Rhs> + DivAssign<Rhs>
{
}
impl<T, Rhs> ArithmeticAssign<Rhs> for T where
    T: AddAssign<Rhs> + SubAssign<Rhs> + MulAssign<Rhs> + DivAssign<Rhs>
{
}

/// Represents a packed vector containing [`N`] values of type [`Element`].
///
/// [`Default::default`] initializes all elements of vector with zero.
///
/// All arithmetic operations ([`Neg`], [`Add`], etc) are applied vertically, i.e. "elementwise".
///
/// # [`extract`] vs [`index`]
///
/// [`index`] (aka operator `[]`) extracts `index`-th element of the vector. If value of the vector is expected to be
/// in a register consider using [`extract`]. Use this function if only the vector is probably stored in memory.
///
/// In the following example the vector is stored in the heap. Using `[]`-indexing in
/// the case is as efficient as dereferencing the corresponding pointer.
/// ```
/// # use vrl::prelude::*;
/// # use std::ops::Index;
/// let many_vectors = vec![Vec4f::new(1.0, 2.0, 3.0, 4.0); 128];
/// assert_eq!(many_vectors.index(64)[2], 3.0);
/// ```
/// Here is an example of inefficient usage of [`index`]. The vector wouldn't even reach memory
/// and would stay in a register without that `[1]`. [`extract`] should be used instead.
/// ```
/// # use vrl::prelude::*;
/// let mut vec = Vec4f::new(1.0, 2.0, 3.0, 4.0);
/// vec *= 3.0;
/// vec -= 2.0;
/// let second_value = vec[1];
/// assert_eq!(second_value, 4.0);
/// ```
///
/// [`N`]: SIMDBase::N
/// [`Element`]: SIMDBase::Element
/// [`extract`]: SIMDBase::extract
/// [`index`]: Index::index
pub trait SIMDVector<const N: usize>:
    SIMDBase<N>
    + Neg<Output = Self>
    + Arithmetic
    + ArithmeticAssign<Self>
    + Arithmetic<Self::Element>
    + ArithmeticAssign<Self::Element>
    + PartialEq
    + Into<Self::Underlying>
    + Into<[Self::Element; N]>
    + for<'a> From<&'a [Self::Element; N]>
    + SIMDPartialLoad<Self::Element>
    + SIMDPartialStore<Self::Element>
    + SIMDFusedCalc
    + Default
    + Copy
    + Clone
    + Debug
    + Index<usize>
    + IndexMut<usize>
    + Sum
    + Product
where
    [Self::Element; N]: Into<Self>,
    Self::Element: Arithmetic<Self, Self>,
    Self::Underlying: Into<Self>,
{
}