1 #![warn(clippy::all, clippy::pedantic, clippy::nursery)] 2 /*! 3 # Two Dimensional Grid 4 Continuous growable 2D data structure. 5 The purpose of this crate is to provide an universal data structure that is faster, 6 uses less memory, and is easier to use than a naive `Vec<Vec<T>>` solution. 7 8 This 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. 10 If 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/). 12 No other dependencies except for the std lib are used. 13 Most 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 17 Similar to *C-like* arrays, `grid` uses a flat 1D `Vec<T>` data structure to have a continuous 18 memory data layout. See also [this](https://stackoverflow.com/questions/17259877/1d-or-2d-array-whats-faster) 19 explanation of why you should probably use a one-dimensional array approach. 20 21 Note that this crate uses a [*row-major*](https://eli.thegreenplace.net/2015/memory-layout-of-multi-dimensional-arrays) memory layout by default. 22 23 If you need a specific memory layout, please seek the `*_with_order` constructors. You should also take note that some transformation methods 24 change the internal memory layout, like [`transpose`](Grid::transpose). 25 26 This choice is important, because operations on rows are faster with a row-major memory layout. 27 Likewise, operations on columns are faster with column-major memory layout. 28 29 # Examples 30 ``` 31 use grid::*; 32 let mut grid = grid![[1,2,3] 33 [4,5,6]]; 34 assert_eq!(grid, Grid::from_vec(vec![1,2,3,4,5,6],3)); 35 assert_eq!(grid.get(0, 2), Some(&3)); 36 assert_eq!(grid[(1, 1)], 5); 37 assert_eq!(grid.size(), (2, 3)); 38 grid.push_row(vec![7,8,9]); 39 assert_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"))] 46 extern crate alloc; 47 #[cfg(not(feature = "std"))] 48 use alloc::{format, vec, vec::Vec}; 49 #[cfg(feature = "serde")] 50 use serde::{ 51 de::{self, Deserialize, Deserializer, MapAccess, SeqAccess, Visitor}, 52 ser::{Serialize, SerializeStruct, Serializer}, 53 }; 54 55 use core::cmp::Eq; 56 use core::fmt; 57 use core::hash; 58 use core::iter::StepBy; 59 use core::ops::Index; 60 use core::ops::IndexMut; 61 use core::slice::Iter; 62 use core::slice::IterMut; 63 use core::{cmp, convert::TryInto}; 64 65 #[doc(hidden)] 66 #[macro_export] 67 macro_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] 98 macro_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] 155 macro_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))] 190 pub 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 199 impl Order { counterpart(self) -> Self200 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`. 215 pub struct Grid<T> { 216 data: Vec<T>, 217 cols: usize, 218 rows: usize, 219 order: Order, 220 } 221 222 #[cfg(feature = "serde")] 223 impl<'de, T: Deserialize<'de>> Deserialize<'de> for Grid<T> { deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: Deserializer<'de>,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")] 304 impl<T: Serialize> Serialize for Grid<T> { serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer,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 318 impl<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] new(rows: usize, cols: usize) -> Self where T: Default,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`. new_with_order(rows: usize, cols: usize, order: Order) -> Self where T: Default,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] init(rows: usize, cols: usize, data: T) -> Self where T: Clone,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`. init_with_order(rows: usize, cols: usize, order: Order, data: T) -> Self where T: Clone,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] with_capacity(rows: usize, cols: usize) -> Self422 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] with_capacity_and_order(rows: usize, cols: usize, order: Order) -> Self432 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] from_vec(vec: Vec<T>, cols: usize) -> Self471 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] from_vec_with_order(vec: Vec<T>, cols: usize, order: Order) -> Self481 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] get_index(&self, row: usize, col: usize) -> usize510 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] get_unchecked(&self, row: impl Into<usize>, col: impl Into<usize>) -> &T525 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] get_unchecked_mut( &mut self, row: impl Into<usize>, col: impl Into<usize>, ) -> &mut T538 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] get(&self, row: impl TryInto<usize>, col: impl TryInto<usize>) -> Option<&T>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] get_mut( &mut self, row: impl TryInto<usize>, col: impl TryInto<usize>, ) -> Option<&mut T>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] size(&self) -> (usize, usize)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] rows(&self) -> usize586 pub const fn rows(&self) -> usize { 587 self.rows 588 } 589 590 /// Returns the number of columns of the grid. 591 #[must_use] cols(&self) -> usize592 pub const fn cols(&self) -> usize { 593 self.cols 594 } 595 596 /// Returns the internal memory layout of the grid. 597 #[must_use] order(&self) -> Order598 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] is_empty(&self) -> bool610 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. clear(&mut self)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 /// ``` iter(&self) -> Iter<T>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 /// ``` iter_mut(&mut self) -> IterMut<T>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. iter_col(&self, col: usize) -> StepBy<Iter<T>>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. iter_col_mut(&mut self, col: usize) -> StepBy<IterMut<T>>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. iter_row(&self, row: usize) -> StepBy<Iter<T>>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. iter_row_mut(&mut self, row: usize) -> StepBy<IterMut<T>>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 /// ``` indexed_iter(&self) -> impl Iterator<Item = ((usize, usize), &T)>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 /// ``` indexed_iter_mut(&mut self) -> impl Iterator<Item = ((usize, usize), &mut T)>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 /// Add a new row to the grid. 885 /// 886 /// # Examples 887 /// 888 /// ``` 889 /// use grid::*; 890 /// let mut grid: Grid<u8> = grid![[1, 2, 3][3, 4, 5]]; 891 /// let row = vec![6,7,8]; 892 /// grid.push_row(row); 893 /// assert_eq!(grid.rows(), 3); 894 /// assert_eq!(grid[(2, 0)], 6); 895 /// assert_eq!(grid[(2, 1)], 7); 896 /// assert_eq!(grid[(2, 2)], 8); 897 /// ``` 898 /// 899 /// Can also be used to init an empty grid: 900 /// 901 /// ``` 902 /// use grid::*; 903 /// let mut grid: Grid<u8> = grid![]; 904 /// let row = vec![1,2,3]; 905 /// grid.push_row(row); 906 /// assert_eq!(grid.size(), (1, 3)); 907 /// ``` 908 /// 909 /// # Performance 910 /// 911 /// This method will be significantly slower if the grid uses a column-major memory layout. 912 /// 913 /// # Panics 914 /// 915 /// Panics if: 916 /// - the grid is not empty and `row.len() != grid.cols()` 917 /// - `row.len() == 0` push_row(&mut self, row: Vec<T>)918 pub fn push_row(&mut self, row: Vec<T>) { 919 assert_ne!(row.len(), 0); 920 assert!( 921 !(self.rows > 0 && row.len() != self.cols), 922 "pushed row does not match. Length must be {:?}, but was {:?}.", 923 self.cols, 924 row.len() 925 ); 926 self.data.extend(row); 927 if self.order == Order::ColumnMajor { 928 for i in (1..self.cols).rev() { 929 let col_idx = i * self.rows; 930 self.data[col_idx..col_idx + self.rows + i].rotate_right(i); 931 } 932 } 933 self.rows += 1; 934 if self.cols == 0 { 935 self.cols = self.data.len(); 936 } 937 } 938 939 /// Add a new column to the grid. 940 /// 941 /// # Examples 942 /// 943 /// ``` 944 /// use grid::*; 945 /// let mut grid: Grid<u8> = grid![[1, 2, 3][3, 4, 5]]; 946 /// let col = vec![4,6]; 947 /// grid.push_col(col); 948 /// assert_eq!(grid.cols(), 4); 949 /// assert_eq!(grid[(0, 3)], 4); 950 /// assert_eq!(grid[(1, 3)], 6); 951 /// ``` 952 /// 953 /// Can also be used to init an empty grid: 954 /// 955 /// ``` 956 /// use grid::*; 957 /// let mut grid: Grid<u8> = grid![]; 958 /// let col = vec![1,2,3]; 959 /// grid.push_col(col); 960 /// assert_eq!(grid.size(), (3, 1)); 961 /// ``` 962 /// 963 /// # Performance 964 /// 965 /// This method will be significantly slower if the grid uses a row-major memory layout, 966 /// which is the default. 967 /// 968 /// # Panics 969 /// 970 /// Panics if: 971 /// - the grid is not empty and `col.len() != grid.rows()` 972 /// - `col.len() == 0` push_col(&mut self, col: Vec<T>)973 pub fn push_col(&mut self, col: Vec<T>) { 974 assert_ne!(col.len(), 0); 975 assert!( 976 !(self.cols > 0 && col.len() != self.rows), 977 "pushed column does not match. Length must be {:?}, but was {:?}.", 978 self.rows, 979 col.len() 980 ); 981 self.data.extend(col); 982 if self.order == Order::RowMajor { 983 for i in (1..self.rows).rev() { 984 let row_idx = i * self.cols; 985 self.data[row_idx..row_idx + self.cols + i].rotate_right(i); 986 } 987 } 988 self.cols += 1; 989 if self.rows == 0 { 990 self.rows = self.data.len(); 991 } 992 } 993 994 /// Removes the last row from a grid and returns it, or None if it is empty. 995 /// 996 /// # Examples 997 /// ``` 998 /// use grid::*; 999 /// let mut grid = grid![[1,2,3][4,5,6]]; 1000 /// assert_eq![grid.pop_row(), Some(vec![4,5,6])]; 1001 /// assert_eq![grid.pop_row(), Some(vec![1,2,3])]; 1002 /// assert_eq![grid.pop_row(), None]; 1003 /// ``` 1004 /// 1005 /// # Performance 1006 /// 1007 /// This method will be significantly slower if the grid uses a column-major memory layout. pop_row(&mut self) -> Option<Vec<T>>1008 pub fn pop_row(&mut self) -> Option<Vec<T>> { 1009 if self.rows == 0 { 1010 return None; 1011 } 1012 if self.order == Order::ColumnMajor { 1013 for i in 1..self.cols { 1014 let col_idx = i * (self.rows - 1); 1015 self.data[col_idx..col_idx + self.rows + i - 1].rotate_left(i); 1016 } 1017 } 1018 let row = self.data.split_off(self.data.len() - self.cols); 1019 self.rows -= 1; 1020 if self.rows == 0 { 1021 self.cols = 0; 1022 } 1023 Some(row) 1024 } 1025 1026 /// Remove a Row at the index and return a vector of it. 1027 /// 1028 /// # Examples 1029 /// ``` 1030 /// use grid::*; 1031 /// let mut grid = grid![[1,2][3,4][5,6]]; 1032 /// assert_eq![grid.remove_row(1), Some(vec![3,4])]; 1033 /// assert_eq![grid.remove_row(0), Some(vec![1,2])]; 1034 /// assert_eq![grid.remove_row(0), Some(vec![5,6])]; 1035 /// assert_eq![grid.remove_row(0), None]; 1036 /// ``` 1037 /// 1038 /// # Performance 1039 /// 1040 /// This method will be significantly slower if the grid uses a column-major memory layout. remove_row(&mut self, row_index: usize) -> Option<Vec<T>>1041 pub fn remove_row(&mut self, row_index: usize) -> Option<Vec<T>> { 1042 if self.cols == 0 || self.rows == 0 || row_index >= self.rows { 1043 return None; 1044 } 1045 let row = match self.order { 1046 Order::RowMajor => self 1047 .data 1048 .drain((row_index * self.cols)..((row_index + 1) * self.cols)) 1049 .collect(), 1050 Order::ColumnMajor => { 1051 for i in 0..self.cols { 1052 let col_idx = row_index + i * (self.rows - 1); 1053 let end = cmp::min(col_idx + self.rows + i, self.data.len()); 1054 self.data[col_idx..end].rotate_left(i + 1); 1055 } 1056 self.data.split_off(self.data.len() - self.cols) 1057 } 1058 }; 1059 self.rows -= 1; 1060 if self.rows == 0 { 1061 self.cols = 0; 1062 } 1063 Some(row) 1064 } 1065 1066 /// Removes the last column from a grid and returns it, or None if it is empty. 1067 /// 1068 /// Note that this operation is much slower than the `pop_row()` because the memory layout 1069 /// of `Grid` is row-major and removing a column requires a lot of move operations. 1070 /// 1071 /// # Examples 1072 /// ``` 1073 /// use grid::*; 1074 /// let mut grid = grid![[1,2,3][4,5,6]]; 1075 /// assert_eq![grid.pop_col(), Some(vec![3,6])]; 1076 /// assert_eq![grid.pop_col(), Some(vec![2,5])]; 1077 /// assert_eq![grid.pop_col(), Some(vec![1,4])]; 1078 /// assert_eq![grid.pop_col(), None]; 1079 /// ``` 1080 /// 1081 /// # Performance 1082 /// 1083 /// This method will be significantly slower if the grid uses a row-major memory layout, 1084 /// which is the default. pop_col(&mut self) -> Option<Vec<T>>1085 pub fn pop_col(&mut self) -> Option<Vec<T>> { 1086 if self.cols == 0 { 1087 return None; 1088 } 1089 if self.order == Order::RowMajor { 1090 for i in 1..self.rows { 1091 let row_idx = i * (self.cols - 1); 1092 self.data[row_idx..row_idx + self.cols + i - 1].rotate_left(i); 1093 } 1094 } 1095 let col = self.data.split_off(self.data.len() - self.rows); 1096 self.cols -= 1; 1097 if self.cols == 0 { 1098 self.rows = 0; 1099 } 1100 Some(col) 1101 } 1102 1103 /// Remove a column at the index and return a vector of it. 1104 /// 1105 /// # Examples 1106 /// ``` 1107 /// use grid::*; 1108 /// let mut grid = grid![[1,2,3,4][5,6,7,8][9,10,11,12][13,14,15,16]]; 1109 /// assert_eq![grid.remove_col(3), Some(vec![4,8,12,16])]; 1110 /// assert_eq![grid.remove_col(0), Some(vec![1,5,9,13])]; 1111 /// assert_eq![grid.remove_col(1), Some(vec![3,7,11,15])]; 1112 /// assert_eq![grid.remove_col(0), Some(vec![2,6,10,14])]; 1113 /// assert_eq![grid.remove_col(0), None]; 1114 /// ``` 1115 /// 1116 /// # Performance 1117 /// 1118 /// This method will be significantly slower if the grid uses a row-major memory layout, 1119 /// which is the default. remove_col(&mut self, col_index: usize) -> Option<Vec<T>>1120 pub fn remove_col(&mut self, col_index: usize) -> Option<Vec<T>> { 1121 if self.cols == 0 || self.rows == 0 || col_index >= self.cols { 1122 return None; 1123 } 1124 let col = match self.order { 1125 Order::RowMajor => { 1126 for i in 0..self.rows { 1127 let row_idx = col_index + i * (self.cols - 1); 1128 let end = cmp::min(row_idx + self.cols + i, self.data.len()); 1129 self.data[row_idx..end].rotate_left(i + 1); 1130 } 1131 self.data.split_off(self.data.len() - self.rows) 1132 } 1133 Order::ColumnMajor => self 1134 .data 1135 .drain((col_index * self.rows)..((col_index + 1) * self.rows)) 1136 .collect(), 1137 }; 1138 self.cols -= 1; 1139 if self.cols == 0 { 1140 self.rows = 0; 1141 } 1142 Some(col) 1143 } 1144 1145 /// Insert a new row at the index and shifts all rows after down. 1146 /// 1147 /// # Examples 1148 /// ``` 1149 /// use grid::*; 1150 /// let mut grid = grid![[1,2,3][4,5,6]]; 1151 /// grid.insert_row(1, vec![7,8,9]); 1152 /// assert_eq!(grid, grid![[1,2,3][7,8,9][4,5,6]]); 1153 /// ``` 1154 /// 1155 /// # Performance 1156 /// 1157 /// This method will be significantly slower if the grid uses a column-major memory layout. 1158 /// 1159 /// # Panics 1160 /// 1161 /// Panics if: 1162 /// - the grid is not empty and `row.len() != grid.cols()`. 1163 /// - the index is greater than the number of rows insert_row(&mut self, index: usize, row: Vec<T>)1164 pub fn insert_row(&mut self, index: usize, row: Vec<T>) { 1165 let input_len = row.len(); 1166 assert!( 1167 !(self.cols > 0 && input_len != self.cols), 1168 "Inserted row must be of length {}, but was {}.", 1169 self.cols, 1170 row.len() 1171 ); 1172 assert!( 1173 index <= self.rows, 1174 "Out of range. Index was {}, but must be less or equal to {}.", 1175 index, 1176 self.rows 1177 ); 1178 match self.order { 1179 Order::RowMajor => { 1180 let data_idx = index * input_len; 1181 self.data.splice(data_idx..data_idx, row); 1182 } 1183 Order::ColumnMajor => { 1184 for (col_iter, row_val) in row.into_iter().enumerate() { 1185 let data_idx = col_iter * self.rows + index + col_iter; 1186 self.data.insert(data_idx, row_val); 1187 } 1188 } 1189 } 1190 self.cols = input_len; 1191 self.rows += 1; 1192 } 1193 1194 /// Insert a new column at the index. 1195 /// 1196 /// Important! Insertion of columns is a lot slower than the lines insertion. 1197 /// This is because of the memory layout of the grid data structure. 1198 /// 1199 /// # Examples 1200 /// ``` 1201 /// use grid::*; 1202 /// let mut grid = grid![[1,2,3][4,5,6]]; 1203 /// grid.insert_col(1, vec![9,9]); 1204 /// assert_eq!(grid, grid![[1,9,2,3][4,9,5,6]]) 1205 /// ``` 1206 /// 1207 /// # Performance 1208 /// 1209 /// This method will be significantly slower if the grid uses a row-major memory layout, 1210 /// which is the default. 1211 /// 1212 /// # Panics 1213 /// 1214 /// Panics if: 1215 /// - the grid is not empty and `col.len() != grid.rows()`. 1216 /// - the index is greater than the number of columns insert_col(&mut self, index: usize, col: Vec<T>)1217 pub fn insert_col(&mut self, index: usize, col: Vec<T>) { 1218 let input_len = col.len(); 1219 assert!( 1220 !(self.rows > 0 && input_len != self.rows), 1221 "Inserted col must be of length {}, but was {}.", 1222 self.rows, 1223 col.len() 1224 ); 1225 assert!( 1226 index <= self.cols, 1227 "Out of range. Index was {}, but must be less or equal to {}.", 1228 index, 1229 self.cols 1230 ); 1231 match self.order { 1232 Order::RowMajor => { 1233 for (row_iter, col_val) in col.into_iter().enumerate() { 1234 let data_idx = row_iter * self.cols + index + row_iter; 1235 self.data.insert(data_idx, col_val); 1236 } 1237 } 1238 Order::ColumnMajor => { 1239 let data_idx = index * input_len; 1240 self.data.splice(data_idx..data_idx, col); 1241 } 1242 } 1243 self.rows = input_len; 1244 self.cols += 1; 1245 } 1246 1247 /// Returns a reference to the internal data structure of the grid. 1248 /// 1249 /// The order of the elements depends on the internal memory layout, which is 1250 /// row-major by default. 1251 /// 1252 /// # Examples 1253 /// ``` 1254 /// use grid::*; 1255 /// let grid = grid![[1,2,3][4,5,6]]; 1256 /// let flat = grid.flatten(); 1257 /// assert_eq!(flat, &vec![1,2,3,4,5,6]); 1258 /// ``` 1259 #[must_use] flatten(&self) -> &Vec<T>1260 pub const fn flatten(&self) -> &Vec<T> { 1261 &self.data 1262 } 1263 1264 /// Converts self into a vector without clones or allocation. 1265 /// 1266 /// The order of the elements depends on the internal memory layout, which is 1267 /// row-major by default. 1268 #[must_use] into_vec(self) -> Vec<T>1269 pub fn into_vec(self) -> Vec<T> { 1270 self.data 1271 } 1272 1273 /// Transpose the grid so that columns become rows in new grid. 1274 /// 1275 /// This method changes the internal memory layout. transpose(&mut self)1276 pub fn transpose(&mut self) { 1277 self.order = self.order.counterpart(); 1278 core::mem::swap(&mut self.rows, &mut self.cols); 1279 } 1280 1281 /// Flip (or mirrors) the columns. 1282 /// 1283 /// # Examples 1284 /// 1285 /// ``` 1286 /// use grid::*; 1287 /// let mut grid = grid![[1,2,3][4,5,6]]; 1288 /// grid.flip_cols(); 1289 /// assert_eq!(grid, grid![[3,2,1][6,5,4]]) 1290 /// ``` 1291 /// 1292 /// # Performance 1293 /// 1294 /// This method will be significantly slower if the grid uses a column-major memory layout. flip_cols(&mut self)1295 pub fn flip_cols(&mut self) { 1296 match self.order { 1297 Order::RowMajor => { 1298 for row in 0..self.rows { 1299 let idx = row * self.cols; 1300 self.data[idx..idx + self.cols].reverse(); 1301 } 1302 } 1303 Order::ColumnMajor => { 1304 for col in 0..self.cols / 2 { 1305 for row in 0..self.rows { 1306 let cell1 = self.get_index(row, col); 1307 let cell2 = self.get_index(row, self.cols - col - 1); 1308 self.data.swap(cell1, cell2); 1309 } 1310 } 1311 } 1312 } 1313 } 1314 1315 /// Flip (or mirrors) the rows. 1316 /// 1317 /// # Examples 1318 /// 1319 /// ``` 1320 /// use grid::*; 1321 /// let mut grid = grid![[1,2,3][4,5,6]]; 1322 /// grid.flip_rows(); 1323 /// assert_eq!(grid, grid![[4,5,6][1,2,3]]) 1324 /// ``` 1325 /// 1326 /// # Performance 1327 /// 1328 /// This method will be significantly slower if the grid uses a row-major memory layout, 1329 /// which is the default. flip_rows(&mut self)1330 pub fn flip_rows(&mut self) { 1331 match self.order { 1332 Order::RowMajor => { 1333 for row in 0..self.rows / 2 { 1334 for col in 0..self.cols { 1335 let cell1 = self.get_index(row, col); 1336 let cell2 = self.get_index(self.rows - row - 1, col); 1337 self.data.swap(cell1, cell2); 1338 } 1339 } 1340 } 1341 Order::ColumnMajor => { 1342 for col in 0..self.cols { 1343 let idx = col * self.rows; 1344 self.data[idx..idx + self.rows].reverse(); 1345 } 1346 } 1347 } 1348 } 1349 1350 /// Rotate the grid 90° counter-clockwise. 1351 /// 1352 /// This method changes the internal memory layout. 1353 /// 1354 /// # Examples 1355 /// 1356 /// ``` 1357 /// use grid::*; 1358 /// let mut grid = grid![[1,2][3,4]]; 1359 /// grid.rotate_left(); 1360 /// assert_eq!(grid, grid![[2,4][1,3]]); 1361 /// ``` 1362 /// 1363 /// # Performance 1364 /// 1365 /// This method will be significantly slower if the grid initialy uses a column-major memory layout, 1366 /// which is the default. rotate_left(&mut self)1367 pub fn rotate_left(&mut self) { 1368 self.transpose(); 1369 self.flip_rows(); 1370 } 1371 1372 /// Rotate the grid 90° clockwise. 1373 /// 1374 /// This method changes the internal memory layout. 1375 /// 1376 /// # Examples 1377 /// 1378 /// ``` 1379 /// use grid::*; 1380 /// let mut grid = grid![[1,2][3,4]]; 1381 /// grid.rotate_right(); 1382 /// assert_eq!(grid, grid![[3,1][4,2]]); 1383 /// ``` 1384 /// 1385 /// # Performance 1386 /// 1387 /// This method will be significantly slower if the grid initialy uses a row-major memory layout, 1388 /// which is the default. rotate_right(&mut self)1389 pub fn rotate_right(&mut self) { 1390 self.transpose(); 1391 self.flip_cols(); 1392 } 1393 1394 /// Rotate the grid 180°. 1395 /// 1396 /// This method **doesn't** change the internal memory layout. 1397 /// 1398 /// # Examples 1399 /// 1400 /// ``` 1401 /// use grid::*; 1402 /// let mut grid = grid![[1,2,3][4,5,6]]; 1403 /// grid.rotate_half(); 1404 /// assert_eq!(grid, grid![[6,5,4][3,2,1]]); 1405 /// ``` 1406 /// 1407 /// # Performance 1408 /// 1409 /// The performances of this method is not affected by the internal memory layout. rotate_half(&mut self)1410 pub fn rotate_half(&mut self) { 1411 self.data.reverse(); 1412 } 1413 1414 /// Fills the grid with elements by cloning `value`. 1415 /// 1416 /// # Examples 1417 /// 1418 /// ``` 1419 /// use grid::*; 1420 /// let mut grid = grid![[1,2,3][4,5,6]]; 1421 /// grid.fill(7); 1422 /// assert_eq!(grid, grid![[7,7,7][7,7,7]]); 1423 /// ``` fill(&mut self, value: T) where T: Clone,1424 pub fn fill(&mut self, value: T) 1425 where 1426 T: Clone, 1427 { 1428 self.data.fill(value); 1429 } 1430 1431 /// Fills the grid with elements returned by calling a closure repeatedly. 1432 /// 1433 /// This method uses a closure to create new values. If you'd rather 1434 /// [`Clone`] a given value, use [`fill`]. If you want to use the [`Default`] 1435 /// trait to generate values, you can pass [`Default::default`] as the 1436 /// argument. 1437 /// 1438 /// [`fill`]: Grid::fill 1439 /// 1440 /// # Examples 1441 /// 1442 /// ``` 1443 /// use grid::*; 1444 /// let mut grid = grid![[1,2,3][4,5,6]]; 1445 /// grid.fill_with(Default::default); 1446 /// assert_eq!(grid, grid![[0,0,0][0,0,0]]); 1447 /// ``` fill_with<F>(&mut self, f: F) where F: FnMut() -> T,1448 pub fn fill_with<F>(&mut self, f: F) 1449 where 1450 F: FnMut() -> T, 1451 { 1452 self.data.fill_with(f); 1453 } 1454 1455 /// Returns a new grid with the same dimensions, but with each element transformed by the closure. 1456 /// 1457 /// # Examples 1458 /// 1459 /// ``` 1460 /// use grid::*; 1461 /// let grid = grid![[1,2][3,4]]; 1462 /// let new_grid = grid.map(|x| x * 2); 1463 /// assert_eq!(new_grid, grid![[2,4][6,8]]); 1464 /// 1465 /// let grid = grid![[1,2][3,4]]; 1466 /// let new_grid = grid.map(|x| x > 2); 1467 /// assert_eq!(new_grid, grid![[false,false][true,true]]); 1468 /// ``` map<U, F>(self, f: F) -> Grid<U> where F: FnMut(T) -> U,1469 pub fn map<U, F>(self, f: F) -> Grid<U> 1470 where 1471 F: FnMut(T) -> U, 1472 { 1473 Grid { 1474 data: self.data.into_iter().map(f).collect(), 1475 cols: self.cols, 1476 rows: self.rows, 1477 order: self.order, 1478 } 1479 } 1480 1481 /// Returns a new grid with the same dimensions, but with each element 1482 /// transformed by the closure. Does not consume the grid. 1483 /// 1484 /// # Examples 1485 /// 1486 /// ``` 1487 /// use grid::*; 1488 /// let grid = grid![[1,2][3,4]]; 1489 /// let new_grid = grid.map(|x| x * 2); 1490 /// assert_eq!(new_grid, grid![[2,4][6,8]]); 1491 /// 1492 /// let grid = grid![[1,2][3,4]]; 1493 /// let new_grid = grid.map(|x| x > 2); 1494 /// assert_eq!(new_grid, grid![[false,false][true,true]]); 1495 /// ``` 1496 #[must_use] map_ref<U, F>(&self, f: F) -> Grid<U> where F: Fn(&T) -> U,1497 pub fn map_ref<U, F>(&self, f: F) -> Grid<U> 1498 where 1499 F: Fn(&T) -> U, 1500 { 1501 Grid { 1502 data: self.data.iter().map(f).collect(), 1503 cols: self.cols, 1504 rows: self.rows, 1505 order: self.order, 1506 } 1507 } 1508 1509 /// Iterate over the rows of the grid. Each time an iterator over a single 1510 /// row is returned. 1511 /// 1512 /// An item in this iterator is equal to a call to `Grid.iter_row(row_index)` 1513 /// of the corresponding row. 1514 /// 1515 /// # Examples 1516 /// 1517 /// ``` 1518 /// use grid::*; 1519 /// let mut grid = grid![[1,2,3][4,5,6]]; 1520 /// let sum_by_row: Vec<u8> = grid.iter_rows().map(|row| row.sum()).collect(); 1521 /// assert_eq!(sum_by_row, vec![1+2+3, 4+5+6]) 1522 /// ``` 1523 #[must_use] iter_rows(&self) -> GridRowIter<'_, T>1524 pub const fn iter_rows(&self) -> GridRowIter<'_, T> { 1525 GridRowIter { 1526 grid: self, 1527 row_start_index: 0, 1528 row_end_index: self.rows, 1529 } 1530 } 1531 1532 /// Iterate over the columns of the grid. Each time an iterator over a single 1533 /// column is returned. 1534 /// 1535 /// An item in this iterator is equal to a call to `Grid.iter_col(col_index)` 1536 /// of the corresponding column. 1537 /// 1538 /// # Examples 1539 /// 1540 /// ``` 1541 /// use grid::*; 1542 /// let mut grid = grid![[1,2,3][4,5,6]]; 1543 /// let sum_by_col: Vec<u8> = grid.iter_cols().map(|col| col.sum()).collect(); 1544 /// assert_eq!(sum_by_col, vec![1+4, 2+5, 3+6]) 1545 /// ``` 1546 #[must_use] iter_cols(&self) -> GridColIter<'_, T>1547 pub const fn iter_cols(&self) -> GridColIter<'_, T> { 1548 GridColIter { 1549 grid: self, 1550 col_start_index: 0, 1551 col_end_index: self.cols, 1552 } 1553 } 1554 1555 /// Swaps two elements in the Grid. 1556 /// Similar to `Vec::swap()`. 1557 /// 1558 /// # Panics 1559 /// 1560 /// Panics if either index is out of bounds. swap(&mut self, (row_a, col_a): (usize, usize), (row_b, col_b): (usize, usize))1561 pub fn swap(&mut self, (row_a, col_a): (usize, usize), (row_b, col_b): (usize, usize)) { 1562 assert!( 1563 !(row_a >= self.rows || col_a >= self.cols), 1564 "grid index out of bounds: ({row_a},{col_a}) out of ({},{})", 1565 self.rows, 1566 self.cols 1567 ); 1568 assert!( 1569 !(row_b >= self.rows || col_b >= self.cols), 1570 "grid index out of bounds: ({row_b},{col_b}) out of ({},{})", 1571 self.rows, 1572 self.cols 1573 ); 1574 1575 let a_idx = self.get_index(row_a, col_a); 1576 let b_idx = self.get_index(row_b, col_b); 1577 1578 self.data.swap(a_idx, b_idx); 1579 } 1580 } 1581 1582 impl<T> Default for Grid<T> { default() -> Self1583 fn default() -> Self { 1584 Self { 1585 data: Vec::default(), 1586 cols: 0, 1587 rows: 0, 1588 order: Order::default(), 1589 } 1590 } 1591 } 1592 1593 impl<T: Clone> Clone for Grid<T> { clone(&self) -> Self1594 fn clone(&self) -> Self { 1595 Self { 1596 rows: self.rows, 1597 cols: self.cols, 1598 data: self.data.clone(), 1599 order: self.order, 1600 } 1601 } 1602 } 1603 1604 impl<T: hash::Hash> hash::Hash for Grid<T> { 1605 #[inline] hash<H: hash::Hasher>(&self, state: &mut H)1606 fn hash<H: hash::Hasher>(&self, state: &mut H) { 1607 self.rows.hash(state); 1608 self.cols.hash(state); 1609 self.order.hash(state); 1610 self.data.hash(state); 1611 } 1612 } 1613 1614 impl<T> Index<(usize, usize)> for Grid<T> { 1615 type Output = T; 1616 1617 #[inline] index(&self, (row, col): (usize, usize)) -> &T1618 fn index(&self, (row, col): (usize, usize)) -> &T { 1619 assert!( 1620 !(row >= self.rows || col >= self.cols), 1621 "grid index out of bounds: ({row},{col}) out of ({},{})", 1622 self.rows, 1623 self.cols 1624 ); 1625 let index = self.get_index(row, col); 1626 &self.data[index] 1627 } 1628 } 1629 1630 impl<T> IndexMut<(usize, usize)> for Grid<T> { 1631 #[inline] index_mut(&mut self, (row, col): (usize, usize)) -> &mut T1632 fn index_mut(&mut self, (row, col): (usize, usize)) -> &mut T { 1633 assert!( 1634 !(row >= self.rows || col >= self.cols), 1635 "grid index out of bounds: ({row},{col}) out of ({},{})", 1636 self.rows, 1637 self.cols 1638 ); 1639 let index = self.get_index(row, col); 1640 &mut self.data[index] 1641 } 1642 } 1643 1644 impl<'a, T> IntoIterator for &'a Grid<T> { 1645 type IntoIter = core::slice::Iter<'a, T>; 1646 type Item = &'a T; 1647 into_iter(self) -> Self::IntoIter1648 fn into_iter(self) -> Self::IntoIter { 1649 self.iter() 1650 } 1651 } 1652 1653 impl<'a, T> IntoIterator for &'a mut Grid<T> { 1654 type IntoIter = core::slice::IterMut<'a, T>; 1655 type Item = &'a mut T; 1656 into_iter(self) -> Self::IntoIter1657 fn into_iter(self) -> Self::IntoIter { 1658 self.iter_mut() 1659 } 1660 } 1661 1662 impl<T: fmt::Debug> fmt::Debug for Grid<T> { fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result1663 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 1664 write!(f, "[")?; 1665 if self.cols > 0 { 1666 if f.alternate() { 1667 writeln!(f)?; 1668 /* 1669 WARNING 1670 1671 Compound types becoming enormous as the entire `fmt::Debug` width is applied to each item individually. 1672 For tuples and structs define padding and precision arguments manually to improve readability. 1673 */ 1674 let width = f.width().unwrap_or_else(|| { 1675 // Conditionally calculate the longest item by default. 1676 self.data 1677 .iter() 1678 .map(|i| format!("{i:?}").len()) 1679 .max() 1680 .unwrap() 1681 }); 1682 let precision = f.precision().unwrap_or(2); 1683 for mut row in self.iter_rows().map(Iterator::peekable) { 1684 write!(f, " [")?; 1685 while let Some(item) = row.next() { 1686 write!(f, " {item:width$.precision$?}")?; 1687 if row.peek().is_some() { 1688 write!(f, ",")?; 1689 } 1690 } 1691 writeln!(f, "]")?; 1692 } 1693 } else { 1694 for row in self.iter_rows() { 1695 f.debug_list().entries(row).finish()?; 1696 } 1697 } 1698 } 1699 write!(f, "]") 1700 } 1701 } 1702 1703 impl<T: PartialEq> PartialEq for Grid<T> { eq(&self, other: &Self) -> bool1704 fn eq(&self, other: &Self) -> bool { 1705 if self.rows != other.rows || self.cols != other.cols { 1706 return false; 1707 } 1708 if self.order == other.order { 1709 return self.data == other.data; 1710 } 1711 for (self_row, other_row) in core::iter::zip(self.iter_rows(), other.iter_rows()) { 1712 if self_row.ne(other_row) { 1713 return false; 1714 } 1715 } 1716 true 1717 } 1718 } 1719 1720 impl<T: Eq> Eq for Grid<T> {} 1721 1722 impl<T> From<Vec<Vec<T>>> for Grid<T> { 1723 #[allow(clippy::redundant_closure_for_method_calls)] from(vec: Vec<Vec<T>>) -> Self1724 fn from(vec: Vec<Vec<T>>) -> Self { 1725 let cols = vec.first().map_or(0, |row| row.len()); 1726 Self::from_vec_with_order(vec.into_iter().flatten().collect(), cols, Order::default()) 1727 } 1728 } 1729 1730 impl<T: Clone> From<&Vec<Vec<T>>> for Grid<T> { 1731 #[allow(clippy::redundant_closure_for_method_calls)] from(vec: &Vec<Vec<T>>) -> Self1732 fn from(vec: &Vec<Vec<T>>) -> Self { 1733 let cols = vec.first().map_or(0, |row| row.len()); 1734 Self::from_vec_with_order( 1735 vec.clone().into_iter().flatten().collect(), 1736 cols, 1737 Order::default(), 1738 ) 1739 } 1740 } 1741 1742 impl<T: Clone> From<&Vec<&Vec<T>>> for Grid<T> { 1743 #[allow(clippy::redundant_closure_for_method_calls)] from(vec: &Vec<&Vec<T>>) -> Self1744 fn from(vec: &Vec<&Vec<T>>) -> Self { 1745 let cols = vec.first().map_or(0, |row| row.len()); 1746 Self::from_vec_with_order( 1747 vec.clone() 1748 .into_iter() 1749 .flat_map(|inner| inner.clone()) 1750 .collect(), 1751 cols, 1752 Order::default(), 1753 ) 1754 } 1755 } 1756 1757 impl<T> From<(Vec<T>, usize)> for Grid<T> { from(value: (Vec<T>, usize)) -> Self1758 fn from(value: (Vec<T>, usize)) -> Self { 1759 Self::from_vec_with_order(value.0, value.1, Order::default()) 1760 } 1761 } 1762 1763 impl<T: Clone> From<(&Vec<T>, usize)> for Grid<T> { from(value: (&Vec<T>, usize)) -> Self1764 fn from(value: (&Vec<T>, usize)) -> Self { 1765 Self::from_vec_with_order(value.0.clone(), value.1, Order::default()) 1766 } 1767 } 1768 1769 impl<T: Clone> From<(&Vec<T>, &usize)> for Grid<T> { from(value: (&Vec<T>, &usize)) -> Self1770 fn from(value: (&Vec<T>, &usize)) -> Self { 1771 Self::from_vec_with_order(value.0.clone(), *value.1, Order::default()) 1772 } 1773 } 1774 1775 #[derive(Clone)] 1776 pub struct GridRowIter<'a, T> { 1777 grid: &'a Grid<T>, 1778 row_start_index: usize, 1779 row_end_index: usize, 1780 } 1781 1782 #[derive(Clone)] 1783 pub struct GridColIter<'a, T> { 1784 grid: &'a Grid<T>, 1785 col_start_index: usize, 1786 col_end_index: usize, 1787 } 1788 1789 impl<'a, T> Iterator for GridRowIter<'a, T> { 1790 type Item = StepBy<Iter<'a, T>>; 1791 next(&mut self) -> Option<Self::Item>1792 fn next(&mut self) -> Option<Self::Item> { 1793 if self.row_start_index >= self.row_end_index { 1794 return None; 1795 } 1796 1797 let row_iter = self.grid.iter_row(self.row_start_index); 1798 self.row_start_index += 1; 1799 Some(row_iter) 1800 } 1801 size_hint(&self) -> (usize, Option<usize>)1802 fn size_hint(&self) -> (usize, Option<usize>) { 1803 let size = self.row_end_index - self.row_start_index; 1804 (size, Some(size)) 1805 } 1806 } 1807 1808 impl<T> ExactSizeIterator for GridRowIter<'_, T> {} 1809 1810 impl<T> DoubleEndedIterator for GridRowIter<'_, T> { next_back(&mut self) -> Option<Self::Item>1811 fn next_back(&mut self) -> Option<Self::Item> { 1812 if self.row_start_index >= self.row_end_index { 1813 return None; 1814 } 1815 1816 let row_iter = self.grid.iter_row(self.row_end_index - 1); 1817 self.row_end_index -= 1; 1818 Some(row_iter) 1819 } 1820 } 1821 1822 impl<'a, T> Iterator for GridColIter<'a, T> { 1823 type Item = StepBy<Iter<'a, T>>; 1824 next(&mut self) -> Option<Self::Item>1825 fn next(&mut self) -> Option<Self::Item> { 1826 if self.col_start_index >= self.col_end_index { 1827 return None; 1828 } 1829 1830 let col_iter = self.grid.iter_col(self.col_start_index); 1831 self.col_start_index += 1; 1832 Some(col_iter) 1833 } 1834 size_hint(&self) -> (usize, Option<usize>)1835 fn size_hint(&self) -> (usize, Option<usize>) { 1836 let size = self.col_end_index - self.col_start_index; 1837 (size, Some(size)) 1838 } 1839 } 1840 1841 impl<T> ExactSizeIterator for GridColIter<'_, T> {} 1842 1843 impl<T> DoubleEndedIterator for GridColIter<'_, T> { next_back(&mut self) -> Option<Self::Item>1844 fn next_back(&mut self) -> Option<Self::Item> { 1845 if self.col_start_index >= self.col_end_index { 1846 return None; 1847 } 1848 1849 let col_iter = self.grid.iter_col(self.col_end_index - 1); 1850 self.col_end_index -= 1; 1851 Some(col_iter) 1852 } 1853 } 1854 1855 #[cfg(test)] 1856 mod test { 1857 use super::*; 1858 #[cfg(not(feature = "std"))] 1859 use alloc::string::String; 1860 test_grid<T>(grid: &Grid<T>, rows: usize, cols: usize, order: Order, data: &[T]) where T: fmt::Debug + PartialEq,1861 fn test_grid<T>(grid: &Grid<T>, rows: usize, cols: usize, order: Order, data: &[T]) 1862 where 1863 T: fmt::Debug + PartialEq, 1864 { 1865 assert_eq!(grid.rows, rows, "number of rows is unexpected"); 1866 assert_eq!(grid.cols, cols, "number of cols is unexpected"); 1867 assert_eq!(grid.order, order, "grid order is unexpected"); 1868 assert_eq!(grid.data, data, "internal data is unexpected"); 1869 } 1870 1871 #[test] from_1d_vec()1872 fn from_1d_vec() { 1873 let grid: Grid<u8> = Grid::from((vec![1, 2, 3], 1)); 1874 test_grid(&grid, 3, 1, Order::RowMajor, &[1, 2, 3]); 1875 } 1876 1877 #[test] 1878 #[should_panic] 1879 #[allow(clippy::should_panic_without_expect)] from_1d_vec_panic()1880 fn from_1d_vec_panic() { 1881 let _: Grid<u8> = Grid::from((vec![1, 2, 3], 2)); 1882 } 1883 1884 #[test] from_1d_vec_reference()1885 fn from_1d_vec_reference() { 1886 let vec = vec![1, 2, 3]; 1887 let grid: Grid<u8> = Grid::from((&vec, 1)); 1888 test_grid(&grid, 3, 1, Order::RowMajor, &[1, 2, 3]); 1889 } 1890 1891 #[test] 1892 #[should_panic] 1893 #[allow(clippy::should_panic_without_expect)] from_1d_vec_reference_panic()1894 fn from_1d_vec_reference_panic() { 1895 let vec = vec![1, 2, 3]; 1896 let _: Grid<u8> = Grid::from((&vec, 2)); 1897 } 1898 1899 #[test] from_1d_vec_reference_and_reference()1900 fn from_1d_vec_reference_and_reference() { 1901 let vec = vec![1, 2, 3]; 1902 let cols = 1; 1903 let grid: Grid<u8> = Grid::from((&vec, &cols)); 1904 test_grid(&grid, 3, 1, Order::RowMajor, &[1, 2, 3]); 1905 } 1906 1907 #[test] 1908 #[should_panic] 1909 #[allow(clippy::should_panic_without_expect)] from_1d_vec_reference_and_reference_panic()1910 fn from_1d_vec_reference_and_reference_panic() { 1911 let vec = vec![1, 2, 3]; 1912 let cols = 2; 1913 let _: Grid<u8> = Grid::from((&vec, &cols)); 1914 } 1915 1916 #[test] from_2d_vec()1917 fn from_2d_vec() { 1918 let grid: Grid<u8> = Grid::from(vec![vec![1, 2, 3], vec![4, 5, 6], vec![7, 8, 9]]); 1919 test_grid(&grid, 3, 3, Order::RowMajor, &[1, 2, 3, 4, 5, 6, 7, 8, 9]); 1920 } 1921 1922 #[test] 1923 #[should_panic] 1924 #[allow(clippy::should_panic_without_expect)] from_2d_vec_panic()1925 fn from_2d_vec_panic() { 1926 let _: Grid<u8> = Grid::from(vec![vec![1, 2, 3], vec![4, 5, 6], vec![7, 8]]); 1927 } 1928 1929 #[test] from_2d_vec_reference()1930 fn from_2d_vec_reference() { 1931 let vec = vec![vec![1, 2, 3], vec![4, 5, 6], vec![7, 8, 9]]; 1932 let grid: Grid<u8> = Grid::from(&vec); 1933 test_grid(&grid, 3, 3, Order::RowMajor, &[1, 2, 3, 4, 5, 6, 7, 8, 9]); 1934 } 1935 1936 #[test] 1937 #[should_panic] 1938 #[allow(clippy::should_panic_without_expect)] from_2d_vec_reference_panic()1939 fn from_2d_vec_reference_panic() { 1940 let vec = vec![vec![1, 2, 3], vec![4, 5, 6], vec![7, 8]]; 1941 let _: Grid<u8> = Grid::from(&vec); 1942 } 1943 1944 #[test] from_2d_vec_reference_of_references()1945 fn from_2d_vec_reference_of_references() { 1946 let inner_vec1 = vec![1, 2, 3]; 1947 let inner_vec2 = vec![4, 5, 6]; 1948 let inner_vec3 = vec![7, 8, 9]; 1949 let vec = vec![&inner_vec1, &inner_vec2, &inner_vec3]; 1950 let grid: Grid<u8> = Grid::from(&vec); 1951 test_grid(&grid, 3, 3, Order::RowMajor, &[1, 2, 3, 4, 5, 6, 7, 8, 9]); 1952 } 1953 1954 #[test] 1955 #[should_panic] 1956 #[allow(clippy::should_panic_without_expect)] from_2d_vec_reference_of_references_panic()1957 fn from_2d_vec_reference_of_references_panic() { 1958 let inner_vec1 = vec![1, 2, 3]; 1959 let inner_vec2 = vec![4, 5, 6]; 1960 let inner_vec3 = vec![7, 8]; 1961 let vec = vec![&inner_vec1, &inner_vec2, &inner_vec3]; 1962 let _: Grid<u8> = Grid::from(&vec); 1963 } 1964 1965 #[test] from_vec_zero_with_cols()1966 fn from_vec_zero_with_cols() { 1967 let grid: Grid<u8> = Grid::from_vec(vec![], 1); 1968 test_grid(&grid, 0, 0, Order::RowMajor, &[]); 1969 } 1970 1971 #[test] from_vec_zero()1972 fn from_vec_zero() { 1973 let grid: Grid<u8> = Grid::from_vec(vec![], 0); 1974 test_grid(&grid, 0, 0, Order::RowMajor, &[]); 1975 } 1976 1977 #[test] 1978 #[should_panic] 1979 #[allow(clippy::should_panic_without_expect)] from_vec_panics_1()1980 fn from_vec_panics_1() { 1981 let _: Grid<u8> = Grid::from_vec(vec![1, 2, 3], 0); 1982 } 1983 1984 #[test] 1985 #[should_panic] 1986 #[allow(clippy::should_panic_without_expect)] from_vec_panics_2()1987 fn from_vec_panics_2() { 1988 let _: Grid<u8> = Grid::from_vec(vec![1, 2, 3], 2); 1989 } 1990 1991 #[test] from_vec_uses_original_vec()1992 fn from_vec_uses_original_vec() { 1993 let capacity = 10_000_000; 1994 let vec = Vec::with_capacity(capacity); 1995 let grid: Grid<u8> = Grid::from_vec(vec, 0); 1996 assert!(grid.into_vec().capacity() >= capacity); 1997 } 1998 1999 #[test] from_vec_with_order_zero_with_cols()2000 fn from_vec_with_order_zero_with_cols() { 2001 let grid: Grid<u8> = Grid::from_vec_with_order(vec![], 1, Order::ColumnMajor); 2002 test_grid(&grid, 0, 0, Order::ColumnMajor, &[]); 2003 } 2004 2005 #[test] from_vec_with_order_zero()2006 fn from_vec_with_order_zero() { 2007 let grid: Grid<u8> = Grid::from_vec_with_order(vec![], 0, Order::ColumnMajor); 2008 test_grid(&grid, 0, 0, Order::ColumnMajor, &[]); 2009 } 2010 2011 #[test] 2012 #[should_panic] 2013 #[allow(clippy::should_panic_without_expect)] from_vec_with_order_panics_1()2014 fn from_vec_with_order_panics_1() { 2015 let _: Grid<u8> = Grid::from_vec_with_order(vec![1, 2, 3], 0, Order::ColumnMajor); 2016 } 2017 2018 #[test] 2019 #[should_panic] 2020 #[allow(clippy::should_panic_without_expect)] from_vec_with_order_panics_2()2021 fn from_vec_with_order_panics_2() { 2022 let _: Grid<u8> = Grid::from_vec_with_order(vec![1, 2, 3], 2, Order::ColumnMajor); 2023 } 2024 2025 #[test] from_vec_with_order_uses_original_vec()2026 fn from_vec_with_order_uses_original_vec() { 2027 let capacity = 10_000_000; 2028 let vec = Vec::with_capacity(capacity); 2029 let grid: Grid<u8> = Grid::from_vec_with_order(vec, 0, Order::ColumnMajor); 2030 assert!(grid.into_vec().capacity() >= capacity); 2031 } 2032 2033 #[test] insert_col_at_end()2034 fn insert_col_at_end() { 2035 let mut grid: Grid<u8> = Grid::from_vec_with_order(vec![1, 2, 3, 4], 2, Order::RowMajor); 2036 grid.insert_col(2, vec![5, 6]); 2037 test_grid(&grid, 2, 3, Order::RowMajor, &[1, 2, 5, 3, 4, 6]); 2038 } 2039 2040 #[test] 2041 #[should_panic] 2042 #[allow(clippy::should_panic_without_expect)] insert_col_out_of_idx()2043 fn insert_col_out_of_idx() { 2044 let mut grid: Grid<u8> = Grid::from_vec_with_order(vec![1, 2, 3, 4], 2, Order::RowMajor); 2045 grid.insert_col(3, vec![4, 5]); 2046 } 2047 2048 #[test] insert_col_empty()2049 fn insert_col_empty() { 2050 let mut grid: Grid<u8> = Grid::from_vec_with_order(vec![], 0, Order::RowMajor); 2051 grid.insert_col(0, vec![1, 2, 3]); 2052 test_grid(&grid, 3, 1, Order::RowMajor, &[1, 2, 3]); 2053 } 2054 2055 #[test] insert_col_at_end_column_major()2056 fn insert_col_at_end_column_major() { 2057 let mut grid: Grid<u8> = Grid::from_vec_with_order(vec![1, 3, 2, 4], 2, Order::ColumnMajor); 2058 grid.insert_col(2, vec![5, 6]); 2059 test_grid(&grid, 2, 3, Order::ColumnMajor, &[1, 3, 2, 4, 5, 6]); 2060 } 2061 2062 #[test] 2063 #[should_panic] 2064 #[allow(clippy::should_panic_without_expect)] insert_col_out_of_idx_column_major()2065 fn insert_col_out_of_idx_column_major() { 2066 let mut grid: Grid<u8> = Grid::from_vec_with_order(vec![1, 3, 2, 4], 2, Order::ColumnMajor); 2067 grid.insert_col(3, vec![4, 5]); 2068 } 2069 2070 #[test] insert_col_empty_column_major()2071 fn insert_col_empty_column_major() { 2072 let mut grid: Grid<u8> = Grid::from_vec_with_order(vec![], 0, Order::ColumnMajor); 2073 grid.insert_col(0, vec![1, 2, 3]); 2074 test_grid(&grid, 3, 1, Order::ColumnMajor, &[1, 2, 3]); 2075 } 2076 2077 #[test] insert_row_at_end()2078 fn insert_row_at_end() { 2079 let mut grid: Grid<u8> = Grid::from_vec_with_order(vec![1, 2, 3, 4], 2, Order::RowMajor); 2080 grid.insert_row(2, vec![5, 6]); 2081 test_grid(&grid, 3, 2, Order::RowMajor, &[1, 2, 3, 4, 5, 6]); 2082 } 2083 2084 #[test] insert_row_empty()2085 fn insert_row_empty() { 2086 let mut grid: Grid<u8> = Grid::from_vec_with_order(vec![], 0, Order::RowMajor); 2087 grid.insert_row(0, vec![1, 2, 3]); 2088 test_grid(&grid, 1, 3, Order::RowMajor, &[1, 2, 3]); 2089 } 2090 2091 #[test] 2092 #[should_panic] 2093 #[allow(clippy::should_panic_without_expect)] insert_row_out_of_idx()2094 fn insert_row_out_of_idx() { 2095 let mut grid: Grid<u8> = Grid::from_vec_with_order(vec![1, 2, 3, 4], 2, Order::RowMajor); 2096 grid.insert_row(3, vec![4, 5]); 2097 } 2098 2099 #[test] 2100 #[should_panic] 2101 #[allow(clippy::should_panic_without_expect)] insert_row_wrong_size_of_idx()2102 fn insert_row_wrong_size_of_idx() { 2103 let mut grid: Grid<u8> = Grid::from_vec_with_order(vec![1, 2, 3, 4], 2, Order::RowMajor); 2104 grid.insert_row(1, vec![4, 5, 4]); 2105 } 2106 2107 #[test] insert_row_start()2108 fn insert_row_start() { 2109 let mut grid: Grid<u8> = Grid::from_vec_with_order(vec![1, 2, 3, 4], 2, Order::RowMajor); 2110 grid.insert_row(1, vec![5, 6]); 2111 test_grid(&grid, 3, 2, Order::RowMajor, &[1, 2, 5, 6, 3, 4]); 2112 } 2113 2114 #[test] insert_row_at_end_column_major()2115 fn insert_row_at_end_column_major() { 2116 let mut grid: Grid<u8> = Grid::from_vec_with_order(vec![1, 3, 2, 4], 2, Order::ColumnMajor); 2117 grid.insert_row(2, vec![5, 6]); 2118 test_grid(&grid, 3, 2, Order::ColumnMajor, &[1, 3, 5, 2, 4, 6]); 2119 } 2120 2121 #[test] insert_row_empty_column_major()2122 fn insert_row_empty_column_major() { 2123 let mut grid: Grid<u8> = Grid::from_vec_with_order(vec![], 0, Order::ColumnMajor); 2124 grid.insert_row(0, vec![1, 2, 3]); 2125 test_grid(&grid, 1, 3, Order::ColumnMajor, &[1, 2, 3]); 2126 } 2127 2128 #[test] 2129 #[should_panic] 2130 #[allow(clippy::should_panic_without_expect)] insert_row_out_of_idx_column_major()2131 fn insert_row_out_of_idx_column_major() { 2132 let mut grid: Grid<u8> = Grid::from_vec_with_order(vec![1, 2, 3, 4], 2, Order::ColumnMajor); 2133 grid.insert_row(3, vec![4, 5]); 2134 } 2135 2136 #[test] 2137 #[should_panic] 2138 #[allow(clippy::should_panic_without_expect)] insert_row_wrong_size_of_idx_column_major()2139 fn insert_row_wrong_size_of_idx_column_major() { 2140 let mut grid: Grid<u8> = Grid::from_vec_with_order(vec![1, 2, 3, 4], 2, Order::ColumnMajor); 2141 grid.insert_row(1, vec![4, 5, 4]); 2142 } 2143 2144 #[test] insert_row_start_column_major()2145 fn insert_row_start_column_major() { 2146 let mut grid: Grid<u8> = Grid::from_vec_with_order(vec![1, 3, 2, 4], 2, Order::ColumnMajor); 2147 grid.insert_row(1, vec![5, 6]); 2148 test_grid(&grid, 3, 2, Order::ColumnMajor, &[1, 5, 3, 2, 6, 4]); 2149 } 2150 2151 #[test] pop_col_1x3()2152 fn pop_col_1x3() { 2153 let mut grid: Grid<u8> = Grid::from_vec_with_order(vec![1, 2, 3], 3, Order::RowMajor); 2154 assert_eq!(grid.pop_col(), Some(vec![3])); 2155 test_grid(&grid, 1, 2, Order::RowMajor, &[1, 2]); 2156 assert_eq!(grid.pop_col(), Some(vec![2])); 2157 test_grid(&grid, 1, 1, Order::RowMajor, &[1]); 2158 assert_eq!(grid.pop_col(), Some(vec![1])); 2159 test_grid(&grid, 0, 0, Order::RowMajor, &[]); 2160 assert_eq!(grid.pop_col(), None); 2161 test_grid(&grid, 0, 0, Order::RowMajor, &[]); 2162 } 2163 2164 #[test] pop_col_3x1()2165 fn pop_col_3x1() { 2166 let mut grid: Grid<u8> = Grid::from_vec_with_order(vec![1, 2, 3], 1, Order::RowMajor); 2167 assert_eq!(grid.pop_col(), Some(vec![1, 2, 3])); 2168 test_grid(&grid, 0, 0, Order::RowMajor, &[]); 2169 assert_eq!(grid.pop_col(), None); 2170 test_grid(&grid, 0, 0, Order::RowMajor, &[]); 2171 } 2172 2173 #[test] pop_col_2x2()2174 fn pop_col_2x2() { 2175 let mut grid: Grid<u8> = Grid::from_vec_with_order(vec![1, 2, 3, 4], 2, Order::RowMajor); 2176 assert_eq!(grid.pop_col(), Some(vec![2, 4])); 2177 assert_eq!(grid.size(), (2, 1)); 2178 test_grid(&grid, 2, 1, Order::RowMajor, &[1, 3]); 2179 assert_eq!(grid.pop_col(), Some(vec![1, 3])); 2180 test_grid(&grid, 0, 0, Order::RowMajor, &[]); 2181 assert_eq!(grid.pop_col(), None); 2182 test_grid(&grid, 0, 0, Order::RowMajor, &[]); 2183 } 2184 2185 #[test] pop_col_3x4()2186 fn pop_col_3x4() { 2187 let internal = vec![1, 2, 3, 4, 11, 22, 33, 44, 111, 222, 333, 444]; 2188 let mut grid: Grid<u16> = Grid::from_vec_with_order(internal, 4, Order::RowMajor); 2189 assert_eq!(grid.pop_col(), Some(vec![4, 44, 444])); 2190 let expected = [1, 2, 3, 11, 22, 33, 111, 222, 333]; 2191 test_grid(&grid, 3, 3, Order::RowMajor, &expected); 2192 assert_eq!(grid.pop_col(), Some(vec![3, 33, 333])); 2193 test_grid(&grid, 3, 2, Order::RowMajor, &[1, 2, 11, 22, 111, 222]); 2194 assert_eq!(grid.pop_col(), Some(vec![2, 22, 222])); 2195 test_grid(&grid, 3, 1, Order::RowMajor, &[1, 11, 111]); 2196 assert_eq!(grid.pop_col(), Some(vec![1, 11, 111])); 2197 test_grid(&grid, 0, 0, Order::RowMajor, &[]); 2198 assert_eq!(grid.pop_col(), None); 2199 test_grid(&grid, 0, 0, Order::RowMajor, &[]); 2200 } 2201 2202 #[test] pop_col_empty()2203 fn pop_col_empty() { 2204 let mut grid: Grid<u8> = Grid::from_vec_with_order(vec![], 0, Order::RowMajor); 2205 assert_eq!(grid.pop_col(), None); 2206 test_grid(&grid, 0, 0, Order::RowMajor, &[]); 2207 } 2208 2209 #[test] pop_col_1x3_column_major()2210 fn pop_col_1x3_column_major() { 2211 let mut grid: Grid<u8> = Grid::from_vec_with_order(vec![1, 2, 3], 3, Order::ColumnMajor); 2212 assert_eq!(grid.pop_col(), Some(vec![3])); 2213 test_grid(&grid, 1, 2, Order::ColumnMajor, &[1, 2]); 2214 assert_eq!(grid.pop_col(), Some(vec![2])); 2215 test_grid(&grid, 1, 1, Order::ColumnMajor, &[1]); 2216 assert_eq!(grid.pop_col(), Some(vec![1])); 2217 test_grid(&grid, 0, 0, Order::ColumnMajor, &[]); 2218 assert_eq!(grid.pop_col(), None); 2219 test_grid(&grid, 0, 0, Order::ColumnMajor, &[]); 2220 } 2221 2222 #[test] pop_col_3x1_column_major()2223 fn pop_col_3x1_column_major() { 2224 let mut grid: Grid<u8> = Grid::from_vec_with_order(vec![1, 2, 3], 1, Order::ColumnMajor); 2225 assert_eq!(grid.pop_col(), Some(vec![1, 2, 3])); 2226 test_grid(&grid, 0, 0, Order::ColumnMajor, &[]); 2227 assert_eq!(grid.pop_col(), None); 2228 test_grid(&grid, 0, 0, Order::ColumnMajor, &[]); 2229 } 2230 2231 #[test] pop_col_2x2_column_major()2232 fn pop_col_2x2_column_major() { 2233 let mut grid: Grid<u8> = Grid::from_vec_with_order(vec![1, 3, 2, 4], 2, Order::ColumnMajor); 2234 assert_eq!(grid.pop_col(), Some(vec![2, 4])); 2235 assert_eq!(grid.size(), (2, 1)); 2236 test_grid(&grid, 2, 1, Order::ColumnMajor, &[1, 3]); 2237 assert_eq!(grid.pop_col(), Some(vec![1, 3])); 2238 test_grid(&grid, 0, 0, Order::ColumnMajor, &[]); 2239 assert_eq!(grid.pop_col(), None); 2240 test_grid(&grid, 0, 0, Order::ColumnMajor, &[]); 2241 } 2242 2243 #[test] pop_col_3x4_column_major()2244 fn pop_col_3x4_column_major() { 2245 let internal = vec![1, 11, 111, 2, 22, 222, 3, 33, 333, 4, 44, 444]; 2246 let mut grid: Grid<u16> = Grid::from_vec_with_order(internal, 4, Order::ColumnMajor); 2247 assert_eq!(grid.pop_col(), Some(vec![4, 44, 444])); 2248 let expected = [1, 11, 111, 2, 22, 222, 3, 33, 333]; 2249 test_grid(&grid, 3, 3, Order::ColumnMajor, &expected); 2250 assert_eq!(grid.pop_col(), Some(vec![3, 33, 333])); 2251 test_grid(&grid, 3, 2, Order::ColumnMajor, &[1, 11, 111, 2, 22, 222]); 2252 assert_eq!(grid.pop_col(), Some(vec![2, 22, 222])); 2253 test_grid(&grid, 3, 1, Order::ColumnMajor, &[1, 11, 111]); 2254 assert_eq!(grid.pop_col(), Some(vec![1, 11, 111])); 2255 test_grid(&grid, 0, 0, Order::ColumnMajor, &[]); 2256 assert_eq!(grid.pop_col(), None); 2257 test_grid(&grid, 0, 0, Order::ColumnMajor, &[]); 2258 } 2259 2260 #[test] pop_col_empty_column_major()2261 fn pop_col_empty_column_major() { 2262 let mut grid: Grid<u8> = Grid::from_vec_with_order(vec![], 0, Order::ColumnMajor); 2263 assert_eq!(grid.pop_col(), None); 2264 test_grid(&grid, 0, 0, Order::ColumnMajor, &[]); 2265 } 2266 2267 #[test] pop_row_2x2()2268 fn pop_row_2x2() { 2269 let mut grid: Grid<u8> = Grid::from_vec(vec![1, 2, 3, 4], 2); 2270 assert_eq!(grid.pop_row(), Some(vec![3, 4])); 2271 test_grid(&grid, 1, 2, Order::RowMajor, &[1, 2]); 2272 assert_eq!(grid.pop_row(), Some(vec![1, 2])); 2273 test_grid(&grid, 0, 0, Order::RowMajor, &[]); 2274 assert_eq!(grid.pop_row(), None); 2275 test_grid(&grid, 0, 0, Order::RowMajor, &[]); 2276 } 2277 2278 #[test] pop_row_empty()2279 fn pop_row_empty() { 2280 let mut grid: Grid<u8> = Grid::from_vec(vec![], 0); 2281 assert_eq!(grid.pop_row(), None); 2282 test_grid(&grid, 0, 0, Order::RowMajor, &[]); 2283 } 2284 2285 #[test] pop_row_2x2_column_major()2286 fn pop_row_2x2_column_major() { 2287 let mut grid: Grid<u8> = Grid::from_vec_with_order(vec![1, 3, 2, 4], 2, Order::ColumnMajor); 2288 assert_eq!(grid.pop_row(), Some(vec![3, 4])); 2289 test_grid(&grid, 1, 2, Order::ColumnMajor, &[1, 2]); 2290 assert_eq!(grid.pop_row(), Some(vec![1, 2])); 2291 test_grid(&grid, 0, 0, Order::ColumnMajor, &[]); 2292 assert_eq!(grid.pop_row(), None); 2293 test_grid(&grid, 0, 0, Order::ColumnMajor, &[]); 2294 } 2295 2296 #[test] pop_row_empty_column_major()2297 fn pop_row_empty_column_major() { 2298 let mut grid: Grid<u8> = Grid::from_vec_with_order(vec![], 0, Order::ColumnMajor); 2299 assert_eq!(grid.pop_row(), None); 2300 test_grid(&grid, 0, 0, Order::ColumnMajor, &[]); 2301 } 2302 2303 #[test] ne_full_empty()2304 fn ne_full_empty() { 2305 let g1 = Grid::from_vec(vec![1, 2, 3, 4], 2); 2306 let g2: Grid<u8> = grid![]; 2307 assert_ne!(g1, g2); 2308 } 2309 2310 #[test] ne()2311 fn ne() { 2312 let g1 = Grid::from_vec(vec![1, 2, 3, 5], 2); 2313 let g2 = Grid::from_vec(vec![1, 2, 3, 4], 2); 2314 assert_ne!(g1, g2); 2315 } 2316 2317 #[test] ne_dif_rows()2318 fn ne_dif_rows() { 2319 let g1 = Grid::from_vec(vec![1, 2, 3, 4], 2); 2320 let g2 = Grid::from_vec(vec![1, 2, 3, 4], 1); 2321 assert_ne!(g1, g2); 2322 } 2323 2324 #[test] equal_empty()2325 fn equal_empty() { 2326 let grid: Grid<char> = grid![]; 2327 let grid2: Grid<char> = grid![]; 2328 assert_eq!(grid, grid2); 2329 } 2330 2331 #[test] equal()2332 fn equal() { 2333 let grid: Grid<char> = grid![['a', 'b', 'c', 'd']['a', 'b', 'c', 'd']['a', 'b', 'c', 'd']]; 2334 let grid2: Grid<char> = grid![['a', 'b', 'c', 'd']['a', 'b', 'c', 'd']['a', 'b', 'c', 'd']]; 2335 assert_eq!(grid, grid2); 2336 } 2337 2338 #[test] equal_different_order()2339 fn equal_different_order() { 2340 let grid = Grid::from_vec_with_order(vec![1, 2, 3, 4], 2, Order::RowMajor); 2341 let grid2 = Grid::from_vec_with_order(vec![1, 3, 2, 4], 2, Order::ColumnMajor); 2342 assert_eq!(grid, grid2); 2343 } 2344 2345 #[test] equal_partial_eq()2346 fn equal_partial_eq() { 2347 let grid = grid![[1.0]]; 2348 let grid2 = Grid::from_vec(vec![1.0], 1); 2349 assert_eq!(grid, grid2); 2350 } 2351 2352 #[test] ne_partial_eq()2353 fn ne_partial_eq() { 2354 let grid = grid![[f64::NAN]]; 2355 assert_ne!(grid, grid); 2356 } 2357 2358 #[test] 2359 #[should_panic] 2360 #[allow(clippy::should_panic_without_expect)] idx_tup_out_of_col_bounds()2361 fn idx_tup_out_of_col_bounds() { 2362 let grid: Grid<char> = grid![['a', 'b', 'c', 'd']['a', 'b', 'c', 'd']['a', 'b', 'c', 'd']]; 2363 let _ = grid[(0, 5)]; 2364 } 2365 2366 #[test] push_col_2x3()2367 fn push_col_2x3() { 2368 let mut grid: Grid<u8> = grid![ 2369 [0, 1, 2] 2370 [10, 11, 12]]; 2371 grid.push_col(vec![3, 13]); 2372 test_grid(&grid, 2, 4, Order::RowMajor, &[0, 1, 2, 3, 10, 11, 12, 13]); 2373 } 2374 2375 #[test] push_col_3x4()2376 fn push_col_3x4() { 2377 let mut grid: Grid<char> = grid![ 2378 ['a', 'b', 'c', 'd'] 2379 ['a', 'b', 'c', 'd'] 2380 ['a', 'b', 'c', 'd']]; 2381 grid.push_col(vec!['x', 'y', 'z']); 2382 let expected = [ 2383 'a', 'b', 'c', 'd', 'x', 'a', 'b', 'c', 'd', 'y', 'a', 'b', 'c', 'd', 'z', 2384 ]; 2385 test_grid(&grid, 3, 5, Order::RowMajor, &expected); 2386 } 2387 2388 #[test] push_col_1x3()2389 fn push_col_1x3() { 2390 let mut grid: Grid<char> = grid![['a', 'b', 'c']]; 2391 grid.push_col(vec!['d']); 2392 test_grid(&grid, 1, 4, Order::RowMajor, &['a', 'b', 'c', 'd']); 2393 } 2394 2395 #[test] push_col_empty()2396 fn push_col_empty() { 2397 let mut grid: Grid<char> = grid![]; 2398 grid.push_col(vec!['b', 'b', 'b', 'b']); 2399 test_grid(&grid, 4, 1, Order::RowMajor, &['b', 'b', 'b', 'b']); 2400 } 2401 2402 #[test] 2403 #[should_panic] 2404 #[allow(clippy::should_panic_without_expect)] push_col_wrong_size()2405 fn push_col_wrong_size() { 2406 let mut grid: Grid<char> = grid![['a','a','a']['a','a','a']]; 2407 grid.push_col(vec!['b']); 2408 grid.push_col(vec!['b', 'b']); 2409 } 2410 2411 #[test] 2412 #[should_panic] 2413 #[allow(clippy::should_panic_without_expect)] push_col_zero_len()2414 fn push_col_zero_len() { 2415 let mut grid: Grid<char> = grid![]; 2416 grid.push_col(vec![]); 2417 } 2418 2419 #[test] push_col_2x3_column_major()2420 fn push_col_2x3_column_major() { 2421 let internal = vec![0, 10, 1, 11, 2, 12]; 2422 let mut grid: Grid<u8> = Grid::from_vec_with_order(internal, 3, Order::ColumnMajor); 2423 grid.push_col(vec![3, 13]); 2424 let expected = [0, 10, 1, 11, 2, 12, 3, 13]; 2425 test_grid(&grid, 2, 4, Order::ColumnMajor, &expected); 2426 } 2427 2428 #[test] push_col_3x4_column_major()2429 fn push_col_3x4_column_major() { 2430 let internal = vec!['a', 'a', 'a', 'b', 'b', 'b', 'c', 'c', 'c', 'd', 'd', 'd']; 2431 let mut grid: Grid<char> = Grid::from_vec_with_order(internal, 4, Order::ColumnMajor); 2432 grid.push_col(vec!['x', 'y', 'z']); 2433 let expected = [ 2434 'a', 'a', 'a', 'b', 'b', 'b', 'c', 'c', 'c', 'd', 'd', 'd', 'x', 'y', 'z', 2435 ]; 2436 test_grid(&grid, 3, 5, Order::ColumnMajor, &expected); 2437 } 2438 2439 #[test] push_col_1x3_column_major()2440 fn push_col_1x3_column_major() { 2441 let mut grid: Grid<char> = 2442 Grid::from_vec_with_order(vec!['a', 'b', 'c'], 3, Order::ColumnMajor); 2443 grid.push_col(vec!['d']); 2444 test_grid(&grid, 1, 4, Order::ColumnMajor, &['a', 'b', 'c', 'd']); 2445 } 2446 2447 #[test] push_col_empty_column_major()2448 fn push_col_empty_column_major() { 2449 let mut grid: Grid<char> = Grid::new_with_order(0, 0, Order::ColumnMajor); 2450 grid.push_col(vec!['b', 'b', 'b', 'b']); 2451 test_grid(&grid, 4, 1, Order::ColumnMajor, &['b', 'b', 'b', 'b']); 2452 } 2453 2454 #[test] 2455 #[should_panic] 2456 #[allow(clippy::should_panic_without_expect)] push_col_wrong_size_column_major()2457 fn push_col_wrong_size_column_major() { 2458 let mut grid: Grid<char> = Grid::init_with_order(2, 3, Order::ColumnMajor, 'a'); 2459 grid.push_col(vec!['b']); 2460 grid.push_col(vec!['b', 'b']); 2461 } 2462 2463 #[test] 2464 #[should_panic] 2465 #[allow(clippy::should_panic_without_expect)] push_col_zero_len_column_major()2466 fn push_col_zero_len_column_major() { 2467 let mut grid: Grid<char> = Grid::new_with_order(0, 0, Order::ColumnMajor); 2468 grid.push_col(vec![]); 2469 } 2470 2471 #[test] push_row()2472 fn push_row() { 2473 let mut grid: Grid<u8> = grid![[1, 2][3, 4]]; 2474 grid.push_row(vec![5, 6]); 2475 test_grid(&grid, 3, 2, Order::RowMajor, &[1, 2, 3, 4, 5, 6]); 2476 } 2477 2478 #[test] push_row_empty()2479 fn push_row_empty() { 2480 let mut grid: Grid<char> = grid![]; 2481 grid.push_row(vec!['b', 'b', 'b', 'b']); 2482 test_grid(&grid, 1, 4, Order::RowMajor, &['b', 'b', 'b', 'b']); 2483 } 2484 2485 #[test] 2486 #[should_panic] 2487 #[allow(clippy::should_panic_without_expect)] push_empty_row()2488 fn push_empty_row() { 2489 let mut grid = Grid::init(0, 1, 0); 2490 grid.push_row(vec![]); 2491 } 2492 2493 #[test] 2494 #[should_panic] 2495 #[allow(clippy::should_panic_without_expect)] push_row_wrong_size()2496 fn push_row_wrong_size() { 2497 let mut grid: Grid<char> = grid![['a','a','a']['a','a','a']]; 2498 grid.push_row(vec!['b']); 2499 grid.push_row(vec!['b', 'b', 'b', 'b']); 2500 } 2501 2502 #[test] push_row_column_major()2503 fn push_row_column_major() { 2504 let mut grid: Grid<u8> = Grid::from_vec_with_order(vec![1, 3, 2, 4], 2, Order::ColumnMajor); 2505 grid.push_row(vec![5, 6]); 2506 test_grid(&grid, 3, 2, Order::ColumnMajor, &[1, 3, 5, 2, 4, 6]); 2507 } 2508 2509 #[test] push_row_empty_column_major()2510 fn push_row_empty_column_major() { 2511 let mut grid: Grid<char> = Grid::new_with_order(0, 0, Order::ColumnMajor); 2512 grid.push_row(vec!['b', 'b', 'b', 'b']); 2513 test_grid(&grid, 1, 4, Order::ColumnMajor, &['b', 'b', 'b', 'b']); 2514 } 2515 2516 #[test] 2517 #[should_panic] 2518 #[allow(clippy::should_panic_without_expect)] push_empty_row_column_major()2519 fn push_empty_row_column_major() { 2520 let mut grid = Grid::init_with_order(0, 1, Order::ColumnMajor, 0); 2521 grid.push_row(vec![]); 2522 } 2523 2524 #[test] 2525 #[should_panic] 2526 #[allow(clippy::should_panic_without_expect)] push_row_wrong_size_column_major()2527 fn push_row_wrong_size_column_major() { 2528 let mut grid: Grid<char> = 2529 Grid::from_vec_with_order(vec!['a', 'a', 'a', 'a', 'a', 'a'], 3, Order::ColumnMajor); 2530 grid.push_row(vec!['b']); 2531 grid.push_row(vec!['b', 'b', 'b', 'b']); 2532 } 2533 2534 #[test] iter_row()2535 fn iter_row() { 2536 let grid = Grid::from_vec_with_order(vec![1, 2, 3, 4, 5, 6], 3, Order::RowMajor); 2537 let row: Vec<_> = grid.iter_row(1).collect(); 2538 assert_eq!(row, [&4, &5, &6]); 2539 } 2540 2541 #[test] 2542 #[should_panic] 2543 #[allow(clippy::should_panic_without_expect)] iter_row_out_of_bound()2544 fn iter_row_out_of_bound() { 2545 let grid = Grid::from_vec_with_order(vec![1, 2, 3, 4, 5, 6], 3, Order::RowMajor); 2546 let _ = grid.iter_row(3); 2547 } 2548 2549 #[test] 2550 #[should_panic] 2551 #[allow(clippy::should_panic_without_expect)] iter_row_zero()2552 fn iter_row_zero() { 2553 let grid: Grid<u8> = Grid::from_vec_with_order(vec![], 0, Order::RowMajor); 2554 let _ = grid.iter_row(0); 2555 } 2556 2557 #[test] iter_row_rowumn_major()2558 fn iter_row_rowumn_major() { 2559 let grid = Grid::from_vec_with_order(vec![1, 4, 2, 5, 3, 6], 3, Order::ColumnMajor); 2560 let row: Vec<_> = grid.iter_row(1).collect(); 2561 assert_eq!(row, [&4, &5, &6]); 2562 } 2563 2564 #[test] 2565 #[should_panic] 2566 #[allow(clippy::should_panic_without_expect)] iter_row_rowumn_major_out_of_bound()2567 fn iter_row_rowumn_major_out_of_bound() { 2568 let grid = Grid::from_vec_with_order(vec![1, 4, 2, 5, 3, 6], 3, Order::ColumnMajor); 2569 let _ = grid.iter_row(3); 2570 } 2571 2572 #[test] 2573 #[should_panic] 2574 #[allow(clippy::should_panic_without_expect)] iter_row_rowumn_major_zero()2575 fn iter_row_rowumn_major_zero() { 2576 let grid: Grid<u8> = Grid::from_vec_with_order(vec![], 0, Order::ColumnMajor); 2577 let _ = grid.iter_row(0); 2578 } 2579 2580 #[test] iter_row_mut()2581 fn iter_row_mut() { 2582 let mut grid = Grid::from_vec_with_order(vec![1, 2, 3, 4, 5, 6], 3, Order::RowMajor); 2583 let row: Vec<_> = grid.iter_row_mut(1).collect(); 2584 assert_eq!(row, [&mut 4, &mut 5, &mut 6]); 2585 } 2586 2587 #[test] 2588 #[should_panic] 2589 #[allow(clippy::should_panic_without_expect)] iter_row_mut_out_of_bound()2590 fn iter_row_mut_out_of_bound() { 2591 let mut grid = Grid::from_vec_with_order(vec![1, 2, 3, 4, 5, 6], 3, Order::RowMajor); 2592 let _ = grid.iter_row_mut(3); 2593 } 2594 2595 #[test] 2596 #[should_panic] 2597 #[allow(clippy::should_panic_without_expect)] iter_row_mut_zero()2598 fn iter_row_mut_zero() { 2599 let mut grid: Grid<u8> = Grid::from_vec_with_order(vec![], 0, Order::RowMajor); 2600 let _ = grid.iter_row_mut(0); 2601 } 2602 2603 #[test] iter_row_mut_rowumn_major()2604 fn iter_row_mut_rowumn_major() { 2605 let mut grid = Grid::from_vec_with_order(vec![1, 4, 2, 5, 3, 6], 3, Order::ColumnMajor); 2606 let row: Vec<_> = grid.iter_row_mut(1).collect(); 2607 assert_eq!(row, [&mut 4, &mut 5, &mut 6]); 2608 } 2609 2610 #[test] 2611 #[should_panic] 2612 #[allow(clippy::should_panic_without_expect)] iter_row_mut_rowumn_major_out_of_bound()2613 fn iter_row_mut_rowumn_major_out_of_bound() { 2614 let mut grid = Grid::from_vec_with_order(vec![1, 4, 2, 5, 3, 6], 3, Order::ColumnMajor); 2615 let _ = grid.iter_row_mut(3); 2616 } 2617 2618 #[test] 2619 #[should_panic] 2620 #[allow(clippy::should_panic_without_expect)] iter_row_mut_rowumn_major_zero()2621 fn iter_row_mut_rowumn_major_zero() { 2622 let mut grid: Grid<u8> = Grid::from_vec_with_order(vec![], 0, Order::ColumnMajor); 2623 let _ = grid.iter_row_mut(0); 2624 } 2625 2626 #[test] iter_col()2627 fn iter_col() { 2628 let grid = Grid::from_vec_with_order(vec![1, 2, 3, 4, 5, 6], 3, Order::RowMajor); 2629 let col: Vec<_> = grid.iter_col(1).collect(); 2630 assert_eq!(col, [&2, &5]); 2631 } 2632 2633 #[test] 2634 #[should_panic] 2635 #[allow(clippy::should_panic_without_expect)] iter_col_out_of_bound()2636 fn iter_col_out_of_bound() { 2637 let grid = Grid::from_vec_with_order(vec![1, 2, 3, 4, 5, 6], 3, Order::RowMajor); 2638 let _ = grid.iter_col(3); 2639 } 2640 2641 #[test] 2642 #[should_panic] 2643 #[allow(clippy::should_panic_without_expect)] iter_col_zero()2644 fn iter_col_zero() { 2645 let grid: Grid<u8> = Grid::from_vec_with_order(vec![], 0, Order::RowMajor); 2646 let _ = grid.iter_col(0); 2647 } 2648 2649 #[test] iter_col_column_major()2650 fn iter_col_column_major() { 2651 let grid = Grid::from_vec_with_order(vec![1, 4, 2, 5, 3, 6], 3, Order::ColumnMajor); 2652 let col: Vec<_> = grid.iter_col(1).collect(); 2653 assert_eq!(col, [&2, &5]); 2654 } 2655 2656 #[test] 2657 #[should_panic] 2658 #[allow(clippy::should_panic_without_expect)] iter_col_column_major_out_of_bound()2659 fn iter_col_column_major_out_of_bound() { 2660 let grid = Grid::from_vec_with_order(vec![1, 4, 2, 5, 3, 6], 3, Order::ColumnMajor); 2661 let _ = grid.iter_col(3); 2662 } 2663 2664 #[test] 2665 #[should_panic] 2666 #[allow(clippy::should_panic_without_expect)] iter_col_column_major_zero()2667 fn iter_col_column_major_zero() { 2668 let grid: Grid<u8> = Grid::from_vec_with_order(vec![], 0, Order::ColumnMajor); 2669 let _ = grid.iter_col(0); 2670 } 2671 2672 #[test] iter_col_mut()2673 fn iter_col_mut() { 2674 let mut grid = Grid::from_vec_with_order(vec![1, 2, 3, 4, 5, 6], 3, Order::RowMajor); 2675 let col: Vec<_> = grid.iter_col_mut(1).collect(); 2676 assert_eq!(col, [&mut 2, &mut 5]); 2677 } 2678 2679 #[test] 2680 #[should_panic] 2681 #[allow(clippy::should_panic_without_expect)] iter_col_mut_out_of_bound()2682 fn iter_col_mut_out_of_bound() { 2683 let mut grid = Grid::from_vec_with_order(vec![1, 2, 3, 4, 5, 6], 3, Order::RowMajor); 2684 let _ = grid.iter_col_mut(3); 2685 } 2686 2687 #[test] 2688 #[should_panic] 2689 #[allow(clippy::should_panic_without_expect)] iter_col_mut_zero()2690 fn iter_col_mut_zero() { 2691 let mut grid: Grid<u8> = Grid::from_vec_with_order(vec![], 0, Order::RowMajor); 2692 let _ = grid.iter_col_mut(0); 2693 } 2694 2695 #[test] iter_col_mut_column_major()2696 fn iter_col_mut_column_major() { 2697 let mut grid = Grid::from_vec_with_order(vec![1, 4, 2, 5, 3, 6], 3, Order::ColumnMajor); 2698 let col: Vec<_> = grid.iter_col_mut(1).collect(); 2699 assert_eq!(col, [&mut 2, &mut 5]); 2700 } 2701 2702 #[test] 2703 #[should_panic] 2704 #[allow(clippy::should_panic_without_expect)] iter_col_mut_column_major_out_of_bound()2705 fn iter_col_mut_column_major_out_of_bound() { 2706 let mut grid = Grid::from_vec_with_order(vec![1, 4, 2, 5, 3, 6], 3, Order::ColumnMajor); 2707 let _ = grid.iter_col_mut(3); 2708 } 2709 2710 #[test] 2711 #[should_panic] 2712 #[allow(clippy::should_panic_without_expect)] iter_col_mut_column_major_zero()2713 fn iter_col_mut_column_major_zero() { 2714 let mut grid: Grid<u8> = Grid::from_vec_with_order(vec![], 0, Order::ColumnMajor); 2715 let _ = grid.iter_col_mut(0); 2716 } 2717 2718 #[test] iter()2719 fn iter() { 2720 let grid: Grid<u8> = grid![[1,2][3,4]]; 2721 let mut iter = grid.iter(); 2722 assert_eq!(iter.next(), Some(&1)); 2723 assert_eq!(iter.next(), Some(&2)); 2724 assert_eq!(iter.next(), Some(&3)); 2725 assert_eq!(iter.next(), Some(&4)); 2726 assert_eq!(iter.next(), None); 2727 } 2728 2729 #[test] into_iter()2730 fn into_iter() { 2731 let grid: Grid<u8> = grid![[1,1][1,1]]; 2732 for val in &grid { 2733 assert_eq!(val, &1); 2734 } 2735 } 2736 2737 #[test] into_iter_mut()2738 fn into_iter_mut() { 2739 let mut grid: Grid<u8> = grid![[1,1][1,1]]; 2740 for val in &mut grid { 2741 *val = 2; 2742 } 2743 assert_eq!(grid, grid![[2, 2][2, 2]]); 2744 } 2745 2746 #[test] indexed_iter()2747 fn indexed_iter() { 2748 let grid: Grid<u8> = grid![[1,2][3,4]]; 2749 let mut iter = grid.indexed_iter(); 2750 assert_eq!(iter.next(), Some(((0, 0), &1))); 2751 assert_eq!(iter.next(), Some(((0, 1), &2))); 2752 assert_eq!(iter.next(), Some(((1, 0), &3))); 2753 assert_eq!(iter.next(), Some(((1, 1), &4))); 2754 assert_eq!(iter.next(), None); 2755 } 2756 2757 #[test] indexed_iter_empty()2758 fn indexed_iter_empty() { 2759 let grid: Grid<u8> = Grid::new(0, 0); 2760 let mut iter = grid.indexed_iter(); 2761 assert_eq!(iter.next(), None); 2762 } 2763 2764 #[test] indexed_iter_column_major()2765 fn indexed_iter_column_major() { 2766 let grid: Grid<u8> = Grid::from_vec_with_order(vec![1, 3, 2, 4], 2, Order::ColumnMajor); 2767 let mut iter = grid.indexed_iter(); 2768 assert_eq!(iter.next(), Some(((0, 0), &1))); 2769 assert_eq!(iter.next(), Some(((1, 0), &3))); 2770 assert_eq!(iter.next(), Some(((0, 1), &2))); 2771 assert_eq!(iter.next(), Some(((1, 1), &4))); 2772 assert_eq!(iter.next(), None); 2773 } 2774 2775 #[test] indexed_iter_empty_column_major()2776 fn indexed_iter_empty_column_major() { 2777 let grid: Grid<u8> = Grid::new_with_order(0, 0, Order::ColumnMajor); 2778 let mut iter = grid.indexed_iter(); 2779 assert_eq!(iter.next(), None); 2780 } 2781 2782 #[test] indexed_iter_mut()2783 fn indexed_iter_mut() { 2784 let mut grid: Grid<u8> = grid![[1,2][3,4]]; 2785 let mut iter = grid.indexed_iter_mut(); 2786 assert_eq!(iter.next(), Some(((0, 0), &mut 1))); 2787 assert_eq!(iter.next(), Some(((0, 1), &mut 2))); 2788 assert_eq!(iter.next(), Some(((1, 0), &mut 3))); 2789 assert_eq!(iter.next(), Some(((1, 1), &mut 4))); 2790 assert_eq!(iter.next(), None); 2791 } 2792 2793 #[test] indexed_iter_mut_empty()2794 fn indexed_iter_mut_empty() { 2795 let mut grid: Grid<u8> = Grid::new(0, 0); 2796 let mut iter = grid.indexed_iter_mut(); 2797 assert_eq!(iter.next(), None); 2798 } 2799 2800 #[test] indexed_iter_mut_column_major()2801 fn indexed_iter_mut_column_major() { 2802 let mut grid: Grid<u8> = Grid::from_vec_with_order(vec![1, 3, 2, 4], 2, Order::ColumnMajor); 2803 let mut iter = grid.indexed_iter_mut(); 2804 assert_eq!(iter.next(), Some(((0, 0), &mut 1))); 2805 assert_eq!(iter.next(), Some(((1, 0), &mut 3))); 2806 assert_eq!(iter.next(), Some(((0, 1), &mut 2))); 2807 assert_eq!(iter.next(), Some(((1, 1), &mut 4))); 2808 assert_eq!(iter.next(), None); 2809 } 2810 2811 #[test] indexed_iter_mut_empty_column_major()2812 fn indexed_iter_mut_empty_column_major() { 2813 let mut grid: Grid<u8> = Grid::new_with_order(0, 0, Order::ColumnMajor); 2814 let mut iter = grid.indexed_iter_mut(); 2815 assert_eq!(iter.next(), None); 2816 } 2817 2818 #[test] clear()2819 fn clear() { 2820 let mut grid: Grid<u8> = grid![[1, 2, 3]]; 2821 assert!(!grid.is_empty()); 2822 grid.clear(); 2823 assert!(grid.is_empty()); 2824 } 2825 2826 #[test] is_empty_false()2827 fn is_empty_false() { 2828 let grid: Grid<u8> = grid![[1, 2, 3]]; 2829 assert!(!grid.is_empty()); 2830 } 2831 2832 #[test] is_empty()2833 fn is_empty() { 2834 let mut g: Grid<u8> = grid![[]]; 2835 assert!(g.is_empty()); 2836 g = grid![]; 2837 assert!(g.is_empty()); 2838 g = Grid::from_vec(vec![], 0); 2839 assert!(g.is_empty()); 2840 g = Grid::new(0, 0); 2841 assert!(g.is_empty()); 2842 g = Grid::new(0, 1); 2843 assert!(g.is_empty()); 2844 g = Grid::new(1, 0); 2845 assert!(g.is_empty()); 2846 g = Grid::init(0, 0, 10); 2847 assert!(g.is_empty()); 2848 } 2849 2850 #[test] fmt_empty()2851 fn fmt_empty() { 2852 let grid: Grid<u8> = grid![]; 2853 assert_eq!(format!("{grid:?}"), "[]"); 2854 } 2855 2856 #[test] fmt_row()2857 fn fmt_row() { 2858 let grid: Grid<u8> = grid![[1, 2, 3]]; 2859 assert_eq!(format!("{grid:?}"), "[[1, 2, 3]]"); 2860 } 2861 2862 #[test] fmt_grid()2863 fn fmt_grid() { 2864 let grid: Grid<u8> = grid![[1,2,3][4,5,6][7,8,9]]; 2865 assert_eq!(format!("{grid:?}"), "[[1, 2, 3][4, 5, 6][7, 8, 9]]"); 2866 } 2867 2868 #[test] fmt_column_major()2869 fn fmt_column_major() { 2870 let grid = Grid::from_vec_with_order(vec![1, 4, 2, 5, 3, 6], 3, Order::ColumnMajor); 2871 assert_eq!(format!("{grid:?}"), "[[1, 2, 3][4, 5, 6]]"); 2872 } 2873 2874 #[test] fmt_pretty_empty()2875 fn fmt_pretty_empty() { 2876 let grid: Grid<f32> = grid![]; 2877 assert_eq!(format!("{grid:#?}"), "[]"); 2878 } 2879 2880 #[test] fmt_pretty_int()2881 fn fmt_pretty_int() { 2882 let grid: Grid<u8> = grid![ 2883 [1,2,3] 2884 [4,5,6] 2885 [7,8,95] 2886 ]; 2887 2888 let expected_output = r"[ 2889 [ 1, 2, 3] 2890 [ 4, 5, 6] 2891 [ 7, 8, 95] 2892 ]"; 2893 2894 assert_eq!(format!("{grid:#?}"), expected_output); 2895 2896 let expected_output = r"[ 2897 [ 1, 2, 3] 2898 [ 4, 5, 6] 2899 [ 7, 8, 95] 2900 ]"; 2901 2902 assert_eq!(format!("{grid:#3?}"), expected_output); 2903 } 2904 2905 #[test] fmt_pretty_float()2906 fn fmt_pretty_float() { 2907 let grid: Grid<f32> = grid![ 2908 [1.5,2.6,3.44] 2909 [4.775,5.,6.] 2910 [7.1,8.23444,95.55] 2911 ]; 2912 2913 let expected_output = r"[ 2914 [ 1.5, 2.6, 3.4] 2915 [ 4.8, 5.0, 6.0] 2916 [ 7.1, 8.2, 95.6] 2917 ]"; 2918 2919 assert_eq!(format!("{grid:#5.1?}"), expected_output); 2920 2921 let expected_output = r"[ 2922 [ 1.50000, 2.60000, 3.44000] 2923 [ 4.77500, 5.00000, 6.00000] 2924 [ 7.10000, 8.23444, 95.55000] 2925 ]"; 2926 2927 assert_eq!(format!("{grid:#8.5?}"), expected_output); 2928 } 2929 2930 #[test] fmt_pretty_tuple()2931 fn fmt_pretty_tuple() { 2932 let grid: Grid<(i32, i32)> = grid![ 2933 [(5,66), (432, 55)] 2934 [(80, 90), (5, 6)] 2935 ]; 2936 2937 let expected_output = r"[ 2938 [ ( 5, 66), ( 432, 55)] 2939 [ ( 80, 90), ( 5, 6)] 2940 ]"; 2941 2942 assert_eq!(format!("{grid:#?}"), expected_output); 2943 2944 let expected_output = r"[ 2945 [ ( 5, 66), (432, 55)] 2946 [ ( 80, 90), ( 5, 6)] 2947 ]"; 2948 2949 assert_eq!(format!("{grid:#3?}"), expected_output); 2950 } 2951 2952 #[test] fmt_pretty_struct_derived()2953 fn fmt_pretty_struct_derived() { 2954 #[derive(Debug)] 2955 struct Person { 2956 _name: String, 2957 _precise_age: f32, 2958 } 2959 2960 impl Person { 2961 fn new(name: &str, precise_age: f32) -> Self { 2962 Self { 2963 _name: name.into(), 2964 _precise_age: precise_age, 2965 } 2966 } 2967 } 2968 2969 let grid: Grid<Person> = grid![ 2970 [Person::new("Vic", 24.5), Person::new("Mr. Very Long Name", 1955.)] 2971 [Person::new("Sam", 8.9995), Person::new("John Doe", 40.14)] 2972 ]; 2973 2974 let expected_output = r#"[ 2975 [ Person { _name: "Vic", _precise_age: 24.50000 }, Person { _name: "Mr. Very Long Name", _precise_age: 1955.00000 }] 2976 [ Person { _name: "Sam", _precise_age: 8.99950 }, Person { _name: "John Doe", _precise_age: 40.14000 }] 2977 ]"#; 2978 2979 assert_eq!(format!("{grid:#5.5?}"), expected_output); 2980 } 2981 2982 #[test] fmt_pretty_column_major()2983 fn fmt_pretty_column_major() { 2984 let grid = Grid::from_vec_with_order(vec![1, 4, 2, 5, 3, 6], 3, Order::ColumnMajor); 2985 let expected_output = r"[ 2986 [ 1, 2, 3] 2987 [ 4, 5, 6] 2988 ]"; 2989 assert_eq!(format!("{grid:#?}"), expected_output); 2990 } 2991 2992 #[test] clone()2993 fn clone() { 2994 let grid = grid![[1, 2, 3][4, 5, 6]]; 2995 let mut clone = grid.clone(); 2996 clone[(0, 2)] = 10; 2997 test_grid(&grid, 2, 3, Order::RowMajor, &[1, 2, 3, 4, 5, 6]); 2998 test_grid(&clone, 2, 3, Order::RowMajor, &[1, 2, 10, 4, 5, 6]); 2999 } 3000 3001 #[cfg(feature = "std")] 3002 #[test] hash_std()3003 fn hash_std() { 3004 let mut set = std::collections::HashSet::new(); 3005 set.insert(grid![[1,2,3][4,5,6]]); 3006 set.insert(grid![[1,3,3][4,5,6]]); 3007 set.insert(grid![[1,2,3][4,5,6]]); 3008 assert_eq!(set.len(), 2); 3009 } 3010 3011 #[test] macro_init()3012 fn macro_init() { 3013 let grid = grid![[1, 2, 3][4, 5, 6]]; 3014 test_grid(&grid, 2, 3, Order::RowMajor, &[1, 2, 3, 4, 5, 6]); 3015 } 3016 3017 #[test] macro_init_2()3018 fn macro_init_2() { 3019 let grid = grid![[1, 2, 3] 3020 [4, 5, 6] 3021 [7, 8, 9]]; 3022 test_grid(&grid, 3, 3, Order::RowMajor, &[1, 2, 3, 4, 5, 6, 7, 8, 9]); 3023 } 3024 3025 #[test] macro_init_char()3026 fn macro_init_char() { 3027 let grid = grid![['a', 'b', 'c'] 3028 ['a', 'b', 'c'] 3029 ['a', 'b', 'c']]; 3030 let expected = ['a', 'b', 'c', 'a', 'b', 'c', 'a', 'b', 'c']; 3031 test_grid(&grid, 3, 3, Order::RowMajor, &expected); 3032 } 3033 3034 #[test] macro_one_row()3035 fn macro_one_row() { 3036 let grid: Grid<usize> = grid![[1, 2, 3, 4]]; 3037 test_grid(&grid, 1, 4, Order::RowMajor, &[1, 2, 3, 4]); 3038 } 3039 3040 #[test] macro2_empty()3041 fn macro2_empty() { 3042 let grid: Grid<u8> = grid_cm![]; 3043 test_grid(&grid, 0, 0, Order::ColumnMajor, &[]); 3044 } 3045 3046 #[test] macro2_init()3047 fn macro2_init() { 3048 let grid = grid_cm![[1, 2, 3] 3049 [4, 5, 6] 3050 [7, 8, 9]]; 3051 let expected = [1, 4, 7, 2, 5, 8, 3, 6, 9]; 3052 test_grid(&grid, 3, 3, Order::ColumnMajor, &expected); 3053 } 3054 3055 #[test] macro2_init_char()3056 fn macro2_init_char() { 3057 let grid = grid_cm![['a', 'b']['c', 'd']]; 3058 test_grid(&grid, 2, 2, Order::ColumnMajor, &['a', 'c', 'b', 'd']); 3059 } 3060 3061 #[test] macro2_one_row()3062 fn macro2_one_row() { 3063 let grid = grid_cm![[1, 2, 3, 4]]; 3064 test_grid(&grid, 1, 4, Order::ColumnMajor, &[1, 2, 3, 4]); 3065 } 3066 3067 #[test] init()3068 fn init() { 3069 let grid = Grid::init(1, 2, 3); 3070 test_grid(&grid, 1, 2, Order::RowMajor, &[3, 3]); 3071 3072 let grid = Grid::init(1, 2, 1.2); 3073 test_grid(&grid, 1, 2, Order::RowMajor, &[1.2, 1.2]); 3074 3075 let grid = Grid::init(1, 2, 'a'); 3076 test_grid(&grid, 1, 2, Order::RowMajor, &['a', 'a']); 3077 } 3078 3079 #[test] 3080 #[should_panic] 3081 #[allow(clippy::should_panic_without_expect)] init_panics()3082 fn init_panics() { 3083 Grid::init(usize::MAX, 2, 3); 3084 } 3085 3086 #[test] init_empty()3087 fn init_empty() { 3088 let grid = Grid::init(0, 1, 0); 3089 test_grid(&grid, 0, 0, Order::RowMajor, &[]); 3090 3091 let grid = Grid::init(1, 0, -1); 3092 test_grid(&grid, 0, 0, Order::RowMajor, &[]); 3093 } 3094 3095 #[test] init_with_order()3096 fn init_with_order() { 3097 let grid = Grid::init_with_order(1, 2, Order::RowMajor, 3); 3098 test_grid(&grid, 1, 2, Order::RowMajor, &[3, 3]); 3099 3100 let grid = Grid::init_with_order(1, 2, Order::ColumnMajor, 1.2); 3101 test_grid(&grid, 1, 2, Order::ColumnMajor, &[1.2, 1.2]); 3102 3103 let grid = Grid::init_with_order(1, 2, Order::ColumnMajor, 'a'); 3104 test_grid(&grid, 1, 2, Order::ColumnMajor, &['a', 'a']); 3105 } 3106 3107 #[test] 3108 #[should_panic] 3109 #[allow(clippy::should_panic_without_expect)] init_with_order_panics()3110 fn init_with_order_panics() { 3111 Grid::init_with_order(usize::MAX, 2, Order::ColumnMajor, 3); 3112 } 3113 3114 #[test] init_with_order_empty()3115 fn init_with_order_empty() { 3116 let grid = Grid::init_with_order(0, 1, Order::ColumnMajor, 0); 3117 test_grid(&grid, 0, 0, Order::ColumnMajor, &[]); 3118 3119 let grid = Grid::init_with_order(1, 0, Order::RowMajor, -1); 3120 test_grid(&grid, 0, 0, Order::RowMajor, &[]); 3121 } 3122 3123 #[test] new()3124 fn new() { 3125 let grid: Grid<u8> = Grid::new(1, 2); 3126 test_grid(&grid, 1, 2, Order::RowMajor, &[0, 0]); 3127 } 3128 3129 #[test] 3130 #[should_panic] 3131 #[allow(clippy::should_panic_without_expect)] new_panics()3132 fn new_panics() { 3133 let _: Grid<u8> = Grid::new(usize::MAX, 2); 3134 } 3135 3136 #[test] new_empty()3137 fn new_empty() { 3138 let grid: Grid<u8> = Grid::new(0, 1); 3139 test_grid(&grid, 0, 0, Order::RowMajor, &[]); 3140 3141 let grid: Grid<u8> = Grid::new(1, 0); 3142 test_grid(&grid, 0, 0, Order::RowMajor, &[]); 3143 } 3144 3145 #[test] new_with_order()3146 fn new_with_order() { 3147 let grid: Grid<u8> = Grid::new_with_order(2, 2, Order::ColumnMajor); 3148 test_grid(&grid, 2, 2, Order::ColumnMajor, &[0, 0, 0, 0]); 3149 } 3150 3151 #[test] 3152 #[should_panic] 3153 #[allow(clippy::should_panic_without_expect)] new_with_order_panics()3154 fn new_with_order_panics() { 3155 let _: Grid<u8> = Grid::new_with_order(usize::MAX, 2, Order::ColumnMajor); 3156 } 3157 3158 #[test] new_with_order_empty()3159 fn new_with_order_empty() { 3160 let grid: Grid<u8> = Grid::new_with_order(0, 3, Order::RowMajor); 3161 test_grid(&grid, 0, 0, Order::RowMajor, &[]); 3162 3163 let grid: Grid<u8> = Grid::new_with_order(3, 0, Order::ColumnMajor); 3164 test_grid(&grid, 0, 0, Order::ColumnMajor, &[]); 3165 } 3166 3167 #[test] with_capacity()3168 fn with_capacity() { 3169 // doesn't impl Default 3170 struct Foo(); 3171 3172 let grid: Grid<Foo> = Grid::with_capacity(20, 20); 3173 assert!(grid.is_empty()); 3174 assert_eq!(grid.order(), Order::default()); 3175 } 3176 3177 #[test] with_capacity_and_order()3178 fn with_capacity_and_order() { 3179 // doesn't impl Default 3180 struct Foo(); 3181 3182 let grid: Grid<Foo> = Grid::with_capacity_and_order(20, 20, Order::ColumnMajor); 3183 assert!(grid.is_empty()); 3184 assert_eq!(grid.order(), Order::ColumnMajor); 3185 } 3186 3187 #[test] 3188 #[should_panic] 3189 #[allow(clippy::should_panic_without_expect)] with_capacity_panics_internal()3190 fn with_capacity_panics_internal() { 3191 // doesn't impl Default 3192 struct Foo(); 3193 3194 let _grid: Grid<Foo> = Grid::with_capacity_and_order(usize::MAX, 2, Order::RowMajor); 3195 } 3196 3197 #[test] 3198 #[should_panic] 3199 #[allow(clippy::should_panic_without_expect)] with_capacity_panics_vec()3200 fn with_capacity_panics_vec() { 3201 let rows: usize = isize::MAX.try_into().expect("isize::MAX is positive"); 3202 assert!( 3203 core::mem::size_of::<u8>() * rows < usize::MAX, 3204 "shows that panic is from Vec::with_capacity, not internal check" 3205 ); 3206 3207 let _grid: Grid<u8> = Grid::with_capacity_and_order(rows, 2, Order::RowMajor); 3208 } 3209 3210 #[test] get()3211 fn get() { 3212 let grid = Grid::from_vec_with_order(vec![1, 2], 2, Order::RowMajor); 3213 assert_eq!(grid.get(0_i64, 1_i32), Some(&2)); 3214 } 3215 3216 #[test] get_column_major()3217 fn get_column_major() { 3218 let grid = Grid::from_vec_with_order(vec![1, 2], 1, Order::ColumnMajor); 3219 assert_eq!(grid.get(1, 0), Some(&2)); 3220 } 3221 3222 #[test] get_none()3223 fn get_none() { 3224 let grid = Grid::from_vec_with_order(vec![1, 2], 2, Order::RowMajor); 3225 assert_eq!(grid.get(1, 0), None); 3226 } 3227 3228 #[test] get_none_column_major()3229 fn get_none_column_major() { 3230 let grid = Grid::from_vec_with_order(vec![1, 2], 1, Order::ColumnMajor); 3231 assert_eq!(grid.get(0, 1), None); 3232 } 3233 3234 #[test] get_mut()3235 fn get_mut() { 3236 let mut grid = Grid::from_vec_with_order(vec![1, 2], 2, Order::RowMajor); 3237 assert_eq!(grid.get_mut(0_i64, 1_i32), Some(&mut 2)); 3238 } 3239 3240 #[test] get_mut_column_major()3241 fn get_mut_column_major() { 3242 let mut grid = Grid::from_vec_with_order(vec![1, 2], 1, Order::ColumnMajor); 3243 assert_eq!(grid.get_mut(1, 0), Some(&mut 2)); 3244 } 3245 3246 #[test] get_mut_none()3247 fn get_mut_none() { 3248 let mut grid = Grid::from_vec_with_order(vec![1, 2], 2, Order::RowMajor); 3249 assert_eq!(grid.get_mut(1, 0), None); 3250 } 3251 3252 #[test] get_mut_none_column_major()3253 fn get_mut_none_column_major() { 3254 let mut grid = Grid::from_vec_with_order(vec![1, 2], 1, Order::ColumnMajor); 3255 assert_eq!(grid.get_mut(0, 1), None); 3256 } 3257 3258 #[test] idx_tup()3259 fn idx_tup() { 3260 let grid: Grid<u8> = Grid::from_vec(vec![1, 2, 3, 4], 2); 3261 assert_eq!(grid[(0, 0)], 1); 3262 assert_eq!(grid[(0, 1)], 2); 3263 assert_eq!(grid[(1, 0)], 3); 3264 assert_eq!(grid[(1, 1)], 4); 3265 } 3266 3267 #[test] 3268 #[should_panic] 3269 #[allow(clippy::should_panic_without_expect)] idx_tup_panic_1()3270 fn idx_tup_panic_1() { 3271 let grid = Grid::init(1, 2, 3); 3272 let _ = grid[(20, 0)]; 3273 } 3274 3275 #[test] 3276 #[should_panic] 3277 #[allow(clippy::should_panic_without_expect)] idx_tup_panic_2()3278 fn idx_tup_panic_2() { 3279 let grid = Grid::init(1, 2, 3); 3280 let _ = grid[(0, 20)]; 3281 } 3282 3283 #[test] idx_tup_set()3284 fn idx_tup_set() { 3285 let mut grid = Grid::init(1, 2, 3); 3286 grid[(0, 0)] = 4; 3287 assert_eq!(grid[(0, 0)], 4); 3288 } 3289 3290 #[test] size()3291 fn size() { 3292 let grid = Grid::init(1, 2, 3); 3293 assert_eq!(grid.size(), (1, 2)); 3294 } 3295 3296 #[test] transpose()3297 fn transpose() { 3298 let mut grid: Grid<u8> = grid![[1,2,3][4,5,6]]; 3299 grid.transpose(); 3300 assert_eq!(grid, grid![[1,4][2,5][3,6]]); 3301 } 3302 3303 #[test] fill()3304 fn fill() { 3305 let mut grid: Grid<u8> = grid![[1,2,3][4,5,6]]; 3306 grid.fill(7); 3307 test_grid(&grid, 2, 3, Order::RowMajor, &[7, 7, 7, 7, 7, 7]); 3308 } 3309 3310 #[test] fill_with()3311 fn fill_with() { 3312 let mut grid: Grid<u8> = grid![[1,2,3][4,5,6]]; 3313 grid.fill_with(Default::default); 3314 test_grid(&grid, 2, 3, Order::RowMajor, &[0, 0, 0, 0, 0, 0]); 3315 } 3316 3317 #[test] map()3318 fn map() { 3319 let grid: Grid<u8> = grid![[1,2,3][4,5,6]]; 3320 let mapped = grid.map(|x| x * 2); 3321 test_grid(&mapped, 2, 3, Order::RowMajor, &[2, 4, 6, 8, 10, 12]); 3322 } 3323 3324 #[test] map_ref()3325 fn map_ref() { 3326 let grid: Grid<u8> = grid![[1,2,3][4,5,6]]; 3327 let mapped = grid.map_ref(|x| *x * 2); 3328 test_grid(&mapped, 2, 3, Order::RowMajor, &[2, 4, 6, 8, 10, 12]); 3329 } 3330 3331 #[test] 3332 #[allow(clippy::redundant_closure_for_method_calls)] iter_rows()3333 fn iter_rows() { 3334 let grid: Grid<u8> = grid![[1,2,3][4,5,6]]; 3335 let max_by_row: Vec<u8> = grid 3336 .iter_rows() 3337 .map(|row| row.max().unwrap()) 3338 .copied() 3339 .collect(); 3340 assert_eq!(max_by_row, vec![3, 6]); 3341 3342 let sum_by_row: Vec<u8> = grid.iter_rows().map(|row| row.sum()).collect(); 3343 assert_eq!(sum_by_row, vec![1 + 2 + 3, 4 + 5 + 6]); 3344 } 3345 3346 #[test] 3347 #[allow(clippy::redundant_closure_for_method_calls)] iter_rows_rev()3348 fn iter_rows_rev() { 3349 let grid: Grid<u8> = grid![[1,2,3][4,5,6]]; 3350 let max_by_row: Vec<u8> = grid 3351 .iter_rows() 3352 .rev() 3353 .map(|row| row.max().unwrap()) 3354 .copied() 3355 .collect(); 3356 assert_eq!(max_by_row, vec![6, 3]); 3357 3358 let sum_by_row: Vec<u8> = grid.iter_rows().rev().map(|row| row.sum()).collect(); 3359 assert_eq!(sum_by_row, vec![4 + 5 + 6, 1 + 2 + 3]); 3360 } 3361 3362 #[test] iter_rows_exact_size()3363 fn iter_rows_exact_size() { 3364 let grid: Grid<u8> = grid![[1,2,3][4,5,6]]; 3365 let mut row_iter = grid.iter_rows(); 3366 assert_eq!(row_iter.len(), 2); 3367 assert!(row_iter.next().is_some()); 3368 assert_eq!(row_iter.len(), 1); 3369 assert!(row_iter.next().is_some()); 3370 assert_eq!(row_iter.len(), 0); 3371 assert!(row_iter.next().is_none()); 3372 } 3373 3374 #[test] 3375 #[allow(clippy::redundant_closure_for_method_calls)] iter_cols()3376 fn iter_cols() { 3377 let grid: Grid<u8> = grid![[1,2,3][4,5,6]]; 3378 let max_by_col: Vec<u8> = grid 3379 .iter_cols() 3380 .map(|col| col.max().unwrap()) 3381 .copied() 3382 .collect(); 3383 3384 assert_eq!(max_by_col, vec![4, 5, 6]); 3385 3386 let sum_by_col: Vec<u8> = grid.iter_cols().map(|row| row.sum()).collect(); 3387 assert_eq!(sum_by_col, vec![1 + 4, 2 + 5, 3 + 6]); 3388 } 3389 3390 #[test] 3391 #[allow(clippy::redundant_closure_for_method_calls)] iter_cols_rev()3392 fn iter_cols_rev() { 3393 let grid: Grid<u8> = grid![[1,2,3][4,5,6]]; 3394 let max_by_col: Vec<u8> = grid 3395 .iter_cols() 3396 .rev() 3397 .map(|col| col.max().unwrap()) 3398 .copied() 3399 .collect(); 3400 3401 assert_eq!(max_by_col, vec![6, 5, 4]); 3402 3403 let sum_by_col: Vec<u8> = grid.iter_cols().rev().map(|row| row.sum()).collect(); 3404 assert_eq!(sum_by_col, vec![3 + 6, 2 + 5, 1 + 4]); 3405 } 3406 3407 #[test] iter_cols_exact_size()3408 fn iter_cols_exact_size() { 3409 let grid: Grid<u8> = grid![[1,2,3][4,5,6]]; 3410 let mut col_iter = grid.iter_cols(); 3411 assert_eq!(col_iter.len(), 3); 3412 assert!(col_iter.next().is_some()); 3413 assert_eq!(col_iter.len(), 2); 3414 assert!(col_iter.next().is_some()); 3415 assert_eq!(col_iter.len(), 1); 3416 assert!(col_iter.next().is_some()); 3417 assert_eq!(col_iter.len(), 0); 3418 assert!(col_iter.next().is_none()); 3419 } 3420 3421 #[test] remove_row()3422 fn remove_row() { 3423 let mut grid = grid![[1,2][3,4][5,6]]; 3424 assert_eq![grid.remove_row(1), Some(vec![3, 4])]; 3425 test_grid(&grid, 2, 2, Order::RowMajor, &[1, 2, 5, 6]); 3426 assert_eq![grid.remove_row(0), Some(vec![1, 2])]; 3427 test_grid(&grid, 1, 2, Order::RowMajor, &[5, 6]); 3428 assert_eq![grid.remove_row(0), Some(vec![5, 6])]; 3429 test_grid(&grid, 0, 0, Order::RowMajor, &[]); 3430 assert_eq![grid.remove_row(0), None]; 3431 test_grid(&grid, 0, 0, Order::RowMajor, &[]); 3432 } 3433 3434 #[test] remove_row_out_of_bound()3435 fn remove_row_out_of_bound() { 3436 let mut grid = grid![[1, 2][3, 4]]; 3437 assert_eq![grid.remove_row(5), None]; 3438 test_grid(&grid, 2, 2, Order::RowMajor, &[1, 2, 3, 4]); 3439 assert_eq![grid.remove_row(1), Some(vec![3, 4])]; 3440 test_grid(&grid, 1, 2, Order::RowMajor, &[1, 2]); 3441 } 3442 3443 #[test] remove_row_column_major()3444 fn remove_row_column_major() { 3445 let mut grid = Grid::from_vec_with_order(vec![1, 3, 5, 2, 4, 6], 2, Order::ColumnMajor); 3446 assert_eq![grid.remove_row(1), Some(vec![3, 4])]; 3447 test_grid(&grid, 2, 2, Order::ColumnMajor, &[1, 5, 2, 6]); 3448 assert_eq![grid.remove_row(0), Some(vec![1, 2])]; 3449 test_grid(&grid, 1, 2, Order::ColumnMajor, &[5, 6]); 3450 assert_eq![grid.remove_row(0), Some(vec![5, 6])]; 3451 test_grid(&grid, 0, 0, Order::ColumnMajor, &[]); 3452 assert_eq![grid.remove_row(0), None]; 3453 test_grid(&grid, 0, 0, Order::ColumnMajor, &[]); 3454 } 3455 3456 #[test] remove_row_out_of_bound_column_major()3457 fn remove_row_out_of_bound_column_major() { 3458 let mut grid = Grid::from_vec_with_order(vec![1, 3, 2, 4], 2, Order::ColumnMajor); 3459 assert_eq![grid.remove_row(5), None]; 3460 test_grid(&grid, 2, 2, Order::ColumnMajor, &[1, 3, 2, 4]); 3461 assert_eq![grid.remove_row(1), Some(vec![3, 4])]; 3462 test_grid(&grid, 1, 2, Order::ColumnMajor, &[1, 2]); 3463 } 3464 3465 #[test] remove_col()3466 fn remove_col() { 3467 let mut grid = grid![[1,2,3,4][5,6,7,8][9,10,11,12][13,14,15,16]]; 3468 assert_eq![grid.remove_col(3), Some(vec![4, 8, 12, 16])]; 3469 let expected = [1, 2, 3, 5, 6, 7, 9, 10, 11, 13, 14, 15]; 3470 test_grid(&grid, 4, 3, Order::RowMajor, &expected); 3471 assert_eq![grid.remove_col(0), Some(vec![1, 5, 9, 13])]; 3472 test_grid(&grid, 4, 2, Order::RowMajor, &[2, 3, 6, 7, 10, 11, 14, 15]); 3473 assert_eq![grid.remove_col(1), Some(vec![3, 7, 11, 15])]; 3474 test_grid(&grid, 4, 1, Order::RowMajor, &[2, 6, 10, 14]); 3475 assert_eq![grid.remove_col(0), Some(vec![2, 6, 10, 14])]; 3476 test_grid(&grid, 0, 0, Order::RowMajor, &[]); 3477 assert_eq![grid.remove_col(0), None]; 3478 test_grid(&grid, 0, 0, Order::RowMajor, &[]); 3479 } 3480 3481 #[test] remove_col_out_of_bound()3482 fn remove_col_out_of_bound() { 3483 let mut grid = grid![[1, 2][3, 4]]; 3484 assert_eq!(grid.remove_col(5), None); 3485 test_grid(&grid, 2, 2, Order::RowMajor, &[1, 2, 3, 4]); 3486 assert_eq!(grid.remove_col(1), Some(vec![2, 4])); 3487 test_grid(&grid, 2, 1, Order::RowMajor, &[1, 3]); 3488 } 3489 3490 #[test] remove_col_column_major()3491 fn remove_col_column_major() { 3492 let internal = vec![1, 5, 9, 13, 2, 6, 10, 14, 3, 7, 11, 15, 4, 8, 12, 16]; 3493 let mut grid = Grid::from_vec_with_order(internal, 4, Order::ColumnMajor); 3494 assert_eq![grid.remove_col(3), Some(vec![4, 8, 12, 16])]; 3495 let expected = [1, 5, 9, 13, 2, 6, 10, 14, 3, 7, 11, 15]; 3496 test_grid(&grid, 4, 3, Order::ColumnMajor, &expected); 3497 assert_eq![grid.remove_col(0), Some(vec![1, 5, 9, 13])]; 3498 let expected = [2, 6, 10, 14, 3, 7, 11, 15]; 3499 test_grid(&grid, 4, 2, Order::ColumnMajor, &expected); 3500 assert_eq![grid.remove_col(1), Some(vec![3, 7, 11, 15])]; 3501 test_grid(&grid, 4, 1, Order::ColumnMajor, &[2, 6, 10, 14]); 3502 assert_eq![grid.remove_col(0), Some(vec![2, 6, 10, 14])]; 3503 test_grid(&grid, 0, 0, Order::ColumnMajor, &[]); 3504 assert_eq![grid.remove_col(0), None]; 3505 test_grid(&grid, 0, 0, Order::ColumnMajor, &[]); 3506 } 3507 3508 #[test] remove_col_out_of_bound_column_major()3509 fn remove_col_out_of_bound_column_major() { 3510 let mut grid = Grid::from_vec_with_order(vec![1, 3, 2, 4], 2, Order::ColumnMajor); 3511 assert_eq!(grid.remove_col(5), None); 3512 test_grid(&grid, 2, 2, Order::ColumnMajor, &[1, 3, 2, 4]); 3513 assert_eq!(grid.remove_col(1), Some(vec![2, 4])); 3514 test_grid(&grid, 2, 1, Order::ColumnMajor, &[1, 3]); 3515 } 3516 3517 #[test] flip_cols()3518 fn flip_cols() { 3519 let mut grid = Grid::from_vec_with_order(vec![1, 2, 3, 4], 2, Order::RowMajor); 3520 grid.flip_cols(); 3521 test_grid(&grid, 2, 2, Order::RowMajor, &[2, 1, 4, 3]); 3522 } 3523 3524 #[test] flip_cols_column_major()3525 fn flip_cols_column_major() { 3526 let mut grid = Grid::from_vec_with_order(vec![1, 3, 2, 4], 2, Order::ColumnMajor); 3527 grid.flip_cols(); 3528 test_grid(&grid, 2, 2, Order::ColumnMajor, &[2, 4, 1, 3]); 3529 } 3530 3531 #[test] flip_rows()3532 fn flip_rows() { 3533 let mut grid = Grid::from_vec_with_order(vec![1, 2, 3, 4], 2, Order::RowMajor); 3534 grid.flip_rows(); 3535 test_grid(&grid, 2, 2, Order::RowMajor, &[3, 4, 1, 2]); 3536 } 3537 3538 #[test] flip_rows_column_major()3539 fn flip_rows_column_major() { 3540 let mut grid = Grid::from_vec_with_order(vec![1, 3, 2, 4], 2, Order::ColumnMajor); 3541 grid.flip_rows(); 3542 test_grid(&grid, 2, 2, Order::ColumnMajor, &[3, 1, 4, 2]); 3543 } 3544 3545 #[test] rotate_left()3546 fn rotate_left() { 3547 let mut grid = Grid::from_vec_with_order(vec![1, 2, 3, 4, 5, 6], 3, Order::RowMajor); 3548 grid.rotate_left(); 3549 test_grid(&grid, 3, 2, Order::ColumnMajor, &[3, 2, 1, 6, 5, 4]); 3550 assert_eq!(grid, grid![[3,6][2,5][1,4]]); 3551 } 3552 3553 #[test] rotate_left_column_major()3554 fn rotate_left_column_major() { 3555 let mut grid = Grid::from_vec_with_order(vec![1, 4, 2, 5, 3, 6], 3, Order::ColumnMajor); 3556 grid.rotate_left(); 3557 test_grid(&grid, 3, 2, Order::RowMajor, &[3, 6, 2, 5, 1, 4]); 3558 assert_eq!(grid, grid![[3,6][2,5][1,4]]); 3559 } 3560 3561 #[test] rotate_right()3562 fn rotate_right() { 3563 let mut grid = Grid::from_vec_with_order(vec![1, 2, 3, 4, 5, 6], 3, Order::RowMajor); 3564 grid.rotate_right(); 3565 test_grid(&grid, 3, 2, Order::ColumnMajor, &[4, 5, 6, 1, 2, 3]); 3566 assert_eq!(grid, grid![[4,1][5,2][6,3]]); 3567 } 3568 3569 #[test] rotate_right_column_major()3570 fn rotate_right_column_major() { 3571 let mut grid = Grid::from_vec_with_order(vec![1, 4, 2, 5, 3, 6], 3, Order::ColumnMajor); 3572 grid.rotate_right(); 3573 test_grid(&grid, 3, 2, Order::RowMajor, &[4, 1, 5, 2, 6, 3]); 3574 assert_eq!(grid, grid![[4,1][5,2][6,3]]); 3575 } 3576 3577 #[test] iter_cols_clone()3578 fn iter_cols_clone() { 3579 let grid = grid![[1,2,3][4,5,6]]; 3580 let mut cols = grid.iter_cols().skip(1); 3581 let c3: u8 = cols.clone().nth(1).unwrap().sum(); 3582 let c2: u8 = cols.next().unwrap().sum(); 3583 assert_eq!(c2, 2 + 5); 3584 assert_eq!(c3, 3 + 6); 3585 } 3586 3587 #[test] iter_rows_clone()3588 fn iter_rows_clone() { 3589 let grid = grid![[1,2,3][4,5,6][7,8,9]]; 3590 let mut rows = grid.iter_rows().skip(1); 3591 let r3: u8 = rows.clone().nth(1).unwrap().sum(); 3592 let r2: u8 = rows.next().unwrap().sum(); 3593 assert_eq!(r2, 4 + 5 + 6); 3594 assert_eq!(r3, 7 + 8 + 9); 3595 } 3596 3597 #[test] swap()3598 fn swap() { 3599 let mut grid = grid![[1,2][4,5]]; 3600 grid.swap((0, 0), (1, 0)); 3601 let end_grid = grid![[4,2][1,5]]; 3602 assert_eq!(grid, end_grid); 3603 } 3604 3605 #[test] 3606 #[should_panic(expected = "grid index out of bounds: (2,0) out of (2,2)")] swap_out_of_bounds()3607 fn swap_out_of_bounds() { 3608 let mut grid = grid![[1,2][4,5]]; 3609 grid.swap((0, 0), (2, 0)); 3610 } 3611 3612 #[cfg(feature = "serde")] 3613 mod serde_tests { 3614 use super::*; 3615 3616 #[test] serialize()3617 fn serialize() { 3618 let grid: Grid<u8> = grid![[1, 2][3, 4]]; 3619 let s = serde_json::to_string(&grid).unwrap(); 3620 assert_eq!(s, r#"{"cols":2,"data":[1,2,3,4],"order":"RowMajor"}"#); 3621 } 3622 3623 #[test] deserialize()3624 fn deserialize() { 3625 let s = "{ \"cols\": 2, \"data\": [1, 2, 3, 4] }"; 3626 let grid: Grid<u8> = serde_json::from_str(s).unwrap(); 3627 assert_eq!(grid, grid![[1, 2][3, 4]]); 3628 } 3629 3630 #[test] deserialize_with_order()3631 fn deserialize_with_order() { 3632 let s = "{ \"cols\": 2, \"data\": [1, 3, 2, 4], \"order\": \"ColumnMajor\" }"; 3633 let grid: Grid<u8> = serde_json::from_str(s).unwrap(); 3634 test_grid(&grid, 2, 2, Order::ColumnMajor, &[1, 3, 2, 4]); 3635 } 3636 } 3637 } 3638