mirror of
https://github.com/cccb/servicepoint.git
synced 2025-01-18 10:00:14 +01:00
improve whitespace handling when converting between string and grid
This commit is contained in:
parent
526f6264bf
commit
ab82900414
|
@ -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::<Vec<_>>();
|
||||
let mut lines = value
|
||||
.split('\n')
|
||||
.map(move |line| line.trim_end())
|
||||
.collect::<Vec<_>>();
|
||||
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::<String>()
|
||||
.replace('\0', " ")
|
||||
.trim_end()
|
||||
.to_string()
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
.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);
|
||||
}
|
||||
}
|
||||
|
|
Loading…
Reference in a new issue