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
1703impl<T> Default for Grid<T> {
1704    fn default() -> Self {
1705        Self {
1706            data: Vec::default(),
1707            cols: 0,
1708            rows: 0,
1709            order: Order::default(),
1710        }
1711    }
1712}
1713
1714impl<T: Clone> Clone for Grid<T> {
1715    fn clone(&self) -> Self {
1716        Self {
1717            rows: self.rows,
1718            cols: self.cols,
1719            data: self.data.clone(),
1720            order: self.order,
1721        }
1722    }
1723}
1724
1725impl<T: hash::Hash> hash::Hash for Grid<T> {
1726    #[inline]
1727    fn hash<H: hash::Hasher>(&self, state: &mut H) {
1728        self.rows.hash(state);
1729        self.cols.hash(state);
1730        self.order.hash(state);
1731        self.data.hash(state);
1732    }
1733}
1734
1735impl<T> Index<(usize, usize)> for Grid<T> {
1736    type Output = T;
1737
1738    #[inline]
1739    fn index(&self, (row, col): (usize, usize)) -> &T {
1740        assert!(
1741            !(row >= self.rows || col >= self.cols),
1742            "grid index out of bounds: ({row},{col}) out of ({},{})",
1743            self.rows,
1744            self.cols
1745        );
1746        let index = self.get_index(row, col);
1747        &self.data[index]
1748    }
1749}
1750
1751impl<T> IndexMut<(usize, usize)> for Grid<T> {
1752    #[inline]
1753    fn index_mut(&mut self, (row, col): (usize, usize)) -> &mut T {
1754        assert!(
1755            !(row >= self.rows || col >= self.cols),
1756            "grid index out of bounds: ({row},{col}) out of ({},{})",
1757            self.rows,
1758            self.cols
1759        );
1760        let index = self.get_index(row, col);
1761        &mut self.data[index]
1762    }
1763}
1764
1765impl<T> IntoIterator for Grid<T> {
1766    type IntoIter = <Vec<T> as IntoIterator>::IntoIter;
1767    type Item = T;
1768
1769    fn into_iter(self) -> Self::IntoIter {
1770        self.data.into_iter()
1771    }
1772}
1773
1774impl<'a, T> IntoIterator for &'a Grid<T> {
1775    type IntoIter = core::slice::Iter<'a, T>;
1776    type Item = &'a T;
1777
1778    fn into_iter(self) -> Self::IntoIter {
1779        self.iter()
1780    }
1781}
1782
1783impl<'a, T> IntoIterator for &'a mut Grid<T> {
1784    type IntoIter = core::slice::IterMut<'a, T>;
1785    type Item = &'a mut T;
1786
1787    fn into_iter(self) -> Self::IntoIter {
1788        self.iter_mut()
1789    }
1790}
1791
1792impl<T: fmt::Debug> fmt::Debug for Grid<T> {
1793    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1794        write!(f, "[")?;
1795        if self.cols > 0 {
1796            if f.alternate() {
1797                writeln!(f)?;
1798                /*
1799                    WARNING
1800
1801                    Compound types becoming enormous as the entire `fmt::Debug` width is applied to each item individually.
1802                    For tuples and structs define padding and precision arguments manually to improve readability.
1803                */
1804                let width = f.width().unwrap_or_else(|| {
1805                    // Conditionally calculate the longest item by default.
1806                    self.data
1807                        .iter()
1808                        .map(|i| format!("{i:?}").len())
1809                        .max()
1810                        .unwrap()
1811                });
1812                let precision = f.precision().unwrap_or(2);
1813                for mut row in self.iter_rows().map(Iterator::peekable) {
1814                    write!(f, "    [")?;
1815                    while let Some(item) = row.next() {
1816                        write!(f, " {item:width$.precision$?}")?;
1817                        if row.peek().is_some() {
1818                            write!(f, ",")?;
1819                        }
1820                    }
1821                    writeln!(f, "]")?;
1822                }
1823            } else {
1824                for row in self.iter_rows() {
1825                    f.debug_list().entries(row).finish()?;
1826                }
1827            }
1828        }
1829        write!(f, "]")
1830    }
1831}
1832
1833impl<T: PartialEq> PartialEq for Grid<T> {
1834    fn eq(&self, other: &Self) -> bool {
1835        if self.rows != other.rows || self.cols != other.cols {
1836            return false;
1837        }
1838        if self.order == other.order {
1839            return self.data == other.data;
1840        }
1841        for (self_row, other_row) in core::iter::zip(self.iter_rows(), other.iter_rows()) {
1842            if self_row.ne(other_row) {
1843                return false;
1844            }
1845        }
1846        true
1847    }
1848}
1849
1850impl<T: Eq> Eq for Grid<T> {}
1851
1852impl<T> From<Vec<Vec<T>>> for Grid<T> {
1853    #[allow(clippy::redundant_closure_for_method_calls)]
1854    fn from(vec: Vec<Vec<T>>) -> Self {
1855        let cols = vec.first().map_or(0, |row| row.len());
1856        Self::from_vec_with_order(vec.into_iter().flatten().collect(), cols, Order::default())
1857    }
1858}
1859
1860impl<T: Clone> From<&Vec<Vec<T>>> for Grid<T> {
1861    #[allow(clippy::redundant_closure_for_method_calls)]
1862    fn from(vec: &Vec<Vec<T>>) -> Self {
1863        let cols = vec.first().map_or(0, |row| row.len());
1864        Self::from_vec_with_order(
1865            vec.clone().into_iter().flatten().collect(),
1866            cols,
1867            Order::default(),
1868        )
1869    }
1870}
1871
1872impl<T: Clone> From<&Vec<&Vec<T>>> for Grid<T> {
1873    #[allow(clippy::redundant_closure_for_method_calls)]
1874    fn from(vec: &Vec<&Vec<T>>) -> Self {
1875        let cols = vec.first().map_or(0, |row| row.len());
1876        Self::from_vec_with_order(
1877            vec.clone()
1878                .into_iter()
1879                .flat_map(|inner| inner.clone())
1880                .collect(),
1881            cols,
1882            Order::default(),
1883        )
1884    }
1885}
1886
1887impl<T> From<(Vec<T>, usize)> for Grid<T> {
1888    fn from(value: (Vec<T>, usize)) -> Self {
1889        Self::from_vec_with_order(value.0, value.1, Order::default())
1890    }
1891}
1892
1893impl<T: Clone> From<(&Vec<T>, usize)> for Grid<T> {
1894    fn from(value: (&Vec<T>, usize)) -> Self {
1895        Self::from_vec_with_order(value.0.clone(), value.1, Order::default())
1896    }
1897}
1898
1899impl<T: Clone> From<(&Vec<T>, &usize)> for Grid<T> {
1900    fn from(value: (&Vec<T>, &usize)) -> Self {
1901        Self::from_vec_with_order(value.0.clone(), *value.1, Order::default())
1902    }
1903}
1904
1905#[derive(Clone)]
1906pub struct GridRowIter<'a, T> {
1907    grid: &'a Grid<T>,
1908    row_start_index: usize,
1909    row_end_index: usize,
1910}
1911
1912#[derive(Clone)]
1913pub struct GridColIter<'a, T> {
1914    grid: &'a Grid<T>,
1915    col_start_index: usize,
1916    col_end_index: usize,
1917}
1918
1919impl<'a, T> Iterator for GridRowIter<'a, T> {
1920    type Item = StepBy<Iter<'a, T>>;
1921
1922    fn next(&mut self) -> Option<Self::Item> {
1923        if self.row_start_index >= self.row_end_index {
1924            return None;
1925        }
1926
1927        let row_iter = self.grid.iter_row(self.row_start_index);
1928        self.row_start_index += 1;
1929        Some(row_iter)
1930    }
1931
1932    fn size_hint(&self) -> (usize, Option<usize>) {
1933        let size = self.row_end_index - self.row_start_index;
1934        (size, Some(size))
1935    }
1936}
1937
1938impl<T> ExactSizeIterator for GridRowIter<'_, T> {}
1939
1940impl<T> DoubleEndedIterator for GridRowIter<'_, T> {
1941    fn next_back(&mut self) -> Option<Self::Item> {
1942        if self.row_start_index >= self.row_end_index {
1943            return None;
1944        }
1945
1946        let row_iter = self.grid.iter_row(self.row_end_index - 1);
1947        self.row_end_index -= 1;
1948        Some(row_iter)
1949    }
1950}
1951
1952impl<'a, T> Iterator for GridColIter<'a, T> {
1953    type Item = StepBy<Iter<'a, T>>;
1954
1955    fn next(&mut self) -> Option<Self::Item> {
1956        if self.col_start_index >= self.col_end_index {
1957            return None;
1958        }
1959
1960        let col_iter = self.grid.iter_col(self.col_start_index);
1961        self.col_start_index += 1;
1962        Some(col_iter)
1963    }
1964
1965    fn size_hint(&self) -> (usize, Option<usize>) {
1966        let size = self.col_end_index - self.col_start_index;
1967        (size, Some(size))
1968    }
1969}
1970
1971impl<T> ExactSizeIterator for GridColIter<'_, T> {}
1972
1973impl<T> DoubleEndedIterator for GridColIter<'_, T> {
1974    fn next_back(&mut self) -> Option<Self::Item> {
1975        if self.col_start_index >= self.col_end_index {
1976            return None;
1977        }
1978
1979        let col_iter = self.grid.iter_col(self.col_end_index - 1);
1980        self.col_end_index -= 1;
1981        Some(col_iter)
1982    }
1983}
1984
1985#[cfg(test)]
1986mod test {
1987    use super::*;
1988    #[cfg(not(feature = "std"))]
1989    use alloc::string::String;
1990
1991    fn test_grid<T>(grid: &Grid<T>, rows: usize, cols: usize, order: Order, data: &[T])
1992    where
1993        T: fmt::Debug + PartialEq,
1994    {
1995        assert_eq!(grid.rows, rows, "number of rows is unexpected");
1996        assert_eq!(grid.cols, cols, "number of cols is unexpected");
1997        assert_eq!(grid.order, order, "grid order is unexpected");
1998        assert_eq!(grid.data, data, "internal data is unexpected");
1999    }
2000
2001    #[test]
2002    fn from_1d_vec() {
2003        let grid: Grid<u8> = Grid::from((vec![1, 2, 3], 1));
2004        test_grid(&grid, 3, 1, Order::RowMajor, &[1, 2, 3]);
2005    }
2006
2007    #[test]
2008    #[should_panic]
2009    #[allow(clippy::should_panic_without_expect)]
2010    fn from_1d_vec_panic() {
2011        let _: Grid<u8> = Grid::from((vec![1, 2, 3], 2));
2012    }
2013
2014    #[test]
2015    fn from_1d_vec_reference() {
2016        let vec = vec![1, 2, 3];
2017        let grid: Grid<u8> = Grid::from((&vec, 1));
2018        test_grid(&grid, 3, 1, Order::RowMajor, &[1, 2, 3]);
2019    }
2020
2021    #[test]
2022    #[should_panic]
2023    #[allow(clippy::should_panic_without_expect)]
2024    fn from_1d_vec_reference_panic() {
2025        let vec = vec![1, 2, 3];
2026        let _: Grid<u8> = Grid::from((&vec, 2));
2027    }
2028
2029    #[test]
2030    fn from_1d_vec_reference_and_reference() {
2031        let vec = vec![1, 2, 3];
2032        let cols = 1;
2033        let grid: Grid<u8> = Grid::from((&vec, &cols));
2034        test_grid(&grid, 3, 1, Order::RowMajor, &[1, 2, 3]);
2035    }
2036
2037    #[test]
2038    #[should_panic]
2039    #[allow(clippy::should_panic_without_expect)]
2040    fn from_1d_vec_reference_and_reference_panic() {
2041        let vec = vec![1, 2, 3];
2042        let cols = 2;
2043        let _: Grid<u8> = Grid::from((&vec, &cols));
2044    }
2045
2046    #[test]
2047    fn from_2d_vec() {
2048        let grid: Grid<u8> = Grid::from(vec![vec![1, 2, 3], vec![4, 5, 6], vec![7, 8, 9]]);
2049        test_grid(&grid, 3, 3, Order::RowMajor, &[1, 2, 3, 4, 5, 6, 7, 8, 9]);
2050    }
2051
2052    #[test]
2053    #[should_panic]
2054    #[allow(clippy::should_panic_without_expect)]
2055    fn from_2d_vec_panic() {
2056        let _: Grid<u8> = Grid::from(vec![vec![1, 2, 3], vec![4, 5, 6], vec![7, 8]]);
2057    }
2058
2059    #[test]
2060    fn from_2d_vec_reference() {
2061        let vec = vec![vec![1, 2, 3], vec![4, 5, 6], vec![7, 8, 9]];
2062        let grid: Grid<u8> = Grid::from(&vec);
2063        test_grid(&grid, 3, 3, Order::RowMajor, &[1, 2, 3, 4, 5, 6, 7, 8, 9]);
2064    }
2065
2066    #[test]
2067    #[should_panic]
2068    #[allow(clippy::should_panic_without_expect)]
2069    fn from_2d_vec_reference_panic() {
2070        let vec = vec![vec![1, 2, 3], vec![4, 5, 6], vec![7, 8]];
2071        let _: Grid<u8> = Grid::from(&vec);
2072    }
2073
2074    #[test]
2075    fn from_2d_vec_reference_of_references() {
2076        let inner_vec1 = vec![1, 2, 3];
2077        let inner_vec2 = vec![4, 5, 6];
2078        let inner_vec3 = vec![7, 8, 9];
2079        let vec = vec![&inner_vec1, &inner_vec2, &inner_vec3];
2080        let grid: Grid<u8> = Grid::from(&vec);
2081        test_grid(&grid, 3, 3, Order::RowMajor, &[1, 2, 3, 4, 5, 6, 7, 8, 9]);
2082    }
2083
2084    #[test]
2085    #[should_panic]
2086    #[allow(clippy::should_panic_without_expect)]
2087    fn from_2d_vec_reference_of_references_panic() {
2088        let inner_vec1 = vec![1, 2, 3];
2089        let inner_vec2 = vec![4, 5, 6];
2090        let inner_vec3 = vec![7, 8];
2091        let vec = vec![&inner_vec1, &inner_vec2, &inner_vec3];
2092        let _: Grid<u8> = Grid::from(&vec);
2093    }
2094
2095    #[test]
2096    fn from_vec_zero_with_cols() {
2097        let grid: Grid<u8> = Grid::from_vec(vec![], 1);
2098        test_grid(&grid, 0, 0, Order::RowMajor, &[]);
2099    }
2100
2101    #[test]
2102    fn from_vec_zero() {
2103        let grid: Grid<u8> = Grid::from_vec(vec![], 0);
2104        test_grid(&grid, 0, 0, Order::RowMajor, &[]);
2105    }
2106
2107    #[test]
2108    #[should_panic]
2109    #[allow(clippy::should_panic_without_expect)]
2110    fn from_vec_panics_1() {
2111        let _: Grid<u8> = Grid::from_vec(vec![1, 2, 3], 0);
2112    }
2113
2114    #[test]
2115    #[should_panic]
2116    #[allow(clippy::should_panic_without_expect)]
2117    fn from_vec_panics_2() {
2118        let _: Grid<u8> = Grid::from_vec(vec![1, 2, 3], 2);
2119    }
2120
2121    #[test]
2122    fn from_vec_uses_original_vec() {
2123        let capacity = 10_000_000;
2124        let vec = Vec::with_capacity(capacity);
2125        let grid: Grid<u8> = Grid::from_vec(vec, 0);
2126        assert!(grid.into_vec().capacity() >= capacity);
2127    }
2128
2129    #[test]
2130    fn from_vec_with_order_zero_with_cols() {
2131        let grid: Grid<u8> = Grid::from_vec_with_order(vec![], 1, Order::ColumnMajor);
2132        test_grid(&grid, 0, 0, Order::ColumnMajor, &[]);
2133    }
2134
2135    #[test]
2136    fn from_vec_with_order_zero() {
2137        let grid: Grid<u8> = Grid::from_vec_with_order(vec![], 0, Order::ColumnMajor);
2138        test_grid(&grid, 0, 0, Order::ColumnMajor, &[]);
2139    }
2140
2141    #[test]
2142    #[should_panic]
2143    #[allow(clippy::should_panic_without_expect)]
2144    fn from_vec_with_order_panics_1() {
2145        let _: Grid<u8> = Grid::from_vec_with_order(vec![1, 2, 3], 0, Order::ColumnMajor);
2146    }
2147
2148    #[test]
2149    #[should_panic]
2150    #[allow(clippy::should_panic_without_expect)]
2151    fn from_vec_with_order_panics_2() {
2152        let _: Grid<u8> = Grid::from_vec_with_order(vec![1, 2, 3], 2, Order::ColumnMajor);
2153    }
2154
2155    #[test]
2156    fn from_vec_with_order_uses_original_vec() {
2157        let capacity = 10_000_000;
2158        let vec = Vec::with_capacity(capacity);
2159        let grid: Grid<u8> = Grid::from_vec_with_order(vec, 0, Order::ColumnMajor);
2160        assert!(grid.into_vec().capacity() >= capacity);
2161    }
2162
2163    #[test]
2164    fn insert_col_at_end() {
2165        let mut grid: Grid<u8> = Grid::from_vec_with_order(vec![1, 2, 3, 4], 2, Order::RowMajor);
2166        grid.insert_col(2, vec![5, 6]);
2167        test_grid(&grid, 2, 3, Order::RowMajor, &[1, 2, 5, 3, 4, 6]);
2168    }
2169
2170    #[test]
2171    #[should_panic]
2172    #[allow(clippy::should_panic_without_expect)]
2173    fn insert_col_out_of_idx() {
2174        let mut grid: Grid<u8> = Grid::from_vec_with_order(vec![1, 2, 3, 4], 2, Order::RowMajor);
2175        grid.insert_col(3, vec![4, 5]);
2176    }
2177
2178    #[test]
2179    fn insert_col_empty() {
2180        let mut grid: Grid<u8> = Grid::from_vec_with_order(vec![], 0, Order::RowMajor);
2181        grid.insert_col(0, vec![1, 2, 3]);
2182        test_grid(&grid, 3, 1, Order::RowMajor, &[1, 2, 3]);
2183    }
2184
2185    #[test]
2186    fn insert_col_at_end_column_major() {
2187        let mut grid: Grid<u8> = Grid::from_vec_with_order(vec![1, 3, 2, 4], 2, Order::ColumnMajor);
2188        grid.insert_col(2, vec![5, 6]);
2189        test_grid(&grid, 2, 3, Order::ColumnMajor, &[1, 3, 2, 4, 5, 6]);
2190    }
2191
2192    #[test]
2193    #[should_panic]
2194    #[allow(clippy::should_panic_without_expect)]
2195    fn insert_col_out_of_idx_column_major() {
2196        let mut grid: Grid<u8> = Grid::from_vec_with_order(vec![1, 3, 2, 4], 2, Order::ColumnMajor);
2197        grid.insert_col(3, vec![4, 5]);
2198    }
2199
2200    #[test]
2201    fn insert_col_empty_column_major() {
2202        let mut grid: Grid<u8> = Grid::from_vec_with_order(vec![], 0, Order::ColumnMajor);
2203        grid.insert_col(0, vec![1, 2, 3]);
2204        test_grid(&grid, 3, 1, Order::ColumnMajor, &[1, 2, 3]);
2205    }
2206
2207    #[test]
2208    fn insert_row_at_end() {
2209        let mut grid: Grid<u8> = Grid::from_vec_with_order(vec![1, 2, 3, 4], 2, Order::RowMajor);
2210        grid.insert_row(2, vec![5, 6]);
2211        test_grid(&grid, 3, 2, Order::RowMajor, &[1, 2, 3, 4, 5, 6]);
2212    }
2213
2214    #[test]
2215    fn insert_row_empty() {
2216        let mut grid: Grid<u8> = Grid::from_vec_with_order(vec![], 0, Order::RowMajor);
2217        grid.insert_row(0, vec![1, 2, 3]);
2218        test_grid(&grid, 1, 3, Order::RowMajor, &[1, 2, 3]);
2219    }
2220
2221    #[test]
2222    #[should_panic]
2223    #[allow(clippy::should_panic_without_expect)]
2224    fn insert_row_out_of_idx() {
2225        let mut grid: Grid<u8> = Grid::from_vec_with_order(vec![1, 2, 3, 4], 2, Order::RowMajor);
2226        grid.insert_row(3, vec![4, 5]);
2227    }
2228
2229    #[test]
2230    #[should_panic]
2231    #[allow(clippy::should_panic_without_expect)]
2232    fn insert_row_wrong_size_of_idx() {
2233        let mut grid: Grid<u8> = Grid::from_vec_with_order(vec![1, 2, 3, 4], 2, Order::RowMajor);
2234        grid.insert_row(1, vec![4, 5, 4]);
2235    }
2236
2237    #[test]
2238    fn insert_row_start() {
2239        let mut grid: Grid<u8> = Grid::from_vec_with_order(vec![1, 2, 3, 4], 2, Order::RowMajor);
2240        grid.insert_row(1, vec![5, 6]);
2241        test_grid(&grid, 3, 2, Order::RowMajor, &[1, 2, 5, 6, 3, 4]);
2242    }
2243
2244    #[test]
2245    fn insert_row_at_end_column_major() {
2246        let mut grid: Grid<u8> = Grid::from_vec_with_order(vec![1, 3, 2, 4], 2, Order::ColumnMajor);
2247        grid.insert_row(2, vec![5, 6]);
2248        test_grid(&grid, 3, 2, Order::ColumnMajor, &[1, 3, 5, 2, 4, 6]);
2249    }
2250
2251    #[test]
2252    fn insert_row_empty_column_major() {
2253        let mut grid: Grid<u8> = Grid::from_vec_with_order(vec![], 0, Order::ColumnMajor);
2254        grid.insert_row(0, vec![1, 2, 3]);
2255        test_grid(&grid, 1, 3, Order::ColumnMajor, &[1, 2, 3]);
2256    }
2257
2258    #[test]
2259    #[should_panic]
2260    #[allow(clippy::should_panic_without_expect)]
2261    fn insert_row_out_of_idx_column_major() {
2262        let mut grid: Grid<u8> = Grid::from_vec_with_order(vec![1, 2, 3, 4], 2, Order::ColumnMajor);
2263        grid.insert_row(3, vec![4, 5]);
2264    }
2265
2266    #[test]
2267    #[should_panic]
2268    #[allow(clippy::should_panic_without_expect)]
2269    fn insert_row_wrong_size_of_idx_column_major() {
2270        let mut grid: Grid<u8> = Grid::from_vec_with_order(vec![1, 2, 3, 4], 2, Order::ColumnMajor);
2271        grid.insert_row(1, vec![4, 5, 4]);
2272    }
2273
2274    #[test]
2275    fn insert_row_start_column_major() {
2276        let mut grid: Grid<u8> = Grid::from_vec_with_order(vec![1, 3, 2, 4], 2, Order::ColumnMajor);
2277        grid.insert_row(1, vec![5, 6]);
2278        test_grid(&grid, 3, 2, Order::ColumnMajor, &[1, 5, 3, 2, 6, 4]);
2279    }
2280
2281    #[test]
2282    fn pop_col_1x3() {
2283        let mut grid: Grid<u8> = Grid::from_vec_with_order(vec![1, 2, 3], 3, Order::RowMajor);
2284        assert_eq!(grid.pop_col(), Some(vec![3]));
2285        test_grid(&grid, 1, 2, Order::RowMajor, &[1, 2]);
2286        assert_eq!(grid.pop_col(), Some(vec![2]));
2287        test_grid(&grid, 1, 1, Order::RowMajor, &[1]);
2288        assert_eq!(grid.pop_col(), Some(vec![1]));
2289        test_grid(&grid, 0, 0, Order::RowMajor, &[]);
2290        assert_eq!(grid.pop_col(), None);
2291        test_grid(&grid, 0, 0, Order::RowMajor, &[]);
2292    }
2293
2294    #[test]
2295    fn pop_col_3x1() {
2296        let mut grid: Grid<u8> = Grid::from_vec_with_order(vec![1, 2, 3], 1, Order::RowMajor);
2297        assert_eq!(grid.pop_col(), Some(vec![1, 2, 3]));
2298        test_grid(&grid, 0, 0, Order::RowMajor, &[]);
2299        assert_eq!(grid.pop_col(), None);
2300        test_grid(&grid, 0, 0, Order::RowMajor, &[]);
2301    }
2302
2303    #[test]
2304    fn pop_col_2x2() {
2305        let mut grid: Grid<u8> = Grid::from_vec_with_order(vec![1, 2, 3, 4], 2, Order::RowMajor);
2306        assert_eq!(grid.pop_col(), Some(vec![2, 4]));
2307        assert_eq!(grid.size(), (2, 1));
2308        test_grid(&grid, 2, 1, Order::RowMajor, &[1, 3]);
2309        assert_eq!(grid.pop_col(), Some(vec![1, 3]));
2310        test_grid(&grid, 0, 0, Order::RowMajor, &[]);
2311        assert_eq!(grid.pop_col(), None);
2312        test_grid(&grid, 0, 0, Order::RowMajor, &[]);
2313    }
2314
2315    #[test]
2316    fn pop_col_3x4() {
2317        let internal = vec![1, 2, 3, 4, 11, 22, 33, 44, 111, 222, 333, 444];
2318        let mut grid: Grid<u16> = Grid::from_vec_with_order(internal, 4, Order::RowMajor);
2319        assert_eq!(grid.pop_col(), Some(vec![4, 44, 444]));
2320        let expected = [1, 2, 3, 11, 22, 33, 111, 222, 333];
2321        test_grid(&grid, 3, 3, Order::RowMajor, &expected);
2322        assert_eq!(grid.pop_col(), Some(vec![3, 33, 333]));
2323        test_grid(&grid, 3, 2, Order::RowMajor, &[1, 2, 11, 22, 111, 222]);
2324        assert_eq!(grid.pop_col(), Some(vec![2, 22, 222]));
2325        test_grid(&grid, 3, 1, Order::RowMajor, &[1, 11, 111]);
2326        assert_eq!(grid.pop_col(), Some(vec![1, 11, 111]));
2327        test_grid(&grid, 0, 0, Order::RowMajor, &[]);
2328        assert_eq!(grid.pop_col(), None);
2329        test_grid(&grid, 0, 0, Order::RowMajor, &[]);
2330    }
2331
2332    #[test]
2333    fn pop_col_empty() {
2334        let mut grid: Grid<u8> = Grid::from_vec_with_order(vec![], 0, Order::RowMajor);
2335        assert_eq!(grid.pop_col(), None);
2336        test_grid(&grid, 0, 0, Order::RowMajor, &[]);
2337    }
2338
2339    #[test]
2340    fn pop_col_1x3_column_major() {
2341        let mut grid: Grid<u8> = Grid::from_vec_with_order(vec![1, 2, 3], 3, Order::ColumnMajor);
2342        assert_eq!(grid.pop_col(), Some(vec![3]));
2343        test_grid(&grid, 1, 2, Order::ColumnMajor, &[1, 2]);
2344        assert_eq!(grid.pop_col(), Some(vec![2]));
2345        test_grid(&grid, 1, 1, Order::ColumnMajor, &[1]);
2346        assert_eq!(grid.pop_col(), Some(vec![1]));
2347        test_grid(&grid, 0, 0, Order::ColumnMajor, &[]);
2348        assert_eq!(grid.pop_col(), None);
2349        test_grid(&grid, 0, 0, Order::ColumnMajor, &[]);
2350    }
2351
2352    #[test]
2353    fn pop_col_3x1_column_major() {
2354        let mut grid: Grid<u8> = Grid::from_vec_with_order(vec![1, 2, 3], 1, Order::ColumnMajor);
2355        assert_eq!(grid.pop_col(), Some(vec![1, 2, 3]));
2356        test_grid(&grid, 0, 0, Order::ColumnMajor, &[]);
2357        assert_eq!(grid.pop_col(), None);
2358        test_grid(&grid, 0, 0, Order::ColumnMajor, &[]);
2359    }
2360
2361    #[test]
2362    fn pop_col_2x2_column_major() {
2363        let mut grid: Grid<u8> = Grid::from_vec_with_order(vec![1, 3, 2, 4], 2, Order::ColumnMajor);
2364        assert_eq!(grid.pop_col(), Some(vec![2, 4]));
2365        assert_eq!(grid.size(), (2, 1));
2366        test_grid(&grid, 2, 1, Order::ColumnMajor, &[1, 3]);
2367        assert_eq!(grid.pop_col(), Some(vec![1, 3]));
2368        test_grid(&grid, 0, 0, Order::ColumnMajor, &[]);
2369        assert_eq!(grid.pop_col(), None);
2370        test_grid(&grid, 0, 0, Order::ColumnMajor, &[]);
2371    }
2372
2373    #[test]
2374    fn pop_col_3x4_column_major() {
2375        let internal = vec![1, 11, 111, 2, 22, 222, 3, 33, 333, 4, 44, 444];
2376        let mut grid: Grid<u16> = Grid::from_vec_with_order(internal, 4, Order::ColumnMajor);
2377        assert_eq!(grid.pop_col(), Some(vec![4, 44, 444]));
2378        let expected = [1, 11, 111, 2, 22, 222, 3, 33, 333];
2379        test_grid(&grid, 3, 3, Order::ColumnMajor, &expected);
2380        assert_eq!(grid.pop_col(), Some(vec![3, 33, 333]));
2381        test_grid(&grid, 3, 2, Order::ColumnMajor, &[1, 11, 111, 2, 22, 222]);
2382        assert_eq!(grid.pop_col(), Some(vec![2, 22, 222]));
2383        test_grid(&grid, 3, 1, Order::ColumnMajor, &[1, 11, 111]);
2384        assert_eq!(grid.pop_col(), Some(vec![1, 11, 111]));
2385        test_grid(&grid, 0, 0, Order::ColumnMajor, &[]);
2386        assert_eq!(grid.pop_col(), None);
2387        test_grid(&grid, 0, 0, Order::ColumnMajor, &[]);
2388    }
2389
2390    #[test]
2391    fn pop_col_empty_column_major() {
2392        let mut grid: Grid<u8> = Grid::from_vec_with_order(vec![], 0, Order::ColumnMajor);
2393        assert_eq!(grid.pop_col(), None);
2394        test_grid(&grid, 0, 0, Order::ColumnMajor, &[]);
2395    }
2396
2397    #[test]
2398    fn pop_row_2x2() {
2399        let mut grid: Grid<u8> = Grid::from_vec(vec![1, 2, 3, 4], 2);
2400        assert_eq!(grid.pop_row(), Some(vec![3, 4]));
2401        test_grid(&grid, 1, 2, Order::RowMajor, &[1, 2]);
2402        assert_eq!(grid.pop_row(), Some(vec![1, 2]));
2403        test_grid(&grid, 0, 0, Order::RowMajor, &[]);
2404        assert_eq!(grid.pop_row(), None);
2405        test_grid(&grid, 0, 0, Order::RowMajor, &[]);
2406    }
2407
2408    #[test]
2409    fn pop_row_empty() {
2410        let mut grid: Grid<u8> = Grid::from_vec(vec![], 0);
2411        assert_eq!(grid.pop_row(), None);
2412        test_grid(&grid, 0, 0, Order::RowMajor, &[]);
2413    }
2414
2415    #[test]
2416    fn pop_row_2x2_column_major() {
2417        let mut grid: Grid<u8> = Grid::from_vec_with_order(vec![1, 3, 2, 4], 2, Order::ColumnMajor);
2418        assert_eq!(grid.pop_row(), Some(vec![3, 4]));
2419        test_grid(&grid, 1, 2, Order::ColumnMajor, &[1, 2]);
2420        assert_eq!(grid.pop_row(), Some(vec![1, 2]));
2421        test_grid(&grid, 0, 0, Order::ColumnMajor, &[]);
2422        assert_eq!(grid.pop_row(), None);
2423        test_grid(&grid, 0, 0, Order::ColumnMajor, &[]);
2424    }
2425
2426    #[test]
2427    fn pop_row_empty_column_major() {
2428        let mut grid: Grid<u8> = Grid::from_vec_with_order(vec![], 0, Order::ColumnMajor);
2429        assert_eq!(grid.pop_row(), None);
2430        test_grid(&grid, 0, 0, Order::ColumnMajor, &[]);
2431    }
2432
2433    #[test]
2434    fn ne_full_empty() {
2435        let g1 = Grid::from_vec(vec![1, 2, 3, 4], 2);
2436        let g2: Grid<u8> = grid![];
2437        assert_ne!(g1, g2);
2438    }
2439
2440    #[test]
2441    fn ne() {
2442        let g1 = Grid::from_vec(vec![1, 2, 3, 5], 2);
2443        let g2 = Grid::from_vec(vec![1, 2, 3, 4], 2);
2444        assert_ne!(g1, g2);
2445    }
2446
2447    #[test]
2448    fn ne_dif_rows() {
2449        let g1 = Grid::from_vec(vec![1, 2, 3, 4], 2);
2450        let g2 = Grid::from_vec(vec![1, 2, 3, 4], 1);
2451        assert_ne!(g1, g2);
2452    }
2453
2454    #[test]
2455    fn equal_empty() {
2456        let grid: Grid<char> = grid![];
2457        let grid2: Grid<char> = grid![];
2458        assert_eq!(grid, grid2);
2459    }
2460
2461    #[test]
2462    fn equal() {
2463        let grid: Grid<char> = grid![['a', 'b', 'c', 'd']['a', 'b', 'c', 'd']['a', 'b', 'c', 'd']];
2464        let grid2: Grid<char> = grid![['a', 'b', 'c', 'd']['a', 'b', 'c', 'd']['a', 'b', 'c', 'd']];
2465        assert_eq!(grid, grid2);
2466    }
2467
2468    #[test]
2469    fn equal_different_order() {
2470        let grid = Grid::from_vec_with_order(vec![1, 2, 3, 4], 2, Order::RowMajor);
2471        let grid2 = Grid::from_vec_with_order(vec![1, 3, 2, 4], 2, Order::ColumnMajor);
2472        assert_eq!(grid, grid2);
2473    }
2474
2475    #[test]
2476    fn equal_partial_eq() {
2477        let grid = grid![[1.0]];
2478        let grid2 = Grid::from_vec(vec![1.0], 1);
2479        assert_eq!(grid, grid2);
2480    }
2481
2482    #[test]
2483    fn ne_partial_eq() {
2484        let grid = grid![[f64::NAN]];
2485        assert_ne!(grid, grid);
2486    }
2487
2488    #[test]
2489    #[should_panic]
2490    #[allow(clippy::should_panic_without_expect)]
2491    fn idx_tup_out_of_col_bounds() {
2492        let grid: Grid<char> = grid![['a', 'b', 'c', 'd']['a', 'b', 'c', 'd']['a', 'b', 'c', 'd']];
2493        let _ = grid[(0, 5)];
2494    }
2495
2496    #[test]
2497    fn push_col_2x3() {
2498        let mut grid: Grid<u8> = grid![
2499                    [0, 1, 2]
2500                    [10, 11, 12]];
2501        grid.push_col(vec![3, 13]);
2502        test_grid(&grid, 2, 4, Order::RowMajor, &[0, 1, 2, 3, 10, 11, 12, 13]);
2503    }
2504
2505    #[test]
2506    fn push_col_3x4() {
2507        let mut grid: Grid<char> = grid![
2508                    ['a', 'b', 'c', 'd']
2509                    ['a', 'b', 'c', 'd']
2510                    ['a', 'b', 'c', 'd']];
2511        grid.push_col(vec!['x', 'y', 'z']);
2512        let expected = [
2513            'a', 'b', 'c', 'd', 'x', 'a', 'b', 'c', 'd', 'y', 'a', 'b', 'c', 'd', 'z',
2514        ];
2515        test_grid(&grid, 3, 5, Order::RowMajor, &expected);
2516    }
2517
2518    #[test]
2519    fn push_col_1x3() {
2520        let mut grid: Grid<char> = grid![['a', 'b', 'c']];
2521        grid.push_col(vec!['d']);
2522        test_grid(&grid, 1, 4, Order::RowMajor, &['a', 'b', 'c', 'd']);
2523    }
2524
2525    #[test]
2526    fn push_col_empty() {
2527        let mut grid: Grid<char> = grid![];
2528        grid.push_col(vec!['b', 'b', 'b', 'b']);
2529        test_grid(&grid, 4, 1, Order::RowMajor, &['b', 'b', 'b', 'b']);
2530    }
2531
2532    #[test]
2533    #[should_panic]
2534    #[allow(clippy::should_panic_without_expect)]
2535    fn push_col_wrong_size() {
2536        let mut grid: Grid<char> = grid![['a','a','a']['a','a','a']];
2537        grid.push_col(vec!['b']);
2538        grid.push_col(vec!['b', 'b']);
2539    }
2540
2541    #[test]
2542    #[should_panic]
2543    #[allow(clippy::should_panic_without_expect)]
2544    fn push_col_zero_len() {
2545        let mut grid: Grid<char> = grid![];
2546        grid.push_col(vec![]);
2547    }
2548
2549    #[test]
2550    fn push_col_2x3_column_major() {
2551        let internal = vec![0, 10, 1, 11, 2, 12];
2552        let mut grid: Grid<u8> = Grid::from_vec_with_order(internal, 3, Order::ColumnMajor);
2553        grid.push_col(vec![3, 13]);
2554        let expected = [0, 10, 1, 11, 2, 12, 3, 13];
2555        test_grid(&grid, 2, 4, Order::ColumnMajor, &expected);
2556    }
2557
2558    #[test]
2559    fn push_col_3x4_column_major() {
2560        let internal = vec!['a', 'a', 'a', 'b', 'b', 'b', 'c', 'c', 'c', 'd', 'd', 'd'];
2561        let mut grid: Grid<char> = Grid::from_vec_with_order(internal, 4, Order::ColumnMajor);
2562        grid.push_col(vec!['x', 'y', 'z']);
2563        let expected = [
2564            'a', 'a', 'a', 'b', 'b', 'b', 'c', 'c', 'c', 'd', 'd', 'd', 'x', 'y', 'z',
2565        ];
2566        test_grid(&grid, 3, 5, Order::ColumnMajor, &expected);
2567    }
2568
2569    #[test]
2570    fn push_col_1x3_column_major() {
2571        let mut grid: Grid<char> =
2572            Grid::from_vec_with_order(vec!['a', 'b', 'c'], 3, Order::ColumnMajor);
2573        grid.push_col(vec!['d']);
2574        test_grid(&grid, 1, 4, Order::ColumnMajor, &['a', 'b', 'c', 'd']);
2575    }
2576
2577    #[test]
2578    fn push_col_empty_column_major() {
2579        let mut grid: Grid<char> = Grid::new_with_order(0, 0, Order::ColumnMajor);
2580        grid.push_col(vec!['b', 'b', 'b', 'b']);
2581        test_grid(&grid, 4, 1, Order::ColumnMajor, &['b', 'b', 'b', 'b']);
2582    }
2583
2584    #[test]
2585    #[should_panic]
2586    #[allow(clippy::should_panic_without_expect)]
2587    fn push_col_wrong_size_column_major() {
2588        let mut grid: Grid<char> = Grid::init_with_order(2, 3, Order::ColumnMajor, 'a');
2589        grid.push_col(vec!['b']);
2590        grid.push_col(vec!['b', 'b']);
2591    }
2592
2593    #[test]
2594    #[should_panic]
2595    #[allow(clippy::should_panic_without_expect)]
2596    fn push_col_zero_len_column_major() {
2597        let mut grid: Grid<char> = Grid::new_with_order(0, 0, Order::ColumnMajor);
2598        grid.push_col(vec![]);
2599    }
2600
2601    #[test]
2602    fn push_row() {
2603        let mut grid: Grid<u8> = grid![[1, 2][3, 4]];
2604        grid.push_row(vec![5, 6]);
2605        test_grid(&grid, 3, 2, Order::RowMajor, &[1, 2, 3, 4, 5, 6]);
2606    }
2607
2608    #[test]
2609    fn push_row_empty() {
2610        let mut grid: Grid<char> = grid![];
2611        grid.push_row(vec!['b', 'b', 'b', 'b']);
2612        test_grid(&grid, 1, 4, Order::RowMajor, &['b', 'b', 'b', 'b']);
2613    }
2614
2615    #[test]
2616    #[should_panic]
2617    #[allow(clippy::should_panic_without_expect)]
2618    fn push_empty_row() {
2619        let mut grid = Grid::init(0, 1, 0);
2620        grid.push_row(vec![]);
2621    }
2622
2623    #[test]
2624    #[should_panic]
2625    #[allow(clippy::should_panic_without_expect)]
2626    fn push_row_wrong_size() {
2627        let mut grid: Grid<char> = grid![['a','a','a']['a','a','a']];
2628        grid.push_row(vec!['b']);
2629        grid.push_row(vec!['b', 'b', 'b', 'b']);
2630    }
2631
2632    #[test]
2633    fn push_row_column_major() {
2634        let mut grid: Grid<u8> = Grid::from_vec_with_order(vec![1, 3, 2, 4], 2, Order::ColumnMajor);
2635        grid.push_row(vec![5, 6]);
2636        test_grid(&grid, 3, 2, Order::ColumnMajor, &[1, 3, 5, 2, 4, 6]);
2637    }
2638
2639    #[test]
2640    fn push_row_empty_column_major() {
2641        let mut grid: Grid<char> = Grid::new_with_order(0, 0, Order::ColumnMajor);
2642        grid.push_row(vec!['b', 'b', 'b', 'b']);
2643        test_grid(&grid, 1, 4, Order::ColumnMajor, &['b', 'b', 'b', 'b']);
2644    }
2645
2646    #[test]
2647    #[should_panic]
2648    #[allow(clippy::should_panic_without_expect)]
2649    fn push_empty_row_column_major() {
2650        let mut grid = Grid::init_with_order(0, 1, Order::ColumnMajor, 0);
2651        grid.push_row(vec![]);
2652    }
2653
2654    #[test]
2655    #[should_panic]
2656    #[allow(clippy::should_panic_without_expect)]
2657    fn push_row_wrong_size_column_major() {
2658        let mut grid: Grid<char> =
2659            Grid::from_vec_with_order(vec!['a', 'a', 'a', 'a', 'a', 'a'], 3, Order::ColumnMajor);
2660        grid.push_row(vec!['b']);
2661        grid.push_row(vec!['b', 'b', 'b', 'b']);
2662    }
2663
2664    #[test]
2665    fn expand_rows() {
2666        let mut grid = Grid::from_vec_with_order(vec![1, 1, 1, 2, 2, 2], 3, Order::RowMajor);
2667        grid.expand_rows(2);
2668
2669        assert_eq!(grid.size(), (4, 3));
2670        assert_eq!(grid.order, Order::RowMajor);
2671        assert_eq!(grid.rows(), 4);
2672        assert_eq!(grid.cols(), 3);
2673        assert_eq!(grid.into_vec(), vec![1, 1, 1, 2, 2, 2, 0, 0, 0, 0, 0, 0]);
2674    }
2675
2676    #[test]
2677    fn expand_rows_column_major() {
2678        let mut grid = Grid::from_vec_with_order(vec![1, 2, 1, 2, 1, 2], 3, Order::ColumnMajor);
2679        grid.expand_rows(2);
2680
2681        assert_eq!(grid.size(), (4, 3));
2682        assert_eq!(grid.order, Order::ColumnMajor);
2683        assert_eq!(grid.rows(), 4);
2684        assert_eq!(grid.cols(), 3);
2685        assert_eq!(grid.into_vec(), vec![1, 2, 0, 0, 1, 2, 0, 0, 1, 2, 0, 0]);
2686    }
2687
2688    #[test]
2689    fn expand_rows_zero() {
2690        let mut grid = Grid::from_vec_with_order(vec![1, 1, 1], 3, Order::RowMajor);
2691        grid.expand_rows(0);
2692
2693        assert_eq!(grid.size(), (1, 3));
2694        assert_eq!(grid.order, Order::RowMajor);
2695        assert_eq!(grid.rows(), 1);
2696        assert_eq!(grid.cols(), 3);
2697        assert_eq!(grid.into_vec(), vec![1, 1, 1]);
2698    }
2699
2700    #[test]
2701    fn expand_rows_empty_grid() {
2702        let mut grid: Grid<u8> = Grid::init(0, 0, 0);
2703        grid.expand_rows(2);
2704
2705        assert_eq!(grid.size(), (0, 0));
2706        assert_eq!(grid.order, Order::RowMajor);
2707        assert_eq!(grid.rows(), 0);
2708        assert_eq!(grid.cols(), 0);
2709        assert_eq!(grid.into_vec(), Vec::<u8>::new());
2710    }
2711
2712    #[test]
2713    fn expand_cols() {
2714        let mut grid = Grid::from_vec_with_order(vec![1, 1, 1, 2, 2, 2], 3, Order::RowMajor);
2715        grid.expand_cols(2);
2716
2717        assert_eq!(grid.size(), (2, 5));
2718        assert_eq!(grid.order, Order::RowMajor);
2719        assert_eq!(grid.rows(), 2);
2720        assert_eq!(grid.cols(), 5);
2721        assert_eq!(grid.into_vec(), vec![1, 1, 1, 0, 0, 2, 2, 2, 0, 0]);
2722    }
2723
2724    #[test]
2725    fn expand_cols_column_major() {
2726        let mut grid = Grid::from_vec_with_order(vec![1, 2, 1, 2, 1, 2], 3, Order::ColumnMajor);
2727        grid.expand_cols(2);
2728
2729        assert_eq!(grid.size(), (2, 5));
2730        assert_eq!(grid.order, Order::ColumnMajor);
2731        assert_eq!(grid.rows(), 2);
2732        assert_eq!(grid.cols(), 5);
2733        assert_eq!(grid.into_vec(), vec![1, 2, 1, 2, 1, 2, 0, 0, 0, 0]);
2734    }
2735
2736    #[test]
2737    fn expand_cols_zero() {
2738        let mut grid = Grid::from_vec_with_order(vec![1, 2, 1, 2], 2, Order::RowMajor);
2739        grid.expand_cols(0);
2740
2741        assert_eq!(grid.size(), (2, 2));
2742        assert_eq!(grid.order, Order::RowMajor);
2743        assert_eq!(grid.rows(), 2);
2744        assert_eq!(grid.cols(), 2);
2745        assert_eq!(grid.into_vec(), vec![1, 2, 1, 2]);
2746    }
2747
2748    #[test]
2749    fn expand_cols_empty_grid() {
2750        let mut grid: Grid<u8> = Grid::init(0, 0, 0);
2751        grid.expand_cols(2);
2752
2753        assert_eq!(grid.size(), (0, 0));
2754        assert_eq!(grid.order, Order::RowMajor);
2755        assert_eq!(grid.rows(), 0);
2756        assert_eq!(grid.cols(), 0);
2757        assert_eq!(grid.into_vec(), Vec::<u8>::new());
2758    }
2759
2760    #[test]
2761    fn iter_row() {
2762        let grid = Grid::from_vec_with_order(vec![1, 2, 3, 4, 5, 6], 3, Order::RowMajor);
2763        let row: Vec<_> = grid.iter_row(1).collect();
2764        assert_eq!(row, [&4, &5, &6]);
2765    }
2766
2767    #[test]
2768    #[should_panic]
2769    #[allow(clippy::should_panic_without_expect)]
2770    fn iter_row_out_of_bound() {
2771        let grid = Grid::from_vec_with_order(vec![1, 2, 3, 4, 5, 6], 3, Order::RowMajor);
2772        let _ = grid.iter_row(3);
2773    }
2774
2775    #[test]
2776    #[should_panic]
2777    #[allow(clippy::should_panic_without_expect)]
2778    fn iter_row_zero() {
2779        let grid: Grid<u8> = Grid::from_vec_with_order(vec![], 0, Order::RowMajor);
2780        let _ = grid.iter_row(0);
2781    }
2782
2783    #[test]
2784    fn iter_row_rowumn_major() {
2785        let grid = Grid::from_vec_with_order(vec![1, 4, 2, 5, 3, 6], 3, Order::ColumnMajor);
2786        let row: Vec<_> = grid.iter_row(1).collect();
2787        assert_eq!(row, [&4, &5, &6]);
2788    }
2789
2790    #[test]
2791    #[should_panic]
2792    #[allow(clippy::should_panic_without_expect)]
2793    fn iter_row_rowumn_major_out_of_bound() {
2794        let grid = Grid::from_vec_with_order(vec![1, 4, 2, 5, 3, 6], 3, Order::ColumnMajor);
2795        let _ = grid.iter_row(3);
2796    }
2797
2798    #[test]
2799    #[should_panic]
2800    #[allow(clippy::should_panic_without_expect)]
2801    fn iter_row_rowumn_major_zero() {
2802        let grid: Grid<u8> = Grid::from_vec_with_order(vec![], 0, Order::ColumnMajor);
2803        let _ = grid.iter_row(0);
2804    }
2805
2806    #[test]
2807    fn iter_row_mut() {
2808        let mut grid = Grid::from_vec_with_order(vec![1, 2, 3, 4, 5, 6], 3, Order::RowMajor);
2809        let row: Vec<_> = grid.iter_row_mut(1).collect();
2810        assert_eq!(row, [&mut 4, &mut 5, &mut 6]);
2811    }
2812
2813    #[test]
2814    #[should_panic]
2815    #[allow(clippy::should_panic_without_expect)]
2816    fn iter_row_mut_out_of_bound() {
2817        let mut grid = Grid::from_vec_with_order(vec![1, 2, 3, 4, 5, 6], 3, Order::RowMajor);
2818        let _ = grid.iter_row_mut(3);
2819    }
2820
2821    #[test]
2822    #[should_panic]
2823    #[allow(clippy::should_panic_without_expect)]
2824    fn iter_row_mut_zero() {
2825        let mut grid: Grid<u8> = Grid::from_vec_with_order(vec![], 0, Order::RowMajor);
2826        let _ = grid.iter_row_mut(0);
2827    }
2828
2829    #[test]
2830    fn iter_row_mut_rowumn_major() {
2831        let mut grid = Grid::from_vec_with_order(vec![1, 4, 2, 5, 3, 6], 3, Order::ColumnMajor);
2832        let row: Vec<_> = grid.iter_row_mut(1).collect();
2833        assert_eq!(row, [&mut 4, &mut 5, &mut 6]);
2834    }
2835
2836    #[test]
2837    #[should_panic]
2838    #[allow(clippy::should_panic_without_expect)]
2839    fn iter_row_mut_rowumn_major_out_of_bound() {
2840        let mut grid = Grid::from_vec_with_order(vec![1, 4, 2, 5, 3, 6], 3, Order::ColumnMajor);
2841        let _ = grid.iter_row_mut(3);
2842    }
2843
2844    #[test]
2845    #[should_panic]
2846    #[allow(clippy::should_panic_without_expect)]
2847    fn iter_row_mut_rowumn_major_zero() {
2848        let mut grid: Grid<u8> = Grid::from_vec_with_order(vec![], 0, Order::ColumnMajor);
2849        let _ = grid.iter_row_mut(0);
2850    }
2851
2852    #[test]
2853    fn iter_col() {
2854        let grid = Grid::from_vec_with_order(vec![1, 2, 3, 4, 5, 6], 3, Order::RowMajor);
2855        let col: Vec<_> = grid.iter_col(1).collect();
2856        assert_eq!(col, [&2, &5]);
2857    }
2858
2859    #[test]
2860    #[should_panic]
2861    #[allow(clippy::should_panic_without_expect)]
2862    fn iter_col_out_of_bound() {
2863        let grid = Grid::from_vec_with_order(vec![1, 2, 3, 4, 5, 6], 3, Order::RowMajor);
2864        let _ = grid.iter_col(3);
2865    }
2866
2867    #[test]
2868    #[should_panic]
2869    #[allow(clippy::should_panic_without_expect)]
2870    fn iter_col_zero() {
2871        let grid: Grid<u8> = Grid::from_vec_with_order(vec![], 0, Order::RowMajor);
2872        let _ = grid.iter_col(0);
2873    }
2874
2875    #[test]
2876    fn iter_col_column_major() {
2877        let grid = Grid::from_vec_with_order(vec![1, 4, 2, 5, 3, 6], 3, Order::ColumnMajor);
2878        let col: Vec<_> = grid.iter_col(1).collect();
2879        assert_eq!(col, [&2, &5]);
2880    }
2881
2882    #[test]
2883    #[should_panic]
2884    #[allow(clippy::should_panic_without_expect)]
2885    fn iter_col_column_major_out_of_bound() {
2886        let grid = Grid::from_vec_with_order(vec![1, 4, 2, 5, 3, 6], 3, Order::ColumnMajor);
2887        let _ = grid.iter_col(3);
2888    }
2889
2890    #[test]
2891    #[should_panic]
2892    #[allow(clippy::should_panic_without_expect)]
2893    fn iter_col_column_major_zero() {
2894        let grid: Grid<u8> = Grid::from_vec_with_order(vec![], 0, Order::ColumnMajor);
2895        let _ = grid.iter_col(0);
2896    }
2897
2898    #[test]
2899    fn iter_col_mut() {
2900        let mut grid = Grid::from_vec_with_order(vec![1, 2, 3, 4, 5, 6], 3, Order::RowMajor);
2901        let col: Vec<_> = grid.iter_col_mut(1).collect();
2902        assert_eq!(col, [&mut 2, &mut 5]);
2903    }
2904
2905    #[test]
2906    #[should_panic]
2907    #[allow(clippy::should_panic_without_expect)]
2908    fn iter_col_mut_out_of_bound() {
2909        let mut grid = Grid::from_vec_with_order(vec![1, 2, 3, 4, 5, 6], 3, Order::RowMajor);
2910        let _ = grid.iter_col_mut(3);
2911    }
2912
2913    #[test]
2914    #[should_panic]
2915    #[allow(clippy::should_panic_without_expect)]
2916    fn iter_col_mut_zero() {
2917        let mut grid: Grid<u8> = Grid::from_vec_with_order(vec![], 0, Order::RowMajor);
2918        let _ = grid.iter_col_mut(0);
2919    }
2920
2921    #[test]
2922    fn iter_col_mut_column_major() {
2923        let mut grid = Grid::from_vec_with_order(vec![1, 4, 2, 5, 3, 6], 3, Order::ColumnMajor);
2924        let col: Vec<_> = grid.iter_col_mut(1).collect();
2925        assert_eq!(col, [&mut 2, &mut 5]);
2926    }
2927
2928    #[test]
2929    #[should_panic]
2930    #[allow(clippy::should_panic_without_expect)]
2931    fn iter_col_mut_column_major_out_of_bound() {
2932        let mut grid = Grid::from_vec_with_order(vec![1, 4, 2, 5, 3, 6], 3, Order::ColumnMajor);
2933        let _ = grid.iter_col_mut(3);
2934    }
2935
2936    #[test]
2937    #[should_panic]
2938    #[allow(clippy::should_panic_without_expect)]
2939    fn iter_col_mut_column_major_zero() {
2940        let mut grid: Grid<u8> = Grid::from_vec_with_order(vec![], 0, Order::ColumnMajor);
2941        let _ = grid.iter_col_mut(0);
2942    }
2943
2944    #[test]
2945    fn iter() {
2946        let grid: Grid<u8> = grid![[1,2][3,4]];
2947        let mut iter = grid.iter();
2948        assert_eq!(iter.next(), Some(&1));
2949        assert_eq!(iter.next(), Some(&2));
2950        assert_eq!(iter.next(), Some(&3));
2951        assert_eq!(iter.next(), Some(&4));
2952        assert_eq!(iter.next(), None);
2953    }
2954
2955    #[test]
2956    fn into_iter() {
2957        let grid: Grid<u8> = grid![[1,1][1,1]];
2958        for val in grid {
2959            assert_eq!(val, 1);
2960        }
2961    }
2962
2963    #[test]
2964    fn into_iter_ref() {
2965        let grid: Grid<u8> = grid![[1,1][1,1]];
2966        for val in &grid {
2967            assert_eq!(val, &1);
2968        }
2969    }
2970
2971    #[test]
2972    fn into_iter_mut() {
2973        let mut grid: Grid<u8> = grid![[1,1][1,1]];
2974        grid.fill(2);
2975        assert_eq!(grid, grid![[2, 2][2, 2]]);
2976    }
2977
2978    #[test]
2979    fn indexed_iter() {
2980        let grid: Grid<u8> = grid![[1,2][3,4]];
2981        let mut iter = grid.indexed_iter();
2982        assert_eq!(iter.next(), Some(((0, 0), &1)));
2983        assert_eq!(iter.next(), Some(((0, 1), &2)));
2984        assert_eq!(iter.next(), Some(((1, 0), &3)));
2985        assert_eq!(iter.next(), Some(((1, 1), &4)));
2986        assert_eq!(iter.next(), None);
2987    }
2988
2989    #[test]
2990    fn indexed_iter_empty() {
2991        let grid: Grid<u8> = Grid::new(0, 0);
2992        let mut iter = grid.indexed_iter();
2993        assert_eq!(iter.next(), None);
2994    }
2995
2996    #[test]
2997    fn indexed_into_iter() {
2998        let grid: Grid<u8> = grid![[1,2][3,4]];
2999        let mut iter = grid.indexed_into_iter();
3000        assert_eq!(iter.next(), Some(((0, 0), 1)));
3001        assert_eq!(iter.next(), Some(((0, 1), 2)));
3002        assert_eq!(iter.next(), Some(((1, 0), 3)));
3003        assert_eq!(iter.next(), Some(((1, 1), 4)));
3004        assert_eq!(iter.next(), None);
3005    }
3006
3007    #[test]
3008    fn indexed_iter_column_major() {
3009        let grid: Grid<u8> = Grid::from_vec_with_order(vec![1, 3, 2, 4], 2, Order::ColumnMajor);
3010        let mut iter = grid.indexed_iter();
3011        assert_eq!(iter.next(), Some(((0, 0), &1)));
3012        assert_eq!(iter.next(), Some(((1, 0), &3)));
3013        assert_eq!(iter.next(), Some(((0, 1), &2)));
3014        assert_eq!(iter.next(), Some(((1, 1), &4)));
3015        assert_eq!(iter.next(), None);
3016    }
3017
3018    #[test]
3019    fn indexed_iter_empty_column_major() {
3020        let grid: Grid<u8> = Grid::new_with_order(0, 0, Order::ColumnMajor);
3021        let mut iter = grid.indexed_iter();
3022        assert_eq!(iter.next(), None);
3023    }
3024
3025    #[test]
3026    fn indexed_iter_mut() {
3027        let mut grid: Grid<u8> = grid![[1,2][3,4]];
3028        let mut iter = grid.indexed_iter_mut();
3029        assert_eq!(iter.next(), Some(((0, 0), &mut 1)));
3030        assert_eq!(iter.next(), Some(((0, 1), &mut 2)));
3031        assert_eq!(iter.next(), Some(((1, 0), &mut 3)));
3032        assert_eq!(iter.next(), Some(((1, 1), &mut 4)));
3033        assert_eq!(iter.next(), None);
3034    }
3035
3036    #[test]
3037    fn indexed_iter_mut_empty() {
3038        let mut grid: Grid<u8> = Grid::new(0, 0);
3039        let mut iter = grid.indexed_iter_mut();
3040        assert_eq!(iter.next(), None);
3041    }
3042
3043    #[test]
3044    fn indexed_iter_mut_column_major() {
3045        let mut grid: Grid<u8> = Grid::from_vec_with_order(vec![1, 3, 2, 4], 2, Order::ColumnMajor);
3046        let mut iter = grid.indexed_iter_mut();
3047        assert_eq!(iter.next(), Some(((0, 0), &mut 1)));
3048        assert_eq!(iter.next(), Some(((1, 0), &mut 3)));
3049        assert_eq!(iter.next(), Some(((0, 1), &mut 2)));
3050        assert_eq!(iter.next(), Some(((1, 1), &mut 4)));
3051        assert_eq!(iter.next(), None);
3052    }
3053
3054    #[test]
3055    fn indexed_iter_mut_empty_column_major() {
3056        let mut grid: Grid<u8> = Grid::new_with_order(0, 0, Order::ColumnMajor);
3057        let mut iter = grid.indexed_iter_mut();
3058        assert_eq!(iter.next(), None);
3059    }
3060
3061    #[test]
3062    fn clear() {
3063        let mut grid: Grid<u8> = grid![[1, 2, 3]];
3064        assert!(!grid.is_empty());
3065        grid.clear();
3066        assert!(grid.is_empty());
3067    }
3068
3069    #[test]
3070    fn is_empty_false() {
3071        let grid: Grid<u8> = grid![[1, 2, 3]];
3072        assert!(!grid.is_empty());
3073    }
3074
3075    #[test]
3076    fn is_empty() {
3077        let mut g: Grid<u8> = grid![[]];
3078        assert!(g.is_empty());
3079        g = grid![];
3080        assert!(g.is_empty());
3081        g = Grid::from_vec(vec![], 0);
3082        assert!(g.is_empty());
3083        g = Grid::new(0, 0);
3084        assert!(g.is_empty());
3085        g = Grid::new(0, 1);
3086        assert!(g.is_empty());
3087        g = Grid::new(1, 0);
3088        assert!(g.is_empty());
3089        g = Grid::init(0, 0, 10);
3090        assert!(g.is_empty());
3091    }
3092
3093    #[test]
3094    fn fmt_empty() {
3095        let grid: Grid<u8> = grid![];
3096        assert_eq!(format!("{grid:?}"), "[]");
3097    }
3098
3099    #[test]
3100    fn fmt_row() {
3101        let grid: Grid<u8> = grid![[1, 2, 3]];
3102        assert_eq!(format!("{grid:?}"), "[[1, 2, 3]]");
3103    }
3104
3105    #[test]
3106    fn fmt_grid() {
3107        let grid: Grid<u8> = grid![[1,2,3][4,5,6][7,8,9]];
3108        assert_eq!(format!("{grid:?}"), "[[1, 2, 3][4, 5, 6][7, 8, 9]]");
3109    }
3110
3111    #[test]
3112    fn fmt_column_major() {
3113        let grid = Grid::from_vec_with_order(vec![1, 4, 2, 5, 3, 6], 3, Order::ColumnMajor);
3114        assert_eq!(format!("{grid:?}"), "[[1, 2, 3][4, 5, 6]]");
3115    }
3116
3117    #[test]
3118    fn fmt_pretty_empty() {
3119        let grid: Grid<f32> = grid![];
3120        assert_eq!(format!("{grid:#?}"), "[]");
3121    }
3122
3123    #[test]
3124    fn fmt_pretty_int() {
3125        let grid: Grid<u8> = grid![
3126            [1,2,3]
3127            [4,5,6]
3128            [7,8,95]
3129        ];
3130
3131        let expected_output = r"[
3132    [  1,  2,  3]
3133    [  4,  5,  6]
3134    [  7,  8, 95]
3135]";
3136
3137        assert_eq!(format!("{grid:#?}"), expected_output);
3138
3139        let expected_output = r"[
3140    [   1,   2,   3]
3141    [   4,   5,   6]
3142    [   7,   8,  95]
3143]";
3144
3145        assert_eq!(format!("{grid:#3?}"), expected_output);
3146    }
3147
3148    #[test]
3149    fn fmt_pretty_float() {
3150        let grid: Grid<f32> = grid![
3151            [1.5,2.6,3.44]
3152            [4.775,5.,6.]
3153            [7.1,8.23444,95.55]
3154        ];
3155
3156        let expected_output = r"[
3157    [   1.5,   2.6,   3.4]
3158    [   4.8,   5.0,   6.0]
3159    [   7.1,   8.2,  95.6]
3160]";
3161
3162        assert_eq!(format!("{grid:#5.1?}"), expected_output);
3163
3164        let expected_output = r"[
3165    [  1.50000,  2.60000,  3.44000]
3166    [  4.77500,  5.00000,  6.00000]
3167    [  7.10000,  8.23444, 95.55000]
3168]";
3169
3170        assert_eq!(format!("{grid:#8.5?}"), expected_output);
3171    }
3172
3173    #[test]
3174    fn fmt_pretty_tuple() {
3175        let grid: Grid<(i32, i32)> = grid![
3176            [(5,66), (432, 55)]
3177            [(80, 90), (5, 6)]
3178        ];
3179
3180        let expected_output = r"[
3181    [ (        5,        66), (      432,        55)]
3182    [ (       80,        90), (        5,         6)]
3183]";
3184
3185        assert_eq!(format!("{grid:#?}"), expected_output);
3186
3187        let expected_output = r"[
3188    [ (  5,  66), (432,  55)]
3189    [ ( 80,  90), (  5,   6)]
3190]";
3191
3192        assert_eq!(format!("{grid:#3?}"), expected_output);
3193    }
3194
3195    #[test]
3196    fn fmt_pretty_struct_derived() {
3197        #[derive(Debug)]
3198        struct Person {
3199            _name: String,
3200            _precise_age: f32,
3201        }
3202
3203        impl Person {
3204            fn new(name: &str, precise_age: f32) -> Self {
3205                Self {
3206                    _name: name.into(),
3207                    _precise_age: precise_age,
3208                }
3209            }
3210        }
3211
3212        let grid: Grid<Person> = grid![
3213            [Person::new("Vic", 24.5), Person::new("Mr. Very Long Name", 1955.)]
3214            [Person::new("Sam", 8.9995), Person::new("John Doe", 40.14)]
3215        ];
3216
3217        let expected_output = r#"[
3218    [ Person { _name: "Vic", _precise_age: 24.50000 }, Person { _name: "Mr. Very Long Name", _precise_age: 1955.00000 }]
3219    [ Person { _name: "Sam", _precise_age: 8.99950 }, Person { _name: "John Doe", _precise_age: 40.14000 }]
3220]"#;
3221
3222        assert_eq!(format!("{grid:#5.5?}"), expected_output);
3223    }
3224
3225    #[test]
3226    fn fmt_pretty_column_major() {
3227        let grid = Grid::from_vec_with_order(vec![1, 4, 2, 5, 3, 6], 3, Order::ColumnMajor);
3228        let expected_output = r"[
3229    [ 1, 2, 3]
3230    [ 4, 5, 6]
3231]";
3232        assert_eq!(format!("{grid:#?}"), expected_output);
3233    }
3234
3235    #[test]
3236    fn clone() {
3237        let grid = grid![[1, 2, 3][4, 5, 6]];
3238        let mut clone = grid.clone();
3239        clone[(0, 2)] = 10;
3240        test_grid(&grid, 2, 3, Order::RowMajor, &[1, 2, 3, 4, 5, 6]);
3241        test_grid(&clone, 2, 3, Order::RowMajor, &[1, 2, 10, 4, 5, 6]);
3242    }
3243
3244    #[cfg(feature = "std")]
3245    #[test]
3246    fn hash_std() {
3247        let mut set = std::collections::HashSet::new();
3248        set.insert(grid![[1,2,3][4,5,6]]);
3249        set.insert(grid![[1,3,3][4,5,6]]);
3250        set.insert(grid![[1,2,3][4,5,6]]);
3251        assert_eq!(set.len(), 2);
3252    }
3253
3254    #[test]
3255    fn macro_init() {
3256        let grid = grid![[1, 2, 3][4, 5, 6]];
3257        test_grid(&grid, 2, 3, Order::RowMajor, &[1, 2, 3, 4, 5, 6]);
3258    }
3259
3260    #[test]
3261    fn macro_init_2() {
3262        let grid = grid![[1, 2, 3]
3263                         [4, 5, 6]
3264                         [7, 8, 9]];
3265        test_grid(&grid, 3, 3, Order::RowMajor, &[1, 2, 3, 4, 5, 6, 7, 8, 9]);
3266    }
3267
3268    #[test]
3269    fn macro_init_char() {
3270        let grid = grid![['a', 'b', 'c']
3271                         ['a', 'b', 'c']
3272                         ['a', 'b', 'c']];
3273        let expected = ['a', 'b', 'c', 'a', 'b', 'c', 'a', 'b', 'c'];
3274        test_grid(&grid, 3, 3, Order::RowMajor, &expected);
3275    }
3276
3277    #[test]
3278    fn macro_one_row() {
3279        let grid: Grid<usize> = grid![[1, 2, 3, 4]];
3280        test_grid(&grid, 1, 4, Order::RowMajor, &[1, 2, 3, 4]);
3281    }
3282
3283    #[test]
3284    fn macro2_empty() {
3285        let grid: Grid<u8> = grid_cm![];
3286        test_grid(&grid, 0, 0, Order::ColumnMajor, &[]);
3287    }
3288
3289    #[test]
3290    fn macro2_init() {
3291        let grid = grid_cm![[1, 2, 3]
3292                          [4, 5, 6]
3293                          [7, 8, 9]];
3294        let expected = [1, 4, 7, 2, 5, 8, 3, 6, 9];
3295        test_grid(&grid, 3, 3, Order::ColumnMajor, &expected);
3296    }
3297
3298    #[test]
3299    fn macro2_init_char() {
3300        let grid = grid_cm![['a', 'b']['c', 'd']];
3301        test_grid(&grid, 2, 2, Order::ColumnMajor, &['a', 'c', 'b', 'd']);
3302    }
3303
3304    #[test]
3305    fn macro2_one_row() {
3306        let grid = grid_cm![[1, 2, 3, 4]];
3307        test_grid(&grid, 1, 4, Order::ColumnMajor, &[1, 2, 3, 4]);
3308    }
3309
3310    #[test]
3311    fn init() {
3312        let grid = Grid::init(1, 2, 3);
3313        test_grid(&grid, 1, 2, Order::RowMajor, &[3, 3]);
3314
3315        let grid = Grid::init(1, 2, 1.2);
3316        test_grid(&grid, 1, 2, Order::RowMajor, &[1.2, 1.2]);
3317
3318        let grid = Grid::init(1, 2, 'a');
3319        test_grid(&grid, 1, 2, Order::RowMajor, &['a', 'a']);
3320    }
3321
3322    #[test]
3323    #[should_panic]
3324    #[allow(clippy::should_panic_without_expect)]
3325    fn init_panics() {
3326        Grid::init(usize::MAX, 2, 3);
3327    }
3328
3329    #[test]
3330    fn init_empty() {
3331        let grid = Grid::init(0, 1, 0);
3332        test_grid(&grid, 0, 0, Order::RowMajor, &[]);
3333
3334        let grid = Grid::init(1, 0, -1);
3335        test_grid(&grid, 0, 0, Order::RowMajor, &[]);
3336    }
3337
3338    #[test]
3339    fn init_with_order() {
3340        let grid = Grid::init_with_order(1, 2, Order::RowMajor, 3);
3341        test_grid(&grid, 1, 2, Order::RowMajor, &[3, 3]);
3342
3343        let grid = Grid::init_with_order(1, 2, Order::ColumnMajor, 1.2);
3344        test_grid(&grid, 1, 2, Order::ColumnMajor, &[1.2, 1.2]);
3345
3346        let grid = Grid::init_with_order(1, 2, Order::ColumnMajor, 'a');
3347        test_grid(&grid, 1, 2, Order::ColumnMajor, &['a', 'a']);
3348    }
3349
3350    #[test]
3351    #[should_panic]
3352    #[allow(clippy::should_panic_without_expect)]
3353    fn init_with_order_panics() {
3354        Grid::init_with_order(usize::MAX, 2, Order::ColumnMajor, 3);
3355    }
3356
3357    #[test]
3358    fn init_with_order_empty() {
3359        let grid = Grid::init_with_order(0, 1, Order::ColumnMajor, 0);
3360        test_grid(&grid, 0, 0, Order::ColumnMajor, &[]);
3361
3362        let grid = Grid::init_with_order(1, 0, Order::RowMajor, -1);
3363        test_grid(&grid, 0, 0, Order::RowMajor, &[]);
3364    }
3365
3366    #[test]
3367    fn new() {
3368        let grid: Grid<u8> = Grid::new(1, 2);
3369        test_grid(&grid, 1, 2, Order::RowMajor, &[0, 0]);
3370    }
3371
3372    #[test]
3373    #[should_panic]
3374    #[allow(clippy::should_panic_without_expect)]
3375    fn new_panics() {
3376        let _: Grid<u8> = Grid::new(usize::MAX, 2);
3377    }
3378
3379    #[test]
3380    fn new_empty() {
3381        let grid: Grid<u8> = Grid::new(0, 1);
3382        test_grid(&grid, 0, 0, Order::RowMajor, &[]);
3383
3384        let grid: Grid<u8> = Grid::new(1, 0);
3385        test_grid(&grid, 0, 0, Order::RowMajor, &[]);
3386    }
3387
3388    #[test]
3389    fn new_with_order() {
3390        let grid: Grid<u8> = Grid::new_with_order(2, 2, Order::ColumnMajor);
3391        test_grid(&grid, 2, 2, Order::ColumnMajor, &[0, 0, 0, 0]);
3392    }
3393
3394    #[test]
3395    #[should_panic]
3396    #[allow(clippy::should_panic_without_expect)]
3397    fn new_with_order_panics() {
3398        let _: Grid<u8> = Grid::new_with_order(usize::MAX, 2, Order::ColumnMajor);
3399    }
3400
3401    #[test]
3402    fn new_with_order_empty() {
3403        let grid: Grid<u8> = Grid::new_with_order(0, 3, Order::RowMajor);
3404        test_grid(&grid, 0, 0, Order::RowMajor, &[]);
3405
3406        let grid: Grid<u8> = Grid::new_with_order(3, 0, Order::ColumnMajor);
3407        test_grid(&grid, 0, 0, Order::ColumnMajor, &[]);
3408    }
3409
3410    #[test]
3411    fn with_capacity() {
3412        // doesn't impl Default
3413        struct Foo();
3414
3415        let grid: Grid<Foo> = Grid::with_capacity(20, 20);
3416        assert!(grid.is_empty());
3417        assert_eq!(grid.order(), Order::default());
3418    }
3419
3420    #[test]
3421    fn with_capacity_and_order() {
3422        // doesn't impl Default
3423        struct Foo();
3424
3425        let grid: Grid<Foo> = Grid::with_capacity_and_order(20, 20, Order::ColumnMajor);
3426        assert!(grid.is_empty());
3427        assert_eq!(grid.order(), Order::ColumnMajor);
3428    }
3429
3430    #[test]
3431    #[should_panic]
3432    #[allow(clippy::should_panic_without_expect)]
3433    fn with_capacity_panics_internal() {
3434        // doesn't impl Default
3435        struct Foo();
3436
3437        let _grid: Grid<Foo> = Grid::with_capacity_and_order(usize::MAX, 2, Order::RowMajor);
3438    }
3439
3440    #[test]
3441    #[should_panic]
3442    #[allow(clippy::should_panic_without_expect)]
3443    fn with_capacity_panics_vec() {
3444        let rows: usize = isize::MAX.try_into().expect("isize::MAX is positive");
3445        assert!(
3446            core::mem::size_of::<u8>() * rows < usize::MAX,
3447            "shows that panic is from Vec::with_capacity, not internal check"
3448        );
3449
3450        let _grid: Grid<u8> = Grid::with_capacity_and_order(rows, 2, Order::RowMajor);
3451    }
3452
3453    #[test]
3454    fn get() {
3455        let grid = Grid::from_vec_with_order(vec![1, 2], 2, Order::RowMajor);
3456        assert_eq!(grid.get(0_i64, 1_i32), Some(&2));
3457    }
3458
3459    #[test]
3460    fn get_column_major() {
3461        let grid = Grid::from_vec_with_order(vec![1, 2], 1, Order::ColumnMajor);
3462        assert_eq!(grid.get(1, 0), Some(&2));
3463    }
3464
3465    #[test]
3466    fn get_none() {
3467        let grid = Grid::from_vec_with_order(vec![1, 2], 2, Order::RowMajor);
3468        assert_eq!(grid.get(1, 0), None);
3469    }
3470
3471    #[test]
3472    fn get_none_column_major() {
3473        let grid = Grid::from_vec_with_order(vec![1, 2], 1, Order::ColumnMajor);
3474        assert_eq!(grid.get(0, 1), None);
3475    }
3476
3477    #[test]
3478    fn get_mut() {
3479        let mut grid = Grid::from_vec_with_order(vec![1, 2], 2, Order::RowMajor);
3480        assert_eq!(grid.get_mut(0_i64, 1_i32), Some(&mut 2));
3481    }
3482
3483    #[test]
3484    fn get_mut_column_major() {
3485        let mut grid = Grid::from_vec_with_order(vec![1, 2], 1, Order::ColumnMajor);
3486        assert_eq!(grid.get_mut(1, 0), Some(&mut 2));
3487    }
3488
3489    #[test]
3490    fn get_mut_none() {
3491        let mut grid = Grid::from_vec_with_order(vec![1, 2], 2, Order::RowMajor);
3492        assert_eq!(grid.get_mut(1, 0), None);
3493    }
3494
3495    #[test]
3496    fn get_mut_none_column_major() {
3497        let mut grid = Grid::from_vec_with_order(vec![1, 2], 1, Order::ColumnMajor);
3498        assert_eq!(grid.get_mut(0, 1), None);
3499    }
3500
3501    #[test]
3502    fn idx_tup() {
3503        let grid: Grid<u8> = Grid::from_vec(vec![1, 2, 3, 4], 2);
3504        assert_eq!(grid[(0, 0)], 1);
3505        assert_eq!(grid[(0, 1)], 2);
3506        assert_eq!(grid[(1, 0)], 3);
3507        assert_eq!(grid[(1, 1)], 4);
3508    }
3509
3510    #[test]
3511    #[should_panic]
3512    #[allow(clippy::should_panic_without_expect)]
3513    fn idx_tup_panic_1() {
3514        let grid = Grid::init(1, 2, 3);
3515        let _ = grid[(20, 0)];
3516    }
3517
3518    #[test]
3519    #[should_panic]
3520    #[allow(clippy::should_panic_without_expect)]
3521    fn idx_tup_panic_2() {
3522        let grid = Grid::init(1, 2, 3);
3523        let _ = grid[(0, 20)];
3524    }
3525
3526    #[test]
3527    fn idx_tup_set() {
3528        let mut grid = Grid::init(1, 2, 3);
3529        grid[(0, 0)] = 4;
3530        assert_eq!(grid[(0, 0)], 4);
3531    }
3532
3533    #[test]
3534    fn size() {
3535        let grid = Grid::init(1, 2, 3);
3536        assert_eq!(grid.size(), (1, 2));
3537    }
3538
3539    #[test]
3540    fn transpose() {
3541        let mut grid: Grid<u8> = grid![[1,2,3][4,5,6]];
3542        grid.transpose();
3543        assert_eq!(grid, grid![[1,4][2,5][3,6]]);
3544    }
3545
3546    #[test]
3547    fn fill() {
3548        let mut grid: Grid<u8> = grid![[1,2,3][4,5,6]];
3549        grid.fill(7);
3550        test_grid(&grid, 2, 3, Order::RowMajor, &[7, 7, 7, 7, 7, 7]);
3551    }
3552
3553    #[test]
3554    fn fill_with() {
3555        let mut grid: Grid<u8> = grid![[1,2,3][4,5,6]];
3556        grid.fill_with(Default::default);
3557        test_grid(&grid, 2, 3, Order::RowMajor, &[0, 0, 0, 0, 0, 0]);
3558    }
3559
3560    #[test]
3561    fn map() {
3562        let grid: Grid<u8> = grid![[1,2,3][4,5,6]];
3563        let mapped = grid.map(|x| x * 2);
3564        test_grid(&mapped, 2, 3, Order::RowMajor, &[2, 4, 6, 8, 10, 12]);
3565    }
3566
3567    #[test]
3568    fn map_ref() {
3569        let grid: Grid<u8> = grid![[1,2,3][4,5,6]];
3570        let mapped = grid.map_ref(|x| *x * 2);
3571        test_grid(&mapped, 2, 3, Order::RowMajor, &[2, 4, 6, 8, 10, 12]);
3572    }
3573
3574    #[test]
3575    #[allow(clippy::redundant_closure_for_method_calls)]
3576    fn iter_rows() {
3577        let grid: Grid<u8> = grid![[1,2,3][4,5,6]];
3578        let max_by_row: Vec<u8> = grid
3579            .iter_rows()
3580            .map(|row| row.max().unwrap())
3581            .copied()
3582            .collect();
3583        assert_eq!(max_by_row, vec![3, 6]);
3584
3585        let sum_by_row: Vec<u8> = grid.iter_rows().map(|row| row.sum()).collect();
3586        assert_eq!(sum_by_row, vec![1 + 2 + 3, 4 + 5 + 6]);
3587    }
3588
3589    #[test]
3590    #[allow(clippy::redundant_closure_for_method_calls)]
3591    fn iter_rows_rev() {
3592        let grid: Grid<u8> = grid![[1,2,3][4,5,6]];
3593        let max_by_row: Vec<u8> = grid
3594            .iter_rows()
3595            .rev()
3596            .map(|row| row.max().unwrap())
3597            .copied()
3598            .collect();
3599        assert_eq!(max_by_row, vec![6, 3]);
3600
3601        let sum_by_row: Vec<u8> = grid.iter_rows().rev().map(|row| row.sum()).collect();
3602        assert_eq!(sum_by_row, vec![4 + 5 + 6, 1 + 2 + 3]);
3603    }
3604
3605    #[test]
3606    fn iter_rows_exact_size() {
3607        let grid: Grid<u8> = grid![[1,2,3][4,5,6]];
3608        let mut row_iter = grid.iter_rows();
3609        assert_eq!(row_iter.len(), 2);
3610        assert!(row_iter.next().is_some());
3611        assert_eq!(row_iter.len(), 1);
3612        assert!(row_iter.next().is_some());
3613        assert_eq!(row_iter.len(), 0);
3614        assert!(row_iter.next().is_none());
3615    }
3616
3617    #[test]
3618    #[allow(clippy::redundant_closure_for_method_calls)]
3619    fn iter_cols() {
3620        let grid: Grid<u8> = grid![[1,2,3][4,5,6]];
3621        let max_by_col: Vec<u8> = grid
3622            .iter_cols()
3623            .map(|col| col.max().unwrap())
3624            .copied()
3625            .collect();
3626
3627        assert_eq!(max_by_col, vec![4, 5, 6]);
3628
3629        let sum_by_col: Vec<u8> = grid.iter_cols().map(|row| row.sum()).collect();
3630        assert_eq!(sum_by_col, vec![1 + 4, 2 + 5, 3 + 6]);
3631    }
3632
3633    #[test]
3634    #[allow(clippy::redundant_closure_for_method_calls)]
3635    fn iter_cols_rev() {
3636        let grid: Grid<u8> = grid![[1,2,3][4,5,6]];
3637        let max_by_col: Vec<u8> = grid
3638            .iter_cols()
3639            .rev()
3640            .map(|col| col.max().unwrap())
3641            .copied()
3642            .collect();
3643
3644        assert_eq!(max_by_col, vec![6, 5, 4]);
3645
3646        let sum_by_col: Vec<u8> = grid.iter_cols().rev().map(|row| row.sum()).collect();
3647        assert_eq!(sum_by_col, vec![3 + 6, 2 + 5, 1 + 4]);
3648    }
3649
3650    #[test]
3651    fn iter_cols_exact_size() {
3652        let grid: Grid<u8> = grid![[1,2,3][4,5,6]];
3653        let mut col_iter = grid.iter_cols();
3654        assert_eq!(col_iter.len(), 3);
3655        assert!(col_iter.next().is_some());
3656        assert_eq!(col_iter.len(), 2);
3657        assert!(col_iter.next().is_some());
3658        assert_eq!(col_iter.len(), 1);
3659        assert!(col_iter.next().is_some());
3660        assert_eq!(col_iter.len(), 0);
3661        assert!(col_iter.next().is_none());
3662    }
3663
3664    #[test]
3665    fn remove_row() {
3666        let mut grid = grid![[1,2][3,4][5,6]];
3667        assert_eq![grid.remove_row(1), Some(vec![3, 4])];
3668        test_grid(&grid, 2, 2, Order::RowMajor, &[1, 2, 5, 6]);
3669        assert_eq![grid.remove_row(0), Some(vec![1, 2])];
3670        test_grid(&grid, 1, 2, Order::RowMajor, &[5, 6]);
3671        assert_eq![grid.remove_row(0), Some(vec![5, 6])];
3672        test_grid(&grid, 0, 0, Order::RowMajor, &[]);
3673        assert_eq![grid.remove_row(0), None];
3674        test_grid(&grid, 0, 0, Order::RowMajor, &[]);
3675    }
3676
3677    #[test]
3678    fn remove_row_out_of_bound() {
3679        let mut grid = grid![[1, 2][3, 4]];
3680        assert_eq![grid.remove_row(5), None];
3681        test_grid(&grid, 2, 2, Order::RowMajor, &[1, 2, 3, 4]);
3682        assert_eq![grid.remove_row(1), Some(vec![3, 4])];
3683        test_grid(&grid, 1, 2, Order::RowMajor, &[1, 2]);
3684    }
3685
3686    #[test]
3687    fn remove_row_column_major() {
3688        let mut grid = Grid::from_vec_with_order(vec![1, 3, 5, 2, 4, 6], 2, Order::ColumnMajor);
3689        assert_eq![grid.remove_row(1), Some(vec![3, 4])];
3690        test_grid(&grid, 2, 2, Order::ColumnMajor, &[1, 5, 2, 6]);
3691        assert_eq![grid.remove_row(0), Some(vec![1, 2])];
3692        test_grid(&grid, 1, 2, Order::ColumnMajor, &[5, 6]);
3693        assert_eq![grid.remove_row(0), Some(vec![5, 6])];
3694        test_grid(&grid, 0, 0, Order::ColumnMajor, &[]);
3695        assert_eq![grid.remove_row(0), None];
3696        test_grid(&grid, 0, 0, Order::ColumnMajor, &[]);
3697    }
3698
3699    #[test]
3700    fn remove_row_out_of_bound_column_major() {
3701        let mut grid = Grid::from_vec_with_order(vec![1, 3, 2, 4], 2, Order::ColumnMajor);
3702        assert_eq![grid.remove_row(5), None];
3703        test_grid(&grid, 2, 2, Order::ColumnMajor, &[1, 3, 2, 4]);
3704        assert_eq![grid.remove_row(1), Some(vec![3, 4])];
3705        test_grid(&grid, 1, 2, Order::ColumnMajor, &[1, 2]);
3706    }
3707
3708    #[test]
3709    fn remove_col() {
3710        let mut grid = grid![[1,2,3,4][5,6,7,8][9,10,11,12][13,14,15,16]];
3711        assert_eq![grid.remove_col(3), Some(vec![4, 8, 12, 16])];
3712        let expected = [1, 2, 3, 5, 6, 7, 9, 10, 11, 13, 14, 15];
3713        test_grid(&grid, 4, 3, Order::RowMajor, &expected);
3714        assert_eq![grid.remove_col(0), Some(vec![1, 5, 9, 13])];
3715        test_grid(&grid, 4, 2, Order::RowMajor, &[2, 3, 6, 7, 10, 11, 14, 15]);
3716        assert_eq![grid.remove_col(1), Some(vec![3, 7, 11, 15])];
3717        test_grid(&grid, 4, 1, Order::RowMajor, &[2, 6, 10, 14]);
3718        assert_eq![grid.remove_col(0), Some(vec![2, 6, 10, 14])];
3719        test_grid(&grid, 0, 0, Order::RowMajor, &[]);
3720        assert_eq![grid.remove_col(0), None];
3721        test_grid(&grid, 0, 0, Order::RowMajor, &[]);
3722    }
3723
3724    #[test]
3725    fn remove_col_out_of_bound() {
3726        let mut grid = grid![[1, 2][3, 4]];
3727        assert_eq!(grid.remove_col(5), None);
3728        test_grid(&grid, 2, 2, Order::RowMajor, &[1, 2, 3, 4]);
3729        assert_eq!(grid.remove_col(1), Some(vec![2, 4]));
3730        test_grid(&grid, 2, 1, Order::RowMajor, &[1, 3]);
3731    }
3732
3733    #[test]
3734    fn remove_col_column_major() {
3735        let internal = vec![1, 5, 9, 13, 2, 6, 10, 14, 3, 7, 11, 15, 4, 8, 12, 16];
3736        let mut grid = Grid::from_vec_with_order(internal, 4, Order::ColumnMajor);
3737        assert_eq![grid.remove_col(3), Some(vec![4, 8, 12, 16])];
3738        let expected = [1, 5, 9, 13, 2, 6, 10, 14, 3, 7, 11, 15];
3739        test_grid(&grid, 4, 3, Order::ColumnMajor, &expected);
3740        assert_eq![grid.remove_col(0), Some(vec![1, 5, 9, 13])];
3741        let expected = [2, 6, 10, 14, 3, 7, 11, 15];
3742        test_grid(&grid, 4, 2, Order::ColumnMajor, &expected);
3743        assert_eq![grid.remove_col(1), Some(vec![3, 7, 11, 15])];
3744        test_grid(&grid, 4, 1, Order::ColumnMajor, &[2, 6, 10, 14]);
3745        assert_eq![grid.remove_col(0), Some(vec![2, 6, 10, 14])];
3746        test_grid(&grid, 0, 0, Order::ColumnMajor, &[]);
3747        assert_eq![grid.remove_col(0), None];
3748        test_grid(&grid, 0, 0, Order::ColumnMajor, &[]);
3749    }
3750
3751    #[test]
3752    fn remove_col_out_of_bound_column_major() {
3753        let mut grid = Grid::from_vec_with_order(vec![1, 3, 2, 4], 2, Order::ColumnMajor);
3754        assert_eq!(grid.remove_col(5), None);
3755        test_grid(&grid, 2, 2, Order::ColumnMajor, &[1, 3, 2, 4]);
3756        assert_eq!(grid.remove_col(1), Some(vec![2, 4]));
3757        test_grid(&grid, 2, 1, Order::ColumnMajor, &[1, 3]);
3758    }
3759
3760    #[test]
3761    fn flip_cols() {
3762        let mut grid = Grid::from_vec_with_order(vec![1, 2, 3, 4], 2, Order::RowMajor);
3763        grid.flip_cols();
3764        test_grid(&grid, 2, 2, Order::RowMajor, &[2, 1, 4, 3]);
3765    }
3766
3767    #[test]
3768    fn flip_cols_column_major() {
3769        let mut grid = Grid::from_vec_with_order(vec![1, 3, 2, 4], 2, Order::ColumnMajor);
3770        grid.flip_cols();
3771        test_grid(&grid, 2, 2, Order::ColumnMajor, &[2, 4, 1, 3]);
3772    }
3773
3774    #[test]
3775    fn flip_rows() {
3776        let mut grid = Grid::from_vec_with_order(vec![1, 2, 3, 4], 2, Order::RowMajor);
3777        grid.flip_rows();
3778        test_grid(&grid, 2, 2, Order::RowMajor, &[3, 4, 1, 2]);
3779    }
3780
3781    #[test]
3782    fn flip_rows_column_major() {
3783        let mut grid = Grid::from_vec_with_order(vec![1, 3, 2, 4], 2, Order::ColumnMajor);
3784        grid.flip_rows();
3785        test_grid(&grid, 2, 2, Order::ColumnMajor, &[3, 1, 4, 2]);
3786    }
3787
3788    #[test]
3789    fn rotate_left() {
3790        let mut grid = Grid::from_vec_with_order(vec![1, 2, 3, 4, 5, 6], 3, Order::RowMajor);
3791        grid.rotate_left();
3792        test_grid(&grid, 3, 2, Order::ColumnMajor, &[3, 2, 1, 6, 5, 4]);
3793        assert_eq!(grid, grid![[3,6][2,5][1,4]]);
3794    }
3795
3796    #[test]
3797    fn rotate_left_column_major() {
3798        let mut grid = Grid::from_vec_with_order(vec![1, 4, 2, 5, 3, 6], 3, Order::ColumnMajor);
3799        grid.rotate_left();
3800        test_grid(&grid, 3, 2, Order::RowMajor, &[3, 6, 2, 5, 1, 4]);
3801        assert_eq!(grid, grid![[3,6][2,5][1,4]]);
3802    }
3803
3804    #[test]
3805    fn rotate_right() {
3806        let mut grid = Grid::from_vec_with_order(vec![1, 2, 3, 4, 5, 6], 3, Order::RowMajor);
3807        grid.rotate_right();
3808        test_grid(&grid, 3, 2, Order::ColumnMajor, &[4, 5, 6, 1, 2, 3]);
3809        assert_eq!(grid, grid![[4,1][5,2][6,3]]);
3810    }
3811
3812    #[test]
3813    fn rotate_right_column_major() {
3814        let mut grid = Grid::from_vec_with_order(vec![1, 4, 2, 5, 3, 6], 3, Order::ColumnMajor);
3815        grid.rotate_right();
3816        test_grid(&grid, 3, 2, Order::RowMajor, &[4, 1, 5, 2, 6, 3]);
3817        assert_eq!(grid, grid![[4,1][5,2][6,3]]);
3818    }
3819
3820    #[test]
3821    fn iter_cols_clone() {
3822        let grid = grid![[1,2,3][4,5,6]];
3823        let mut cols = grid.iter_cols().skip(1);
3824        let c3: u8 = cols.clone().nth(1).unwrap().sum();
3825        let c2: u8 = cols.next().unwrap().sum();
3826        assert_eq!(c2, 2 + 5);
3827        assert_eq!(c3, 3 + 6);
3828    }
3829
3830    #[test]
3831    fn iter_rows_clone() {
3832        let grid = grid![[1,2,3][4,5,6][7,8,9]];
3833        let mut rows = grid.iter_rows().skip(1);
3834        let r3: u8 = rows.clone().nth(1).unwrap().sum();
3835        let r2: u8 = rows.next().unwrap().sum();
3836        assert_eq!(r2, 4 + 5 + 6);
3837        assert_eq!(r3, 7 + 8 + 9);
3838    }
3839
3840    #[test]
3841    fn swap() {
3842        let mut grid = grid![[1,2][4,5]];
3843        grid.swap((0, 0), (1, 0));
3844        let end_grid = grid![[4,2][1,5]];
3845        assert_eq!(grid, end_grid);
3846    }
3847
3848    #[test]
3849    #[should_panic(expected = "grid index out of bounds: (2,0) out of (2,2)")]
3850    fn swap_out_of_bounds() {
3851        let mut grid = grid![[1,2][4,5]];
3852        grid.swap((0, 0), (2, 0));
3853    }
3854
3855    #[cfg(feature = "serde")]
3856    mod serde_tests {
3857        use super::*;
3858
3859        #[test]
3860        fn serialize() {
3861            let grid: Grid<u8> = grid![[1, 2][3, 4]];
3862            let s = serde_json::to_string(&grid).unwrap();
3863            assert_eq!(s, r#"{"cols":2,"data":[1,2,3,4],"order":"RowMajor"}"#);
3864        }
3865
3866        #[test]
3867        fn deserialize() {
3868            let s = "{ \"cols\": 2, \"data\": [1, 2, 3, 4] }";
3869            let grid: Grid<u8> = serde_json::from_str(s).unwrap();
3870            assert_eq!(grid, grid![[1, 2][3, 4]]);
3871        }
3872
3873        #[test]
3874        fn deserialize_with_order() {
3875            let s = "{ \"cols\": 2, \"data\": [1, 3, 2, 4], \"order\": \"ColumnMajor\" }";
3876            let grid: Grid<u8> = serde_json::from_str(s).unwrap();
3877            test_grid(&grid, 2, 2, Order::ColumnMajor, &[1, 3, 2, 4]);
3878        }
3879    }
3880}