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
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
use crate::linear::mat::Matrix;
use crate::linear::scalar::{Scalar, Two};
use crate::numeric::cmp::Cmp;
use crate::numeric::float::Float;
use crate::numeric::sign::Signed;
use paste::paste;
use std::fmt::{Display, Formatter};
use std::iter::Sum;
use std::ops::{Add, AddAssign, Div, DivAssign, Index, IndexMut, Mul, MulAssign, Sub, SubAssign};

pub type Point<T, const N: usize> = Vector<T, { N }>;

#[repr(C)]
#[derive(Debug, Copy, Clone, PartialEq)]
pub struct Vector<T, const N: usize> {
    pub data: [T; N],
}

impl<T: Default + Copy, const N: usize> Default for Vector<T, { N }> {
    #[inline]
    fn default() -> Self {
        Self {
            data: [<T>::default(); N],
        }
    }
}

impl<T: Display, const N: usize> Display for Vector<T, { N }> {
    #[inline]
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        let mut string = String::new();
        for n in 0..N {
            &string.push_str(&format!("|{}|\n", self.data[n]));
        }
        write!(f, "{}", string)
    }
}

impl<T, const N: usize> Vector<T, { N }> {
    #[inline]
    pub const fn new(data: [T; N]) -> Self {
        Self { data }
    }

    #[inline]
    pub const fn len(&self) -> usize {
        N
    }

    #[inline]
    pub const fn as_array(&self) -> &[T; N] {
        &self.data
    }

    #[inline]
    pub fn as_array_mut(&mut self) -> &mut [T; N] {
        &mut self.data
    }

    #[inline]
    pub fn as_slice(&self) -> &[T] {
        unsafe { std::slice::from_raw_parts(self as *const Self as *const T, N) }
    }

    #[inline]
    pub fn as_slice_mut(&mut self) -> &mut [T] {
        unsafe { std::slice::from_raw_parts_mut(self as *mut Self as *mut T, N) }
    }

    #[inline]
    pub const fn as_ptr(&self) -> *const T {
        self as *const Self as *const T
    }

    #[inline]
    pub fn as_mut_ptr(&mut self) -> *mut T {
        self as *mut Self as *mut T
    }

    #[inline]
    pub fn as_bytes(&self) -> &[u8] {
        unsafe {
            std::slice::from_raw_parts(
                self as *const Self as *const u8,
                N * std::mem::size_of::<Self>(),
            )
        }
    }
}

impl<T: Copy, const N: usize> Vector<T, { N }> {
    #[inline]
    pub fn broadcast(value: T) -> Self {
        Self { data: [value; N] }
    }
}

impl<T: Scalar, const N: usize> Vector<T, { N }> {
    #[inline]
    pub fn unit(n: usize) -> Self {
        let mut data = [<T>::default(); N];
        data[n] = <T>::one();
        Self { data }
    }

    #[inline]
    pub fn dot(&self, other: Self) -> T {
        let mut sum = <T>::default();
        for i in 0..N {
            sum += self.data[i] * other.data[i];
        }
        sum
    }

    #[inline]
    pub fn reverse(&mut self) {
        self.data.reverse()
    }

    #[inline]
    pub fn reversed(&self) -> Self {
        let mut vec = *self;
        vec.reverse();
        vec
    }

    #[inline]
    pub fn map<F: Fn(T) -> T>(&self, f: F) -> Self {
        let mut vector = *self;
        vector.data.iter_mut().for_each(|e| *e = f(*e));
        vector
    }

    #[inline]
    pub fn apply<F: Fn(T) -> T>(&mut self, f: F) {
        self.data.iter_mut().for_each(|e| *e = f(*e));
    }

    /// constructs a new VecN with all values being 0
    #[inline]
    pub fn zero() -> Self {
        Self::broadcast(<T>::zero())
    }

    /// constructs a new VecN with all values being 1
    #[inline]
    pub fn one() -> Self {
        Self::broadcast(<T>::one())
    }
}

impl<T: Scalar + Float + Sum, const N: usize> Vector<T, { N }> {
    #[inline]
    pub fn magnitude_squared(&self) -> T {
        self.data.iter().map(|e| *e * *e).sum()
    }

    #[inline]
    pub fn magnitude(&self) -> T {
        self.magnitude_squared().sqrt()
    }

    #[inline]
    pub fn normalize(&mut self) {
        let magnitude = self.magnitude();
        self.data.iter_mut().for_each(|e| *e /= magnitude);
    }

    #[inline]
    pub fn normalized(&self) -> Self {
        let mut vec = *self;
        vec.normalize();
        vec
    }
}

impl<T: Scalar + Signed, const N: usize> Vector<T, { N }> {
    #[inline]
    pub fn abs(&mut self) {
        self.data.iter_mut().for_each(|e| *e = e.abs());
    }

    // I can't find a good name for this, expect a rename in the future
    #[inline]
    pub fn abs_copy(&self) -> Self {
        let mut vec = *self;
        vec.abs();
        vec
    }
}

impl<T: Scalar + Two, const N: usize> Vector<T, { N }> {
    #[inline]
    pub fn reflect(&mut self, normal: Self) {
        *self -= normal * <T>::two() * self.dot(normal);
    }
}

impl<T: Scalar + Cmp, const N: usize> Vector<T, { N }> {
    #[inline]
    pub fn clamp(&mut self, min: Self, max: Self) {
        for i in 0..N {
            self.data[i] = self.data[i].maximum(min.data[i]).minimum(max.data[i])
        }
    }

    /// returns a VecN' with clamped values without consuming VecN
    #[inline]
    pub fn clamped(&self, min: Self, max: Self) -> Self {
        let mut vec = *self;
        vec.clamp(min, max);
        vec
    }

    /// returns a new VecN' with each component having the bigger number from either VecN1 or VecN2
    #[inline]
    pub fn max_by_component(&self, other: &Self) -> Self {
        let mut vector = *self;
        for i in 0..N {
            vector.data[i] = self.data[i].maximum(other.data[i]);
        }
        vector
    }

    /// returns a new VecN' with each component having the smaller number from either VecN1 or VecN2
    #[inline]
    pub fn min_by_component(&self, other: &Self) -> Self {
        let mut vector = *self;
        for i in 0..N {
            vector.data[i] = self.data[i].minimum(other.data[i]);
        }
        vector
    }
}

// update when M = N comes out
impl<T: Default + Copy, const N: usize> Vector<T, { N }> {
    #[inline]
    pub fn from_other<const M: usize>(rhs: Vector<T, { M }>) -> Self {
        if N == M {
            // I have no idea how to cast Array of size M to size N
            // this works for now I guess?
            let pointer = &rhs.data as *const T;
            let data: [T; N] = unsafe { *pointer.cast() };
            Self::new(data)
        } else if N > M {
            let mut data = [<T>::default(); N];
            for i in 0..M {
                data[i] = rhs.data[i];
            }
            Self::new(data)
        } else {
            let mut data = [<T>::default(); N];
            for i in 0..N {
                data[i] = rhs.data[i];
            }
            Self::new(data)
        }
    }
}

impl<T, const N: usize> From<[T; N]> for Vector<T, { N }> {
    #[inline]
    fn from(arr: [T; N]) -> Self {
        Self { data: arr }
    }
}

impl<T: Scalar, const N: usize> Add for Vector<T, { N }> {
    type Output = Self;
    #[inline]
    fn add(self, rhs: Self) -> Self::Output {
        let mut data = [<T>::default(); N];
        for i in 0..N {
            data[i] = self[i] + rhs[i];
        }
        Self { data }
    }
}

impl<T: Scalar, const N: usize> AddAssign for Vector<T, { N }> {
    #[inline]
    fn add_assign(&mut self, rhs: Self) {
        for i in 0..N {
            self[i] += rhs[i];
        }
    }
}

impl<T: Scalar, const N: usize> Sub for Vector<T, { N }> {
    type Output = Self;
    #[inline]
    fn sub(self, rhs: Self) -> Self::Output {
        let mut data = [<T>::default(); N];

        for i in 0..N {
            data[i] = self[i] - rhs[i]
        }

        Self { data }
    }
}

impl<T: Scalar, const N: usize> SubAssign for Vector<T, { N }> {
    #[inline]
    fn sub_assign(&mut self, rhs: Self) {
        for i in 0..N {
            self[i] -= rhs[i]
        }
    }
}

impl<T: Scalar, const N: usize> Mul for Vector<T, { N }> {
    type Output = Self;
    #[inline]
    fn mul(self, rhs: Self) -> Self::Output {
        let mut data = [<T>::default(); N];
        for i in 0..N {
            data[i] = self[i] * rhs[i];
        }
        Self { data }
    }
}

impl<T: Scalar, const N: usize> MulAssign for Vector<T, { N }> {
    #[inline]
    fn mul_assign(&mut self, rhs: Self) {
        for i in 0..N {
            self[i] *= rhs[i];
        }
    }
}

impl<T: Scalar, const N: usize> Div for Vector<T, { N }> {
    type Output = Self;
    #[inline]
    fn div(self, rhs: Self) -> Self::Output {
        let mut data = [<T>::default(); N];
        for i in 0..N {
            data[i] = self[i] / rhs[i];
        }
        Self { data }
    }
}

impl<T: Scalar, const N: usize> DivAssign for Vector<T, { N }> {
    #[inline]
    fn div_assign(&mut self, rhs: Self) {
        for i in 0..N {
            self[i] /= rhs[i];
        }
    }
}

impl<T: Scalar, const N: usize> Mul<T> for Vector<T, { N }> {
    type Output = Self;
    #[inline]
    fn mul(self, rhs: T) -> Self::Output {
        let mut data = [<T>::default(); N];
        for i in 0..N {
            data[i] = self[i] * rhs;
        }
        Self { data }
    }
}

impl<T: Scalar, const N: usize> MulAssign<T> for Vector<T, { N }> {
    #[inline]
    fn mul_assign(&mut self, rhs: T) {
        for i in 0..N {
            self[i] *= rhs;
        }
    }
}

impl<T: Scalar, const N: usize> Div<T> for Vector<T, { N }> {
    type Output = Self;
    #[inline]
    fn div(self, rhs: T) -> Self::Output {
        let mut vec = Self::zero();
        for i in 0..N {
            vec[i] = self[i] / rhs;
        }
        vec
    }
}

impl<T: Scalar, const N: usize> DivAssign<T> for Vector<T, { N }> {
    #[inline]
    fn div_assign(&mut self, rhs: T) {
        for i in 0..N {
            self[i] /= rhs;
        }
    }
}

impl<T: Copy, const N: usize> From<Matrix<T, { N }, 1>> for Vector<T, { N }> {
    #[inline]
    fn from(rhs: Matrix<T, { N }, 1>) -> Self {
        rhs.data[0]
    }
}

impl<T, const N: usize> Index<usize> for Vector<T, { N }> {
    type Output = T;

    fn index(&self, index: usize) -> &Self::Output {
        &self.data[index]
    }
}

impl<T, const N: usize> IndexMut<usize> for Vector<T, { N }> {
    fn index_mut(&mut self, index: usize) -> &mut Self::Output {
        &mut self.data[index]
    }
}

impl<T: Default + Copy, const N: usize> From<Vec<T>> for Vector<T, { N }> {
    fn from(rhs: Vec<T>) -> Self {
        let mut vec = Self::default();
        for (i, k) in rhs.iter().enumerate() {
            vec[i] = *k;
        }
        vec
    }
}
#[macro_export]
macro_rules! vec_short {
    ($($n:ident => $t:ty),+) => {
        $(
            type $n<const N: usize> = Vector<$t, N>;
        )+
    };
    ($($n:ident => $d:expr),+) => {
        $(
            type $n<T> = Vector<T, $d>;
        )+
    };
    ($($n:ident => [$t:ty; $d:expr]),+) => {
        $(
            type $n = Vector<$t, $d>;
        )+
    }
}

/// A macro to add lettered getter and setter functions to a VecN
///
/// # Usage
/// * `<...>` : replace with values
/// * `,+` can repeat infinite times but can not be empty
///
/// `<Vector Dimension> => [<<index for data[n]> => <corresponding letter>>,+],+`
///
/// # Example
/// ```
// letters_for_vectors! {
//     2 => [0, x; 1, y],
//     3 => [0, x; 1, y; 2, z]
// }
/// ```
// TODO: add recursive parsing so the inner expression can be omitted
#[macro_export]
macro_rules! letters_for_vectors {
    ($($e:expr => [$($c:expr, $d:ident);+]),+) => {
        $(
            impl<T: Scalar> Vector<T, $e> {
                $(
                    #[inline]
                    pub const fn $d(&self) -> T {
                        self.data[$c]
                    }

                    paste! {
                        /// sets the `data[n]` to the value f
                        #[inline]
                        pub fn [<set_ $d>](&mut self, value: T) {
                            self.data[$c] = value;
                        }

                        // Creates a new unit vector from the corresponding letter
                        #[inline]
                        pub fn [<unit_ $d>]() -> Self {
                            Self::unit($c)
                        }
                    }

                )+
            }
        )+
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::time::Instant;

    #[test]
    fn create_numeric_vectors() {
        let vec_float = Vector::new([2.0, 3.0, 1.0]);
        let vec_int = Vector::new([2, 3, 1]);
        assert_eq!(vec_float.data, [2.0, 3.0, 1.0]);
        assert_eq!(vec_int.data, [2, 3, 1]);
    }

    #[test]
    fn create_non_numeric_vector() {
        let vec = Vector::new(["string", "test"]);
        assert_eq!(vec.data, ["string", "test"])
    }

    #[test]
    fn create_probably_illegal_vector() {
        // this compiles but this doesn't really have any implementations
        // and it shouldn't have any!
        let vec = Vector::new([["lol", "is"], ["why", "no"]]);
    }

    #[test]
    fn vector_from_trait() {
        let vec: Vector<f32, 2> = [2.0, 1.0].into();
        assert_eq!(vec.data, [2.0, 1.0]);
    }

    #[test]
    fn vector_from_vector() {
        let vec_3 = Vector::new([3.0, 2.0, 1.0]);
        let vec_1: Vector<f32, 1> = Vector::from_other(vec_3);
        let vec_2: Vector<f32, 2> = Vector::from_other(vec_3);
        let vec_4: Vector<f32, 4> = Vector::from_other(vec_3);
        let vec_5: Vector<f32, 5> = Vector::from_other(vec_3);

        assert_eq!(vec_1.data, [3.0]);
        assert_eq!(vec_2.data, [3.0, 2.0]);
        assert_eq!(vec_4.data, [3.0, 2.0, 1.0, 0.0]);
        assert_eq!(vec_5.data, [3.0, 2.0, 1.0, 0.0, 0.0]);
    }

    #[test]
    fn vector_add() {
        let vec1 = Vector::new([3.0, 2.0, 1.0]);
        let mut vec1_copy = vec1;
        let vec2 = Vector::new([2.0, 4.2, 1.1]);
        let vec3 = vec1 + vec2;
        vec1_copy += vec2;

        assert_eq!(vec3.data, [5.0, 6.2, 2.1]);
        assert_eq!(vec1_copy.data, [5.0, 6.2, 2.1]);
    }

    #[test]
    fn vector_sub() {
        let vec1 = Vector::new([3.0, 2.0, 1.0]);
        let mut vec1_copy = vec1;
        let vec2 = Vector::new([2.0, 4.2, 1.0]);
        let vec3 = vec1 - vec2;
        vec1_copy -= vec2;

        assert_eq!(vec3.data, [1.0, -2.2, 0.0]);
        assert_eq!(vec1_copy.data, [1.0, -2.2, 0.0]);
    }
}