From ab82900414e4066a7263e7e051a49a24bf47a4cc Mon Sep 17 00:00:00 2001 From: Vinzenz Schroeter Date: Sun, 13 Oct 2024 16:31:03 +0200 Subject: [PATCH] improve whitespace handling when converting between string and grid --- crates/servicepoint/src/cp437.rs | 34 +++++++++++++++++++++++++++++++- 1 file changed, 33 insertions(+), 1 deletion(-) diff --git a/crates/servicepoint/src/cp437.rs b/crates/servicepoint/src/cp437.rs index 5909296..f779025 100644 --- a/crates/servicepoint/src/cp437.rs +++ b/crates/servicepoint/src/cp437.rs @@ -146,10 +146,17 @@ mod feature_cp437 { impl From<&str> for CharGrid { fn from(value: &str) -> Self { let value = value.replace("\r\n", "\n"); - let lines = value.split('\n').collect::>(); + let mut lines = value + .split('\n') + .map(move |line| line.trim_end()) + .collect::>(); let width = lines.iter().fold(0, move |a, x| std::cmp::max(a, x.len())); + while lines.last().is_some_and(move |line| line.is_empty()) { + _ = lines.pop(); + } + let mut grid = Self::new(width, lines.len()); for (y, line) in lines.iter().enumerate() { for (x, char) in line.chars().enumerate() { @@ -161,6 +168,22 @@ mod feature_cp437 { } } + impl From<&CharGrid> for String { + fn from(value: &CharGrid) -> Self { + value + .iter_rows() + .map(move |chars| { + chars + .collect::() + .replace('\0', " ") + .trim_end() + .to_string() + }) + .collect::>() + .join("\n") + } + } + /// Convert the provided bytes to UTF-8. pub fn cp437_to_str(cp437: &[u8]) -> String { cp437.iter().map(move |char| cp437_to_char(*char)).collect() @@ -258,4 +281,13 @@ mod tests_feature_cp437 { fn convert_invalid() { assert_eq!(cp437_to_char(char_to_cp437('😜')), '?'); } + + #[test] + fn str_to_char_grid() { + let original = "Hello\r\nWorld!\n...\n"; + let grid = CharGrid::from(original); + assert_eq!(3, grid.height()); + let actual = String::from(&grid); + assert_eq!("Hello\nWorld!\n...", actual); + } }