From 405f2fb1def2c825373c53edd146ed691f912aa5 Mon Sep 17 00:00:00 2001 From: Armin Becher Date: Sun, 5 Apr 2020 15:16:53 +0200 Subject: [PATCH] Add is empty --- src/lib.rs | 53 ++++++++++++++++++++++++++++++++++++++--------------- 1 file changed, 38 insertions(+), 15 deletions(-) diff --git a/src/lib.rs b/src/lib.rs index 63a6731..332c177 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -27,11 +27,7 @@ macro_rules! count { #[macro_export] macro_rules! grid { () => { - Grid { - rows: 0, - cols: 0, - data: vec![], - } + $crate::Grid::from_vec(vec![], 0) }; ( [$( $x:expr ),* ]) => { { let vec = vec![$($x),*]; @@ -116,21 +112,25 @@ impl Grid { /// Grid::from_vec(vec![1,2,3,4,5], 3); /// ``` pub fn from_vec(vec: Vec, cols: usize) -> Grid { - if vec.len() == 0 { + let rows = vec.len(); + if rows == 0 { if cols == 0 { - return grid![]; + return Grid { + data: vec![], + rows: 0, + cols: 0, + }; } else { panic!("Vector length is zero, but cols is {:?}", cols); } - } - if vec.len() % cols != 0 { + } else if rows % cols != 0 { panic!("Vector length must be a multiple of cols."); - } - let rows = vec.len(); - Grid { - data: vec, - rows: rows / cols, - cols: cols, + } else { + Grid { + data: vec, + rows: rows / cols, + cols: cols, + } } } @@ -184,6 +184,17 @@ impl Grid { pub fn cols(&self) -> usize { self.cols } + + /// Returns true if the grid contains no elements. + /// For example: + /// ``` + /// use grid::*; + /// let grid : Grid = grid![]; + /// assert!(grid.is_empty()); + /// ``` + pub fn is_empty(&self) -> bool { + self.cols == 0 && self.rows == 0 + } } impl Clone for Grid { @@ -234,6 +245,18 @@ impl fmt::Debug for Grid { mod test { use super::*; + #[test] + fn is_empty_false() { + let grid: Grid = grid![[1, 2, 3]]; + assert!(!grid.is_empty()); + } + + #[test] + fn is_empty_true() { + let grid: Grid = grid![]; + assert!(grid.is_empty()); + } + #[test] fn fmt_empty() { let grid: Grid = grid![];