From 526f6264bff69ed32fffc7b22df3a08363a0116c Mon Sep 17 00:00:00 2001 From: Vinzenz Schroeter Date: Sun, 13 Oct 2024 16:13:12 +0200 Subject: [PATCH] easier conversion of PrimitiveGrids --- crates/servicepoint/src/cp437.rs | 25 ++--------------------- crates/servicepoint/src/primitive_grid.rs | 10 +++++++++ 2 files changed, 12 insertions(+), 23 deletions(-) diff --git a/crates/servicepoint/src/cp437.rs b/crates/servicepoint/src/cp437.rs index a2250b3..5909296 100644 --- a/crates/servicepoint/src/cp437.rs +++ b/crates/servicepoint/src/cp437.rs @@ -133,34 +133,13 @@ mod feature_cp437 { impl From<&Cp437Grid> for CharGrid { fn from(value: &Cp437Grid) -> Self { - let mut grid = Self::new(value.width(), value.height()); - - for y in 0..grid.height() { - for x in 0..grid.width() { - let converted = CP437_TO_UTF8[value.get(x, y) as usize]; - grid.set(x, y, converted); - } - } - - grid + value.convert(move |cp437| cp437_to_char(*cp437)) } } impl From<&CharGrid> for Cp437Grid { fn from(value: &CharGrid) -> Self { - let mut grid = Self::new(value.width(), value.height()); - - for y in 0..grid.height() { - for x in 0..grid.width() { - let char = value.get(x, y); - let converted = *UTF8_TO_CP437 - .get(&char) - .unwrap_or(&MISSING_CHAR_CP437); - grid.set(x, y, converted); - } - } - - grid + value.convert(move |char| char_to_cp437(*char)) } } diff --git a/crates/servicepoint/src/primitive_grid.rs b/crates/servicepoint/src/primitive_grid.rs index 2b02ca3..0b947b6 100644 --- a/crates/servicepoint/src/primitive_grid.rs +++ b/crates/servicepoint/src/primitive_grid.rs @@ -110,6 +110,16 @@ impl PrimitiveGrid { None } } + + /// Convert between PrimitiveGrid types + pub fn convert(&self, f: F) -> PrimitiveGrid + where + TConverted: PrimitiveGridType, + F: FnMut(&T) -> TConverted, + { + let data = self.data_ref().iter().map(f).collect::>(); + PrimitiveGrid::load(self.width(), self.height(), &*data) + } } impl Grid for PrimitiveGrid {