multid 1.0.0

2-d arrays, badly
Documentation
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
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
//! 2d vector type, parameterized by number of rows and columns
use crate::errors::VError;
use crate::ix::Ix2;

/// 2d vector type, parameterized by number of rows and columns
pub struct V2<T, const N_ROWS: usize, const N_COLS: usize> {
    data: Vec<T>,
}

impl<T, const N_ROWS: usize, const N_COLS: usize> V2<T, N_ROWS, N_COLS> {
    /// create a new 2d vector from a preexisting 1d vector
    ///
    /// errors if the provided data is the wrong length
    pub fn new(data: Vec<T>) -> Result<Self, VError> {
        if N_ROWS * N_COLS != data.len() {
            Err(VError::SizingError {
                expected: data.len(),
                actual: N_ROWS * N_COLS,
            })
        } else {
            Ok(Self { data })
        }
    }
    fn get_ix(&self, Ix2 { row_ix, col_ix }: Ix2) -> Option<usize> {
        if row_ix >= N_ROWS || col_ix >= N_COLS {
            None
        } else {
            Some(self.convert_ix(col_ix, row_ix))
        }
    }
    /// get a value by 2d index
    pub fn get(&self, ix: Ix2) -> Option<&T> {
        self.get_ix(ix).map(|i| &self.data[i])
    }
    /// get a mutable value by 2d index
    pub fn get_mut(&mut self, ix: Ix2) -> Option<&mut T> {
        self.get_ix(ix).map(|i| &mut self.data[i])
    }
    /// an iterator over the vector's indices left to right, top to bottom
    pub fn indices(&self) -> V2Indices<N_ROWS, N_COLS> {
        V2Indices::new()
    }
    /// an iterator over the vector's rows from top to bottom
    pub fn rows(&self) -> V2Rows<'_, T, N_ROWS, N_COLS> {
        V2Rows::new(&self.data)
    }
    /// an iterator over the vector's columns from left to right
    pub fn cols(&self) -> V2Cols<'_, T, N_ROWS, N_COLS> {
        V2Cols::new(&self.data)
    }
    /// an iterator over the neighboring values of a position in the vector
    ///
    /// the iterator starts at the "upper-left" and proceeds left to right, top to bottom
    /// only in-bounds results will be returned
    ///
    /// given a 2d vector like
    ///
    /// `0 1 2`    
    /// `3 4 5`    
    /// `6 7 8`
    ///
    ///
    /// the neighbors of `4` are `[0,1,2,3,5,6,7,8]`, while the neighbors of `2` would be
    /// `[1,4,5]`
    pub fn neighbors_of(&self, ix: Ix2) -> V2Neighbors<'_, T, N_ROWS, N_COLS> {
        V2Neighbors::new(&self.data, ix)
    }
    /// an iterator over the cardinal neighbors of a position in the vector
    ///
    /// like [`V2::neighbors_of`], excluding "diagonals"
    ///
    /// given a 2d vector like
    ///
    ///
    /// `0 1 2`    
    /// `3 4 5`    
    /// `6 7 8`
    ///
    ///
    /// the cardinal neighbors of `4` are `[1,3,5,8]`, while the neighbors of `2` would be
    /// `[1,5]`
    pub fn cardinal_neighbors_of(&self, ix: Ix2) -> V2CardinalNeighbors<'_, T, N_ROWS, N_COLS> {
        V2CardinalNeighbors::new(&self.data, ix)
    }
    /// an iterator over tuples of corresponding indices and values, left to right, top to bottom
    pub fn indexed(&self) -> V2Indexed<'_, T, N_ROWS, N_COLS> {
        V2Indexed::new(&self.data)
    }
    /// alter a value in-place
    pub fn mutate_at<F: Fn(&mut T)>(&mut self, Ix2 { row_ix, col_ix }: Ix2, f: F) {
        let i = self.convert_ix(col_ix, row_ix);
        if let Some(v) = self.data.get_mut(i) {
            f(v);
        }
    }
    /// possibly get a reference to the value "north" (same column, previous row)
    pub fn north_of(&self, ix: Ix2) -> Option<&T> {
        self.north_ix(ix).and_then(|i| self.get(i))
    }
    /// possibly get a reference to the value "south" (same column, following row)
    pub fn south_of(&self, ix: Ix2) -> Option<&T> {
        self.south_ix(ix).and_then(|i| self.get(i))
    }
    /// possibly get a reference to the value "east" (same row, following column)
    pub fn east_of(&self, ix: Ix2) -> Option<&T> {
        self.east_ix(ix).and_then(|i| self.get(i))
    }
    /// possibly get a reference to the value "west" (same row, previous column)
    pub fn west_of(&self, ix: Ix2) -> Option<&T> {
        self.west_ix(ix).and_then(|i| self.get(i))
    }
    /// possibly get a reference to the value "northeast" (previous column, previous row)
    pub fn northeast_of(&self, ix: Ix2) -> Option<&T> {
        self.northeast_ix(ix).and_then(|i| self.get(i))
    }
    /// possibly get a reference to the value "northwest" (previous column, previous row)
    pub fn northwest_of(&self, ix: Ix2) -> Option<&T> {
        self.northwest_ix(ix).and_then(|i| self.get(i))
    }
    /// possibly get a reference to the value "southeast" (following column, following row)
    pub fn southeast_of(&self, ix: Ix2) -> Option<&T> {
        self.southeast_ix(ix).and_then(|i| self.get(i))
    }
    /// possibly get a reference to the value "southwest" (following column, previous row)
    pub fn southwest_of(&self, ix: Ix2) -> Option<&T> {
        self.southwest_ix(ix).and_then(|i| self.get(i))
    }
    /// possibly get a mutable reference to the value "north" (same column, previous row)
    pub fn north_of_mut(&mut self, ix: Ix2) -> Option<&mut T> {
        self.north_ix(ix).and_then(|i| self.get_mut(i))
    }
    /// possibly get a mutable reference to the value "south" (same column, following row)
    pub fn south_of_mut(&mut self, ix: Ix2) -> Option<&mut T> {
        self.south_ix(ix).and_then(|i| self.get_mut(i))
    }
    /// possibly get a mutable reference to the value "east" (same row, following column)
    pub fn east_of_mut(&mut self, ix: Ix2) -> Option<&mut T> {
        self.east_ix(ix).and_then(|i| self.get_mut(i))
    }
    /// possibly get a mutable reference to the value "west" (same row, previous column)
    pub fn west_of_mut(&mut self, ix: Ix2) -> Option<&mut T> {
        self.west_ix(ix).and_then(|i| self.get_mut(i))
    }
    /// possibly get a mutable reference to the value "northeast" (previous column, previous row)
    pub fn northeast_of_mut(&mut self, ix: Ix2) -> Option<&mut T> {
        self.northeast_ix(ix).and_then(|i| self.get_mut(i))
    }
    /// possibly get a mutable reference to the value "northwest" (previous column, previous row)
    pub fn northwest_of_mut(&mut self, ix: Ix2) -> Option<&mut T> {
        self.northwest_ix(ix).and_then(|i| self.get_mut(i))
    }
    /// possibly get a mutable reference to the value "southeast" (following column, following row)
    pub fn southeast_of_mut(&mut self, ix: Ix2) -> Option<&mut T> {
        self.southeast_ix(ix).and_then(|i| self.get_mut(i))
    }
    /// possibly get a mutable reference to the value "southwest" (following column, previous row)
    pub fn southwest_of_mut(&mut self, ix: Ix2) -> Option<&mut T> {
        self.southwest_ix(ix).and_then(|i| self.get_mut(i))
    }
    /// possibly get the index "north" (same column, previous row)
    pub fn north_ix(&self, ix: Ix2) -> Option<Ix2> {
        ix.dec_row()
    }
    /// possibly get the index "south" (same column, following row)
    pub fn south_ix(&self, ix: Ix2) -> Option<Ix2> {
        ix.inc_row()
    }
    /// possibly get the index "east" (same row, following column)
    pub fn east_ix(&self, ix: Ix2) -> Option<Ix2> {
        ix.inc_col()
    }
    /// possibly get the index "west" (same row, previous column)
    pub fn west_ix(&self, ix: Ix2) -> Option<Ix2> {
        ix.dec_col()
    }
    /// possibly get the index "northeast" (following column, previous row)
    pub fn northeast_ix(&self, ix: Ix2) -> Option<Ix2> {
        ix.dec_row().and_then(|i| i.inc_col())
    }
    /// possibly get the index "northwest" (previous column, previous row)
    pub fn northwest_ix(&self, ix: Ix2) -> Option<Ix2> {
        ix.dec_row().and_then(|i| i.dec_col())
    }
    /// possibly get the index "southeast" (following column, following row)
    pub fn southeast_ix(&self, ix: Ix2) -> Option<Ix2> {
        ix.inc_row().and_then(|i| i.inc_col())
    }
    /// possibly get the index "southwest" (previous column, following row)
    pub fn southwest_ix(&self, ix: Ix2) -> Option<Ix2> {
        ix.inc_row().and_then(|i| i.dec_col())
    }
    fn convert_ix(&self, col_ix: usize, row_ix: usize) -> usize {
        row_ix * N_COLS + col_ix
    }
}
impl<T, const N_ROWS: usize, const N_COLS: usize> V2<T, N_ROWS, N_COLS>
where
    T: Clone,
{
    /// create a clone of this vector with an additional column
    ///
    /// errors if the length of the new column doesn't match the number of rows in the vector
    pub fn add_col(self, col: Vec<T>) -> Result<V2<T, N_ROWS, { N_COLS + 1 }>, VError> {
        if col.len() != N_ROWS {
            Err(VError::SizingError {
                expected: N_ROWS,
                actual: col.len(),
            })
        } else {
            let mut new_data = self.data;
            for (row_ix, item) in col.iter().enumerate() {
                new_data.insert(row_ix * N_COLS + (N_COLS + row_ix), item.clone())
            }
            Ok(V2 { data: new_data })
        }
    }
    /// create a clone of this vector with an additional row
    ///
    /// errors if the length of the new row doesn't match the number of columns in the vector
    pub fn add_row(self, row: Vec<T>) -> Result<V2<T, { N_ROWS + 1 }, N_COLS>, VError> {
        if row.len() != N_COLS {
            Err(VError::SizingError {
                expected: N_COLS,
                actual: row.len(),
            })
        } else {
            let mut new_data = self.data;
            new_data.extend(row);
            Ok(V2 { data: new_data })
        }
    }
}

impl<T, const N_ROWS: usize, const N_COLS: usize> std::fmt::Debug for V2<T, N_ROWS, N_COLS>
where
    T: std::fmt::Debug,
{
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
        write!(f, "V2<{}, {}> {{ data: {:?} }}", N_ROWS, N_COLS, self.data)
    }
}

impl<T, const N_ROWS: usize, const N_COLS: usize> Clone for V2<T, N_ROWS, N_COLS>
where
    T: Clone,
{
    fn clone(&self) -> Self {
        Self {
            data: self.data.clone(),
        }
    }
}

impl<T, const N_ROWS: usize, const N_COLS: usize> Default for V2<T, N_ROWS, N_COLS>
where
    T: Default,
{
    fn default() -> Self {
        let len = N_ROWS * N_COLS;
        let mut data = Vec::with_capacity(len);
        for _ in 0..len {
            data.push(T::default())
        }
        Self { data }
    }
}

impl<T, const N_ROWS: usize, const N_COLS: usize> std::fmt::Display for V2<T, N_ROWS, N_COLS>
where
    T: std::fmt::Display,
{
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
        let mut d = self.data.iter().enumerate();
        write!(f, "{} ", d.next().unwrap().1)?;
        for (i, v) in d {
            let ni = i + 1;
            if ni == self.data.len() {
                write!(f, "{}", v)?;
            } else if ni % N_COLS == 0 {
                writeln!(f, "{}", v)?;
            } else {
                write!(f, "{} ", v)?;
            }
        }
        Ok(())
    }
}

/// iterator over vector indices
pub struct V2Indices<const N_ROWS: usize, const N_COLS: usize> {
    curr_row: usize,
    curr_col: usize,
}

impl<const N_ROWS: usize, const N_COLS: usize> V2Indices<N_ROWS, N_COLS> {
    fn new() -> Self {
        Self {
            curr_row: 0,
            curr_col: 0,
        }
    }
}

impl<const N_ROWS: usize, const N_COLS: usize> Iterator for V2Indices<N_ROWS, N_COLS> {
    type Item = Ix2;

    fn next(&mut self) -> Option<Self::Item> {
        if self.curr_row < N_ROWS {
            let col_ix = self.curr_col;
            let row_ix = self.curr_row;
            if self.curr_col == N_COLS - 1 {
                self.curr_col = 0;
                self.curr_row += 1;
            } else {
                self.curr_col += 1;
            }
            Some(Ix2 { row_ix, col_ix })
        } else {
            None
        }
    }
}

/// iterator over vector rows, top to bottom
pub struct V2Rows<'a, T, const N_ROWS: usize, const N_COLS: usize> {
    curr_row: usize,
    data: &'a [T],
}

impl<'a, T, const N_ROWS: usize, const N_COLS: usize> V2Rows<'a, T, N_ROWS, N_COLS> {
    fn new(data: &'a [T]) -> Self {
        Self { data, curr_row: 0 }
    }
}

impl<'a, T, const N_ROWS: usize, const N_COLS: usize> Iterator for V2Rows<'a, T, N_ROWS, N_COLS> {
    type Item = &'a [T];

    fn next(&mut self) -> Option<Self::Item> {
        if self.curr_row == N_ROWS {
            None
        } else {
            let start = N_COLS * self.curr_row;
            self.curr_row += 1;
            let end = N_COLS * self.curr_row;
            Some(&self.data[start..end])
        }
    }
}

/// iterator over vector columns, left to right
pub struct V2Cols<'a, T, const N_ROWS: usize, const N_COLS: usize> {
    curr_col: usize,
    data: &'a [T],
}

impl<'a, T, const N_ROWS: usize, const N_COLS: usize> V2Cols<'a, T, N_ROWS, N_COLS> {
    fn new(data: &'a [T]) -> Self {
        Self { data, curr_col: 0 }
    }
}

impl<'a, T, const N_ROWS: usize, const N_COLS: usize> Iterator for V2Cols<'a, T, N_ROWS, N_COLS> {
    type Item = Vec<&'a T>;

    fn next(&mut self) -> Option<Self::Item> {
        if self.curr_col == N_COLS {
            None
        } else {
            let mut v = Vec::with_capacity(N_ROWS);
            for row_ix in 0..N_ROWS {
                let ix = row_ix * N_COLS + self.curr_col;
                v.push(&self.data[ix]);
            }
            self.curr_col += 1;
            Some(v)
        }
    }
}

/// iterator over neighbors
pub struct V2Neighbors<'a, T, const N_ROWS: usize, const N_COLS: usize> {
    data: &'a [T],
    center_col_ix: usize,
    center_row_ix: usize,
    curr_col_ix: usize,
    curr_row_ix: usize,
}

impl<'a, T, const N_ROWS: usize, const N_COLS: usize> V2Neighbors<'a, T, N_ROWS, N_COLS> {
    fn new(data: &'a [T], Ix2 { row_ix, col_ix }: Ix2) -> Self {
        Self {
            data,
            center_col_ix: col_ix,
            center_row_ix: row_ix,
            curr_col_ix: 0,
            curr_row_ix: 0,
        }
    }
    fn dec_col(&self) -> Option<usize> {
        if self.center_col_ix == 0 {
            None
        } else {
            Some(self.center_col_ix - 1)
        }
    }
    fn inc_col(&self) -> Option<usize> {
        if self.center_col_ix == N_COLS - 1 {
            None
        } else {
            Some(self.center_col_ix + 1)
        }
    }
    fn dec_row(&self) -> Option<usize> {
        if self.center_row_ix == 0 {
            None
        } else {
            Some(self.center_row_ix - 1)
        }
    }
    fn inc_row(&self) -> Option<usize> {
        if self.center_row_ix == N_ROWS - 1 {
            None
        } else {
            Some(self.center_row_ix + 1)
        }
    }
}

impl<'a, T, const N_ROWS: usize, const N_COLS: usize> Iterator
    for V2Neighbors<'a, T, N_ROWS, N_COLS>
{
    type Item = &'a T;

    fn next(&mut self) -> Option<Self::Item> {
        while self.curr_row_ix < 3 {
            if self.curr_col_ix == 1 && self.curr_row_ix == 1 {
                self.curr_col_ix = 2;
                continue;
            }
            let col_ix = match self.curr_col_ix {
                0 => self.dec_col(),
                1 => Some(self.center_col_ix),
                2 => self.inc_col(),
                _ => panic!("unreachable col"),
            };
            let row_ix = match self.curr_row_ix {
                0 => self.dec_row(),
                1 => Some(self.center_row_ix),
                2 => self.inc_row(),
                _ => panic!("unreachable row"),
            };
            if col_ix.is_none() {
                self.curr_col_ix = if self.curr_col_ix == 2 {
                    0
                } else {
                    self.curr_col_ix + 1
                };
                continue;
            };
            if row_ix.is_none() {
                self.curr_row_ix += 1;
                continue;
            }
            if self.curr_col_ix == 2 {
                self.curr_row_ix += 1;
                self.curr_col_ix = 0;
            } else {
                self.curr_col_ix += 1;
            }
            return Some(&self.data[row_ix.unwrap() * N_COLS + col_ix.unwrap()]);
        }
        None
    }
}

#[derive(Copy, Clone, PartialEq, Eq)]
enum NeighborDirection {
    N,
    S,
    E,
    W,
}

impl NeighborDirection {
    fn new() -> Option<Self> {
        Some(Self::N)
    }
    fn next(&self) -> Option<Self> {
        match self {
            Self::N => Some(Self::E),
            Self::E => Some(Self::S),
            Self::S => Some(Self::W),
            Self::W => None,
        }
    }
}

/// iterator over cardinal neighbors
pub struct V2CardinalNeighbors<'a, T, const N_ROWS: usize, const N_COLS: usize> {
    data: &'a [T],
    center_col_ix: usize,
    center_row_ix: usize,
    direction: Option<NeighborDirection>,
}

impl<'a, T, const N_ROWS: usize, const N_COLS: usize> V2CardinalNeighbors<'a, T, N_ROWS, N_COLS> {
    pub fn new(data: &'a [T], Ix2 { row_ix, col_ix }: Ix2) -> Self {
        Self {
            data,
            center_col_ix: col_ix,
            center_row_ix: row_ix,
            direction: NeighborDirection::new(),
        }
    }
    fn dec_col(&self) -> Option<usize> {
        if self.center_col_ix == 0 {
            None
        } else {
            Some(self.center_col_ix - 1)
        }
    }
    fn inc_col(&self) -> Option<usize> {
        if self.center_col_ix == N_COLS - 1 {
            None
        } else {
            Some(self.center_col_ix + 1)
        }
    }
    fn dec_row(&self) -> Option<usize> {
        if self.center_row_ix == 0 {
            None
        } else {
            Some(self.center_row_ix - 1)
        }
    }
    fn inc_row(&self) -> Option<usize> {
        if self.center_row_ix == N_ROWS - 1 {
            None
        } else {
            Some(self.center_row_ix + 1)
        }
    }
    fn get_north(&self) -> Option<usize> {
        self.dec_row().map(|nr| nr * N_COLS + self.center_col_ix)
    }
    fn get_south(&self) -> Option<usize> {
        self.inc_row().map(|nr| nr * N_COLS * self.center_col_ix)
    }
    fn get_east(&self) -> Option<usize> {
        self.inc_col().map(|nc| self.center_row_ix * N_COLS + nc)
    }
    fn get_west(&self) -> Option<usize> {
        self.dec_col().map(|nc| self.center_row_ix * N_COLS + nc)
    }
    fn get_dir(&self, direction: NeighborDirection) -> Option<usize> {
        match direction {
            NeighborDirection::N => self.get_north(),
            NeighborDirection::S => self.get_south(),
            NeighborDirection::E => self.get_east(),
            NeighborDirection::W => self.get_west(),
        }
    }
    fn next_direction(&mut self) {
        self.direction = self.direction.and_then(|d: NeighborDirection| d.next());
    }
}

impl<'a, T, const N_ROWS: usize, const N_COLS: usize> Iterator
    for V2CardinalNeighbors<'a, T, N_ROWS, N_COLS>
{
    type Item = &'a T;

    fn next(&mut self) -> Option<Self::Item> {
        while let Some(dir) = self.direction {
            self.next_direction();
            if let Some(d) = self.get_dir(dir) {
                return Some(&self.data[d]);
            }
        }
        None
    }
}

/// iterator over `(index, reference to value)` tuples
pub struct V2Indexed<'a, T, const N_ROWS: usize, const N_COLS: usize> {
    indices: V2Indices<N_ROWS, N_COLS>,
    i: usize,
    data: &'a [T],
}

impl<'a, T, const N_ROWS: usize, const N_COLS: usize> V2Indexed<'a, T, N_ROWS, N_COLS> {
    fn new(data: &'a [T]) -> Self {
        Self {
            indices: V2Indices::new(),
            i: 0,
            data,
        }
    }
}

impl<'a, T, const N_ROWS: usize, const N_COLS: usize> Iterator
    for V2Indexed<'a, T, N_ROWS, N_COLS>
{
    type Item = (Ix2, &'a T);

    fn next(&mut self) -> Option<Self::Item> {
        if let Some(ix) = self.indices.next() {
            let old_ix = self.i;
            self.i += 1;
            Some((ix, &self.data[old_ix]))
        } else {
            None
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    #[test]
    fn test_add_col() {
        let v: V2<u8, 3, 3> = V2::new((0..=8).collect()).unwrap();
        let c: Vec<u8> = vec![9, 10, 11];
        let expected = vec![0, 1, 2, 9, 3, 4, 5, 10, 6, 7, 8, 11];
        let actual = v.add_col(c).unwrap();
        assert_eq!(expected, actual.data);
    }

    #[test]
    fn test_add_row() {
        let v: V2<u8, 3, 3> = V2::new((0..=8).collect()).unwrap();
        let r: Vec<u8> = vec![9, 10, 11];
        let expected = vec![0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11];
        let actual = v.add_row(r).unwrap();
        assert_eq!(expected, actual.data);
    }
    #[test]
    fn test_display() {
        let v: V2<u8, 3, 3> = V2::new((0..=8).collect()).unwrap();
        let expected = "0 1 2\n3 4 5\n6 7 8";
        let actual = format!("{}", v);
        assert_eq!(expected, actual);
    }
    #[test]
    fn test_indices() {
        let ixs: V2Indices<3, 3> = V2Indices::new();
        let expected = vec![
            Ix2 {
                row_ix: 0,
                col_ix: 0,
            },
            Ix2 {
                row_ix: 0,
                col_ix: 1,
            },
            Ix2 {
                row_ix: 0,
                col_ix: 2,
            },
            Ix2 {
                row_ix: 1,
                col_ix: 0,
            },
            Ix2 {
                row_ix: 1,
                col_ix: 1,
            },
            Ix2 {
                row_ix: 1,
                col_ix: 2,
            },
            Ix2 {
                row_ix: 2,
                col_ix: 0,
            },
            Ix2 {
                row_ix: 2,
                col_ix: 1,
            },
            Ix2 {
                row_ix: 2,
                col_ix: 2,
            },
        ];
        let actual = ixs.into_iter().collect::<Vec<Ix2>>();
        assert_eq!(expected, actual);
    }
    #[test]
    fn test_rows() {
        let data: Vec<u8> = (0..9).collect();
        let rows: V2Rows<u8, 3, 3> = V2Rows::new(&data);
        let expected: Vec<&[u8]> = vec![&[0, 1, 2], &[3, 4, 5], &[6, 7, 8]];
        let actual = rows.into_iter().collect::<Vec<&[u8]>>();
        assert_eq!(expected, actual);
    }
    #[test]
    fn test_cols() {
        let data: Vec<u8> = (0..9).collect();
        let cols: V2Cols<u8, 3, 3> = V2Cols::new(&data);
        let expected: Vec<Vec<&u8>> = vec![vec![&0, &3, &6], vec![&1, &4, &7], vec![&2, &5, &8]];
        let actual = cols.into_iter().collect::<Vec<Vec<&u8>>>();
        assert_eq!(expected, actual);
    }
    #[test]
    fn test_neighbors() {
        let v2: V2<u8, 3, 3> = V2::new((0..=8).collect::<Vec<u8>>()).unwrap();

        let expected_upper_left: Vec<&u8> = vec![&1, &3, &4];
        let actual_upper_left: Vec<&u8> = v2
            .neighbors_of(Ix2 {
                row_ix: 0,
                col_ix: 0,
            })
            .collect();
        assert_eq!(expected_upper_left, actual_upper_left, "upper_left");

        let expected_center: Vec<&u8> = vec![&0, &1, &2, &3, &5, &6, &7, &8];
        let actual_center: Vec<&u8> = v2
            .neighbors_of(Ix2 {
                row_ix: 1,
                col_ix: 1,
            })
            .collect();
        assert_eq!(expected_center, actual_center, "center");

        let expected_bottom_middle: Vec<&u8> = vec![&3, &4, &5, &6, &8];
        let actual_bottom_middle: Vec<&u8> = v2
            .neighbors_of(Ix2 {
                row_ix: 2,
                col_ix: 1,
            })
            .collect();
        assert_eq!(
            expected_bottom_middle, actual_bottom_middle,
            "bottom middle"
        );
    }
    #[test]
    fn test_mutate_at() {
        let mut v: V2<u8, 3, 3> = V2::new((0..=8).collect()).unwrap();
        let expected = vec![0, 1, 9, 3, 4, 5, 6, 7, 8];
        v.mutate_at(
            Ix2 {
                row_ix: 0,
                col_ix: 2,
            },
            |v: &mut u8| *v = 9,
        );
        assert_eq!(expected, v.data);
    }
    #[test]
    fn test_indexed() {
        let v: V2<u8, 3, 3> = V2::new((0..=8).collect()).unwrap();
        let expected = vec![
            (
                Ix2 {
                    row_ix: 0,
                    col_ix: 0,
                },
                &0,
            ),
            (
                Ix2 {
                    row_ix: 0,
                    col_ix: 1,
                },
                &1,
            ),
            (
                Ix2 {
                    row_ix: 0,
                    col_ix: 2,
                },
                &2,
            ),
            (
                Ix2 {
                    row_ix: 1,
                    col_ix: 0,
                },
                &3,
            ),
            (
                Ix2 {
                    row_ix: 1,
                    col_ix: 1,
                },
                &4,
            ),
            (
                Ix2 {
                    row_ix: 1,
                    col_ix: 2,
                },
                &5,
            ),
            (
                Ix2 {
                    row_ix: 2,
                    col_ix: 0,
                },
                &6,
            ),
            (
                Ix2 {
                    row_ix: 2,
                    col_ix: 1,
                },
                &7,
            ),
            (
                Ix2 {
                    row_ix: 2,
                    col_ix: 2,
                },
                &8,
            ),
        ];
        let actual = v.indexed().collect::<Vec<(Ix2, &u8)>>();
        assert_eq!(expected, actual);
    }
    #[test]
    fn test_get() {
        let v2: V2<u8, 3, 3> = V2::new((0..=8).collect::<Vec<u8>>()).unwrap();
        assert!(
            v2.get(Ix2 {
                row_ix: 2,
                col_ix: 3
            })
            .is_none()
        );
        assert!(
            v2.get(Ix2 {
                row_ix: 3,
                col_ix: 2
            })
            .is_none()
        );
        assert_eq!(
            v2.get(Ix2 {
                row_ix: 2,
                col_ix: 2
            }),
            Some(&8)
        );
    }
    #[test]
    fn test_north() {
        let v2: V2<u8, 3, 3> = V2::new((0..=8).collect::<Vec<u8>>()).unwrap();
        assert!(
            v2.north_ix(Ix2 {
                row_ix: 0,
                col_ix: 0
            })
            .is_none()
        );
        assert_eq!(
            v2.north_ix(Ix2 {
                row_ix: 1,
                col_ix: 0
            }),
            Some(Ix2 {
                row_ix: 0,
                col_ix: 0
            })
        );
    }
    #[test]
    fn test_south() {
        let v2: V2<u8, 3, 3> = V2::new((0..=8).collect::<Vec<u8>>()).unwrap();
        assert_eq!(
            v2.south_ix(Ix2 {
                row_ix: 2,
                col_ix: 2
            }),
            Some(Ix2 {
                row_ix: 3,
                col_ix: 2
            })
        );
    }
    #[test]
    fn test_east() {
        let v2: V2<u8, 3, 3> = V2::new((0..=8).collect::<Vec<u8>>()).unwrap();
        assert_eq!(
            v2.east_ix(Ix2 {
                row_ix: 2,
                col_ix: 2
            }),
            Some(Ix2 {
                row_ix: 2,
                col_ix: 3
            })
        );
    }
    #[test]
    fn test_west() {
        let v2: V2<u8, 3, 3> = V2::new((0..=8).collect::<Vec<u8>>()).unwrap();
        assert!(
            v2.west_ix(Ix2 {
                row_ix: 0,
                col_ix: 0
            })
            .is_none()
        );
        assert_eq!(
            v2.west_ix(Ix2 {
                row_ix: 2,
                col_ix: 2
            }),
            Some(Ix2 {
                row_ix: 2,
                col_ix: 1
            })
        );
    }
    #[test]
    fn test_northwest() {
        let v2: V2<u8, 3, 3> = V2::new((0..=8).collect::<Vec<u8>>()).unwrap();
        assert!(
            v2.northwest_of(Ix2 {
                row_ix: 0,
                col_ix: 1
            })
            .is_none()
        );
        assert_eq!(
            v2.northwest_ix(Ix2 {
                row_ix: 2,
                col_ix: 2
            }),
            Some(Ix2 {
                row_ix: 1,
                col_ix: 1
            })
        );
    }
    #[test]
    fn test_northeast() {
        let v2: V2<u8, 3, 3> = V2::new((0..=8).collect::<Vec<u8>>()).unwrap();
        assert!(
            v2.northeast_ix(Ix2 {
                row_ix: 0,
                col_ix: 1
            })
            .is_none()
        );
        assert_eq!(
            v2.northeast_ix(Ix2 {
                row_ix: 2,
                col_ix: 2
            }),
            Some(Ix2 {
                row_ix: 1,
                col_ix: 3
            })
        );
    }
    #[test]
    fn test_southwest() {
        let v2: V2<u8, 3, 3> = V2::new((0..=8).collect::<Vec<u8>>()).unwrap();
        assert_eq!(
            v2.southwest_ix(Ix2 {
                row_ix: 2,
                col_ix: 2
            }),
            Some(Ix2 {
                row_ix: 3,
                col_ix: 1
            })
        );
    }
    #[test]
    fn test_southeast() {
        let v2: V2<u8, 3, 3> = V2::new((0..=8).collect::<Vec<u8>>()).unwrap();
        assert_eq!(
            v2.southeast_ix(Ix2 {
                row_ix: 2,
                col_ix: 2
            }),
            Some(Ix2 {
                row_ix: 3,
                col_ix: 3
            })
        );
    }
}