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
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
/*!

A simple multidimensional point struct, based on an array.

See the ```PointND``` struct for basic usage

 */

use std::{
    ops::{
        Add, Sub, Mul, Div,
        Index, IndexMut
    },
    slice::SliceIndex,
    convert::TryInto,
};


/**

The whole _point_ of the crate (get it?)

This is basically just a small wrapper around an array with convenience methods for accessing values if it's dimensions are within ```1..=4```

# Examples

## Constructing a Point

No matter how a PointND is constructed, the second generic arg must be filled with the number of dimensions it needs to have

If a point of zero dimensions is constructed, it will panic

```
use point_nd::PointND;

// Creates a 2D point from values of a given vector or array
let vec: Vec<i32> = vec![0, 1];
let p: PointND<_, 2> = PointND::from(&vec);

// Creates a 3D point with all values set to 5
//  When using this function, complete type annotation is necessary
let p: PointND<i32, 3> = PointND::fill(5);

// ERROR: Can't create a point with zero dimensions
// let p: PointND<_, 0> = PointND::fill(9);

// If you don't like writing PointND twice, use this syntax instead
//  Note: The second generic must still be specified
let p = PointND::<_, 2>::from(&vec);
```

## Accessing Values

It is recommended to use the convenience getters if the dimensions of the point are from ```1..=4```

```
use point_nd::PointND;

// A 2D point
let arr: [i32; 2] = [0,1];
let p: PointND<_, 2> = PointND::from(&arr);

// As the point has 2 dimensions, we can access it's values with the x() and y() methods
let x: &i32 = p.x();
let y = p.y();

assert_eq!(*y, arr[1]);

// If the point had 3 dimensions, we could use the above and:
// let z = p.z();

// Or 4:
// ...
// let w = p.w();
```

Otherwise indexing or the ```get()``` method can be used

```
use point_nd::PointND;

let arr: [i32; 2] = [0,1];
let p: PointND<_, 2> = PointND::from(&arr);

// Safely getting
//  Returns None if index is out of bounds
let x: Option<&i32> = p.get(0);
assert_eq!(*x.unwrap(), arr[0]);

// Unsafely indexing
//  If the index is out of bounds, this will panic
//  Note that unlike other accessing methods, this will return a copy of the value
let y: i32 = p[1];
assert_eq!(y, arr[1]);
```

## Querying Size

The number of dimensions can be retrieved using the ```dims()``` method (short for _dimensions_)

```
use point_nd::PointND;

let p: PointND<i32, 2> = PointND::fill(10);
assert_eq!(p.dims(), 2);
```

 */
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub struct PointND<T, const N: usize>
    where T: Clone + Copy  {
    arr: [T; N],
}

// Constructors
impl<T, const N: usize>  PointND<T, N>
    where T: Clone + Copy  {

    /**
     Returns a new ```PointND``` with values from the specified array or vector

     ### Panics

     If the length of the slice is zero
     */
    pub fn from(slice: &[T]) -> Self {
        if slice.len() == 0 {
            panic!("Cannot construct Point with zero dimensions");
        }
        let arr: [T; N] = slice.try_into().unwrap();
        PointND { arr }
    }

    /**
     Returns a new ```PointND``` with all values set as specified

     ### Panics

     If the dimensions of the point being constructed is zero
     */
    pub fn fill(value: T) -> Self {
        PointND::<T, N>::from(&[value; N])
    }

}

// Standard Getters
impl<T, const N: usize>  PointND<T, N>
    where T: Clone + Copy  {


    /**
     Returns the number of dimensions of the point (a 2D point will return 2, a 3D point 3, _etc_)
     */
    pub fn dims(&self) -> usize {
        self.arr.len()
    }

    /**
     Returns the ```Some(value)``` at the specified dimension or ```None``` if the dimension is out of bounds

     The value of the first dimension is indexed at ```0``` for easier interoperability with standard indexing
     */
    pub fn get(&self, dim: usize) -> Option<&T> {
        self.arr.get(dim)
    }

}

// Modifiers
impl<T, const N: usize>  PointND<T, N>
    where T: Clone + Copy  {

    /**
     Returns a new ```PointND``` from the values contained by self after applying the modifier function to them

     ### Examples

     ```
     use point_nd::PointND;

     // Multiplies each item by 10
     let p = PointND::<i32, 3>::from(&[0, 1, 2]);
     let p = p.apply(|item| item * 10);

     assert_eq!(p.as_arr(), [0, 10, 20]);
     ```
     */
    pub fn apply<F>(self, modifier: F) -> Self
        where F: Fn(T) -> T {

        let mut vec = Vec::<T>::with_capacity(N);
        for item in self.as_arr() {
            vec.push(modifier(item));
        }

        PointND::<T, N>::from(&vec)
    }

    /**
     Returns a new ```PointND``` from the values at the specified dimensions after applying the modifier function to them

     Any values at dimensions that were not specified are passed as is

     If any dimensions specified are out of bounds, this method will ignore it

    ### Examples

     ```
     use point_nd::PointND;

     // Multiplies items at indexes 1 and 2 by 2
     let p = PointND::<i32, 4>::from(&[0, 1, 2, 3]);
     let p = p.apply_dims(&[1, 2], |item| item * 2);

     assert_eq!(p.as_arr(), [0, 2, 4, 3]);
     ```
     */
    pub fn apply_dims<F>(self, dims: &[usize], modifier: F) -> Self
        where F: Fn(T) -> T {

        let mut vec = Vec::<T>::with_capacity(N);
        for (i, item) in self.as_arr().into_iter().enumerate() {
            if dims.contains(&i) {
                vec.push(modifier(item));
            } else {
                vec.push(item);
            }
        }

        PointND::<T, N>::from(&vec)
    }

    /**
     Returns a new ```PointND``` from the values specified and those contained by self after applying the modifier to both

     ### Examples

     ```
     use point_nd::PointND;

     // Adds each item in the PointND with their respective items in the array
     let p = PointND::<i32, 3>::from(&[0, 1, 2]);
     let p = p.apply_with([1, 2, 3], |a, b| a + b);

     assert_eq!(p.as_arr(), [1, 3, 5]);
     ```
     */
    pub fn apply_with<F>(self, values: [T; N], modifier: F) -> Self
        where F: Fn(T, T) -> T {

        let mut vec = Vec::<T>::with_capacity(N);
        for (a, b) in self.as_arr().into_iter().zip(values) {
            vec.push(modifier(a, b));
        }

        PointND::<T, N>::from(&vec)
    }

}

// Wholesale Getters
impl<T, const N: usize>  PointND<T, N>
    where T: Clone + Copy  {

    /**
     Returns a pointer to the array values stored by self
     */
    pub fn values(&self) -> &[T; N] {
        &self.arr
    }

    /**
     Returns an array of all the values contained by the point
     */
    pub fn as_arr(&self) -> [T; N] {
        self.arr.clone()
    }

    /**
     Returns a vector of all the values contained by the point
     */
    pub fn as_vec(&self) -> Vec<T> {
        Vec::from(&self.arr[..])
    }

}

// Convenience Getters and Setters
/// Function for safely getting and setting the first value contained by a 1D ```PointND```
impl<T> PointND<T, 1> where T: Clone + Copy  {

    pub fn x(&self) -> &T { &self.arr[0] }

    pub fn set_x(&mut self, new_value: T) { self.arr[0] = new_value; }

}
/// Functions for safely getting and setting the first and second values contained by a 2D ```PointND```
impl<T> PointND<T, 2> where T: Clone + Copy  {

    pub fn x(&self) -> &T { &self.arr[0] }
    pub fn y(&self) -> &T { &self.arr[1] }

    pub fn set_x(&mut self, new_value: T) { self.arr[0] = new_value; }
    pub fn set_y(&mut self, new_value: T) { self.arr[1] = new_value; }

}
/// Functions for safely getting and setting the first, second and third values contained by a 3D ```PointND```
impl<T> PointND<T, 3> where T: Clone + Copy  {

    pub fn x(&self) -> &T { &self.arr[0] }
    pub fn y(&self) -> &T { &self.arr[1] }
    pub fn z(&self) -> &T { &self.arr[2] }

    pub fn set_x(&mut self, new_value: T) { self.arr[0] = new_value; }
    pub fn set_y(&mut self, new_value: T) { self.arr[1] = new_value; }
    pub fn set_z(&mut self, new_value: T) { self.arr[2] = new_value; }

}
/// Functions for safely getting and setting the first, second, third and fourth values contained by a 4D ```PointND```
impl<T> PointND<T, 4> where T: Clone + Copy  {

    pub fn x(&self) -> &T { &self.arr[0] }
    pub fn y(&self) -> &T { &self.arr[1] }
    pub fn z(&self) -> &T { &self.arr[2] }
    pub fn w(&self) -> &T { &self.arr[3] }

    pub fn set_x(&mut self, new_value: T) { self.arr[0] = new_value; }
    pub fn set_y(&mut self, new_value: T) { self.arr[1] = new_value; }
    pub fn set_z(&mut self, new_value: T) { self.arr[2] = new_value; }
    pub fn set_w(&mut self, new_value: T) { self.arr[3] = new_value; }

}

// Basic math operators
impl<T, const N: usize> Add for PointND<T, N> where T: Add<Output = T> + Clone + Copy  {

    type Output = Self;
    fn add(self, rhs: Self) -> Self::Output {
        if &self.dims() != &rhs.dims() { panic!("Tried to add two PointND's of unequal length"); }

        let values_left= self.values();
        let values_right = rhs.values();

        let mut ret_values = Vec::<T>::with_capacity(N);
        for i in 0..N {
            ret_values.push(values_left[i].clone() + values_right[i].clone());
        }

        PointND::<T, N>::from(&ret_values)
    }

}
impl<T, const N: usize> Sub for PointND<T, N> where T: Sub<Output = T> + Clone + Copy  {

    type Output = Self;
    fn sub(self, rhs: Self) -> Self::Output {
        if &self.dims() != &rhs.dims() { panic!("Tried to add two PointND's of unequal length"); }

        let values_left= self.values();
        let values_right = rhs.values();

        let mut ret_values = Vec::<T>::with_capacity(N);
        for i in 0..N {
            ret_values.push(values_left[i].clone() - values_right[i].clone());
        }

        PointND::<T, N>::from(&ret_values)
    }

}
impl<T, const N: usize> Mul for PointND<T, N> where T: Mul<Output = T> + Clone + Copy  {

    type Output = Self;
    fn mul(self, rhs: Self) -> Self::Output {
        if &self.dims() != &rhs.dims() { panic!("Tried to add two PointND's of unequal length"); }

        let values_left= self.values();
        let values_right = rhs.values();

        let mut ret_values = Vec::<T>::with_capacity(N);
        for i in 0..N {
            ret_values.push(values_left[i].clone() * values_right[i].clone());
        }

        PointND::<T, N>::from(&ret_values)
    }

}
impl<T, const N: usize> Div for PointND<T, N> where T: Div<Output = T> + Clone + Copy  {

    type Output = Self;
    fn div(self, rhs: Self) -> Self::Output {
        if &self.dims() != &rhs.dims() { panic!("Tried to add two PointND's of unequal length"); }

        let values_left= self.values();
        let values_right = rhs.values();

        let mut ret_values = Vec::<T>::with_capacity(N);
        for i in 0..N {
            ret_values.push(values_left[i].clone() / values_right[i].clone());
        }

        PointND::<T, N>::from(&ret_values)
    }

}

// Indexing operators
impl<I, T, const N: usize> Index<I> for PointND<T, N> where T: Clone + Copy, I: Sized + SliceIndex<[T], Output = T> {
    type Output = T;
    fn index(&self, index: I) -> & Self::Output {
        &self.arr[index]
    }
}
impl<I, T, const N: usize> IndexMut<I> for PointND<T, N> where T: Clone + Copy, I: Sized + SliceIndex<[T], Output = T> {
    fn index_mut(&mut self, index: I) -> &mut Self::Output {
        &mut self.arr[index]
    }
}


#[cfg(test)]
mod tests {

    #[cfg(test)]
    mod constructor {

        use crate::*;

        #[test]
        fn constructable_with_from_function() {
            let vec = vec![1,2,3,4];

            let _p = PointND::<_, 4>::from(&vec);
            let _p = PointND::<_, 3>::from(&vec[..3]);
        }

        #[test]
        fn constructable_with_fill_function() {

            #[derive(Clone, Copy, PartialEq, Eq, Debug)]
            struct A {
                pub x: i32
            }
            impl A {
                pub fn new(x: i32) -> Self { A{ x } }
            }
            impl Add for A {
                type Output = Self;
                fn add(self, rhs: Self) -> Self::Output {
                    A::new(self.x + rhs.x)
                }
            }

            let p = PointND::<A, 3>::fill(A::new(0));
            let p = p + PointND::from(&[
                A::new(1),
                A::new(2),
                A::new(3)
            ]);

            assert_ne!(p.x(), p.y());
            assert_ne!(p.x(), p.z());
            assert_ne!(p.y(), p.z());
        }

        #[test]
        #[should_panic]
        fn cant_construct_0_dim_point_with_from_function() {
            let _p = PointND::<u8, 0>::from(&[]);
        }
        #[test]
        #[should_panic]
        fn cant_construct_0_dim_point_with_fill_function() {
            let _p = PointND::<u8, 0>::fill(0);
        }

    }

    #[cfg(test)]
    mod dimensions {

        use crate::*;

        #[test]
        fn returns_correct_dimensions() {
            let vec = vec![0,1,2,3];
            let p = PointND::<_, 4>::from(&vec);

            assert_eq!(p.dims(), vec.len());
        }

    }

    #[cfg(test)]
    mod values {

        use crate::*;

        #[test]
        fn returns_value_on_get() {
            let vec = vec![0,1,2,3];
            let p = PointND::<_, 4>::from(&vec);

            for i in 0..vec.len() {
                assert_eq!(p.get(i).unwrap(), &vec[i]);
            }
        }

        #[test]
        fn convenience_getters_for_1d_points_work() {
            let vec = vec![0];
            let p = PointND::<_, 1>::from(&vec);

            assert_eq!(p.x(), &vec[0]);
        }
        #[test]
        fn convenience_getters_for_2d_points_work() {
            let vec = vec![0,1];
            let p = PointND::<_, 2>::from(&vec);

            assert_eq!(p.x(), &vec[0]);
            assert_eq!(p.y(), &vec[1]);
        }
        #[test]
        fn convenience_getters_for_3d_points_work() {
            let vec = vec![0,1,2];
            let p = PointND::<_, 3>::from(&vec);

            assert_eq!(p.x(), &vec[0]);
            assert_eq!(p.y(), &vec[1]);
            assert_eq!(p.z(), &vec[2]);
        }
        #[test]
        fn convenience_getters_for_4d_points_work() {
            let vec = vec![0,1,2,3];
            let p = PointND::<_, 4>::from(&vec);

            assert_eq!(p.x(), &vec[0]);
            assert_eq!(p.y(), &vec[1]);
            assert_eq!(p.z(), &vec[2]);
            assert_eq!(p.w(), &vec[3]);
        }

    }

    #[cfg(test)]
    mod operators {

        use crate::*;

        #[test]
        #[should_panic]
        fn cannot_get_index_out_of_bounds() {
            let p = PointND::<i32, 3>::from(&[0,1,2]);
            let _x = p[p.dims() + 1];
        }

        #[test]
        fn can_set_value_by_index() {

            let arr = [0, 1, 2];
            let mut p = PointND::<_, 3>::from(&arr);

            let new_val = 9999;
            p[1] = new_val;

            assert_eq!(p.as_arr(), [0, new_val, 2]);
        }

        #[test]
        #[should_panic]
        fn cannot_set_out_of_bounds_value() {

            let arr = [0, 1, 2];
            let mut p = PointND::<_, 3>::from(&arr);

            let new_val = 9999;
            p[1002] = new_val;
        }

        #[test]
        fn can_add_two() {
            let vec = vec![0,1,2,3];
            let p1 = PointND::<_, 4>::from(&vec);
            let p2 = PointND::from(&vec);

            let p3 = p1 + p2;
            for (a, b) in p3.as_arr().into_iter().zip(vec){
                assert_eq!(a, b + b);
            }
        }

        #[test]
        fn can_subtract() {
            let vec = vec![0,1,2,3];
            let p1 = PointND::<_, 4>::from(&vec);
            let p2 = PointND::from(&vec);

            let p3 = p1 - p2;
            for (a, b) in p3.as_arr().into_iter().zip(vec){
                assert_eq!(a, b - b);
            }
        }

        #[test]
        fn can_multiply() {
            let vec = vec![0,1,2,3];
            let p1 = PointND::<_, 4>::from(&vec);
            let p2 = PointND::from(&vec);

            let p3 = p1 * p2;
            for (a, b) in p3.as_arr().into_iter().zip(vec){
                assert_eq!(a, b * b);
            }
        }

        #[test]
        fn can_divide() {
            let vec = vec![1,2,3,4];
            let p1 = PointND::<_, 4>::from(&vec);
            let p2 = PointND::from(&vec);

            let p3 = p1 / p2;
            for (a, b) in p3.as_arr().into_iter().zip(vec){
                assert_eq!(a, b / b);
            }
        }

        #[test]
        #[should_panic]
        fn cannot_divide_if_one_item_is_zero() {
            let vec = vec![0, 1,2,3,4];
            let p1 = PointND::<_, 5>::from(&vec);
            let p2 = PointND::from(&vec);

            let p3 = p1 / p2;
            for (a, b) in p3.as_arr().into_iter().zip(vec){
                assert_eq!(a, b / b);
            }
        }

        #[test]
        fn can_equal() {
            let vec = vec![1,2,3,4];
            let p1 = PointND::<_, 4>::from(&vec);
            let p2 = PointND::from(&vec);

            assert_eq!(p1, p2);
        }

        #[test]
        fn can_not_equal() {
            let vec1 = vec![1,2,3,4];
            let p1 = PointND::<_, 4>::from(&vec1);
            let vec2 = vec![5,6,7,8];
            let p2 = PointND::from(&vec2);

            assert_ne!(p1, p2);
        }

    }

    #[cfg(test)]
    mod modifiers {

        use crate::*;

        #[test]
        fn apply_does_work() {

            let arr = [0, 1, 2];
            let arr_to_be = [0, 2, 4];

            let p = PointND::<_, 3>::from(&arr).apply(|i| i * 2);
            assert_eq!(p.as_arr(), arr_to_be);
        }

        #[test]
        fn apply_dims_does_work() {

            let arr = [0, 1, 2, 3, 4];
            let arr_to_be = [0, 1, 4, 3, 16];

            let p = PointND::<_, 5>::from(&arr).apply_dims(&[2, 4], |i| i * i);
            assert_eq!(p.as_arr(), arr_to_be);
        }

        #[test]
        fn apply_with_does_work() {

            let arr = [0, 1, 2];
            let apply_values = [10, 20, 30];
            let arr_to_be = [10, 21, 32];

            let p = PointND::<_, 3>::from(&arr).apply_with(apply_values, |a, b| a + b);
            assert_eq!(p.as_arr(), arr_to_be);
        }

    }

}