grid/
lib.rs

1#![warn(clippy::all, clippy::pedantic, clippy::nursery)]
2/*!
3# Two Dimensional Grid
4Continuous growable 2D data structure.
5The purpose of this crate is to provide an universal data structure that is faster,
6uses less memory, and is easier to use than a naive `Vec<Vec<T>>` solution.
7
8This crate will always provide a 2D data structure. If you need three or more dimensions take a look at the
9[ndarray](https://docs.rs/ndarray/0.13.0/ndarray/) library. The `grid` crate is a container for all kind of data.
10If you need to perform matrix operations, you are better off with a linear algebra lib, such as
11[cgmath](https://docs.rs/cgmath/0.17.0/cgmath/) or [nalgebra](https://docs.rs/nalgebra/0.21.0/nalgebra/).
12No other dependencies except for the std lib are used.
13Most of the functions `std::Vec<T>` offer are also implemented in `grid` and slightly modified for a 2D data object.
14
15# Memory layout
16
17Similar to *C-like* arrays, `grid` uses a flat 1D `Vec<T>` data structure to have a continuous
18memory data layout. See also [this](https://stackoverflow.com/questions/17259877/1d-or-2d-array-whats-faster)
19explanation of why you should probably use a one-dimensional array approach.
20
21Note that this crate uses a [*row-major*](https://eli.thegreenplace.net/2015/memory-layout-of-multi-dimensional-arrays) memory layout by default.
22
23If you need a specific memory layout, please seek the `*_with_order` constructors. You should also take note that some transformation methods
24change the internal memory layout, like [`transpose`](Grid::transpose).
25
26This choice is important, because operations on rows are faster with a row-major memory layout.
27Likewise, operations on columns are faster with column-major memory layout.
28
29# Examples
30```
31use grid::*;
32let mut grid = grid![[1,2,3]
33                     [4,5,6]];
34assert_eq!(grid, Grid::from_vec(vec![1,2,3,4,5,6],3));
35assert_eq!(grid.get(0, 2), Some(&3));
36assert_eq!(grid[(1, 1)], 5);
37assert_eq!(grid.size(), (2, 3));
38grid.push_row(vec![7,8,9]);
39assert_eq!(grid, grid![[1,2,3][4,5,6][7,8,9]])
40 ```
41*/
42
43#![cfg_attr(not(feature = "std"), no_std)]
44
45#[cfg(not(feature = "std"))]
46extern crate alloc;
47#[cfg(not(feature = "std"))]
48use alloc::{format, vec, vec::Vec};
49#[cfg(feature = "serde")]
50use serde::{
51    de::{self, Deserialize, Deserializer, MapAccess, SeqAccess, Visitor},
52    ser::{Serialize, SerializeStruct, Serializer},
53};
54
55use core::cmp::Eq;
56use core::fmt;
57use core::hash;
58use core::iter::StepBy;
59use core::ops::Index;
60use core::ops::IndexMut;
61use core::slice::Iter;
62use core::slice::IterMut;
63use core::{cmp, convert::TryInto};
64
65#[doc(hidden)]
66#[macro_export]
67macro_rules! count {
68    () => (0usize);
69    ( $x:tt $($xs:tt)* ) => (1usize + $crate::count!($($xs)*));
70}
71
72/// Init a grid with values.
73///
74/// Each array within `[]` represents a row starting from top to button.
75///
76/// # Examples
77///
78/// In this example a grid of numbers from 1 to 9 is created:
79///
80///  
81/// ```
82/// use grid::grid;
83/// let grid = grid![[1, 2, 3]
84/// [4, 5, 6]
85/// [7, 8, 9]];
86/// assert_eq!(grid.size(), (3, 3))
87/// ```
88///
89/// Note that each row must be of the same length. The following example will not compile:
90///  
91/// ``` ignore
92/// use grid::grid;
93/// let grid = grid![[1, 2, 3]
94/// [4, 5] // This does not work!
95/// [7, 8, 9]];
96/// ```
97#[macro_export]
98macro_rules! grid {
99    () => {
100        $crate::Grid::from_vec(vec![], 0)
101    };
102    ( [$( $x:expr ),* ]) => { {
103        let vec = vec![$($x),*];
104        let len  = vec.len();
105        $crate::Grid::from_vec(vec, len)
106    } };
107    ( [$( $x0:expr ),*] $([$( $x:expr ),*])* ) => {
108        {
109            let mut _assert_width0 = [(); $crate::count!($($x0)*)];
110            let cols = $crate::count!($($x0)*);
111            let rows = 1usize;
112
113            $(
114                let _assert_width = [(); $crate::count!($($x)*)];
115                _assert_width0 = _assert_width;
116                let rows = rows + 1usize;
117            )*
118
119            let mut vec = Vec::with_capacity(rows.checked_mul(cols).unwrap());
120
121            $( vec.push($x0); )*
122            $( $( vec.push($x); )* )*
123
124            $crate::Grid::from_vec(vec, cols)
125        }
126    };
127}
128
129/// Init a column-major grid with values.
130///
131/// Each array within `[]` represents a row starting from top to button.
132///
133/// # Examples
134///
135/// In this example a grid of numbers from 1 to 9 is created:
136///
137/// ```
138/// use grid::grid_cm;
139/// let grid = grid_cm![[1, 2, 3]
140/// [4, 5, 6]
141/// [7, 8, 9]];
142/// assert_eq!(grid.size(), (3, 3));
143/// assert_eq!(grid[(1, 1)], 5);
144/// ```
145///
146/// Note that each row must be of the same length. The following example will not compile:
147///
148/// ``` ignore
149/// use grid::grid_cm;
150/// let grid = grid_cm![[1, 2, 3]
151/// [4, 5] // This does not work!
152/// [7, 8, 9]];
153/// ```
154#[macro_export]
155macro_rules! grid_cm {
156    () => {
157        $crate::Grid::from_vec_with_order(vec![], 0, $crate::Order::ColumnMajor)
158    };
159    ( [$( $x:expr ),* ]) => { {
160        let vec = vec![$($x),*];
161        let len  = vec.len();
162        $crate::Grid::from_vec_with_order(vec, len, $crate::Order::ColumnMajor)
163    } };
164    ( [$( $x0:expr ),*] $([$( $x:expr ),*])* ) => {
165        {
166            let mut _assert_width0 = [(); $crate::count!($($x0)*)];
167            let cols = $crate::count!($($x0)*);
168            let rows = 1usize;
169
170            $(
171                let _assert_width = [(); $crate::count!($($x)*)];
172                _assert_width0 = _assert_width;
173                let rows = rows + 1usize;
174            )*
175
176            let vec = Vec::with_capacity(rows.checked_mul(cols).unwrap());
177            let mut grid = $crate::Grid::from_vec_with_order(vec, cols, $crate::Order::ColumnMajor);
178
179            grid.push_row(vec![$($x0),*]);
180            $( grid.push_row(vec![$($x),*]); )*
181
182            grid
183        }
184    };
185}
186
187/// Define the internal memory layout of the grid.
188#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
189#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
190pub enum Order {
191    /// The data is ordered row by row.
192    #[default]
193    RowMajor,
194
195    /// The data is ordered column by column.
196    ColumnMajor,
197}
198
199impl Order {
200    const fn counterpart(self) -> Self {
201        match self {
202            Self::RowMajor => Self::ColumnMajor,
203            Self::ColumnMajor => Self::RowMajor,
204        }
205    }
206}
207
208/// Stores elements of a certain type in a 2D grid structure.
209///
210/// Uses a rust `Vec<T>` type to reference the grid data on the heap.
211/// Also the internal memory layout as well as the number of
212/// rows and columns are stored in the grid data structure.
213///
214/// The size limit of a grid is `rows * cols < usize`.
215pub struct Grid<T> {
216    data: Vec<T>,
217    cols: usize,
218    rows: usize,
219    order: Order,
220}
221
222#[cfg(feature = "serde")]
223impl<'de, T: Deserialize<'de>> Deserialize<'de> for Grid<T> {
224    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
225    where
226        D: Deserializer<'de>,
227    {
228        use std::marker::PhantomData;
229        #[derive(serde::Deserialize)]
230        #[serde(field_identifier, rename_all = "lowercase")]
231        enum Field {
232            Data,
233            Cols,
234            Order,
235        }
236
237        struct GridVisitor<T> {
238            _p: PhantomData<T>,
239        }
240
241        impl<'de, T: Deserialize<'de>> Visitor<'de> for GridVisitor<T> {
242            type Value = Grid<T>;
243
244            fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
245                formatter.write_str("struct Grid")
246            }
247
248            fn visit_seq<V>(self, mut seq: V) -> Result<Grid<T>, V::Error>
249            where
250                V: SeqAccess<'de>,
251            {
252                let cols = seq
253                    .next_element()?
254                    .ok_or_else(|| de::Error::invalid_length(0, &self))?;
255                let data = seq
256                    .next_element()?
257                    .ok_or_else(|| de::Error::invalid_length(1, &self))?;
258                let order = seq.next_element()?.unwrap_or_default();
259                Ok(Grid::from_vec_with_order(data, cols, order))
260            }
261
262            fn visit_map<V>(self, mut map: V) -> Result<Grid<T>, V::Error>
263            where
264                V: MapAccess<'de>,
265            {
266                let mut cols = None;
267                let mut data = None;
268                let mut order = None;
269                while let Some(key) = map.next_key()? {
270                    match key {
271                        Field::Data => {
272                            if data.is_some() {
273                                return Err(de::Error::duplicate_field("data"));
274                            }
275                            data = Some(map.next_value()?);
276                        }
277                        Field::Cols => {
278                            if cols.is_some() {
279                                return Err(de::Error::duplicate_field("cols"));
280                            }
281                            cols = Some(map.next_value()?);
282                        }
283                        Field::Order => {
284                            if order.is_some() {
285                                return Err(de::Error::duplicate_field("order"));
286                            }
287                            order = Some(map.next_value()?);
288                        }
289                    }
290                }
291                let cols = cols.ok_or_else(|| de::Error::missing_field("cols"))?;
292                let data = data.ok_or_else(|| de::Error::missing_field("data"))?;
293                let order = order.unwrap_or_default();
294                Ok(Grid::from_vec_with_order(data, cols, order))
295            }
296        }
297
298        const FIELDS: &[&str] = &["cols", "data", "order"];
299        deserializer.deserialize_struct("Grid", FIELDS, GridVisitor { _p: PhantomData })
300    }
301}
302
303#[cfg(feature = "serde")]
304impl<T: Serialize> Serialize for Grid<T> {
305    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
306    where
307        S: Serializer,
308    {
309        // 3 is the number of fields in the struct.
310        let mut state = serializer.serialize_struct("Grid", 3)?;
311        state.serialize_field("cols", &self.cols)?;
312        state.serialize_field("data", &self.data)?;
313        state.serialize_field("order", &self.order)?;
314        state.end()
315    }
316}
317
318impl<T> Grid<T> {
319    /// Init a grid of size rows x columns with default values of the given type.
320    /// For example this will generate a 2x3 grid of zeros:
321    ///
322    /// ```
323    /// use grid::Grid;
324    /// let grid : Grid<u8> = Grid::new(2,3);
325    /// assert_eq!(grid[(0, 0)], 0);
326    /// ```
327    ///
328    /// If `rows == 0` or `cols == 0` the grid will be empty with no cols and rows.
329    ///
330    /// This create a grid with a row-major memory layout.
331    /// If you need a column-major one, see [`new_with_order`](Grid::new_with_order).
332    ///
333    /// # Panics
334    ///
335    /// Panics if `rows * cols > usize::MAX`.
336    #[must_use]
337    #[inline]
338    pub fn new(rows: usize, cols: usize) -> Self
339    where
340        T: Default,
341    {
342        Self::new_with_order(rows, cols, Order::default())
343    }
344
345    /// Same as [`new`](Self::new) but with a specific [`Order`].
346    ///
347    /// # Panics
348    ///
349    /// Panics if `rows * cols > usize::MAX`.
350    pub fn new_with_order(rows: usize, cols: usize, order: Order) -> Self
351    where
352        T: Default,
353    {
354        if rows == 0 || cols == 0 {
355            return Self {
356                data: Vec::new(),
357                rows: 0,
358                cols: 0,
359                order,
360            };
361        }
362        let mut data = Vec::new();
363        data.resize_with(rows.checked_mul(cols).unwrap(), T::default);
364        Self {
365            data,
366            cols,
367            rows,
368            order,
369        }
370    }
371
372    /// Init a grid of size rows x columns with the given data element.
373    ///
374    /// If `rows == 0` or `cols == 0` the grid will be empty with no cols and rows.
375    ///
376    /// This create a grid with a row-major memory layout.
377    /// If you need a column-major one, see [`init_with_order`](Grid::init_with_order).
378    ///
379    /// # Panics
380    ///
381    /// Panics if `rows * cols > usize::MAX`.
382    #[inline]
383    pub fn init(rows: usize, cols: usize, data: T) -> Self
384    where
385        T: Clone,
386    {
387        Self::init_with_order(rows, cols, Order::default(), data)
388    }
389
390    /// Same as [`init`](Self::init) but with a specific [`Order`].
391    ///
392    /// # Panics
393    ///
394    /// Panics if `rows * cols > usize::MAX`.
395    pub fn init_with_order(rows: usize, cols: usize, order: Order, data: T) -> Self
396    where
397        T: Clone,
398    {
399        if rows == 0 || cols == 0 {
400            return Self {
401                data: Vec::new(),
402                rows: 0,
403                cols: 0,
404                order,
405            };
406        }
407        Self {
408            data: vec![data; rows.checked_mul(cols).unwrap()],
409            cols,
410            rows,
411            order,
412        }
413    }
414
415    /// Initialises an empty Grid with the capacity to store `cols * rows` elements.
416    /// Similar to `Vec::with_capacity`.
417    ///
418    /// # Panics
419    ///
420    /// Panics if `rows * cols > usize::MAX` or if `rows * cols * size_of::<T>() > isize::MAX`
421    #[must_use]
422    pub fn with_capacity(rows: usize, cols: usize) -> Self {
423        Self::with_capacity_and_order(rows, cols, Order::default())
424    }
425
426    /// Same as [`with_capacity`](Self::with_capacity) but with a specified [`Order`]
427    ///
428    /// # Panics
429    ///
430    /// Panics if `rows * cols > usize::MAX` or if `rows * cols * size_of::<T>() > isize::MAX`
431    #[must_use]
432    pub fn with_capacity_and_order(rows: usize, cols: usize, order: Order) -> Self {
433        Self {
434            data: Vec::with_capacity(rows.checked_mul(cols).unwrap()),
435            cols: 0,
436            rows: 0,
437            order,
438        }
439    }
440
441    /// Returns a grid from a vector with a given column length.
442    /// The length of `vec` must be a multiple of `cols`.
443    ///
444    /// This create a grid with a row-major memory layout.
445    /// If you need a column-major one, see [`from_vec_with_order`](Grid::from_vec_with_order).
446    ///
447    /// For example:
448    ///
449    /// ```
450    /// use grid::Grid;
451    /// let grid = Grid::from_vec(vec![1,2,3,4,5,6], 3);
452    /// assert_eq!(grid.size(), (2, 3));
453    /// ```
454    ///
455    /// will create a grid with the following layout:
456    /// \[1,2,3\]
457    /// \[4,5,6\]
458    ///
459    /// This example will fail, because `vec.len()` is not a multiple of `cols`:
460    ///
461    /// ``` should_panic
462    /// use grid::Grid;
463    /// Grid::from_vec(vec![1,2,3,4,5], 3);
464    /// ```
465    ///
466    /// # Panics
467    ///
468    /// This panics if the vector length isn't a multiple of the number of columns.
469    #[must_use]
470    #[inline]
471    pub fn from_vec(vec: Vec<T>, cols: usize) -> Self {
472        Self::from_vec_with_order(vec, cols, Order::default())
473    }
474
475    /// Same as [`from_vec`](Self::from_vec) but with a specific [`Order`].
476    ///
477    /// # Panics
478    ///
479    /// This panics if the vector length isn't a multiple of the number of columns.
480    #[must_use]
481    pub fn from_vec_with_order(vec: Vec<T>, cols: usize, order: Order) -> Self {
482        let rows = vec.len().checked_div(cols).unwrap_or(0);
483        assert_eq!(
484            rows * cols,
485            vec.len(),
486            "Vector length {:?} should be a multiple of cols = {:?}",
487            vec.len(),
488            cols
489        );
490        if rows == 0 || cols == 0 {
491            Self {
492                data: vec,
493                rows: 0,
494                cols: 0,
495                order,
496            }
497        } else {
498            Self {
499                data: vec,
500                rows,
501                cols,
502                order,
503            }
504        }
505    }
506
507    /// Returns the index of the coordinates in the internal vector.
508    #[inline]
509    #[must_use]
510    const fn get_index(&self, row: usize, col: usize) -> usize {
511        match self.order {
512            Order::RowMajor => row * self.cols + col,
513            Order::ColumnMajor => col * self.rows + row,
514        }
515    }
516
517    /// Returns a reference to an element, without performing bound checks.
518    /// Generally not recommended, use with caution!
519    ///
520    /// # Safety
521    ///
522    /// Calling this method with an out-of-bounds index is undefined behavior even if the resulting reference is not used.
523    #[inline]
524    #[must_use]
525    pub unsafe fn get_unchecked(&self, row: impl Into<usize>, col: impl Into<usize>) -> &T {
526        let index = self.get_index(row.into(), col.into());
527        self.data.get_unchecked(index)
528    }
529
530    /// Returns a mutable reference to an element, without performing bound checks.
531    /// Generally not recommended, use with caution!
532    ///
533    /// # Safety
534    ///
535    /// Calling this method with an out-of-bounds index is undefined behavior even if the resulting reference is not used.
536    #[inline]
537    #[must_use]
538    pub unsafe fn get_unchecked_mut(
539        &mut self,
540        row: impl Into<usize>,
541        col: impl Into<usize>,
542    ) -> &mut T {
543        let index = self.get_index(row.into(), col.into());
544        self.data.get_unchecked_mut(index)
545    }
546
547    /// Access a certain element in the grid.
548    /// Returns `None` if an element beyond the grid bounds is tried to be accessed.
549    #[must_use]
550    pub fn get(&self, row: impl TryInto<usize>, col: impl TryInto<usize>) -> Option<&T> {
551        let row_usize = row.try_into().ok()?;
552        let col_usize = col.try_into().ok()?;
553        if row_usize < self.rows && col_usize < self.cols {
554            unsafe { Some(self.get_unchecked(row_usize, col_usize)) }
555        } else {
556            None
557        }
558    }
559
560    /// Mutable access to a certain element in the grid.
561    /// Returns `None` if an element beyond the grid bounds is tried to be accessed.
562    #[must_use]
563    pub fn get_mut(
564        &mut self,
565        row: impl TryInto<usize>,
566        col: impl TryInto<usize>,
567    ) -> Option<&mut T> {
568        let row_usize = row.try_into().ok()?;
569        let col_usize = col.try_into().ok()?;
570        if row_usize < self.rows && col_usize < self.cols {
571            unsafe { Some(self.get_unchecked_mut(row_usize, col_usize)) }
572        } else {
573            None
574        }
575    }
576
577    /// Returns the size of the grid as a two element tuple.
578    /// First element are the number of rows and the second the columns.
579    #[must_use]
580    pub const fn size(&self) -> (usize, usize) {
581        (self.rows, self.cols)
582    }
583
584    /// Returns the number of rows of the grid.
585    #[must_use]
586    pub const fn rows(&self) -> usize {
587        self.rows
588    }
589
590    /// Returns the number of columns of the grid.
591    #[must_use]
592    pub const fn cols(&self) -> usize {
593        self.cols
594    }
595
596    /// Returns the internal memory layout of the grid.
597    #[must_use]
598    pub const fn order(&self) -> Order {
599        self.order
600    }
601
602    /// Returns `true` if the grid contains no elements.
603    /// For example:
604    /// ```
605    /// use grid::*;
606    /// let grid : Grid<u8> = grid![];
607    /// assert!(grid.is_empty());
608    /// ```
609    #[must_use]
610    pub fn is_empty(&self) -> bool {
611        self.data.is_empty()
612    }
613
614    /// Clears the grid.
615    ///
616    /// This doesn't change the grid order.
617    pub fn clear(&mut self) {
618        self.rows = 0;
619        self.cols = 0;
620        self.data.clear();
621    }
622
623    /// Returns an iterator over the whole grid, starting from the first row and column.
624    ///
625    /// The iteration order is dependant on the internal memory layout.
626    /// If you need a specific order, see [`iter_rows`](Grid::iter_rows) or
627    /// [`iter_cols`](Grid::iter_cols).
628    ///
629    /// ```
630    /// use grid::*;
631    /// let grid: Grid<u8> = grid![[1,2][3,4]];
632    /// let mut iter = grid.iter();
633    /// assert_eq!(iter.next(), Some(&1));
634    /// assert_eq!(iter.next(), Some(&2));
635    /// assert_eq!(iter.next(), Some(&3));
636    /// assert_eq!(iter.next(), Some(&4));
637    /// assert_eq!(iter.next(), None);
638    /// ```
639    pub fn iter(&self) -> Iter<T> {
640        self.data.iter()
641    }
642
643    /// Returns an mutable iterator over the whole grid that allows modifying each value.
644    ///
645    /// The iteration order is dependant on the internal memory layout.
646    ///
647    /// ```
648    /// use grid::*;
649    /// let mut grid: Grid<u8> = grid![[1,2][3,4]];
650    /// let mut iter = grid.iter_mut();
651    /// let next = iter.next();
652    /// assert_eq!(next, Some(&mut 1));
653    /// *next.unwrap() = 10;
654    /// ```
655    pub fn iter_mut(&mut self) -> IterMut<T> {
656        self.data.iter_mut()
657    }
658
659    /// Returns an iterator over a column.
660    ///
661    /// # Examples
662    ///
663    /// ```
664    /// use grid::*;
665    /// let grid: Grid<u8> = grid![[1, 2, 3][3, 4, 5]];
666    /// let mut col_iter = grid.iter_col(1);
667    /// assert_eq!(col_iter.next(), Some(&2));
668    /// assert_eq!(col_iter.next(), Some(&4));
669    /// assert_eq!(col_iter.next(), None);
670    /// ```
671    ///
672    /// # Performance
673    ///
674    /// This method will be significantly slower if the grid uses a row-major memory layout,
675    /// which is the default.
676    ///
677    /// # Panics
678    ///
679    /// Panics if the col index is out of bounds.
680    pub fn iter_col(&self, col: usize) -> StepBy<Iter<T>> {
681        assert!(
682            col < self.cols,
683            "out of bounds. Column must be less than {:?}, but is {:?}",
684            self.cols,
685            col
686        );
687        match self.order {
688            Order::RowMajor => self.data[col..].iter().step_by(self.cols),
689            Order::ColumnMajor => {
690                let start = col * self.rows;
691                self.data[start..(start + self.rows)].iter().step_by(1)
692            }
693        }
694    }
695
696    /// Returns a mutable iterator over a column.
697    ///
698    /// # Examples
699    ///
700    /// ```
701    /// use grid::*;
702    /// let mut grid: Grid<u8> = grid![[1, 2, 3][3, 4, 5]];
703    /// let mut col_iter = grid.iter_col_mut(1);
704    /// let next = col_iter.next();
705    /// assert_eq!(next, Some(&mut 2));
706    /// *next.unwrap() = 10;
707    /// assert_eq!(grid[(0, 1)], 10);
708    /// ```
709    ///
710    /// # Performance
711    ///
712    /// This method will be significantly slower if the grid uses a row-major memory layout,
713    /// which is the default.
714    ///
715    /// # Panics
716    ///
717    /// Panics if the col index is out of bounds.
718    pub fn iter_col_mut(&mut self, col: usize) -> StepBy<IterMut<T>> {
719        assert!(
720            col < self.cols,
721            "out of bounds. Column must be less than {:?}, but is {:?}",
722            self.cols,
723            col
724        );
725        match self.order {
726            Order::RowMajor => self.data[col..].iter_mut().step_by(self.cols),
727            Order::ColumnMajor => {
728                let start = col * self.rows;
729                self.data[start..(start + self.rows)].iter_mut().step_by(1)
730            }
731        }
732    }
733
734    /// Returns an iterator over a row.
735    ///
736    /// # Examples
737    ///
738    /// ```
739    /// use grid::*;
740    /// let grid: Grid<u8> = grid![[1, 2, 3][3, 4, 5]];
741    /// let mut col_iter = grid.iter_row(1);
742    /// assert_eq!(col_iter.next(), Some(&3));
743    /// assert_eq!(col_iter.next(), Some(&4));
744    /// assert_eq!(col_iter.next(), Some(&5));
745    /// assert_eq!(col_iter.next(), None);
746    /// ```
747    ///
748    /// # Performance
749    ///
750    /// This method will be significantly slower if the grid uses a column-major memory layout.
751    ///
752    /// # Panics
753    ///
754    /// Panics if the row index is out of bounds.
755    pub fn iter_row(&self, row: usize) -> StepBy<Iter<T>> {
756        assert!(
757            row < self.rows,
758            "out of bounds. Row must be less than {:?}, but is {:?}",
759            self.rows,
760            row
761        );
762        match self.order {
763            Order::RowMajor => {
764                let start = row * self.cols;
765                self.data[start..(start + self.cols)].iter().step_by(1)
766            }
767            Order::ColumnMajor => self.data[row..].iter().step_by(self.rows),
768        }
769    }
770
771    /// Returns a mutable iterator over a row.
772    ///
773    /// # Examples
774    ///
775    /// ```
776    /// use grid::*;
777    /// let mut grid: Grid<u8> = grid![[1, 2, 3][3, 4, 5]];
778    /// let mut col_iter = grid.iter_row_mut(1);
779    /// let next = col_iter.next();
780    /// *next.unwrap() = 10;
781    /// assert_eq!(grid[(1, 0)], 10);
782    /// ```
783    ///
784    /// # Performance
785    ///
786    /// This method will be significantly slower if the grid uses a column-major memory layout.
787    ///
788    /// # Panics
789    ///
790    /// Panics if the row index is out of bounds.
791    pub fn iter_row_mut(&mut self, row: usize) -> StepBy<IterMut<T>> {
792        assert!(
793            row < self.rows,
794            "out of bounds. Row must be less than {:?}, but is {:?}",
795            self.rows,
796            row
797        );
798        match self.order {
799            Order::RowMajor => {
800                let start = row * self.cols;
801                self.data[start..(start + self.cols)].iter_mut().step_by(1)
802            }
803            Order::ColumnMajor => self.data[row..].iter_mut().step_by(self.rows),
804        }
805    }
806
807    /// Traverse the grid with row and column indexes.
808    ///
809    /// The iteration order is dependent on the internal memory layout,
810    /// but the indexes will be accurate either way.
811    ///
812    /// # Examples
813    ///
814    /// ```
815    /// use grid::*;
816    /// let grid: Grid<u8> = grid![[1,2][3,4]];
817    /// let mut iter = grid.indexed_iter();
818    /// assert_eq!(iter.next(), Some(((0, 0), &1)));
819    /// ```
820    ///
821    /// Or simply unpack in a `for` loop:
822    ///
823    /// ```
824    /// use grid::*;
825    /// let grid: Grid<u8> = grid![[1,2][3,4]];
826    /// for ((row, col), i) in grid.indexed_iter() {
827    ///     println!("value at row {row} and column {col} is: {i}");
828    /// }
829    /// ```
830    pub fn indexed_iter(&self) -> impl Iterator<Item = ((usize, usize), &T)> {
831        self.data.iter().enumerate().map(move |(idx, i)| {
832            let position = match self.order {
833                Order::RowMajor => (idx / self.cols, idx % self.cols),
834                Order::ColumnMajor => (idx % self.rows, idx / self.rows),
835            };
836            (position, i)
837        })
838    }
839
840    /// Traverse the grid with row and column indexes,
841    /// and mutable access to each element.
842    ///
843    /// The iteration order is dependent on the internal memory layout,
844    /// but the indexes will be accurate either way.
845    ///
846    /// # Examples
847    ///
848    /// ```
849    /// use grid::*;
850    /// let mut grid: Grid<u8> = grid![[1,2][3,4]];
851    /// let mut iter = grid.indexed_iter_mut();
852    /// assert_eq!(iter.next(), Some(((0, 0), &mut 1)));
853    /// ```
854    ///
855    /// Or simply unpack in a `for` loop:
856    ///
857    /// ```
858    /// use grid::*;
859    /// let mut grid: Grid<u8> = grid![[1,2][3,4]];
860    /// for ((row, col), i) in grid.indexed_iter_mut() {
861    ///     *i += 1;
862    ///     println!("value at row {row} and column {col} is: {i}");
863    /// }
864    ///
865    /// assert_eq!(grid[(0, 0)], 2);
866    /// assert_eq!(grid[(0, 1)], 3);
867    /// assert_eq!(grid[(1, 0)], 4);
868    /// assert_eq!(grid[(1, 1)], 5);
869    /// ```
870    pub fn indexed_iter_mut(&mut self) -> impl Iterator<Item = ((usize, usize), &mut T)> {
871        let order = self.order;
872        let cols = self.cols;
873        let rows = self.rows;
874
875        self.data.iter_mut().enumerate().map(move |(idx, i)| {
876            let position = match order {
877                Order::RowMajor => (idx / cols, idx % cols),
878                Order::ColumnMajor => (idx % rows, idx / rows),
879            };
880            (position, i)
881        })
882    }
883
884    /// Consume grid the grid with row and column indexes.
885    ///
886    /// The iteration order is dependent on the internal memory layout,
887    /// but the indexes will be accurate either way.
888    ///
889    /// # Examples
890    ///
891    /// ```
892    /// use grid::*;
893    /// use std::rc::Rc;
894    ///
895    /// let grid: Grid<Rc<u8>> = grid![[Rc::new(1),Rc::new(2)][Rc::new(3),Rc::new(4)]];
896    /// let mut iter = grid.indexed_into_iter();
897    /// assert_eq!(iter.next(), Some(((0, 0), Rc::new(1))));
898    /// ```
899    ///
900    /// Or simply unpack in a `for` loop:
901    ///
902    /// ```
903    /// use grid::*;
904    /// use std::rc::Rc;
905    ///
906    /// let grid: Grid<Rc<i32>> = grid![[Rc::new(1),Rc::new(2)][Rc::new(3),Rc::new(4)]];
907    /// for ((row, col), i) in grid.indexed_into_iter() {
908    ///     println!("value at row {row} and column {col} is: {i}");
909    /// }
910    /// ```
911    pub fn indexed_into_iter(self) -> impl Iterator<Item = ((usize, usize), T)> {
912        let Self {
913            data,
914            cols,
915            rows,
916            order,
917        } = self;
918        data.into_iter().enumerate().map(move |(idx, i)| {
919            let position = match order {
920                Order::RowMajor => (idx / cols, idx % cols),
921                Order::ColumnMajor => (idx % rows, idx / rows),
922            };
923            (position, i)
924        })
925    }
926
927    /// Add a new row to the grid.
928    ///
929    /// # Examples
930    ///
931    /// ```
932    /// use grid::*;
933    /// let mut grid: Grid<u8> = grid![[1, 2, 3][3, 4, 5]];
934    /// let row = vec![6,7,8];
935    /// grid.push_row(row);
936    /// assert_eq!(grid.rows(), 3);
937    /// assert_eq!(grid[(2, 0)], 6);
938    /// assert_eq!(grid[(2, 1)], 7);
939    /// assert_eq!(grid[(2, 2)], 8);
940    /// ```
941    ///
942    /// Can also be used to init an empty grid:
943    ///
944    /// ```
945    /// use grid::*;
946    /// let mut grid: Grid<u8> = grid![];
947    /// let row = vec![1,2,3];
948    /// grid.push_row(row);
949    /// assert_eq!(grid.size(), (1, 3));
950    /// ```
951    ///
952    /// # Performance
953    ///
954    /// This method will be significantly slower if the grid uses a column-major memory layout.
955    ///
956    /// # Panics
957    ///
958    /// Panics if:
959    ///  - the grid is not empty and `row.len() != grid.cols()`
960    ///  - `row.len() == 0`
961    pub fn push_row(&mut self, row: Vec<T>) {
962        assert_ne!(row.len(), 0);
963        assert!(
964            !(self.rows > 0 && row.len() != self.cols),
965            "pushed row does not match. Length must be {:?}, but was {:?}.",
966            self.cols,
967            row.len()
968        );
969        self.data.extend(row);
970        if self.order == Order::ColumnMajor {
971            for i in (1..self.cols).rev() {
972                let col_idx = i * self.rows;
973                self.data[col_idx..col_idx + self.rows + i].rotate_right(i);
974            }
975        }
976        self.rows += 1;
977        if self.cols == 0 {
978            self.cols = self.data.len();
979        }
980    }
981
982    /// Add a new column to the grid.
983    ///
984    /// # Examples
985    ///
986    /// ```
987    /// use grid::*;
988    /// let mut grid: Grid<u8> = grid![[1, 2, 3][3, 4, 5]];
989    /// let col = vec![4,6];
990    /// grid.push_col(col);
991    /// assert_eq!(grid.cols(), 4);
992    /// assert_eq!(grid[(0, 3)], 4);
993    /// assert_eq!(grid[(1, 3)], 6);
994    /// ```
995    ///
996    /// Can also be used to init an empty grid:
997    ///
998    /// ```
999    /// use grid::*;
1000    /// let mut grid: Grid<u8> = grid![];
1001    /// let col = vec![1,2,3];
1002    /// grid.push_col(col);
1003    /// assert_eq!(grid.size(), (3, 1));
1004    /// ```
1005    ///
1006    /// # Performance
1007    ///
1008    /// This method will be significantly slower if the grid uses a row-major memory layout,
1009    /// which is the default.
1010    ///
1011    /// # Panics
1012    ///
1013    /// Panics if:
1014    ///  - the grid is not empty and `col.len() != grid.rows()`
1015    ///  - `col.len() == 0`
1016    pub fn push_col(&mut self, col: Vec<T>) {
1017        assert_ne!(col.len(), 0);
1018        assert!(
1019            !(self.cols > 0 && col.len() != self.rows),
1020            "pushed column does not match. Length must be {:?}, but was {:?}.",
1021            self.rows,
1022            col.len()
1023        );
1024        self.data.extend(col);
1025        if self.order == Order::RowMajor {
1026            for i in (1..self.rows).rev() {
1027                let row_idx = i * self.cols;
1028                self.data[row_idx..row_idx + self.cols + i].rotate_right(i);
1029            }
1030        }
1031        self.cols += 1;
1032        if self.rows == 0 {
1033            self.rows = self.data.len();
1034        }
1035    }
1036
1037    /// Removes the last row from a grid and returns it, or None if it is empty.
1038    ///
1039    /// # Examples
1040    /// ```
1041    /// use grid::*;
1042    /// let mut grid = grid![[1,2,3][4,5,6]];
1043    /// assert_eq![grid.pop_row(), Some(vec![4,5,6])];
1044    /// assert_eq![grid.pop_row(), Some(vec![1,2,3])];
1045    /// assert_eq![grid.pop_row(), None];
1046    /// ```
1047    ///
1048    /// # Performance
1049    ///
1050    /// This method will be significantly slower if the grid uses a column-major memory layout.
1051    pub fn pop_row(&mut self) -> Option<Vec<T>> {
1052        if self.rows == 0 {
1053            return None;
1054        }
1055        if self.order == Order::ColumnMajor {
1056            for i in 1..self.cols {
1057                let col_idx = i * (self.rows - 1);
1058                self.data[col_idx..col_idx + self.rows + i - 1].rotate_left(i);
1059            }
1060        }
1061        let row = self.data.split_off(self.data.len() - self.cols);
1062        self.rows -= 1;
1063        if self.rows == 0 {
1064            self.cols = 0;
1065        }
1066        Some(row)
1067    }
1068
1069    /// Remove a Row at the index and return a vector of it.
1070    ///
1071    /// # Examples
1072    /// ```
1073    /// use grid::*;
1074    /// let mut grid = grid![[1,2][3,4][5,6]];
1075    /// assert_eq![grid.remove_row(1), Some(vec![3,4])];   
1076    /// assert_eq![grid.remove_row(0), Some(vec![1,2])];
1077    /// assert_eq![grid.remove_row(0), Some(vec![5,6])];
1078    /// assert_eq![grid.remove_row(0), None];
1079    /// ```
1080    ///
1081    /// # Performance
1082    ///
1083    /// This method will be significantly slower if the grid uses a column-major memory layout.
1084    pub fn remove_row(&mut self, row_index: usize) -> Option<Vec<T>> {
1085        if self.cols == 0 || self.rows == 0 || row_index >= self.rows {
1086            return None;
1087        }
1088        let row = match self.order {
1089            Order::RowMajor => self
1090                .data
1091                .drain((row_index * self.cols)..((row_index + 1) * self.cols))
1092                .collect(),
1093            Order::ColumnMajor => {
1094                for i in 0..self.cols {
1095                    let col_idx = row_index + i * (self.rows - 1);
1096                    let end = cmp::min(col_idx + self.rows + i, self.data.len());
1097                    self.data[col_idx..end].rotate_left(i + 1);
1098                }
1099                self.data.split_off(self.data.len() - self.cols)
1100            }
1101        };
1102        self.rows -= 1;
1103        if self.rows == 0 {
1104            self.cols = 0;
1105        }
1106        Some(row)
1107    }
1108
1109    /// Removes the last column from a grid and returns it, or None if it is empty.
1110    ///
1111    /// Note that this operation is much slower than the `pop_row()` because the memory layout
1112    /// of `Grid` is row-major and removing a column requires a lot of move operations.
1113    ///
1114    /// # Examples
1115    /// ```
1116    /// use grid::*;
1117    /// let mut grid = grid![[1,2,3][4,5,6]];
1118    /// assert_eq![grid.pop_col(), Some(vec![3,6])];
1119    /// assert_eq![grid.pop_col(), Some(vec![2,5])];
1120    /// assert_eq![grid.pop_col(), Some(vec![1,4])];
1121    /// assert_eq![grid.pop_col(), None];
1122    /// ```
1123    ///
1124    /// # Performance
1125    ///
1126    /// This method will be significantly slower if the grid uses a row-major memory layout,
1127    /// which is the default.
1128    pub fn pop_col(&mut self) -> Option<Vec<T>> {
1129        if self.cols == 0 {
1130            return None;
1131        }
1132        if self.order == Order::RowMajor {
1133            for i in 1..self.rows {
1134                let row_idx = i * (self.cols - 1);
1135                self.data[row_idx..row_idx + self.cols + i - 1].rotate_left(i);
1136            }
1137        }
1138        let col = self.data.split_off(self.data.len() - self.rows);
1139        self.cols -= 1;
1140        if self.cols == 0 {
1141            self.rows = 0;
1142        }
1143        Some(col)
1144    }
1145
1146    /// Remove a column at the index and return a vector of it.
1147    ///
1148    /// # Examples
1149    /// ```
1150    /// use grid::*;
1151    /// let mut grid = grid![[1,2,3,4][5,6,7,8][9,10,11,12][13,14,15,16]];
1152    /// assert_eq![grid.remove_col(3), Some(vec![4,8,12,16])];
1153    /// assert_eq![grid.remove_col(0), Some(vec![1,5,9,13])];
1154    /// assert_eq![grid.remove_col(1), Some(vec![3,7,11,15])];
1155    /// assert_eq![grid.remove_col(0), Some(vec![2,6,10,14])];
1156    /// assert_eq![grid.remove_col(0), None];
1157    /// ```
1158    ///
1159    /// # Performance
1160    ///
1161    /// This method will be significantly slower if the grid uses a row-major memory layout,
1162    /// which is the default.
1163    pub fn remove_col(&mut self, col_index: usize) -> Option<Vec<T>> {
1164        if self.cols == 0 || self.rows == 0 || col_index >= self.cols {
1165            return None;
1166        }
1167        let col = match self.order {
1168            Order::RowMajor => {
1169                for i in 0..self.rows {
1170                    let row_idx = col_index + i * (self.cols - 1);
1171                    let end = cmp::min(row_idx + self.cols + i, self.data.len());
1172                    self.data[row_idx..end].rotate_left(i + 1);
1173                }
1174                self.data.split_off(self.data.len() - self.rows)
1175            }
1176            Order::ColumnMajor => self
1177                .data
1178                .drain((col_index * self.rows)..((col_index + 1) * self.rows))
1179                .collect(),
1180        };
1181        self.cols -= 1;
1182        if self.cols == 0 {
1183            self.rows = 0;
1184        }
1185        Some(col)
1186    }
1187
1188    /// Insert a new row at the index and shifts all rows after down.
1189    ///
1190    /// # Examples
1191    /// ```
1192    /// use grid::*;
1193    /// let mut grid = grid![[1,2,3][4,5,6]];
1194    /// grid.insert_row(1, vec![7,8,9]);
1195    /// assert_eq!(grid, grid![[1,2,3][7,8,9][4,5,6]]);
1196    /// ```
1197    ///
1198    /// # Performance
1199    ///
1200    /// This method will be significantly slower if the grid uses a column-major memory layout.
1201    ///
1202    /// # Panics
1203    ///
1204    /// Panics if:
1205    /// - the grid is not empty and `row.len() != grid.cols()`.
1206    /// - the index is greater than the number of rows
1207    pub fn insert_row(&mut self, index: usize, row: Vec<T>) {
1208        let input_len = row.len();
1209        assert!(
1210            !(self.cols > 0 && input_len != self.cols),
1211            "Inserted row must be of length {}, but was {}.",
1212            self.cols,
1213            row.len()
1214        );
1215        assert!(
1216            index <= self.rows,
1217            "Out of range. Index was {}, but must be less or equal to {}.",
1218            index,
1219            self.rows
1220        );
1221        match self.order {
1222            Order::RowMajor => {
1223                let data_idx = index * input_len;
1224                self.data.splice(data_idx..data_idx, row);
1225            }
1226            Order::ColumnMajor => {
1227                for (col_iter, row_val) in row.into_iter().enumerate() {
1228                    let data_idx = col_iter * self.rows + index + col_iter;
1229                    self.data.insert(data_idx, row_val);
1230                }
1231            }
1232        }
1233        self.cols = input_len;
1234        self.rows += 1;
1235    }
1236
1237    /// Insert a new column at the index.
1238    ///
1239    /// Important! Insertion of columns is a lot slower than the lines insertion.
1240    /// This is because of the memory layout of the grid data structure.
1241    ///
1242    /// # Examples
1243    /// ```
1244    /// use grid::*;
1245    /// let mut grid = grid![[1,2,3][4,5,6]];
1246    /// grid.insert_col(1, vec![9,9]);
1247    /// assert_eq!(grid, grid![[1,9,2,3][4,9,5,6]])
1248    /// ```
1249    ///
1250    /// # Performance
1251    ///
1252    /// This method will be significantly slower if the grid uses a row-major memory layout,
1253    /// which is the default.
1254    ///
1255    /// # Panics
1256    ///
1257    /// Panics if:
1258    /// - the grid is not empty and `col.len() != grid.rows()`.
1259    /// - the index is greater than the number of columns
1260    pub fn insert_col(&mut self, index: usize, col: Vec<T>) {
1261        let input_len = col.len();
1262        assert!(
1263            !(self.rows > 0 && input_len != self.rows),
1264            "Inserted col must be of length {}, but was {}.",
1265            self.rows,
1266            col.len()
1267        );
1268        assert!(
1269            index <= self.cols,
1270            "Out of range. Index was {}, but must be less or equal to {}.",
1271            index,
1272            self.cols
1273        );
1274        match self.order {
1275            Order::RowMajor => {
1276                for (row_iter, col_val) in col.into_iter().enumerate() {
1277                    let data_idx = row_iter * self.cols + index + row_iter;
1278                    self.data.insert(data_idx, col_val);
1279                }
1280            }
1281            Order::ColumnMajor => {
1282                let data_idx = index * input_len;
1283                self.data.splice(data_idx..data_idx, col);
1284            }
1285        }
1286        self.rows = input_len;
1287        self.cols += 1;
1288    }
1289
1290    /// Returns a reference to the internal data structure of the grid.
1291    ///
1292    /// The order of the elements depends on the internal memory layout, which is
1293    /// row-major by default.
1294    ///
1295    /// # Examples
1296    /// ```
1297    /// use grid::*;
1298    /// let grid = grid![[1,2,3][4,5,6]];
1299    /// let flat = grid.flatten();
1300    /// assert_eq!(flat, &vec![1,2,3,4,5,6]);
1301    /// ```
1302    #[must_use]
1303    pub const fn flatten(&self) -> &Vec<T> {
1304        &self.data
1305    }
1306
1307    /// Converts self into a vector without clones or allocation.
1308    ///
1309    /// The order of the elements depends on the internal memory layout, which is
1310    /// row-major by default.
1311    #[must_use]
1312    pub fn into_vec(self) -> Vec<T> {
1313        self.data
1314    }
1315
1316    /// Transpose the grid so that columns become rows in new grid.
1317    ///
1318    /// This method changes the internal memory layout.
1319    pub fn transpose(&mut self) {
1320        self.order = self.order.counterpart();
1321        core::mem::swap(&mut self.rows, &mut self.cols);
1322    }
1323
1324    /// Flip (or mirrors) the columns.
1325    ///
1326    /// # Examples
1327    ///
1328    /// ```
1329    /// use grid::*;
1330    /// let mut grid = grid![[1,2,3][4,5,6]];
1331    /// grid.flip_cols();
1332    /// assert_eq!(grid, grid![[3,2,1][6,5,4]])
1333    /// ```
1334    ///
1335    /// # Performance
1336    ///
1337    /// This method will be significantly slower if the grid uses a column-major memory layout.
1338    pub fn flip_cols(&mut self) {
1339        match self.order {
1340            Order::RowMajor => {
1341                for row in 0..self.rows {
1342                    let idx = row * self.cols;
1343                    self.data[idx..idx + self.cols].reverse();
1344                }
1345            }
1346            Order::ColumnMajor => {
1347                for col in 0..self.cols / 2 {
1348                    for row in 0..self.rows {
1349                        let cell1 = self.get_index(row, col);
1350                        let cell2 = self.get_index(row, self.cols - col - 1);
1351                        self.data.swap(cell1, cell2);
1352                    }
1353                }
1354            }
1355        }
1356    }
1357
1358    /// Flip (or mirrors) the rows.
1359    ///
1360    /// # Examples
1361    ///
1362    /// ```
1363    /// use grid::*;
1364    /// let mut grid = grid![[1,2,3][4,5,6]];
1365    /// grid.flip_rows();
1366    /// assert_eq!(grid, grid![[4,5,6][1,2,3]])
1367    /// ```
1368    ///
1369    /// # Performance
1370    ///
1371    /// This method will be significantly slower if the grid uses a row-major memory layout,
1372    /// which is the default.
1373    pub fn flip_rows(&mut self) {
1374        match self.order {
1375            Order::RowMajor => {
1376                for row in 0..self.rows / 2 {
1377                    for col in 0..self.cols {
1378                        let cell1 = self.get_index(row, col);
1379                        let cell2 = self.get_index(self.rows - row - 1, col);
1380                        self.data.swap(cell1, cell2);
1381                    }
1382                }
1383            }
1384            Order::ColumnMajor => {
1385                for col in 0..self.cols {
1386                    let idx = col * self.rows;
1387                    self.data[idx..idx + self.rows].reverse();
1388                }
1389            }
1390        }
1391    }
1392
1393    /// Rotate the grid 90° counter-clockwise.
1394    ///
1395    /// This method changes the internal memory layout.
1396    ///
1397    /// # Examples
1398    ///
1399    /// ```
1400    /// use grid::*;
1401    /// let mut grid = grid![[1,2][3,4]];
1402    /// grid.rotate_left();
1403    /// assert_eq!(grid, grid![[2,4][1,3]]);
1404    /// ```
1405    ///
1406    /// # Performance
1407    ///
1408    /// This method will be significantly slower if the grid initialy uses a column-major memory layout,
1409    /// which is the default.
1410    pub fn rotate_left(&mut self) {
1411        self.transpose();
1412        self.flip_rows();
1413    }
1414
1415    /// Rotate the grid 90° clockwise.
1416    ///
1417    /// This method changes the internal memory layout.
1418    ///
1419    /// # Examples
1420    ///
1421    /// ```
1422    /// use grid::*;
1423    /// let mut grid = grid![[1,2][3,4]];
1424    /// grid.rotate_right();
1425    /// assert_eq!(grid, grid![[3,1][4,2]]);
1426    /// ```
1427    ///
1428    /// # Performance
1429    ///
1430    /// This method will be significantly slower if the grid initialy uses a row-major memory layout,
1431    /// which is the default.
1432    pub fn rotate_right(&mut self) {
1433        self.transpose();
1434        self.flip_cols();
1435    }
1436
1437    /// Rotate the grid 180°.
1438    ///
1439    /// This method **doesn't** change the internal memory layout.
1440    ///
1441    /// # Examples
1442    ///
1443    /// ```
1444    /// use grid::*;
1445    /// let mut grid = grid![[1,2,3][4,5,6]];
1446    /// grid.rotate_half();
1447    /// assert_eq!(grid, grid![[6,5,4][3,2,1]]);
1448    /// ```
1449    ///
1450    /// # Performance
1451    ///
1452    /// The performances of this method is not affected by the internal memory layout.
1453    pub fn rotate_half(&mut self) {
1454        self.data.reverse();
1455    }
1456
1457    /// Fills the grid with elements by cloning `value`.
1458    ///
1459    /// # Examples
1460    ///
1461    /// ```
1462    /// use grid::*;
1463    /// let mut grid = grid![[1,2,3][4,5,6]];
1464    /// grid.fill(7);
1465    /// assert_eq!(grid, grid![[7,7,7][7,7,7]]);
1466    /// ```
1467    pub fn fill(&mut self, value: T)
1468    where
1469        T: Clone,
1470    {
1471        self.data.fill(value);
1472    }
1473
1474    /// Fills the grid with elements returned by calling a closure repeatedly.
1475    ///
1476    /// This method uses a closure to create new values. If you'd rather
1477    /// [`Clone`] a given value, use [`fill`]. If you want to use the [`Default`]
1478    /// trait to generate values, you can pass [`Default::default`] as the
1479    /// argument.
1480    ///
1481    /// [`fill`]: Grid::fill
1482    ///
1483    /// # Examples
1484    ///
1485    /// ```
1486    /// use grid::*;
1487    /// let mut grid = grid![[1,2,3][4,5,6]];
1488    /// grid.fill_with(Default::default);
1489    /// assert_eq!(grid, grid![[0,0,0][0,0,0]]);
1490    /// ```
1491    pub fn fill_with<F>(&mut self, f: F)
1492    where
1493        F: FnMut() -> T,
1494    {
1495        self.data.fill_with(f);
1496    }
1497
1498    /// Returns a new grid with the same dimensions, but with each element transformed by the closure.
1499    ///
1500    /// # Examples
1501    ///
1502    /// ```
1503    /// use grid::*;
1504    /// let grid = grid![[1,2][3,4]];
1505    /// let new_grid = grid.map(|x| x * 2);
1506    /// assert_eq!(new_grid, grid![[2,4][6,8]]);
1507    ///
1508    /// let grid = grid![[1,2][3,4]];
1509    /// let new_grid = grid.map(|x| x > 2);
1510    /// assert_eq!(new_grid, grid![[false,false][true,true]]);
1511    /// ```
1512    pub fn map<U, F>(self, f: F) -> Grid<U>
1513    where
1514        F: FnMut(T) -> U,
1515    {
1516        Grid {
1517            data: self.data.into_iter().map(f).collect(),
1518            cols: self.cols,
1519            rows: self.rows,
1520            order: self.order,
1521        }
1522    }
1523
1524    /// Returns a new grid with the same dimensions, but with each element
1525    /// transformed by the closure. Does not consume the grid.
1526    ///
1527    /// # Examples
1528    ///
1529    /// ```
1530    /// use grid::*;
1531    /// let grid = grid![[1,2][3,4]];
1532    /// let new_grid = grid.map(|x| x * 2);
1533    /// assert_eq!(new_grid, grid![[2,4][6,8]]);
1534    ///
1535    /// let grid = grid![[1,2][3,4]];
1536    /// let new_grid = grid.map(|x| x > 2);
1537    /// assert_eq!(new_grid, grid![[false,false][true,true]]);
1538    /// ```
1539    #[must_use]
1540    pub fn map_ref<U, F>(&self, f: F) -> Grid<U>
1541    where
1542        F: Fn(&T) -> U,
1543    {
1544        Grid {
1545            data: self.data.iter().map(f).collect(),
1546            cols: self.cols,
1547            rows: self.rows,
1548            order: self.order,
1549        }
1550    }
1551
1552    /// Iterate over the rows of the grid. Each time an iterator over a single
1553    /// row is returned.
1554    ///
1555    /// An item in this iterator is equal to a call to `Grid.iter_row(row_index)`
1556    /// of the corresponding row.
1557    ///
1558    /// # Examples
1559    ///
1560    /// ```
1561    /// use grid::*;
1562    /// let mut grid = grid![[1,2,3][4,5,6]];
1563    /// let sum_by_row: Vec<u8> = grid.iter_rows().map(|row| row.sum()).collect();
1564    /// assert_eq!(sum_by_row, vec![1+2+3, 4+5+6])
1565    /// ```
1566    #[must_use]
1567    pub const fn iter_rows(&self) -> GridRowIter<'_, T> {
1568        GridRowIter {
1569            grid: self,
1570            row_start_index: 0,
1571            row_end_index: self.rows,
1572        }
1573    }
1574
1575    /// Iterate over the columns of the grid. Each time an iterator over a single
1576    /// column is returned.
1577    ///
1578    /// An item in this iterator is equal to a call to `Grid.iter_col(col_index)`
1579    /// of the corresponding column.
1580    ///
1581    /// # Examples
1582    ///
1583    /// ```
1584    /// use grid::*;
1585    /// let mut grid = grid![[1,2,3][4,5,6]];
1586    /// let sum_by_col: Vec<u8> = grid.iter_cols().map(|col| col.sum()).collect();
1587    /// assert_eq!(sum_by_col, vec![1+4, 2+5, 3+6])
1588    /// ```
1589    #[must_use]
1590    pub const fn iter_cols(&self) -> GridColIter<'_, T> {
1591        GridColIter {
1592            grid: self,
1593            col_start_index: 0,
1594            col_end_index: self.cols,
1595        }
1596    }
1597
1598    /// Swaps two elements in the Grid.
1599    /// Similar to `Vec::swap()`.
1600    ///
1601    /// # Panics
1602    ///
1603    /// Panics if either index is out of bounds.
1604    pub fn swap(&mut self, (row_a, col_a): (usize, usize), (row_b, col_b): (usize, usize)) {
1605        assert!(
1606            !(row_a >= self.rows || col_a >= self.cols),
1607            "grid index out of bounds: ({row_a},{col_a}) out of ({},{})",
1608            self.rows,
1609            self.cols
1610        );
1611        assert!(
1612            !(row_b >= self.rows || col_b >= self.cols),
1613            "grid index out of bounds: ({row_b},{col_b}) out of ({},{})",
1614            self.rows,
1615            self.cols
1616        );
1617
1618        let a_idx = self.get_index(row_a, col_a);
1619        let b_idx = self.get_index(row_b, col_b);
1620
1621        self.data.swap(a_idx, b_idx);
1622    }
1623}
1624
1625impl<T: Default> Grid<T> {
1626    /// Expands the grid with the given amount of rows filling the new rows with `T::default()`.
1627    /// If the grid has no rows or no columns, nothing will happen.
1628    ///
1629    /// # Examples
1630    ///
1631    /// ```
1632    /// use grid::*;
1633    /// let mut grid: Grid<u8> = grid![[1, 2, 3][3, 4, 5]];
1634    /// grid.expand_rows(2);
1635    /// assert_eq!(grid.rows(), 4);
1636    /// assert_eq!(grid[(2, 0)], 0);
1637    /// assert_eq!(grid[(2, 1)], 0);
1638    /// assert_eq!(grid[(2, 2)], 0);
1639    /// assert_eq!(grid[(3, 0)], 0);
1640    /// assert_eq!(grid[(3, 1)], 0);
1641    /// assert_eq!(grid[(3, 2)], 0);
1642    /// ```
1643    ///
1644    /// # Performance
1645    ///
1646    /// This method will be significantly slower if the grid uses a column-major memory layout.
1647    pub fn expand_rows(&mut self, rows: usize) {
1648        if rows > 0 && self.cols > 0 {
1649            self.data
1650                .resize_with(self.data.len() + rows * self.cols, T::default);
1651
1652            if self.order == Order::ColumnMajor {
1653                for row_added in 0..rows {
1654                    for i in (1..self.cols).rev() {
1655                        let total_rows = self.rows + row_added;
1656                        let col_idx = i * total_rows;
1657                        self.data[col_idx..col_idx + total_rows + i].rotate_right(i);
1658                    }
1659                }
1660            }
1661            self.rows += rows;
1662        }
1663    }
1664
1665    /// Expands the grid with the given amount of cols filling the new cols with `T::default()`.
1666    /// If the grid has no rows or no columns, nothing will happen.
1667    ///
1668    /// # Examples
1669    ///
1670    /// ```
1671    /// use grid::*;
1672    /// let mut grid: Grid<u8> = grid![[1, 2, 3][3, 4, 5]];
1673    /// grid.expand_cols(2);
1674    /// assert_eq!(grid.cols(), 5);
1675    /// assert_eq!(grid[(0, 3)], 0);
1676    /// assert_eq!(grid[(0, 4)], 0);
1677    /// assert_eq!(grid[(1, 3)], 0);
1678    /// assert_eq!(grid[(1, 4)], 0);
1679    /// ```
1680    ///
1681    /// # Performance
1682    ///
1683    /// This method will be significantly slower if the grid uses a row-major memory layout.
1684    pub fn expand_cols(&mut self, cols: usize) {
1685        if cols > 0 && self.rows > 0 {
1686            self.data
1687                .resize_with(self.data.len() + cols * self.rows, T::default);
1688
1689            if self.order == Order::RowMajor {
1690                for col_added in 0..cols {
1691                    for i in (1..self.rows).rev() {
1692                        let total_cols = self.cols + col_added;
1693                        let row_idx = i * total_cols;
1694                        self.data[row_idx..row_idx + total_cols + i].rotate_right(i);
1695                    }
1696                }
1697            }
1698            self.cols += cols;
1699        }
1700    }
1701
1702    /// Expands the grid by inserting a given amount of rows at the beginning, filling the new rows with `T::default()`.
1703    /// If the grid has no rows or no columns, nothing will happen.
1704    ///
1705    /// # Examples
1706    ///
1707    /// ```
1708    /// use grid::*;
1709    /// let mut grid: Grid<u8> = grid![[1, 2, 3][3, 4, 5]];
1710    /// grid.prepend_rows(2);
1711    /// assert_eq!(grid.rows(), 4);
1712    /// assert_eq!(grid[(0, 0)], 0);
1713    /// assert_eq!(grid[(0, 1)], 0);
1714    /// assert_eq!(grid[(0, 2)], 0);
1715    /// assert_eq!(grid[(1, 0)], 0);
1716    /// assert_eq!(grid[(1, 1)], 0);
1717    /// assert_eq!(grid[(1, 2)], 0);
1718    /// ```
1719    ///
1720    /// # Performance
1721    ///
1722    /// This method will be significantly slower if the grid uses a column-major memory layout.
1723    pub fn prepend_rows(&mut self, rows: usize) {
1724        if rows > 0 && self.cols > 0 {
1725            self.data
1726                .resize_with(self.data.len() + rows * self.cols, T::default);
1727
1728            match self.order {
1729                Order::RowMajor => {
1730                    for i in (0..self.rows).rev() {
1731                        let s = i * self.cols;
1732                        let e = (i + rows + 1) * self.cols;
1733                        self.data[s..e].rotate_left(self.cols);
1734                    }
1735                }
1736                Order::ColumnMajor => {
1737                    for row_added in 0..rows {
1738                        for i in (0..self.cols).rev() {
1739                            let total_rows = self.rows + row_added;
1740                            let col_idx = i * total_rows;
1741                            self.data[col_idx..=col_idx + total_rows + i].rotate_right(i + 1);
1742                        }
1743                    }
1744                }
1745            }
1746            self.rows += rows;
1747        }
1748    }
1749
1750    /// Expands the grid by inserting a given amount of columns at the beginning, filling the new columns with `T::default()`.
1751    /// If the grid has no rows or no columns, nothing will happen.
1752    ///
1753    /// # Examples
1754    ///
1755    /// ```
1756    /// use grid::*;
1757    /// let mut grid: Grid<u8> = grid![[1, 2, 3][3, 4, 5]];
1758    /// grid.prepend_cols(2);
1759    /// assert_eq!(grid.cols(), 5);
1760    /// assert_eq!(grid[(0, 0)], 0);
1761    /// assert_eq!(grid[(0, 1)], 0);
1762    /// assert_eq!(grid[(1, 0)], 0);
1763    /// assert_eq!(grid[(1, 1)], 0);
1764    /// ```
1765    ///
1766    /// # Performance
1767    ///
1768    /// This method will be significantly slower if the grid uses a row-major memory layout.
1769    pub fn prepend_cols(&mut self, cols: usize) {
1770        if cols > 0 && self.rows > 0 {
1771            self.data
1772                .resize_with(self.data.len() + cols * self.rows, T::default);
1773
1774            match self.order {
1775                Order::RowMajor => {
1776                    for col_added in 0..cols {
1777                        for i in (0..self.rows).rev() {
1778                            let total_cols = self.cols + col_added;
1779                            let row_idx = i * total_cols;
1780                            self.data[row_idx..=row_idx + total_cols + i].rotate_right(i + 1);
1781                        }
1782                    }
1783                }
1784                Order::ColumnMajor => {
1785                    for i in (0..self.cols).rev() {
1786                        let s = i * self.rows;
1787                        let e = (i + cols + 1) * self.rows;
1788                        self.data[s..e].rotate_left(self.rows);
1789                    }
1790                }
1791            }
1792            self.cols += cols;
1793        }
1794    }
1795}
1796
1797impl<T> Default for Grid<T> {
1798    fn default() -> Self {
1799        Self {
1800            data: Vec::default(),
1801            cols: 0,
1802            rows: 0,
1803            order: Order::default(),
1804        }
1805    }
1806}
1807
1808impl<T: Clone> Clone for Grid<T> {
1809    fn clone(&self) -> Self {
1810        Self {
1811            rows: self.rows,
1812            cols: self.cols,
1813            data: self.data.clone(),
1814            order: self.order,
1815        }
1816    }
1817}
1818
1819impl<T: hash::Hash> hash::Hash for Grid<T> {
1820    #[inline]
1821    fn hash<H: hash::Hasher>(&self, state: &mut H) {
1822        self.rows.hash(state);
1823        self.cols.hash(state);
1824        self.order.hash(state);
1825        self.data.hash(state);
1826    }
1827}
1828
1829impl<T> Index<(usize, usize)> for Grid<T> {
1830    type Output = T;
1831
1832    #[inline]
1833    fn index(&self, (row, col): (usize, usize)) -> &T {
1834        assert!(
1835            !(row >= self.rows || col >= self.cols),
1836            "grid index out of bounds: ({row},{col}) out of ({},{})",
1837            self.rows,
1838            self.cols
1839        );
1840        let index = self.get_index(row, col);
1841        &self.data[index]
1842    }
1843}
1844
1845impl<T> IndexMut<(usize, usize)> for Grid<T> {
1846    #[inline]
1847    fn index_mut(&mut self, (row, col): (usize, usize)) -> &mut T {
1848        assert!(
1849            !(row >= self.rows || col >= self.cols),
1850            "grid index out of bounds: ({row},{col}) out of ({},{})",
1851            self.rows,
1852            self.cols
1853        );
1854        let index = self.get_index(row, col);
1855        &mut self.data[index]
1856    }
1857}
1858
1859impl<T> IntoIterator for Grid<T> {
1860    type IntoIter = <Vec<T> as IntoIterator>::IntoIter;
1861    type Item = T;
1862
1863    fn into_iter(self) -> Self::IntoIter {
1864        self.data.into_iter()
1865    }
1866}
1867
1868impl<'a, T> IntoIterator for &'a Grid<T> {
1869    type IntoIter = core::slice::Iter<'a, T>;
1870    type Item = &'a T;
1871
1872    fn into_iter(self) -> Self::IntoIter {
1873        self.iter()
1874    }
1875}
1876
1877impl<'a, T> IntoIterator for &'a mut Grid<T> {
1878    type IntoIter = core::slice::IterMut<'a, T>;
1879    type Item = &'a mut T;
1880
1881    fn into_iter(self) -> Self::IntoIter {
1882        self.iter_mut()
1883    }
1884}
1885
1886impl<T: fmt::Debug> fmt::Debug for Grid<T> {
1887    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1888        write!(f, "[")?;
1889        if self.cols > 0 {
1890            if f.alternate() {
1891                writeln!(f)?;
1892                /*
1893                    WARNING
1894
1895                    Compound types becoming enormous as the entire `fmt::Debug` width is applied to each item individually.
1896                    For tuples and structs define padding and precision arguments manually to improve readability.
1897                */
1898                let width = f.width().unwrap_or_else(|| {
1899                    // Conditionally calculate the longest item by default.
1900                    self.data
1901                        .iter()
1902                        .map(|i| format!("{i:?}").len())
1903                        .max()
1904                        .unwrap()
1905                });
1906                let precision = f.precision().unwrap_or(2);
1907                for mut row in self.iter_rows().map(Iterator::peekable) {
1908                    write!(f, "    [")?;
1909                    while let Some(item) = row.next() {
1910                        write!(f, " {item:width$.precision$?}")?;
1911                        if row.peek().is_some() {
1912                            write!(f, ",")?;
1913                        }
1914                    }
1915                    writeln!(f, "]")?;
1916                }
1917            } else {
1918                for row in self.iter_rows() {
1919                    f.debug_list().entries(row).finish()?;
1920                }
1921            }
1922        }
1923        write!(f, "]")
1924    }
1925}
1926
1927impl<T: PartialEq> PartialEq for Grid<T> {
1928    fn eq(&self, other: &Self) -> bool {
1929        if self.rows != other.rows || self.cols != other.cols {
1930            return false;
1931        }
1932        if self.order == other.order {
1933            return self.data == other.data;
1934        }
1935        for (self_row, other_row) in core::iter::zip(self.iter_rows(), other.iter_rows()) {
1936            if self_row.ne(other_row) {
1937                return false;
1938            }
1939        }
1940        true
1941    }
1942}
1943
1944impl<T: Eq> Eq for Grid<T> {}
1945
1946impl<T> From<Vec<Vec<T>>> for Grid<T> {
1947    #[allow(clippy::redundant_closure_for_method_calls)]
1948    fn from(vec: Vec<Vec<T>>) -> Self {
1949        let cols = vec.first().map_or(0, |row| row.len());
1950        Self::from_vec_with_order(vec.into_iter().flatten().collect(), cols, Order::default())
1951    }
1952}
1953
1954impl<T: Clone> From<&Vec<Vec<T>>> for Grid<T> {
1955    #[allow(clippy::redundant_closure_for_method_calls)]
1956    fn from(vec: &Vec<Vec<T>>) -> Self {
1957        let cols = vec.first().map_or(0, |row| row.len());
1958        Self::from_vec_with_order(
1959            vec.clone().into_iter().flatten().collect(),
1960            cols,
1961            Order::default(),
1962        )
1963    }
1964}
1965
1966impl<T: Clone> From<&Vec<&Vec<T>>> for Grid<T> {
1967    #[allow(clippy::redundant_closure_for_method_calls)]
1968    fn from(vec: &Vec<&Vec<T>>) -> Self {
1969        let cols = vec.first().map_or(0, |row| row.len());
1970        Self::from_vec_with_order(
1971            vec.clone()
1972                .into_iter()
1973                .flat_map(|inner| inner.clone())
1974                .collect(),
1975            cols,
1976            Order::default(),
1977        )
1978    }
1979}
1980
1981impl<T> From<(Vec<T>, usize)> for Grid<T> {
1982    fn from(value: (Vec<T>, usize)) -> Self {
1983        Self::from_vec_with_order(value.0, value.1, Order::default())
1984    }
1985}
1986
1987impl<T: Clone> From<(&Vec<T>, usize)> for Grid<T> {
1988    fn from(value: (&Vec<T>, usize)) -> Self {
1989        Self::from_vec_with_order(value.0.clone(), value.1, Order::default())
1990    }
1991}
1992
1993impl<T: Clone> From<(&Vec<T>, &usize)> for Grid<T> {
1994    fn from(value: (&Vec<T>, &usize)) -> Self {
1995        Self::from_vec_with_order(value.0.clone(), *value.1, Order::default())
1996    }
1997}
1998
1999#[derive(Clone)]
2000pub struct GridRowIter<'a, T> {
2001    grid: &'a Grid<T>,
2002    row_start_index: usize,
2003    row_end_index: usize,
2004}
2005
2006#[derive(Clone)]
2007pub struct GridColIter<'a, T> {
2008    grid: &'a Grid<T>,
2009    col_start_index: usize,
2010    col_end_index: usize,
2011}
2012
2013impl<'a, T> Iterator for GridRowIter<'a, T> {
2014    type Item = StepBy<Iter<'a, T>>;
2015
2016    fn next(&mut self) -> Option<Self::Item> {
2017        if self.row_start_index >= self.row_end_index {
2018            return None;
2019        }
2020
2021        let row_iter = self.grid.iter_row(self.row_start_index);
2022        self.row_start_index += 1;
2023        Some(row_iter)
2024    }
2025
2026    fn size_hint(&self) -> (usize, Option<usize>) {
2027        let size = self.row_end_index - self.row_start_index;
2028        (size, Some(size))
2029    }
2030}
2031
2032impl<T> ExactSizeIterator for GridRowIter<'_, T> {}
2033
2034impl<T> DoubleEndedIterator for GridRowIter<'_, T> {
2035    fn next_back(&mut self) -> Option<Self::Item> {
2036        if self.row_start_index >= self.row_end_index {
2037            return None;
2038        }
2039
2040        let row_iter = self.grid.iter_row(self.row_end_index - 1);
2041        self.row_end_index -= 1;
2042        Some(row_iter)
2043    }
2044}
2045
2046impl<'a, T> Iterator for GridColIter<'a, T> {
2047    type Item = StepBy<Iter<'a, T>>;
2048
2049    fn next(&mut self) -> Option<Self::Item> {
2050        if self.col_start_index >= self.col_end_index {
2051            return None;
2052        }
2053
2054        let col_iter = self.grid.iter_col(self.col_start_index);
2055        self.col_start_index += 1;
2056        Some(col_iter)
2057    }
2058
2059    fn size_hint(&self) -> (usize, Option<usize>) {
2060        let size = self.col_end_index - self.col_start_index;
2061        (size, Some(size))
2062    }
2063}
2064
2065impl<T> ExactSizeIterator for GridColIter<'_, T> {}
2066
2067impl<T> DoubleEndedIterator for GridColIter<'_, T> {
2068    fn next_back(&mut self) -> Option<Self::Item> {
2069        if self.col_start_index >= self.col_end_index {
2070            return None;
2071        }
2072
2073        let col_iter = self.grid.iter_col(self.col_end_index - 1);
2074        self.col_end_index -= 1;
2075        Some(col_iter)
2076    }
2077}
2078
2079#[cfg(test)]
2080mod test {
2081    use super::*;
2082    #[cfg(not(feature = "std"))]
2083    use alloc::string::String;
2084
2085    fn test_grid<T>(grid: &Grid<T>, rows: usize, cols: usize, order: Order, data: &[T])
2086    where
2087        T: fmt::Debug + PartialEq,
2088    {
2089        assert_eq!(grid.rows, rows, "number of rows is unexpected");
2090        assert_eq!(grid.cols, cols, "number of cols is unexpected");
2091        assert_eq!(grid.order, order, "grid order is unexpected");
2092        assert_eq!(grid.data, data, "internal data is unexpected");
2093    }
2094
2095    #[test]
2096    fn from_1d_vec() {
2097        let grid: Grid<u8> = Grid::from((vec![1, 2, 3], 1));
2098        test_grid(&grid, 3, 1, Order::RowMajor, &[1, 2, 3]);
2099    }
2100
2101    #[test]
2102    #[should_panic]
2103    #[allow(clippy::should_panic_without_expect)]
2104    fn from_1d_vec_panic() {
2105        let _: Grid<u8> = Grid::from((vec![1, 2, 3], 2));
2106    }
2107
2108    #[test]
2109    fn from_1d_vec_reference() {
2110        let vec = vec![1, 2, 3];
2111        let grid: Grid<u8> = Grid::from((&vec, 1));
2112        test_grid(&grid, 3, 1, Order::RowMajor, &[1, 2, 3]);
2113    }
2114
2115    #[test]
2116    #[should_panic]
2117    #[allow(clippy::should_panic_without_expect)]
2118    fn from_1d_vec_reference_panic() {
2119        let vec = vec![1, 2, 3];
2120        let _: Grid<u8> = Grid::from((&vec, 2));
2121    }
2122
2123    #[test]
2124    fn from_1d_vec_reference_and_reference() {
2125        let vec = vec![1, 2, 3];
2126        let cols = 1;
2127        let grid: Grid<u8> = Grid::from((&vec, &cols));
2128        test_grid(&grid, 3, 1, Order::RowMajor, &[1, 2, 3]);
2129    }
2130
2131    #[test]
2132    #[should_panic]
2133    #[allow(clippy::should_panic_without_expect)]
2134    fn from_1d_vec_reference_and_reference_panic() {
2135        let vec = vec![1, 2, 3];
2136        let cols = 2;
2137        let _: Grid<u8> = Grid::from((&vec, &cols));
2138    }
2139
2140    #[test]
2141    fn from_2d_vec() {
2142        let grid: Grid<u8> = Grid::from(vec![vec![1, 2, 3], vec![4, 5, 6], vec![7, 8, 9]]);
2143        test_grid(&grid, 3, 3, Order::RowMajor, &[1, 2, 3, 4, 5, 6, 7, 8, 9]);
2144    }
2145
2146    #[test]
2147    #[should_panic]
2148    #[allow(clippy::should_panic_without_expect)]
2149    fn from_2d_vec_panic() {
2150        let _: Grid<u8> = Grid::from(vec![vec![1, 2, 3], vec![4, 5, 6], vec![7, 8]]);
2151    }
2152
2153    #[test]
2154    fn from_2d_vec_reference() {
2155        let vec = vec![vec![1, 2, 3], vec![4, 5, 6], vec![7, 8, 9]];
2156        let grid: Grid<u8> = Grid::from(&vec);
2157        test_grid(&grid, 3, 3, Order::RowMajor, &[1, 2, 3, 4, 5, 6, 7, 8, 9]);
2158    }
2159
2160    #[test]
2161    #[should_panic]
2162    #[allow(clippy::should_panic_without_expect)]
2163    fn from_2d_vec_reference_panic() {
2164        let vec = vec![vec![1, 2, 3], vec![4, 5, 6], vec![7, 8]];
2165        let _: Grid<u8> = Grid::from(&vec);
2166    }
2167
2168    #[test]
2169    fn from_2d_vec_reference_of_references() {
2170        let inner_vec1 = vec![1, 2, 3];
2171        let inner_vec2 = vec![4, 5, 6];
2172        let inner_vec3 = vec![7, 8, 9];
2173        let vec = vec![&inner_vec1, &inner_vec2, &inner_vec3];
2174        let grid: Grid<u8> = Grid::from(&vec);
2175        test_grid(&grid, 3, 3, Order::RowMajor, &[1, 2, 3, 4, 5, 6, 7, 8, 9]);
2176    }
2177
2178    #[test]
2179    #[should_panic]
2180    #[allow(clippy::should_panic_without_expect)]
2181    fn from_2d_vec_reference_of_references_panic() {
2182        let inner_vec1 = vec![1, 2, 3];
2183        let inner_vec2 = vec![4, 5, 6];
2184        let inner_vec3 = vec![7, 8];
2185        let vec = vec![&inner_vec1, &inner_vec2, &inner_vec3];
2186        let _: Grid<u8> = Grid::from(&vec);
2187    }
2188
2189    #[test]
2190    fn from_vec_zero_with_cols() {
2191        let grid: Grid<u8> = Grid::from_vec(vec![], 1);
2192        test_grid(&grid, 0, 0, Order::RowMajor, &[]);
2193    }
2194
2195    #[test]
2196    fn from_vec_zero() {
2197        let grid: Grid<u8> = Grid::from_vec(vec![], 0);
2198        test_grid(&grid, 0, 0, Order::RowMajor, &[]);
2199    }
2200
2201    #[test]
2202    #[should_panic]
2203    #[allow(clippy::should_panic_without_expect)]
2204    fn from_vec_panics_1() {
2205        let _: Grid<u8> = Grid::from_vec(vec![1, 2, 3], 0);
2206    }
2207
2208    #[test]
2209    #[should_panic]
2210    #[allow(clippy::should_panic_without_expect)]
2211    fn from_vec_panics_2() {
2212        let _: Grid<u8> = Grid::from_vec(vec![1, 2, 3], 2);
2213    }
2214
2215    #[test]
2216    fn from_vec_uses_original_vec() {
2217        let capacity = 10_000_000;
2218        let vec = Vec::with_capacity(capacity);
2219        let grid: Grid<u8> = Grid::from_vec(vec, 0);
2220        assert!(grid.into_vec().capacity() >= capacity);
2221    }
2222
2223    #[test]
2224    fn from_vec_with_order_zero_with_cols() {
2225        let grid: Grid<u8> = Grid::from_vec_with_order(vec![], 1, Order::ColumnMajor);
2226        test_grid(&grid, 0, 0, Order::ColumnMajor, &[]);
2227    }
2228
2229    #[test]
2230    fn from_vec_with_order_zero() {
2231        let grid: Grid<u8> = Grid::from_vec_with_order(vec![], 0, Order::ColumnMajor);
2232        test_grid(&grid, 0, 0, Order::ColumnMajor, &[]);
2233    }
2234
2235    #[test]
2236    #[should_panic]
2237    #[allow(clippy::should_panic_without_expect)]
2238    fn from_vec_with_order_panics_1() {
2239        let _: Grid<u8> = Grid::from_vec_with_order(vec![1, 2, 3], 0, Order::ColumnMajor);
2240    }
2241
2242    #[test]
2243    #[should_panic]
2244    #[allow(clippy::should_panic_without_expect)]
2245    fn from_vec_with_order_panics_2() {
2246        let _: Grid<u8> = Grid::from_vec_with_order(vec![1, 2, 3], 2, Order::ColumnMajor);
2247    }
2248
2249    #[test]
2250    fn from_vec_with_order_uses_original_vec() {
2251        let capacity = 10_000_000;
2252        let vec = Vec::with_capacity(capacity);
2253        let grid: Grid<u8> = Grid::from_vec_with_order(vec, 0, Order::ColumnMajor);
2254        assert!(grid.into_vec().capacity() >= capacity);
2255    }
2256
2257    #[test]
2258    fn insert_col_at_end() {
2259        let mut grid: Grid<u8> = Grid::from_vec_with_order(vec![1, 2, 3, 4], 2, Order::RowMajor);
2260        grid.insert_col(2, vec![5, 6]);
2261        test_grid(&grid, 2, 3, Order::RowMajor, &[1, 2, 5, 3, 4, 6]);
2262    }
2263
2264    #[test]
2265    #[should_panic]
2266    #[allow(clippy::should_panic_without_expect)]
2267    fn insert_col_out_of_idx() {
2268        let mut grid: Grid<u8> = Grid::from_vec_with_order(vec![1, 2, 3, 4], 2, Order::RowMajor);
2269        grid.insert_col(3, vec![4, 5]);
2270    }
2271
2272    #[test]
2273    fn insert_col_empty() {
2274        let mut grid: Grid<u8> = Grid::from_vec_with_order(vec![], 0, Order::RowMajor);
2275        grid.insert_col(0, vec![1, 2, 3]);
2276        test_grid(&grid, 3, 1, Order::RowMajor, &[1, 2, 3]);
2277    }
2278
2279    #[test]
2280    fn insert_col_at_end_column_major() {
2281        let mut grid: Grid<u8> = Grid::from_vec_with_order(vec![1, 3, 2, 4], 2, Order::ColumnMajor);
2282        grid.insert_col(2, vec![5, 6]);
2283        test_grid(&grid, 2, 3, Order::ColumnMajor, &[1, 3, 2, 4, 5, 6]);
2284    }
2285
2286    #[test]
2287    #[should_panic]
2288    #[allow(clippy::should_panic_without_expect)]
2289    fn insert_col_out_of_idx_column_major() {
2290        let mut grid: Grid<u8> = Grid::from_vec_with_order(vec![1, 3, 2, 4], 2, Order::ColumnMajor);
2291        grid.insert_col(3, vec![4, 5]);
2292    }
2293
2294    #[test]
2295    fn insert_col_empty_column_major() {
2296        let mut grid: Grid<u8> = Grid::from_vec_with_order(vec![], 0, Order::ColumnMajor);
2297        grid.insert_col(0, vec![1, 2, 3]);
2298        test_grid(&grid, 3, 1, Order::ColumnMajor, &[1, 2, 3]);
2299    }
2300
2301    #[test]
2302    fn insert_row_at_end() {
2303        let mut grid: Grid<u8> = Grid::from_vec_with_order(vec![1, 2, 3, 4], 2, Order::RowMajor);
2304        grid.insert_row(2, vec![5, 6]);
2305        test_grid(&grid, 3, 2, Order::RowMajor, &[1, 2, 3, 4, 5, 6]);
2306    }
2307
2308    #[test]
2309    fn insert_row_empty() {
2310        let mut grid: Grid<u8> = Grid::from_vec_with_order(vec![], 0, Order::RowMajor);
2311        grid.insert_row(0, vec![1, 2, 3]);
2312        test_grid(&grid, 1, 3, Order::RowMajor, &[1, 2, 3]);
2313    }
2314
2315    #[test]
2316    #[should_panic]
2317    #[allow(clippy::should_panic_without_expect)]
2318    fn insert_row_out_of_idx() {
2319        let mut grid: Grid<u8> = Grid::from_vec_with_order(vec![1, 2, 3, 4], 2, Order::RowMajor);
2320        grid.insert_row(3, vec![4, 5]);
2321    }
2322
2323    #[test]
2324    #[should_panic]
2325    #[allow(clippy::should_panic_without_expect)]
2326    fn insert_row_wrong_size_of_idx() {
2327        let mut grid: Grid<u8> = Grid::from_vec_with_order(vec![1, 2, 3, 4], 2, Order::RowMajor);
2328        grid.insert_row(1, vec![4, 5, 4]);
2329    }
2330
2331    #[test]
2332    fn insert_row_start() {
2333        let mut grid: Grid<u8> = Grid::from_vec_with_order(vec![1, 2, 3, 4], 2, Order::RowMajor);
2334        grid.insert_row(1, vec![5, 6]);
2335        test_grid(&grid, 3, 2, Order::RowMajor, &[1, 2, 5, 6, 3, 4]);
2336    }
2337
2338    #[test]
2339    fn insert_row_at_end_column_major() {
2340        let mut grid: Grid<u8> = Grid::from_vec_with_order(vec![1, 3, 2, 4], 2, Order::ColumnMajor);
2341        grid.insert_row(2, vec![5, 6]);
2342        test_grid(&grid, 3, 2, Order::ColumnMajor, &[1, 3, 5, 2, 4, 6]);
2343    }
2344
2345    #[test]
2346    fn insert_row_empty_column_major() {
2347        let mut grid: Grid<u8> = Grid::from_vec_with_order(vec![], 0, Order::ColumnMajor);
2348        grid.insert_row(0, vec![1, 2, 3]);
2349        test_grid(&grid, 1, 3, Order::ColumnMajor, &[1, 2, 3]);
2350    }
2351
2352    #[test]
2353    #[should_panic]
2354    #[allow(clippy::should_panic_without_expect)]
2355    fn insert_row_out_of_idx_column_major() {
2356        let mut grid: Grid<u8> = Grid::from_vec_with_order(vec![1, 2, 3, 4], 2, Order::ColumnMajor);
2357        grid.insert_row(3, vec![4, 5]);
2358    }
2359
2360    #[test]
2361    #[should_panic]
2362    #[allow(clippy::should_panic_without_expect)]
2363    fn insert_row_wrong_size_of_idx_column_major() {
2364        let mut grid: Grid<u8> = Grid::from_vec_with_order(vec![1, 2, 3, 4], 2, Order::ColumnMajor);
2365        grid.insert_row(1, vec![4, 5, 4]);
2366    }
2367
2368    #[test]
2369    fn insert_row_start_column_major() {
2370        let mut grid: Grid<u8> = Grid::from_vec_with_order(vec![1, 3, 2, 4], 2, Order::ColumnMajor);
2371        grid.insert_row(1, vec![5, 6]);
2372        test_grid(&grid, 3, 2, Order::ColumnMajor, &[1, 5, 3, 2, 6, 4]);
2373    }
2374
2375    #[test]
2376    fn pop_col_1x3() {
2377        let mut grid: Grid<u8> = Grid::from_vec_with_order(vec![1, 2, 3], 3, Order::RowMajor);
2378        assert_eq!(grid.pop_col(), Some(vec![3]));
2379        test_grid(&grid, 1, 2, Order::RowMajor, &[1, 2]);
2380        assert_eq!(grid.pop_col(), Some(vec![2]));
2381        test_grid(&grid, 1, 1, Order::RowMajor, &[1]);
2382        assert_eq!(grid.pop_col(), Some(vec![1]));
2383        test_grid(&grid, 0, 0, Order::RowMajor, &[]);
2384        assert_eq!(grid.pop_col(), None);
2385        test_grid(&grid, 0, 0, Order::RowMajor, &[]);
2386    }
2387
2388    #[test]
2389    fn pop_col_3x1() {
2390        let mut grid: Grid<u8> = Grid::from_vec_with_order(vec![1, 2, 3], 1, Order::RowMajor);
2391        assert_eq!(grid.pop_col(), Some(vec![1, 2, 3]));
2392        test_grid(&grid, 0, 0, Order::RowMajor, &[]);
2393        assert_eq!(grid.pop_col(), None);
2394        test_grid(&grid, 0, 0, Order::RowMajor, &[]);
2395    }
2396
2397    #[test]
2398    fn pop_col_2x2() {
2399        let mut grid: Grid<u8> = Grid::from_vec_with_order(vec![1, 2, 3, 4], 2, Order::RowMajor);
2400        assert_eq!(grid.pop_col(), Some(vec![2, 4]));
2401        assert_eq!(grid.size(), (2, 1));
2402        test_grid(&grid, 2, 1, Order::RowMajor, &[1, 3]);
2403        assert_eq!(grid.pop_col(), Some(vec![1, 3]));
2404        test_grid(&grid, 0, 0, Order::RowMajor, &[]);
2405        assert_eq!(grid.pop_col(), None);
2406        test_grid(&grid, 0, 0, Order::RowMajor, &[]);
2407    }
2408
2409    #[test]
2410    fn pop_col_3x4() {
2411        let internal = vec![1, 2, 3, 4, 11, 22, 33, 44, 111, 222, 333, 444];
2412        let mut grid: Grid<u16> = Grid::from_vec_with_order(internal, 4, Order::RowMajor);
2413        assert_eq!(grid.pop_col(), Some(vec![4, 44, 444]));
2414        let expected = [1, 2, 3, 11, 22, 33, 111, 222, 333];
2415        test_grid(&grid, 3, 3, Order::RowMajor, &expected);
2416        assert_eq!(grid.pop_col(), Some(vec![3, 33, 333]));
2417        test_grid(&grid, 3, 2, Order::RowMajor, &[1, 2, 11, 22, 111, 222]);
2418        assert_eq!(grid.pop_col(), Some(vec![2, 22, 222]));
2419        test_grid(&grid, 3, 1, Order::RowMajor, &[1, 11, 111]);
2420        assert_eq!(grid.pop_col(), Some(vec![1, 11, 111]));
2421        test_grid(&grid, 0, 0, Order::RowMajor, &[]);
2422        assert_eq!(grid.pop_col(), None);
2423        test_grid(&grid, 0, 0, Order::RowMajor, &[]);
2424    }
2425
2426    #[test]
2427    fn pop_col_empty() {
2428        let mut grid: Grid<u8> = Grid::from_vec_with_order(vec![], 0, Order::RowMajor);
2429        assert_eq!(grid.pop_col(), None);
2430        test_grid(&grid, 0, 0, Order::RowMajor, &[]);
2431    }
2432
2433    #[test]
2434    fn pop_col_1x3_column_major() {
2435        let mut grid: Grid<u8> = Grid::from_vec_with_order(vec![1, 2, 3], 3, Order::ColumnMajor);
2436        assert_eq!(grid.pop_col(), Some(vec![3]));
2437        test_grid(&grid, 1, 2, Order::ColumnMajor, &[1, 2]);
2438        assert_eq!(grid.pop_col(), Some(vec![2]));
2439        test_grid(&grid, 1, 1, Order::ColumnMajor, &[1]);
2440        assert_eq!(grid.pop_col(), Some(vec![1]));
2441        test_grid(&grid, 0, 0, Order::ColumnMajor, &[]);
2442        assert_eq!(grid.pop_col(), None);
2443        test_grid(&grid, 0, 0, Order::ColumnMajor, &[]);
2444    }
2445
2446    #[test]
2447    fn pop_col_3x1_column_major() {
2448        let mut grid: Grid<u8> = Grid::from_vec_with_order(vec![1, 2, 3], 1, Order::ColumnMajor);
2449        assert_eq!(grid.pop_col(), Some(vec![1, 2, 3]));
2450        test_grid(&grid, 0, 0, Order::ColumnMajor, &[]);
2451        assert_eq!(grid.pop_col(), None);
2452        test_grid(&grid, 0, 0, Order::ColumnMajor, &[]);
2453    }
2454
2455    #[test]
2456    fn pop_col_2x2_column_major() {
2457        let mut grid: Grid<u8> = Grid::from_vec_with_order(vec![1, 3, 2, 4], 2, Order::ColumnMajor);
2458        assert_eq!(grid.pop_col(), Some(vec![2, 4]));
2459        assert_eq!(grid.size(), (2, 1));
2460        test_grid(&grid, 2, 1, Order::ColumnMajor, &[1, 3]);
2461        assert_eq!(grid.pop_col(), Some(vec![1, 3]));
2462        test_grid(&grid, 0, 0, Order::ColumnMajor, &[]);
2463        assert_eq!(grid.pop_col(), None);
2464        test_grid(&grid, 0, 0, Order::ColumnMajor, &[]);
2465    }
2466
2467    #[test]
2468    fn pop_col_3x4_column_major() {
2469        let internal = vec![1, 11, 111, 2, 22, 222, 3, 33, 333, 4, 44, 444];
2470        let mut grid: Grid<u16> = Grid::from_vec_with_order(internal, 4, Order::ColumnMajor);
2471        assert_eq!(grid.pop_col(), Some(vec![4, 44, 444]));
2472        let expected = [1, 11, 111, 2, 22, 222, 3, 33, 333];
2473        test_grid(&grid, 3, 3, Order::ColumnMajor, &expected);
2474        assert_eq!(grid.pop_col(), Some(vec![3, 33, 333]));
2475        test_grid(&grid, 3, 2, Order::ColumnMajor, &[1, 11, 111, 2, 22, 222]);
2476        assert_eq!(grid.pop_col(), Some(vec![2, 22, 222]));
2477        test_grid(&grid, 3, 1, Order::ColumnMajor, &[1, 11, 111]);
2478        assert_eq!(grid.pop_col(), Some(vec![1, 11, 111]));
2479        test_grid(&grid, 0, 0, Order::ColumnMajor, &[]);
2480        assert_eq!(grid.pop_col(), None);
2481        test_grid(&grid, 0, 0, Order::ColumnMajor, &[]);
2482    }
2483
2484    #[test]
2485    fn pop_col_empty_column_major() {
2486        let mut grid: Grid<u8> = Grid::from_vec_with_order(vec![], 0, Order::ColumnMajor);
2487        assert_eq!(grid.pop_col(), None);
2488        test_grid(&grid, 0, 0, Order::ColumnMajor, &[]);
2489    }
2490
2491    #[test]
2492    fn pop_row_2x2() {
2493        let mut grid: Grid<u8> = Grid::from_vec(vec![1, 2, 3, 4], 2);
2494        assert_eq!(grid.pop_row(), Some(vec![3, 4]));
2495        test_grid(&grid, 1, 2, Order::RowMajor, &[1, 2]);
2496        assert_eq!(grid.pop_row(), Some(vec![1, 2]));
2497        test_grid(&grid, 0, 0, Order::RowMajor, &[]);
2498        assert_eq!(grid.pop_row(), None);
2499        test_grid(&grid, 0, 0, Order::RowMajor, &[]);
2500    }
2501
2502    #[test]
2503    fn pop_row_empty() {
2504        let mut grid: Grid<u8> = Grid::from_vec(vec![], 0);
2505        assert_eq!(grid.pop_row(), None);
2506        test_grid(&grid, 0, 0, Order::RowMajor, &[]);
2507    }
2508
2509    #[test]
2510    fn pop_row_2x2_column_major() {
2511        let mut grid: Grid<u8> = Grid::from_vec_with_order(vec![1, 3, 2, 4], 2, Order::ColumnMajor);
2512        assert_eq!(grid.pop_row(), Some(vec![3, 4]));
2513        test_grid(&grid, 1, 2, Order::ColumnMajor, &[1, 2]);
2514        assert_eq!(grid.pop_row(), Some(vec![1, 2]));
2515        test_grid(&grid, 0, 0, Order::ColumnMajor, &[]);
2516        assert_eq!(grid.pop_row(), None);
2517        test_grid(&grid, 0, 0, Order::ColumnMajor, &[]);
2518    }
2519
2520    #[test]
2521    fn pop_row_empty_column_major() {
2522        let mut grid: Grid<u8> = Grid::from_vec_with_order(vec![], 0, Order::ColumnMajor);
2523        assert_eq!(grid.pop_row(), None);
2524        test_grid(&grid, 0, 0, Order::ColumnMajor, &[]);
2525    }
2526
2527    #[test]
2528    fn ne_full_empty() {
2529        let g1 = Grid::from_vec(vec![1, 2, 3, 4], 2);
2530        let g2: Grid<u8> = grid![];
2531        assert_ne!(g1, g2);
2532    }
2533
2534    #[test]
2535    fn ne() {
2536        let g1 = Grid::from_vec(vec![1, 2, 3, 5], 2);
2537        let g2 = Grid::from_vec(vec![1, 2, 3, 4], 2);
2538        assert_ne!(g1, g2);
2539    }
2540
2541    #[test]
2542    fn ne_dif_rows() {
2543        let g1 = Grid::from_vec(vec![1, 2, 3, 4], 2);
2544        let g2 = Grid::from_vec(vec![1, 2, 3, 4], 1);
2545        assert_ne!(g1, g2);
2546    }
2547
2548    #[test]
2549    fn equal_empty() {
2550        let grid: Grid<char> = grid![];
2551        let grid2: Grid<char> = grid![];
2552        assert_eq!(grid, grid2);
2553    }
2554
2555    #[test]
2556    fn equal() {
2557        let grid: Grid<char> = grid![['a', 'b', 'c', 'd']['a', 'b', 'c', 'd']['a', 'b', 'c', 'd']];
2558        let grid2: Grid<char> = grid![['a', 'b', 'c', 'd']['a', 'b', 'c', 'd']['a', 'b', 'c', 'd']];
2559        assert_eq!(grid, grid2);
2560    }
2561
2562    #[test]
2563    fn equal_different_order() {
2564        let grid = Grid::from_vec_with_order(vec![1, 2, 3, 4], 2, Order::RowMajor);
2565        let grid2 = Grid::from_vec_with_order(vec![1, 3, 2, 4], 2, Order::ColumnMajor);
2566        assert_eq!(grid, grid2);
2567    }
2568
2569    #[test]
2570    fn equal_partial_eq() {
2571        let grid = grid![[1.0]];
2572        let grid2 = Grid::from_vec(vec![1.0], 1);
2573        assert_eq!(grid, grid2);
2574    }
2575
2576    #[test]
2577    fn ne_partial_eq() {
2578        let grid = grid![[f64::NAN]];
2579        assert_ne!(grid, grid);
2580    }
2581
2582    #[test]
2583    #[should_panic]
2584    #[allow(clippy::should_panic_without_expect)]
2585    fn idx_tup_out_of_col_bounds() {
2586        let grid: Grid<char> = grid![['a', 'b', 'c', 'd']['a', 'b', 'c', 'd']['a', 'b', 'c', 'd']];
2587        let _ = grid[(0, 5)];
2588    }
2589
2590    #[test]
2591    fn push_col_2x3() {
2592        let mut grid: Grid<u8> = grid![
2593                    [0, 1, 2]
2594                    [10, 11, 12]];
2595        grid.push_col(vec![3, 13]);
2596        test_grid(&grid, 2, 4, Order::RowMajor, &[0, 1, 2, 3, 10, 11, 12, 13]);
2597    }
2598
2599    #[test]
2600    fn push_col_3x4() {
2601        let mut grid: Grid<char> = grid![
2602                    ['a', 'b', 'c', 'd']
2603                    ['a', 'b', 'c', 'd']
2604                    ['a', 'b', 'c', 'd']];
2605        grid.push_col(vec!['x', 'y', 'z']);
2606        let expected = [
2607            'a', 'b', 'c', 'd', 'x', 'a', 'b', 'c', 'd', 'y', 'a', 'b', 'c', 'd', 'z',
2608        ];
2609        test_grid(&grid, 3, 5, Order::RowMajor, &expected);
2610    }
2611
2612    #[test]
2613    fn push_col_1x3() {
2614        let mut grid: Grid<char> = grid![['a', 'b', 'c']];
2615        grid.push_col(vec!['d']);
2616        test_grid(&grid, 1, 4, Order::RowMajor, &['a', 'b', 'c', 'd']);
2617    }
2618
2619    #[test]
2620    fn push_col_empty() {
2621        let mut grid: Grid<char> = grid![];
2622        grid.push_col(vec!['b', 'b', 'b', 'b']);
2623        test_grid(&grid, 4, 1, Order::RowMajor, &['b', 'b', 'b', 'b']);
2624    }
2625
2626    #[test]
2627    #[should_panic]
2628    #[allow(clippy::should_panic_without_expect)]
2629    fn push_col_wrong_size() {
2630        let mut grid: Grid<char> = grid![['a','a','a']['a','a','a']];
2631        grid.push_col(vec!['b']);
2632        grid.push_col(vec!['b', 'b']);
2633    }
2634
2635    #[test]
2636    #[should_panic]
2637    #[allow(clippy::should_panic_without_expect)]
2638    fn push_col_zero_len() {
2639        let mut grid: Grid<char> = grid![];
2640        grid.push_col(vec![]);
2641    }
2642
2643    #[test]
2644    fn push_col_2x3_column_major() {
2645        let internal = vec![0, 10, 1, 11, 2, 12];
2646        let mut grid: Grid<u8> = Grid::from_vec_with_order(internal, 3, Order::ColumnMajor);
2647        grid.push_col(vec![3, 13]);
2648        let expected = [0, 10, 1, 11, 2, 12, 3, 13];
2649        test_grid(&grid, 2, 4, Order::ColumnMajor, &expected);
2650    }
2651
2652    #[test]
2653    fn push_col_3x4_column_major() {
2654        let internal = vec!['a', 'a', 'a', 'b', 'b', 'b', 'c', 'c', 'c', 'd', 'd', 'd'];
2655        let mut grid: Grid<char> = Grid::from_vec_with_order(internal, 4, Order::ColumnMajor);
2656        grid.push_col(vec!['x', 'y', 'z']);
2657        let expected = [
2658            'a', 'a', 'a', 'b', 'b', 'b', 'c', 'c', 'c', 'd', 'd', 'd', 'x', 'y', 'z',
2659        ];
2660        test_grid(&grid, 3, 5, Order::ColumnMajor, &expected);
2661    }
2662
2663    #[test]
2664    fn push_col_1x3_column_major() {
2665        let mut grid: Grid<char> =
2666            Grid::from_vec_with_order(vec!['a', 'b', 'c'], 3, Order::ColumnMajor);
2667        grid.push_col(vec!['d']);
2668        test_grid(&grid, 1, 4, Order::ColumnMajor, &['a', 'b', 'c', 'd']);
2669    }
2670
2671    #[test]
2672    fn push_col_empty_column_major() {
2673        let mut grid: Grid<char> = Grid::new_with_order(0, 0, Order::ColumnMajor);
2674        grid.push_col(vec!['b', 'b', 'b', 'b']);
2675        test_grid(&grid, 4, 1, Order::ColumnMajor, &['b', 'b', 'b', 'b']);
2676    }
2677
2678    #[test]
2679    #[should_panic]
2680    #[allow(clippy::should_panic_without_expect)]
2681    fn push_col_wrong_size_column_major() {
2682        let mut grid: Grid<char> = Grid::init_with_order(2, 3, Order::ColumnMajor, 'a');
2683        grid.push_col(vec!['b']);
2684        grid.push_col(vec!['b', 'b']);
2685    }
2686
2687    #[test]
2688    #[should_panic]
2689    #[allow(clippy::should_panic_without_expect)]
2690    fn push_col_zero_len_column_major() {
2691        let mut grid: Grid<char> = Grid::new_with_order(0, 0, Order::ColumnMajor);
2692        grid.push_col(vec![]);
2693    }
2694
2695    #[test]
2696    fn push_row() {
2697        let mut grid: Grid<u8> = grid![[1, 2][3, 4]];
2698        grid.push_row(vec![5, 6]);
2699        test_grid(&grid, 3, 2, Order::RowMajor, &[1, 2, 3, 4, 5, 6]);
2700    }
2701
2702    #[test]
2703    fn push_row_empty() {
2704        let mut grid: Grid<char> = grid![];
2705        grid.push_row(vec!['b', 'b', 'b', 'b']);
2706        test_grid(&grid, 1, 4, Order::RowMajor, &['b', 'b', 'b', 'b']);
2707    }
2708
2709    #[test]
2710    #[should_panic]
2711    #[allow(clippy::should_panic_without_expect)]
2712    fn push_empty_row() {
2713        let mut grid = Grid::init(0, 1, 0);
2714        grid.push_row(vec![]);
2715    }
2716
2717    #[test]
2718    #[should_panic]
2719    #[allow(clippy::should_panic_without_expect)]
2720    fn push_row_wrong_size() {
2721        let mut grid: Grid<char> = grid![['a','a','a']['a','a','a']];
2722        grid.push_row(vec!['b']);
2723        grid.push_row(vec!['b', 'b', 'b', 'b']);
2724    }
2725
2726    #[test]
2727    fn push_row_column_major() {
2728        let mut grid: Grid<u8> = Grid::from_vec_with_order(vec![1, 3, 2, 4], 2, Order::ColumnMajor);
2729        grid.push_row(vec![5, 6]);
2730        test_grid(&grid, 3, 2, Order::ColumnMajor, &[1, 3, 5, 2, 4, 6]);
2731    }
2732
2733    #[test]
2734    fn push_row_empty_column_major() {
2735        let mut grid: Grid<char> = Grid::new_with_order(0, 0, Order::ColumnMajor);
2736        grid.push_row(vec!['b', 'b', 'b', 'b']);
2737        test_grid(&grid, 1, 4, Order::ColumnMajor, &['b', 'b', 'b', 'b']);
2738    }
2739
2740    #[test]
2741    #[should_panic]
2742    #[allow(clippy::should_panic_without_expect)]
2743    fn push_empty_row_column_major() {
2744        let mut grid = Grid::init_with_order(0, 1, Order::ColumnMajor, 0);
2745        grid.push_row(vec![]);
2746    }
2747
2748    #[test]
2749    #[should_panic]
2750    #[allow(clippy::should_panic_without_expect)]
2751    fn push_row_wrong_size_column_major() {
2752        let mut grid: Grid<char> =
2753            Grid::from_vec_with_order(vec!['a', 'a', 'a', 'a', 'a', 'a'], 3, Order::ColumnMajor);
2754        grid.push_row(vec!['b']);
2755        grid.push_row(vec!['b', 'b', 'b', 'b']);
2756    }
2757
2758    #[test]
2759    fn expand_rows() {
2760        let mut grid = Grid::from_vec_with_order(vec![1, 1, 1, 2, 2, 2], 3, Order::RowMajor);
2761        grid.expand_rows(2);
2762
2763        assert_eq!(grid.size(), (4, 3));
2764        assert_eq!(grid.order, Order::RowMajor);
2765        assert_eq!(grid.rows(), 4);
2766        assert_eq!(grid.cols(), 3);
2767        assert_eq!(grid.into_vec(), vec![1, 1, 1, 2, 2, 2, 0, 0, 0, 0, 0, 0]);
2768    }
2769
2770    #[test]
2771    fn expand_rows_column_major() {
2772        let mut grid = Grid::from_vec_with_order(vec![1, 2, 1, 2, 1, 2], 3, Order::ColumnMajor);
2773        grid.expand_rows(2);
2774
2775        assert_eq!(grid.size(), (4, 3));
2776        assert_eq!(grid.order, Order::ColumnMajor);
2777        assert_eq!(grid.rows(), 4);
2778        assert_eq!(grid.cols(), 3);
2779        assert_eq!(grid.into_vec(), vec![1, 2, 0, 0, 1, 2, 0, 0, 1, 2, 0, 0]);
2780    }
2781
2782    #[test]
2783    fn expand_rows_zero() {
2784        let mut grid = Grid::from_vec_with_order(vec![1, 1, 1], 3, Order::RowMajor);
2785        grid.expand_rows(0);
2786
2787        assert_eq!(grid.size(), (1, 3));
2788        assert_eq!(grid.order, Order::RowMajor);
2789        assert_eq!(grid.rows(), 1);
2790        assert_eq!(grid.cols(), 3);
2791        assert_eq!(grid.into_vec(), vec![1, 1, 1]);
2792    }
2793
2794    #[test]
2795    fn expand_rows_empty_grid() {
2796        let mut grid: Grid<u8> = Grid::init(0, 0, 0);
2797        grid.expand_rows(2);
2798
2799        assert_eq!(grid.size(), (0, 0));
2800        assert_eq!(grid.order, Order::RowMajor);
2801        assert_eq!(grid.rows(), 0);
2802        assert_eq!(grid.cols(), 0);
2803        assert_eq!(grid.into_vec(), Vec::<u8>::new());
2804    }
2805
2806    #[test]
2807    fn expand_cols() {
2808        let mut grid = Grid::from_vec_with_order(vec![1, 1, 1, 2, 2, 2], 3, Order::RowMajor);
2809        grid.expand_cols(2);
2810
2811        assert_eq!(grid.size(), (2, 5));
2812        assert_eq!(grid.order, Order::RowMajor);
2813        assert_eq!(grid.rows(), 2);
2814        assert_eq!(grid.cols(), 5);
2815        assert_eq!(grid.into_vec(), vec![1, 1, 1, 0, 0, 2, 2, 2, 0, 0]);
2816    }
2817
2818    #[test]
2819    fn expand_cols_column_major() {
2820        let mut grid = Grid::from_vec_with_order(vec![1, 2, 1, 2, 1, 2], 3, Order::ColumnMajor);
2821        grid.expand_cols(2);
2822
2823        assert_eq!(grid.size(), (2, 5));
2824        assert_eq!(grid.order, Order::ColumnMajor);
2825        assert_eq!(grid.rows(), 2);
2826        assert_eq!(grid.cols(), 5);
2827        assert_eq!(grid.into_vec(), vec![1, 2, 1, 2, 1, 2, 0, 0, 0, 0]);
2828    }
2829
2830    #[test]
2831    fn expand_cols_zero() {
2832        let mut grid = Grid::from_vec_with_order(vec![1, 2, 1, 2], 2, Order::RowMajor);
2833        grid.expand_cols(0);
2834
2835        assert_eq!(grid.size(), (2, 2));
2836        assert_eq!(grid.order, Order::RowMajor);
2837        assert_eq!(grid.rows(), 2);
2838        assert_eq!(grid.cols(), 2);
2839        assert_eq!(grid.into_vec(), vec![1, 2, 1, 2]);
2840    }
2841
2842    #[test]
2843    fn expand_cols_empty_grid() {
2844        let mut grid: Grid<u8> = Grid::init(0, 0, 0);
2845        grid.expand_cols(2);
2846
2847        assert_eq!(grid.size(), (0, 0));
2848        assert_eq!(grid.order, Order::RowMajor);
2849        assert_eq!(grid.rows(), 0);
2850        assert_eq!(grid.cols(), 0);
2851        assert_eq!(grid.into_vec(), Vec::<u8>::new());
2852    }
2853
2854    #[test]
2855    fn prepend_rows() {
2856        let mut grid = Grid::from_vec_with_order(vec![1, 1, 1, 2, 2, 2], 3, Order::RowMajor);
2857        grid.prepend_rows(2);
2858
2859        assert_eq!(grid.size(), (4, 3));
2860        assert_eq!(grid.order, Order::RowMajor);
2861        assert_eq!(grid.rows(), 4);
2862        assert_eq!(grid.cols(), 3);
2863        assert_eq!(grid.into_vec(), vec![0, 0, 0, 0, 0, 0, 1, 1, 1, 2, 2, 2]);
2864    }
2865
2866    #[test]
2867    fn prepend_rows_column_major() {
2868        let mut grid = Grid::from_vec_with_order(vec![1, 2, 1, 2, 1, 2], 3, Order::ColumnMajor);
2869        grid.prepend_rows(2);
2870
2871        assert_eq!(grid.size(), (4, 3));
2872        assert_eq!(grid.order, Order::ColumnMajor);
2873        assert_eq!(grid.rows(), 4);
2874        assert_eq!(grid.cols(), 3);
2875        assert_eq!(grid.into_vec(), vec![0, 0, 1, 2, 0, 0, 1, 2, 0, 0, 1, 2]);
2876    }
2877
2878    #[test]
2879    fn prepend_rows_zero() {
2880        let mut grid = Grid::from_vec_with_order(vec![1, 1, 1], 3, Order::RowMajor);
2881        grid.prepend_rows(0);
2882
2883        assert_eq!(grid.size(), (1, 3));
2884        assert_eq!(grid.order, Order::RowMajor);
2885        assert_eq!(grid.rows(), 1);
2886        assert_eq!(grid.cols(), 3);
2887        assert_eq!(grid.into_vec(), vec![1, 1, 1]);
2888    }
2889
2890    #[test]
2891    fn prepend_rows_empty_grid() {
2892        let mut grid: Grid<u8> = Grid::init(0, 0, 0);
2893        grid.prepend_rows(2);
2894
2895        assert_eq!(grid.size(), (0, 0));
2896        assert_eq!(grid.order, Order::RowMajor);
2897        assert_eq!(grid.rows(), 0);
2898        assert_eq!(grid.cols(), 0);
2899        assert_eq!(grid.into_vec(), Vec::<u8>::new());
2900    }
2901
2902    #[test]
2903    fn prepend_cols() {
2904        let mut grid = Grid::from_vec_with_order(vec![1, 1, 1, 2, 2, 2], 3, Order::RowMajor);
2905        grid.prepend_cols(2);
2906
2907        assert_eq!(grid.size(), (2, 5));
2908        assert_eq!(grid.order, Order::RowMajor);
2909        assert_eq!(grid.rows(), 2);
2910        assert_eq!(grid.cols(), 5);
2911        assert_eq!(grid.into_vec(), vec![0, 0, 1, 1, 1, 0, 0, 2, 2, 2]);
2912    }
2913
2914    #[test]
2915    fn prepend_cols_column_major() {
2916        let mut grid = Grid::from_vec_with_order(vec![1, 2, 1, 2, 1, 2], 3, Order::ColumnMajor);
2917        grid.prepend_cols(2);
2918
2919        assert_eq!(grid.size(), (2, 5));
2920        assert_eq!(grid.order, Order::ColumnMajor);
2921        assert_eq!(grid.rows(), 2);
2922        assert_eq!(grid.cols(), 5);
2923        assert_eq!(grid.into_vec(), vec![0, 0, 0, 0, 1, 2, 1, 2, 1, 2]);
2924    }
2925
2926    #[test]
2927    fn prepend_cols_zero() {
2928        let mut grid = Grid::from_vec_with_order(vec![1, 2, 1, 2], 2, Order::RowMajor);
2929        grid.prepend_cols(0);
2930
2931        assert_eq!(grid.size(), (2, 2));
2932        assert_eq!(grid.order, Order::RowMajor);
2933        assert_eq!(grid.rows(), 2);
2934        assert_eq!(grid.cols(), 2);
2935        assert_eq!(grid.into_vec(), vec![1, 2, 1, 2]);
2936    }
2937
2938    #[test]
2939    fn prepend_cols_empty_grid() {
2940        let mut grid: Grid<u8> = Grid::init(0, 0, 0);
2941        grid.prepend_cols(2);
2942
2943        assert_eq!(grid.size(), (0, 0));
2944        assert_eq!(grid.order, Order::RowMajor);
2945        assert_eq!(grid.rows(), 0);
2946        assert_eq!(grid.cols(), 0);
2947        assert_eq!(grid.into_vec(), Vec::<u8>::new());
2948    }
2949
2950    #[test]
2951    fn iter_row() {
2952        let grid = Grid::from_vec_with_order(vec![1, 2, 3, 4, 5, 6], 3, Order::RowMajor);
2953        let row: Vec<_> = grid.iter_row(1).collect();
2954        assert_eq!(row, [&4, &5, &6]);
2955    }
2956
2957    #[test]
2958    #[should_panic]
2959    #[allow(clippy::should_panic_without_expect)]
2960    fn iter_row_out_of_bound() {
2961        let grid = Grid::from_vec_with_order(vec![1, 2, 3, 4, 5, 6], 3, Order::RowMajor);
2962        let _ = grid.iter_row(3);
2963    }
2964
2965    #[test]
2966    #[should_panic]
2967    #[allow(clippy::should_panic_without_expect)]
2968    fn iter_row_zero() {
2969        let grid: Grid<u8> = Grid::from_vec_with_order(vec![], 0, Order::RowMajor);
2970        let _ = grid.iter_row(0);
2971    }
2972
2973    #[test]
2974    fn iter_row_rowumn_major() {
2975        let grid = Grid::from_vec_with_order(vec![1, 4, 2, 5, 3, 6], 3, Order::ColumnMajor);
2976        let row: Vec<_> = grid.iter_row(1).collect();
2977        assert_eq!(row, [&4, &5, &6]);
2978    }
2979
2980    #[test]
2981    #[should_panic]
2982    #[allow(clippy::should_panic_without_expect)]
2983    fn iter_row_rowumn_major_out_of_bound() {
2984        let grid = Grid::from_vec_with_order(vec![1, 4, 2, 5, 3, 6], 3, Order::ColumnMajor);
2985        let _ = grid.iter_row(3);
2986    }
2987
2988    #[test]
2989    #[should_panic]
2990    #[allow(clippy::should_panic_without_expect)]
2991    fn iter_row_rowumn_major_zero() {
2992        let grid: Grid<u8> = Grid::from_vec_with_order(vec![], 0, Order::ColumnMajor);
2993        let _ = grid.iter_row(0);
2994    }
2995
2996    #[test]
2997    fn iter_row_mut() {
2998        let mut grid = Grid::from_vec_with_order(vec![1, 2, 3, 4, 5, 6], 3, Order::RowMajor);
2999        let row: Vec<_> = grid.iter_row_mut(1).collect();
3000        assert_eq!(row, [&mut 4, &mut 5, &mut 6]);
3001    }
3002
3003    #[test]
3004    #[should_panic]
3005    #[allow(clippy::should_panic_without_expect)]
3006    fn iter_row_mut_out_of_bound() {
3007        let mut grid = Grid::from_vec_with_order(vec![1, 2, 3, 4, 5, 6], 3, Order::RowMajor);
3008        let _ = grid.iter_row_mut(3);
3009    }
3010
3011    #[test]
3012    #[should_panic]
3013    #[allow(clippy::should_panic_without_expect)]
3014    fn iter_row_mut_zero() {
3015        let mut grid: Grid<u8> = Grid::from_vec_with_order(vec![], 0, Order::RowMajor);
3016        let _ = grid.iter_row_mut(0);
3017    }
3018
3019    #[test]
3020    fn iter_row_mut_rowumn_major() {
3021        let mut grid = Grid::from_vec_with_order(vec![1, 4, 2, 5, 3, 6], 3, Order::ColumnMajor);
3022        let row: Vec<_> = grid.iter_row_mut(1).collect();
3023        assert_eq!(row, [&mut 4, &mut 5, &mut 6]);
3024    }
3025
3026    #[test]
3027    #[should_panic]
3028    #[allow(clippy::should_panic_without_expect)]
3029    fn iter_row_mut_rowumn_major_out_of_bound() {
3030        let mut grid = Grid::from_vec_with_order(vec![1, 4, 2, 5, 3, 6], 3, Order::ColumnMajor);
3031        let _ = grid.iter_row_mut(3);
3032    }
3033
3034    #[test]
3035    #[should_panic]
3036    #[allow(clippy::should_panic_without_expect)]
3037    fn iter_row_mut_rowumn_major_zero() {
3038        let mut grid: Grid<u8> = Grid::from_vec_with_order(vec![], 0, Order::ColumnMajor);
3039        let _ = grid.iter_row_mut(0);
3040    }
3041
3042    #[test]
3043    fn iter_col() {
3044        let grid = Grid::from_vec_with_order(vec![1, 2, 3, 4, 5, 6], 3, Order::RowMajor);
3045        let col: Vec<_> = grid.iter_col(1).collect();
3046        assert_eq!(col, [&2, &5]);
3047    }
3048
3049    #[test]
3050    #[should_panic]
3051    #[allow(clippy::should_panic_without_expect)]
3052    fn iter_col_out_of_bound() {
3053        let grid = Grid::from_vec_with_order(vec![1, 2, 3, 4, 5, 6], 3, Order::RowMajor);
3054        let _ = grid.iter_col(3);
3055    }
3056
3057    #[test]
3058    #[should_panic]
3059    #[allow(clippy::should_panic_without_expect)]
3060    fn iter_col_zero() {
3061        let grid: Grid<u8> = Grid::from_vec_with_order(vec![], 0, Order::RowMajor);
3062        let _ = grid.iter_col(0);
3063    }
3064
3065    #[test]
3066    fn iter_col_column_major() {
3067        let grid = Grid::from_vec_with_order(vec![1, 4, 2, 5, 3, 6], 3, Order::ColumnMajor);
3068        let col: Vec<_> = grid.iter_col(1).collect();
3069        assert_eq!(col, [&2, &5]);
3070    }
3071
3072    #[test]
3073    #[should_panic]
3074    #[allow(clippy::should_panic_without_expect)]
3075    fn iter_col_column_major_out_of_bound() {
3076        let grid = Grid::from_vec_with_order(vec![1, 4, 2, 5, 3, 6], 3, Order::ColumnMajor);
3077        let _ = grid.iter_col(3);
3078    }
3079
3080    #[test]
3081    #[should_panic]
3082    #[allow(clippy::should_panic_without_expect)]
3083    fn iter_col_column_major_zero() {
3084        let grid: Grid<u8> = Grid::from_vec_with_order(vec![], 0, Order::ColumnMajor);
3085        let _ = grid.iter_col(0);
3086    }
3087
3088    #[test]
3089    fn iter_col_mut() {
3090        let mut grid = Grid::from_vec_with_order(vec![1, 2, 3, 4, 5, 6], 3, Order::RowMajor);
3091        let col: Vec<_> = grid.iter_col_mut(1).collect();
3092        assert_eq!(col, [&mut 2, &mut 5]);
3093    }
3094
3095    #[test]
3096    #[should_panic]
3097    #[allow(clippy::should_panic_without_expect)]
3098    fn iter_col_mut_out_of_bound() {
3099        let mut grid = Grid::from_vec_with_order(vec![1, 2, 3, 4, 5, 6], 3, Order::RowMajor);
3100        let _ = grid.iter_col_mut(3);
3101    }
3102
3103    #[test]
3104    #[should_panic]
3105    #[allow(clippy::should_panic_without_expect)]
3106    fn iter_col_mut_zero() {
3107        let mut grid: Grid<u8> = Grid::from_vec_with_order(vec![], 0, Order::RowMajor);
3108        let _ = grid.iter_col_mut(0);
3109    }
3110
3111    #[test]
3112    fn iter_col_mut_column_major() {
3113        let mut grid = Grid::from_vec_with_order(vec![1, 4, 2, 5, 3, 6], 3, Order::ColumnMajor);
3114        let col: Vec<_> = grid.iter_col_mut(1).collect();
3115        assert_eq!(col, [&mut 2, &mut 5]);
3116    }
3117
3118    #[test]
3119    #[should_panic]
3120    #[allow(clippy::should_panic_without_expect)]
3121    fn iter_col_mut_column_major_out_of_bound() {
3122        let mut grid = Grid::from_vec_with_order(vec![1, 4, 2, 5, 3, 6], 3, Order::ColumnMajor);
3123        let _ = grid.iter_col_mut(3);
3124    }
3125
3126    #[test]
3127    #[should_panic]
3128    #[allow(clippy::should_panic_without_expect)]
3129    fn iter_col_mut_column_major_zero() {
3130        let mut grid: Grid<u8> = Grid::from_vec_with_order(vec![], 0, Order::ColumnMajor);
3131        let _ = grid.iter_col_mut(0);
3132    }
3133
3134    #[test]
3135    fn iter() {
3136        let grid: Grid<u8> = grid![[1,2][3,4]];
3137        let mut iter = grid.iter();
3138        assert_eq!(iter.next(), Some(&1));
3139        assert_eq!(iter.next(), Some(&2));
3140        assert_eq!(iter.next(), Some(&3));
3141        assert_eq!(iter.next(), Some(&4));
3142        assert_eq!(iter.next(), None);
3143    }
3144
3145    #[test]
3146    fn into_iter() {
3147        let grid: Grid<u8> = grid![[1,1][1,1]];
3148        for val in grid {
3149            assert_eq!(val, 1);
3150        }
3151    }
3152
3153    #[test]
3154    fn into_iter_ref() {
3155        let grid: Grid<u8> = grid![[1,1][1,1]];
3156        for val in &grid {
3157            assert_eq!(val, &1);
3158        }
3159    }
3160
3161    #[test]
3162    fn into_iter_mut() {
3163        let mut grid: Grid<u8> = grid![[1,1][1,1]];
3164        grid.fill(2);
3165        assert_eq!(grid, grid![[2, 2][2, 2]]);
3166    }
3167
3168    #[test]
3169    fn indexed_iter() {
3170        let grid: Grid<u8> = grid![[1,2][3,4]];
3171        let mut iter = grid.indexed_iter();
3172        assert_eq!(iter.next(), Some(((0, 0), &1)));
3173        assert_eq!(iter.next(), Some(((0, 1), &2)));
3174        assert_eq!(iter.next(), Some(((1, 0), &3)));
3175        assert_eq!(iter.next(), Some(((1, 1), &4)));
3176        assert_eq!(iter.next(), None);
3177    }
3178
3179    #[test]
3180    fn indexed_iter_empty() {
3181        let grid: Grid<u8> = Grid::new(0, 0);
3182        let mut iter = grid.indexed_iter();
3183        assert_eq!(iter.next(), None);
3184    }
3185
3186    #[test]
3187    fn indexed_into_iter() {
3188        let grid: Grid<u8> = grid![[1,2][3,4]];
3189        let mut iter = grid.indexed_into_iter();
3190        assert_eq!(iter.next(), Some(((0, 0), 1)));
3191        assert_eq!(iter.next(), Some(((0, 1), 2)));
3192        assert_eq!(iter.next(), Some(((1, 0), 3)));
3193        assert_eq!(iter.next(), Some(((1, 1), 4)));
3194        assert_eq!(iter.next(), None);
3195    }
3196
3197    #[test]
3198    fn indexed_iter_column_major() {
3199        let grid: Grid<u8> = Grid::from_vec_with_order(vec![1, 3, 2, 4], 2, Order::ColumnMajor);
3200        let mut iter = grid.indexed_iter();
3201        assert_eq!(iter.next(), Some(((0, 0), &1)));
3202        assert_eq!(iter.next(), Some(((1, 0), &3)));
3203        assert_eq!(iter.next(), Some(((0, 1), &2)));
3204        assert_eq!(iter.next(), Some(((1, 1), &4)));
3205        assert_eq!(iter.next(), None);
3206    }
3207
3208    #[test]
3209    fn indexed_iter_empty_column_major() {
3210        let grid: Grid<u8> = Grid::new_with_order(0, 0, Order::ColumnMajor);
3211        let mut iter = grid.indexed_iter();
3212        assert_eq!(iter.next(), None);
3213    }
3214
3215    #[test]
3216    fn indexed_iter_mut() {
3217        let mut grid: Grid<u8> = grid![[1,2][3,4]];
3218        let mut iter = grid.indexed_iter_mut();
3219        assert_eq!(iter.next(), Some(((0, 0), &mut 1)));
3220        assert_eq!(iter.next(), Some(((0, 1), &mut 2)));
3221        assert_eq!(iter.next(), Some(((1, 0), &mut 3)));
3222        assert_eq!(iter.next(), Some(((1, 1), &mut 4)));
3223        assert_eq!(iter.next(), None);
3224    }
3225
3226    #[test]
3227    fn indexed_iter_mut_empty() {
3228        let mut grid: Grid<u8> = Grid::new(0, 0);
3229        let mut iter = grid.indexed_iter_mut();
3230        assert_eq!(iter.next(), None);
3231    }
3232
3233    #[test]
3234    fn indexed_iter_mut_column_major() {
3235        let mut grid: Grid<u8> = Grid::from_vec_with_order(vec![1, 3, 2, 4], 2, Order::ColumnMajor);
3236        let mut iter = grid.indexed_iter_mut();
3237        assert_eq!(iter.next(), Some(((0, 0), &mut 1)));
3238        assert_eq!(iter.next(), Some(((1, 0), &mut 3)));
3239        assert_eq!(iter.next(), Some(((0, 1), &mut 2)));
3240        assert_eq!(iter.next(), Some(((1, 1), &mut 4)));
3241        assert_eq!(iter.next(), None);
3242    }
3243
3244    #[test]
3245    fn indexed_iter_mut_empty_column_major() {
3246        let mut grid: Grid<u8> = Grid::new_with_order(0, 0, Order::ColumnMajor);
3247        let mut iter = grid.indexed_iter_mut();
3248        assert_eq!(iter.next(), None);
3249    }
3250
3251    #[test]
3252    fn clear() {
3253        let mut grid: Grid<u8> = grid![[1, 2, 3]];
3254        assert!(!grid.is_empty());
3255        grid.clear();
3256        assert!(grid.is_empty());
3257    }
3258
3259    #[test]
3260    fn is_empty_false() {
3261        let grid: Grid<u8> = grid![[1, 2, 3]];
3262        assert!(!grid.is_empty());
3263    }
3264
3265    #[test]
3266    fn is_empty() {
3267        let mut g: Grid<u8> = grid![[]];
3268        assert!(g.is_empty());
3269        g = grid![];
3270        assert!(g.is_empty());
3271        g = Grid::from_vec(vec![], 0);
3272        assert!(g.is_empty());
3273        g = Grid::new(0, 0);
3274        assert!(g.is_empty());
3275        g = Grid::new(0, 1);
3276        assert!(g.is_empty());
3277        g = Grid::new(1, 0);
3278        assert!(g.is_empty());
3279        g = Grid::init(0, 0, 10);
3280        assert!(g.is_empty());
3281    }
3282
3283    #[test]
3284    fn fmt_empty() {
3285        let grid: Grid<u8> = grid![];
3286        assert_eq!(format!("{grid:?}"), "[]");
3287    }
3288
3289    #[test]
3290    fn fmt_row() {
3291        let grid: Grid<u8> = grid![[1, 2, 3]];
3292        assert_eq!(format!("{grid:?}"), "[[1, 2, 3]]");
3293    }
3294
3295    #[test]
3296    fn fmt_grid() {
3297        let grid: Grid<u8> = grid![[1,2,3][4,5,6][7,8,9]];
3298        assert_eq!(format!("{grid:?}"), "[[1, 2, 3][4, 5, 6][7, 8, 9]]");
3299    }
3300
3301    #[test]
3302    fn fmt_column_major() {
3303        let grid = Grid::from_vec_with_order(vec![1, 4, 2, 5, 3, 6], 3, Order::ColumnMajor);
3304        assert_eq!(format!("{grid:?}"), "[[1, 2, 3][4, 5, 6]]");
3305    }
3306
3307    #[test]
3308    fn fmt_pretty_empty() {
3309        let grid: Grid<f32> = grid![];
3310        assert_eq!(format!("{grid:#?}"), "[]");
3311    }
3312
3313    #[test]
3314    fn fmt_pretty_int() {
3315        let grid: Grid<u8> = grid![
3316            [1,2,3]
3317            [4,5,6]
3318            [7,8,95]
3319        ];
3320
3321        let expected_output = r"[
3322    [  1,  2,  3]
3323    [  4,  5,  6]
3324    [  7,  8, 95]
3325]";
3326
3327        assert_eq!(format!("{grid:#?}"), expected_output);
3328
3329        let expected_output = r"[
3330    [   1,   2,   3]
3331    [   4,   5,   6]
3332    [   7,   8,  95]
3333]";
3334
3335        assert_eq!(format!("{grid:#3?}"), expected_output);
3336    }
3337
3338    #[test]
3339    fn fmt_pretty_float() {
3340        let grid: Grid<f32> = grid![
3341            [1.5,2.6,3.44]
3342            [4.775,5.,6.]
3343            [7.1,8.23444,95.55]
3344        ];
3345
3346        let expected_output = r"[
3347    [   1.5,   2.6,   3.4]
3348    [   4.8,   5.0,   6.0]
3349    [   7.1,   8.2,  95.6]
3350]";
3351
3352        assert_eq!(format!("{grid:#5.1?}"), expected_output);
3353
3354        let expected_output = r"[
3355    [  1.50000,  2.60000,  3.44000]
3356    [  4.77500,  5.00000,  6.00000]
3357    [  7.10000,  8.23444, 95.55000]
3358]";
3359
3360        assert_eq!(format!("{grid:#8.5?}"), expected_output);
3361    }
3362
3363    #[test]
3364    fn fmt_pretty_tuple() {
3365        let grid: Grid<(i32, i32)> = grid![
3366            [(5,66), (432, 55)]
3367            [(80, 90), (5, 6)]
3368        ];
3369
3370        let expected_output = r"[
3371    [ (        5,        66), (      432,        55)]
3372    [ (       80,        90), (        5,         6)]
3373]";
3374
3375        assert_eq!(format!("{grid:#?}"), expected_output);
3376
3377        let expected_output = r"[
3378    [ (  5,  66), (432,  55)]
3379    [ ( 80,  90), (  5,   6)]
3380]";
3381
3382        assert_eq!(format!("{grid:#3?}"), expected_output);
3383    }
3384
3385    #[test]
3386    fn fmt_pretty_struct_derived() {
3387        #[derive(Debug)]
3388        struct Person {
3389            _name: String,
3390            _precise_age: f32,
3391        }
3392
3393        impl Person {
3394            fn new(name: &str, precise_age: f32) -> Self {
3395                Self {
3396                    _name: name.into(),
3397                    _precise_age: precise_age,
3398                }
3399            }
3400        }
3401
3402        let grid: Grid<Person> = grid![
3403            [Person::new("Vic", 24.5), Person::new("Mr. Very Long Name", 1955.)]
3404            [Person::new("Sam", 8.9995), Person::new("John Doe", 40.14)]
3405        ];
3406
3407        let expected_output = r#"[
3408    [ Person { _name: "Vic", _precise_age: 24.50000 }, Person { _name: "Mr. Very Long Name", _precise_age: 1955.00000 }]
3409    [ Person { _name: "Sam", _precise_age: 8.99950 }, Person { _name: "John Doe", _precise_age: 40.14000 }]
3410]"#;
3411
3412        assert_eq!(format!("{grid:#5.5?}"), expected_output);
3413    }
3414
3415    #[test]
3416    fn fmt_pretty_column_major() {
3417        let grid = Grid::from_vec_with_order(vec![1, 4, 2, 5, 3, 6], 3, Order::ColumnMajor);
3418        let expected_output = r"[
3419    [ 1, 2, 3]
3420    [ 4, 5, 6]
3421]";
3422        assert_eq!(format!("{grid:#?}"), expected_output);
3423    }
3424
3425    #[test]
3426    fn clone() {
3427        let grid = grid![[1, 2, 3][4, 5, 6]];
3428        let mut clone = grid.clone();
3429        clone[(0, 2)] = 10;
3430        test_grid(&grid, 2, 3, Order::RowMajor, &[1, 2, 3, 4, 5, 6]);
3431        test_grid(&clone, 2, 3, Order::RowMajor, &[1, 2, 10, 4, 5, 6]);
3432    }
3433
3434    #[cfg(feature = "std")]
3435    #[test]
3436    fn hash_std() {
3437        let mut set = std::collections::HashSet::new();
3438        set.insert(grid![[1,2,3][4,5,6]]);
3439        set.insert(grid![[1,3,3][4,5,6]]);
3440        set.insert(grid![[1,2,3][4,5,6]]);
3441        assert_eq!(set.len(), 2);
3442    }
3443
3444    #[test]
3445    fn macro_init() {
3446        let grid = grid![[1, 2, 3][4, 5, 6]];
3447        test_grid(&grid, 2, 3, Order::RowMajor, &[1, 2, 3, 4, 5, 6]);
3448    }
3449
3450    #[test]
3451    fn macro_init_2() {
3452        let grid = grid![[1, 2, 3]
3453                         [4, 5, 6]
3454                         [7, 8, 9]];
3455        test_grid(&grid, 3, 3, Order::RowMajor, &[1, 2, 3, 4, 5, 6, 7, 8, 9]);
3456    }
3457
3458    #[test]
3459    fn macro_init_char() {
3460        let grid = grid![['a', 'b', 'c']
3461                         ['a', 'b', 'c']
3462                         ['a', 'b', 'c']];
3463        let expected = ['a', 'b', 'c', 'a', 'b', 'c', 'a', 'b', 'c'];
3464        test_grid(&grid, 3, 3, Order::RowMajor, &expected);
3465    }
3466
3467    #[test]
3468    fn macro_one_row() {
3469        let grid: Grid<usize> = grid![[1, 2, 3, 4]];
3470        test_grid(&grid, 1, 4, Order::RowMajor, &[1, 2, 3, 4]);
3471    }
3472
3473    #[test]
3474    fn macro2_empty() {
3475        let grid: Grid<u8> = grid_cm![];
3476        test_grid(&grid, 0, 0, Order::ColumnMajor, &[]);
3477    }
3478
3479    #[test]
3480    fn macro2_init() {
3481        let grid = grid_cm![[1, 2, 3]
3482                          [4, 5, 6]
3483                          [7, 8, 9]];
3484        let expected = [1, 4, 7, 2, 5, 8, 3, 6, 9];
3485        test_grid(&grid, 3, 3, Order::ColumnMajor, &expected);
3486    }
3487
3488    #[test]
3489    fn macro2_init_char() {
3490        let grid = grid_cm![['a', 'b']['c', 'd']];
3491        test_grid(&grid, 2, 2, Order::ColumnMajor, &['a', 'c', 'b', 'd']);
3492    }
3493
3494    #[test]
3495    fn macro2_one_row() {
3496        let grid = grid_cm![[1, 2, 3, 4]];
3497        test_grid(&grid, 1, 4, Order::ColumnMajor, &[1, 2, 3, 4]);
3498    }
3499
3500    #[test]
3501    fn init() {
3502        let grid = Grid::init(1, 2, 3);
3503        test_grid(&grid, 1, 2, Order::RowMajor, &[3, 3]);
3504
3505        let grid = Grid::init(1, 2, 1.2);
3506        test_grid(&grid, 1, 2, Order::RowMajor, &[1.2, 1.2]);
3507
3508        let grid = Grid::init(1, 2, 'a');
3509        test_grid(&grid, 1, 2, Order::RowMajor, &['a', 'a']);
3510    }
3511
3512    #[test]
3513    #[should_panic]
3514    #[allow(clippy::should_panic_without_expect)]
3515    fn init_panics() {
3516        Grid::init(usize::MAX, 2, 3);
3517    }
3518
3519    #[test]
3520    fn init_empty() {
3521        let grid = Grid::init(0, 1, 0);
3522        test_grid(&grid, 0, 0, Order::RowMajor, &[]);
3523
3524        let grid = Grid::init(1, 0, -1);
3525        test_grid(&grid, 0, 0, Order::RowMajor, &[]);
3526    }
3527
3528    #[test]
3529    fn init_with_order() {
3530        let grid = Grid::init_with_order(1, 2, Order::RowMajor, 3);
3531        test_grid(&grid, 1, 2, Order::RowMajor, &[3, 3]);
3532
3533        let grid = Grid::init_with_order(1, 2, Order::ColumnMajor, 1.2);
3534        test_grid(&grid, 1, 2, Order::ColumnMajor, &[1.2, 1.2]);
3535
3536        let grid = Grid::init_with_order(1, 2, Order::ColumnMajor, 'a');
3537        test_grid(&grid, 1, 2, Order::ColumnMajor, &['a', 'a']);
3538    }
3539
3540    #[test]
3541    #[should_panic]
3542    #[allow(clippy::should_panic_without_expect)]
3543    fn init_with_order_panics() {
3544        Grid::init_with_order(usize::MAX, 2, Order::ColumnMajor, 3);
3545    }
3546
3547    #[test]
3548    fn init_with_order_empty() {
3549        let grid = Grid::init_with_order(0, 1, Order::ColumnMajor, 0);
3550        test_grid(&grid, 0, 0, Order::ColumnMajor, &[]);
3551
3552        let grid = Grid::init_with_order(1, 0, Order::RowMajor, -1);
3553        test_grid(&grid, 0, 0, Order::RowMajor, &[]);
3554    }
3555
3556    #[test]
3557    fn new() {
3558        let grid: Grid<u8> = Grid::new(1, 2);
3559        test_grid(&grid, 1, 2, Order::RowMajor, &[0, 0]);
3560    }
3561
3562    #[test]
3563    #[should_panic]
3564    #[allow(clippy::should_panic_without_expect)]
3565    fn new_panics() {
3566        let _: Grid<u8> = Grid::new(usize::MAX, 2);
3567    }
3568
3569    #[test]
3570    fn new_empty() {
3571        let grid: Grid<u8> = Grid::new(0, 1);
3572        test_grid(&grid, 0, 0, Order::RowMajor, &[]);
3573
3574        let grid: Grid<u8> = Grid::new(1, 0);
3575        test_grid(&grid, 0, 0, Order::RowMajor, &[]);
3576    }
3577
3578    #[test]
3579    fn new_with_order() {
3580        let grid: Grid<u8> = Grid::new_with_order(2, 2, Order::ColumnMajor);
3581        test_grid(&grid, 2, 2, Order::ColumnMajor, &[0, 0, 0, 0]);
3582    }
3583
3584    #[test]
3585    #[should_panic]
3586    #[allow(clippy::should_panic_without_expect)]
3587    fn new_with_order_panics() {
3588        let _: Grid<u8> = Grid::new_with_order(usize::MAX, 2, Order::ColumnMajor);
3589    }
3590
3591    #[test]
3592    fn new_with_order_empty() {
3593        let grid: Grid<u8> = Grid::new_with_order(0, 3, Order::RowMajor);
3594        test_grid(&grid, 0, 0, Order::RowMajor, &[]);
3595
3596        let grid: Grid<u8> = Grid::new_with_order(3, 0, Order::ColumnMajor);
3597        test_grid(&grid, 0, 0, Order::ColumnMajor, &[]);
3598    }
3599
3600    #[test]
3601    fn with_capacity() {
3602        // doesn't impl Default
3603        struct Foo();
3604
3605        let grid: Grid<Foo> = Grid::with_capacity(20, 20);
3606        assert!(grid.is_empty());
3607        assert_eq!(grid.order(), Order::default());
3608    }
3609
3610    #[test]
3611    fn with_capacity_and_order() {
3612        // doesn't impl Default
3613        struct Foo();
3614
3615        let grid: Grid<Foo> = Grid::with_capacity_and_order(20, 20, Order::ColumnMajor);
3616        assert!(grid.is_empty());
3617        assert_eq!(grid.order(), Order::ColumnMajor);
3618    }
3619
3620    #[test]
3621    #[should_panic]
3622    #[allow(clippy::should_panic_without_expect)]
3623    fn with_capacity_panics_internal() {
3624        // doesn't impl Default
3625        struct Foo();
3626
3627        let _grid: Grid<Foo> = Grid::with_capacity_and_order(usize::MAX, 2, Order::RowMajor);
3628    }
3629
3630    #[test]
3631    #[should_panic]
3632    #[allow(clippy::should_panic_without_expect)]
3633    fn with_capacity_panics_vec() {
3634        let rows: usize = isize::MAX.try_into().expect("isize::MAX is positive");
3635        assert!(
3636            core::mem::size_of::<u8>() * rows < usize::MAX,
3637            "shows that panic is from Vec::with_capacity, not internal check"
3638        );
3639
3640        let _grid: Grid<u8> = Grid::with_capacity_and_order(rows, 2, Order::RowMajor);
3641    }
3642
3643    #[test]
3644    fn get() {
3645        let grid = Grid::from_vec_with_order(vec![1, 2], 2, Order::RowMajor);
3646        assert_eq!(grid.get(0_i64, 1_i32), Some(&2));
3647    }
3648
3649    #[test]
3650    fn get_column_major() {
3651        let grid = Grid::from_vec_with_order(vec![1, 2], 1, Order::ColumnMajor);
3652        assert_eq!(grid.get(1, 0), Some(&2));
3653    }
3654
3655    #[test]
3656    fn get_none() {
3657        let grid = Grid::from_vec_with_order(vec![1, 2], 2, Order::RowMajor);
3658        assert_eq!(grid.get(1, 0), None);
3659    }
3660
3661    #[test]
3662    fn get_none_column_major() {
3663        let grid = Grid::from_vec_with_order(vec![1, 2], 1, Order::ColumnMajor);
3664        assert_eq!(grid.get(0, 1), None);
3665    }
3666
3667    #[test]
3668    fn get_mut() {
3669        let mut grid = Grid::from_vec_with_order(vec![1, 2], 2, Order::RowMajor);
3670        assert_eq!(grid.get_mut(0_i64, 1_i32), Some(&mut 2));
3671    }
3672
3673    #[test]
3674    fn get_mut_column_major() {
3675        let mut grid = Grid::from_vec_with_order(vec![1, 2], 1, Order::ColumnMajor);
3676        assert_eq!(grid.get_mut(1, 0), Some(&mut 2));
3677    }
3678
3679    #[test]
3680    fn get_mut_none() {
3681        let mut grid = Grid::from_vec_with_order(vec![1, 2], 2, Order::RowMajor);
3682        assert_eq!(grid.get_mut(1, 0), None);
3683    }
3684
3685    #[test]
3686    fn get_mut_none_column_major() {
3687        let mut grid = Grid::from_vec_with_order(vec![1, 2], 1, Order::ColumnMajor);
3688        assert_eq!(grid.get_mut(0, 1), None);
3689    }
3690
3691    #[test]
3692    fn idx_tup() {
3693        let grid: Grid<u8> = Grid::from_vec(vec![1, 2, 3, 4], 2);
3694        assert_eq!(grid[(0, 0)], 1);
3695        assert_eq!(grid[(0, 1)], 2);
3696        assert_eq!(grid[(1, 0)], 3);
3697        assert_eq!(grid[(1, 1)], 4);
3698    }
3699
3700    #[test]
3701    #[should_panic]
3702    #[allow(clippy::should_panic_without_expect)]
3703    fn idx_tup_panic_1() {
3704        let grid = Grid::init(1, 2, 3);
3705        let _ = grid[(20, 0)];
3706    }
3707
3708    #[test]
3709    #[should_panic]
3710    #[allow(clippy::should_panic_without_expect)]
3711    fn idx_tup_panic_2() {
3712        let grid = Grid::init(1, 2, 3);
3713        let _ = grid[(0, 20)];
3714    }
3715
3716    #[test]
3717    fn idx_tup_set() {
3718        let mut grid = Grid::init(1, 2, 3);
3719        grid[(0, 0)] = 4;
3720        assert_eq!(grid[(0, 0)], 4);
3721    }
3722
3723    #[test]
3724    fn size() {
3725        let grid = Grid::init(1, 2, 3);
3726        assert_eq!(grid.size(), (1, 2));
3727    }
3728
3729    #[test]
3730    fn transpose() {
3731        let mut grid: Grid<u8> = grid![[1,2,3][4,5,6]];
3732        grid.transpose();
3733        assert_eq!(grid, grid![[1,4][2,5][3,6]]);
3734    }
3735
3736    #[test]
3737    fn fill() {
3738        let mut grid: Grid<u8> = grid![[1,2,3][4,5,6]];
3739        grid.fill(7);
3740        test_grid(&grid, 2, 3, Order::RowMajor, &[7, 7, 7, 7, 7, 7]);
3741    }
3742
3743    #[test]
3744    fn fill_with() {
3745        let mut grid: Grid<u8> = grid![[1,2,3][4,5,6]];
3746        grid.fill_with(Default::default);
3747        test_grid(&grid, 2, 3, Order::RowMajor, &[0, 0, 0, 0, 0, 0]);
3748    }
3749
3750    #[test]
3751    fn map() {
3752        let grid: Grid<u8> = grid![[1,2,3][4,5,6]];
3753        let mapped = grid.map(|x| x * 2);
3754        test_grid(&mapped, 2, 3, Order::RowMajor, &[2, 4, 6, 8, 10, 12]);
3755    }
3756
3757    #[test]
3758    fn map_ref() {
3759        let grid: Grid<u8> = grid![[1,2,3][4,5,6]];
3760        let mapped = grid.map_ref(|x| *x * 2);
3761        test_grid(&mapped, 2, 3, Order::RowMajor, &[2, 4, 6, 8, 10, 12]);
3762    }
3763
3764    #[test]
3765    #[allow(clippy::redundant_closure_for_method_calls)]
3766    fn iter_rows() {
3767        let grid: Grid<u8> = grid![[1,2,3][4,5,6]];
3768        let max_by_row: Vec<u8> = grid
3769            .iter_rows()
3770            .map(|row| row.max().unwrap())
3771            .copied()
3772            .collect();
3773        assert_eq!(max_by_row, vec![3, 6]);
3774
3775        let sum_by_row: Vec<u8> = grid.iter_rows().map(|row| row.sum()).collect();
3776        assert_eq!(sum_by_row, vec![1 + 2 + 3, 4 + 5 + 6]);
3777    }
3778
3779    #[test]
3780    #[allow(clippy::redundant_closure_for_method_calls)]
3781    fn iter_rows_rev() {
3782        let grid: Grid<u8> = grid![[1,2,3][4,5,6]];
3783        let max_by_row: Vec<u8> = grid
3784            .iter_rows()
3785            .rev()
3786            .map(|row| row.max().unwrap())
3787            .copied()
3788            .collect();
3789        assert_eq!(max_by_row, vec![6, 3]);
3790
3791        let sum_by_row: Vec<u8> = grid.iter_rows().rev().map(|row| row.sum()).collect();
3792        assert_eq!(sum_by_row, vec![4 + 5 + 6, 1 + 2 + 3]);
3793    }
3794
3795    #[test]
3796    fn iter_rows_exact_size() {
3797        let grid: Grid<u8> = grid![[1,2,3][4,5,6]];
3798        let mut row_iter = grid.iter_rows();
3799        assert_eq!(row_iter.len(), 2);
3800        assert!(row_iter.next().is_some());
3801        assert_eq!(row_iter.len(), 1);
3802        assert!(row_iter.next().is_some());
3803        assert_eq!(row_iter.len(), 0);
3804        assert!(row_iter.next().is_none());
3805    }
3806
3807    #[test]
3808    #[allow(clippy::redundant_closure_for_method_calls)]
3809    fn iter_cols() {
3810        let grid: Grid<u8> = grid![[1,2,3][4,5,6]];
3811        let max_by_col: Vec<u8> = grid
3812            .iter_cols()
3813            .map(|col| col.max().unwrap())
3814            .copied()
3815            .collect();
3816
3817        assert_eq!(max_by_col, vec![4, 5, 6]);
3818
3819        let sum_by_col: Vec<u8> = grid.iter_cols().map(|row| row.sum()).collect();
3820        assert_eq!(sum_by_col, vec![1 + 4, 2 + 5, 3 + 6]);
3821    }
3822
3823    #[test]
3824    #[allow(clippy::redundant_closure_for_method_calls)]
3825    fn iter_cols_rev() {
3826        let grid: Grid<u8> = grid![[1,2,3][4,5,6]];
3827        let max_by_col: Vec<u8> = grid
3828            .iter_cols()
3829            .rev()
3830            .map(|col| col.max().unwrap())
3831            .copied()
3832            .collect();
3833
3834        assert_eq!(max_by_col, vec![6, 5, 4]);
3835
3836        let sum_by_col: Vec<u8> = grid.iter_cols().rev().map(|row| row.sum()).collect();
3837        assert_eq!(sum_by_col, vec![3 + 6, 2 + 5, 1 + 4]);
3838    }
3839
3840    #[test]
3841    fn iter_cols_exact_size() {
3842        let grid: Grid<u8> = grid![[1,2,3][4,5,6]];
3843        let mut col_iter = grid.iter_cols();
3844        assert_eq!(col_iter.len(), 3);
3845        assert!(col_iter.next().is_some());
3846        assert_eq!(col_iter.len(), 2);
3847        assert!(col_iter.next().is_some());
3848        assert_eq!(col_iter.len(), 1);
3849        assert!(col_iter.next().is_some());
3850        assert_eq!(col_iter.len(), 0);
3851        assert!(col_iter.next().is_none());
3852    }
3853
3854    #[test]
3855    fn remove_row() {
3856        let mut grid = grid![[1,2][3,4][5,6]];
3857        assert_eq![grid.remove_row(1), Some(vec![3, 4])];
3858        test_grid(&grid, 2, 2, Order::RowMajor, &[1, 2, 5, 6]);
3859        assert_eq![grid.remove_row(0), Some(vec![1, 2])];
3860        test_grid(&grid, 1, 2, Order::RowMajor, &[5, 6]);
3861        assert_eq![grid.remove_row(0), Some(vec![5, 6])];
3862        test_grid(&grid, 0, 0, Order::RowMajor, &[]);
3863        assert_eq![grid.remove_row(0), None];
3864        test_grid(&grid, 0, 0, Order::RowMajor, &[]);
3865    }
3866
3867    #[test]
3868    fn remove_row_out_of_bound() {
3869        let mut grid = grid![[1, 2][3, 4]];
3870        assert_eq![grid.remove_row(5), None];
3871        test_grid(&grid, 2, 2, Order::RowMajor, &[1, 2, 3, 4]);
3872        assert_eq![grid.remove_row(1), Some(vec![3, 4])];
3873        test_grid(&grid, 1, 2, Order::RowMajor, &[1, 2]);
3874    }
3875
3876    #[test]
3877    fn remove_row_column_major() {
3878        let mut grid = Grid::from_vec_with_order(vec![1, 3, 5, 2, 4, 6], 2, Order::ColumnMajor);
3879        assert_eq![grid.remove_row(1), Some(vec![3, 4])];
3880        test_grid(&grid, 2, 2, Order::ColumnMajor, &[1, 5, 2, 6]);
3881        assert_eq![grid.remove_row(0), Some(vec![1, 2])];
3882        test_grid(&grid, 1, 2, Order::ColumnMajor, &[5, 6]);
3883        assert_eq![grid.remove_row(0), Some(vec![5, 6])];
3884        test_grid(&grid, 0, 0, Order::ColumnMajor, &[]);
3885        assert_eq![grid.remove_row(0), None];
3886        test_grid(&grid, 0, 0, Order::ColumnMajor, &[]);
3887    }
3888
3889    #[test]
3890    fn remove_row_out_of_bound_column_major() {
3891        let mut grid = Grid::from_vec_with_order(vec![1, 3, 2, 4], 2, Order::ColumnMajor);
3892        assert_eq![grid.remove_row(5), None];
3893        test_grid(&grid, 2, 2, Order::ColumnMajor, &[1, 3, 2, 4]);
3894        assert_eq![grid.remove_row(1), Some(vec![3, 4])];
3895        test_grid(&grid, 1, 2, Order::ColumnMajor, &[1, 2]);
3896    }
3897
3898    #[test]
3899    fn remove_col() {
3900        let mut grid = grid![[1,2,3,4][5,6,7,8][9,10,11,12][13,14,15,16]];
3901        assert_eq![grid.remove_col(3), Some(vec![4, 8, 12, 16])];
3902        let expected = [1, 2, 3, 5, 6, 7, 9, 10, 11, 13, 14, 15];
3903        test_grid(&grid, 4, 3, Order::RowMajor, &expected);
3904        assert_eq![grid.remove_col(0), Some(vec![1, 5, 9, 13])];
3905        test_grid(&grid, 4, 2, Order::RowMajor, &[2, 3, 6, 7, 10, 11, 14, 15]);
3906        assert_eq![grid.remove_col(1), Some(vec![3, 7, 11, 15])];
3907        test_grid(&grid, 4, 1, Order::RowMajor, &[2, 6, 10, 14]);
3908        assert_eq![grid.remove_col(0), Some(vec![2, 6, 10, 14])];
3909        test_grid(&grid, 0, 0, Order::RowMajor, &[]);
3910        assert_eq![grid.remove_col(0), None];
3911        test_grid(&grid, 0, 0, Order::RowMajor, &[]);
3912    }
3913
3914    #[test]
3915    fn remove_col_out_of_bound() {
3916        let mut grid = grid![[1, 2][3, 4]];
3917        assert_eq!(grid.remove_col(5), None);
3918        test_grid(&grid, 2, 2, Order::RowMajor, &[1, 2, 3, 4]);
3919        assert_eq!(grid.remove_col(1), Some(vec![2, 4]));
3920        test_grid(&grid, 2, 1, Order::RowMajor, &[1, 3]);
3921    }
3922
3923    #[test]
3924    fn remove_col_column_major() {
3925        let internal = vec![1, 5, 9, 13, 2, 6, 10, 14, 3, 7, 11, 15, 4, 8, 12, 16];
3926        let mut grid = Grid::from_vec_with_order(internal, 4, Order::ColumnMajor);
3927        assert_eq![grid.remove_col(3), Some(vec![4, 8, 12, 16])];
3928        let expected = [1, 5, 9, 13, 2, 6, 10, 14, 3, 7, 11, 15];
3929        test_grid(&grid, 4, 3, Order::ColumnMajor, &expected);
3930        assert_eq![grid.remove_col(0), Some(vec![1, 5, 9, 13])];
3931        let expected = [2, 6, 10, 14, 3, 7, 11, 15];
3932        test_grid(&grid, 4, 2, Order::ColumnMajor, &expected);
3933        assert_eq![grid.remove_col(1), Some(vec![3, 7, 11, 15])];
3934        test_grid(&grid, 4, 1, Order::ColumnMajor, &[2, 6, 10, 14]);
3935        assert_eq![grid.remove_col(0), Some(vec![2, 6, 10, 14])];
3936        test_grid(&grid, 0, 0, Order::ColumnMajor, &[]);
3937        assert_eq![grid.remove_col(0), None];
3938        test_grid(&grid, 0, 0, Order::ColumnMajor, &[]);
3939    }
3940
3941    #[test]
3942    fn remove_col_out_of_bound_column_major() {
3943        let mut grid = Grid::from_vec_with_order(vec![1, 3, 2, 4], 2, Order::ColumnMajor);
3944        assert_eq!(grid.remove_col(5), None);
3945        test_grid(&grid, 2, 2, Order::ColumnMajor, &[1, 3, 2, 4]);
3946        assert_eq!(grid.remove_col(1), Some(vec![2, 4]));
3947        test_grid(&grid, 2, 1, Order::ColumnMajor, &[1, 3]);
3948    }
3949
3950    #[test]
3951    fn flip_cols() {
3952        let mut grid = Grid::from_vec_with_order(vec![1, 2, 3, 4], 2, Order::RowMajor);
3953        grid.flip_cols();
3954        test_grid(&grid, 2, 2, Order::RowMajor, &[2, 1, 4, 3]);
3955    }
3956
3957    #[test]
3958    fn flip_cols_column_major() {
3959        let mut grid = Grid::from_vec_with_order(vec![1, 3, 2, 4], 2, Order::ColumnMajor);
3960        grid.flip_cols();
3961        test_grid(&grid, 2, 2, Order::ColumnMajor, &[2, 4, 1, 3]);
3962    }
3963
3964    #[test]
3965    fn flip_rows() {
3966        let mut grid = Grid::from_vec_with_order(vec![1, 2, 3, 4], 2, Order::RowMajor);
3967        grid.flip_rows();
3968        test_grid(&grid, 2, 2, Order::RowMajor, &[3, 4, 1, 2]);
3969    }
3970
3971    #[test]
3972    fn flip_rows_column_major() {
3973        let mut grid = Grid::from_vec_with_order(vec![1, 3, 2, 4], 2, Order::ColumnMajor);
3974        grid.flip_rows();
3975        test_grid(&grid, 2, 2, Order::ColumnMajor, &[3, 1, 4, 2]);
3976    }
3977
3978    #[test]
3979    fn rotate_left() {
3980        let mut grid = Grid::from_vec_with_order(vec![1, 2, 3, 4, 5, 6], 3, Order::RowMajor);
3981        grid.rotate_left();
3982        test_grid(&grid, 3, 2, Order::ColumnMajor, &[3, 2, 1, 6, 5, 4]);
3983        assert_eq!(grid, grid![[3,6][2,5][1,4]]);
3984    }
3985
3986    #[test]
3987    fn rotate_left_column_major() {
3988        let mut grid = Grid::from_vec_with_order(vec![1, 4, 2, 5, 3, 6], 3, Order::ColumnMajor);
3989        grid.rotate_left();
3990        test_grid(&grid, 3, 2, Order::RowMajor, &[3, 6, 2, 5, 1, 4]);
3991        assert_eq!(grid, grid![[3,6][2,5][1,4]]);
3992    }
3993
3994    #[test]
3995    fn rotate_right() {
3996        let mut grid = Grid::from_vec_with_order(vec![1, 2, 3, 4, 5, 6], 3, Order::RowMajor);
3997        grid.rotate_right();
3998        test_grid(&grid, 3, 2, Order::ColumnMajor, &[4, 5, 6, 1, 2, 3]);
3999        assert_eq!(grid, grid![[4,1][5,2][6,3]]);
4000    }
4001
4002    #[test]
4003    fn rotate_right_column_major() {
4004        let mut grid = Grid::from_vec_with_order(vec![1, 4, 2, 5, 3, 6], 3, Order::ColumnMajor);
4005        grid.rotate_right();
4006        test_grid(&grid, 3, 2, Order::RowMajor, &[4, 1, 5, 2, 6, 3]);
4007        assert_eq!(grid, grid![[4,1][5,2][6,3]]);
4008    }
4009
4010    #[test]
4011    fn iter_cols_clone() {
4012        let grid = grid![[1,2,3][4,5,6]];
4013        let mut cols = grid.iter_cols().skip(1);
4014        let c3: u8 = cols.clone().nth(1).unwrap().sum();
4015        let c2: u8 = cols.next().unwrap().sum();
4016        assert_eq!(c2, 2 + 5);
4017        assert_eq!(c3, 3 + 6);
4018    }
4019
4020    #[test]
4021    fn iter_rows_clone() {
4022        let grid = grid![[1,2,3][4,5,6][7,8,9]];
4023        let mut rows = grid.iter_rows().skip(1);
4024        let r3: u8 = rows.clone().nth(1).unwrap().sum();
4025        let r2: u8 = rows.next().unwrap().sum();
4026        assert_eq!(r2, 4 + 5 + 6);
4027        assert_eq!(r3, 7 + 8 + 9);
4028    }
4029
4030    #[test]
4031    fn swap() {
4032        let mut grid = grid![[1,2][4,5]];
4033        grid.swap((0, 0), (1, 0));
4034        let end_grid = grid![[4,2][1,5]];
4035        assert_eq!(grid, end_grid);
4036    }
4037
4038    #[test]
4039    #[should_panic(expected = "grid index out of bounds: (2,0) out of (2,2)")]
4040    fn swap_out_of_bounds() {
4041        let mut grid = grid![[1,2][4,5]];
4042        grid.swap((0, 0), (2, 0));
4043    }
4044
4045    #[cfg(feature = "serde")]
4046    mod serde_tests {
4047        use super::*;
4048
4049        #[test]
4050        fn serialize() {
4051            let grid: Grid<u8> = grid![[1, 2][3, 4]];
4052            let s = serde_json::to_string(&grid).unwrap();
4053            assert_eq!(s, r#"{"cols":2,"data":[1,2,3,4],"order":"RowMajor"}"#);
4054        }
4055
4056        #[test]
4057        fn deserialize() {
4058            let s = "{ \"cols\": 2, \"data\": [1, 2, 3, 4] }";
4059            let grid: Grid<u8> = serde_json::from_str(s).unwrap();
4060            assert_eq!(grid, grid![[1, 2][3, 4]]);
4061        }
4062
4063        #[test]
4064        fn deserialize_with_order() {
4065            let s = "{ \"cols\": 2, \"data\": [1, 3, 2, 4], \"order\": \"ColumnMajor\" }";
4066            let grid: Grid<u8> = serde_json::from_str(s).unwrap();
4067            test_grid(&grid, 2, 2, Order::ColumnMajor, &[1, 3, 2, 4]);
4068        }
4069    }
4070}