From 7a23fcb54b118a9a7abb2c75f6d4e61e44e32068 Mon Sep 17 00:00:00 2001 From: Vinzenz Schroeter Date: Sun, 10 Nov 2024 18:11:09 +0100 Subject: [PATCH] add char grid str methods --- crates/servicepoint/src/char_grid.rs | 55 +++++++++++++++++++++++++++- 1 file changed, 54 insertions(+), 1 deletion(-) diff --git a/crates/servicepoint/src/char_grid.rs b/crates/servicepoint/src/char_grid.rs index 1e7e80d..274a5dd 100644 --- a/crates/servicepoint/src/char_grid.rs +++ b/crates/servicepoint/src/char_grid.rs @@ -1,4 +1,57 @@ use crate::PrimitiveGrid; /// A grid containing UTF-8 characters. -pub type CharGrid = PrimitiveGrid; \ No newline at end of file +pub type CharGrid = PrimitiveGrid; + +impl CharGrid { + /// Copies a column from the grid as a String. + /// + /// Returns [None] if x is out of bounds. + pub fn get_col_str(&self, x: usize) -> Option { + Some(String::from_iter(self.get_col(x)?)) + } + + /// Copies a row from the grid as a String. + /// + /// Returns [None] if y is out of bounds. + pub fn get_row_str(&self, y: usize) -> Option { + Some(String::from_iter(self.get_row(y)?)) + } + + /// Overwrites a row in the grid with a str. + /// + /// Returns [None] if y is out of bounds or `row` is not of the correct size. + pub fn set_row_str(&mut self, y: usize, value: &str) -> Option<()> { + self.set_row(y, value.chars().collect::>().as_ref()) + } + + /// Overwrites a column in the grid with a str. + /// + /// Returns [None] if y is out of bounds or `row` is not of the correct size. + pub fn set_col_str(&mut self, x: usize, value: &str) -> Option<()> { + self.set_col(x, value.chars().collect::>().as_ref()) + } +} + +#[cfg(test)] +mod test { + use super::*; + #[test] + fn col_str() { + let mut grid = CharGrid::new(2, 3); + assert_eq!(grid.get_col_str(2), None); + assert_eq!(grid.get_col_str(1), Some(String::from("\0\0\0"))); + assert_eq!(grid.set_col_str(1, "abc"), Some(())); + assert_eq!(grid.get_col_str(1), Some(String::from("abc"))); + } + + #[test] + fn row_str() { + let mut grid = CharGrid::new(2, 3); + assert_eq!(grid.get_row_str(3), None); + assert_eq!(grid.get_row_str(1), Some(String::from("\0\0"))); + assert_eq!(grid.set_row_str(1, "abc"), None); + assert_eq!(grid.set_row_str(1, "ab"), Some(())); + assert_eq!(grid.get_row_str(1), Some(String::from("ab"))); + } +}