improve whitespace handling when converting between string and grid

This commit is contained in:
Vinzenz Schroeter 2024-10-13 16:31:03 +02:00
parent 526f6264bf
commit ab82900414

View file

@ -146,10 +146,17 @@ mod feature_cp437 {
impl From<&str> for CharGrid { impl From<&str> for CharGrid {
fn from(value: &str) -> Self { fn from(value: &str) -> Self {
let value = value.replace("\r\n", "\n"); let value = value.replace("\r\n", "\n");
let lines = value.split('\n').collect::<Vec<_>>(); let mut lines = value
.split('\n')
.map(move |line| line.trim_end())
.collect::<Vec<_>>();
let width = let width =
lines.iter().fold(0, move |a, x| std::cmp::max(a, x.len())); 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()); let mut grid = Self::new(width, lines.len());
for (y, line) in lines.iter().enumerate() { for (y, line) in lines.iter().enumerate() {
for (x, char) in line.chars().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::<String>()
.replace('\0', " ")
.trim_end()
.to_string()
})
.collect::<Vec<_>>()
.join("\n")
}
}
/// Convert the provided bytes to UTF-8. /// Convert the provided bytes to UTF-8.
pub fn cp437_to_str(cp437: &[u8]) -> String { pub fn cp437_to_str(cp437: &[u8]) -> String {
cp437.iter().map(move |char| cp437_to_char(*char)).collect() cp437.iter().map(move |char| cp437_to_char(*char)).collect()
@ -258,4 +281,13 @@ mod tests_feature_cp437 {
fn convert_invalid() { fn convert_invalid() {
assert_eq!(cp437_to_char(char_to_cp437('😜')), '?'); 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);
}
} }