easier conversion of PrimitiveGrids

This commit is contained in:
Vinzenz Schroeter 2024-10-13 16:13:12 +02:00
parent e1ca802268
commit 526f6264bf
2 changed files with 12 additions and 23 deletions

View file

@ -133,34 +133,13 @@ mod feature_cp437 {
impl From<&Cp437Grid> for CharGrid { impl From<&Cp437Grid> for CharGrid {
fn from(value: &Cp437Grid) -> Self { fn from(value: &Cp437Grid) -> Self {
let mut grid = Self::new(value.width(), value.height()); value.convert(move |cp437| cp437_to_char(*cp437))
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
} }
} }
impl From<&CharGrid> for Cp437Grid { impl From<&CharGrid> for Cp437Grid {
fn from(value: &CharGrid) -> Self { fn from(value: &CharGrid) -> Self {
let mut grid = Self::new(value.width(), value.height()); value.convert(move |char| char_to_cp437(*char))
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
} }
} }

View file

@ -110,6 +110,16 @@ impl<T: PrimitiveGridType> PrimitiveGrid<T> {
None None
} }
} }
/// Convert between PrimitiveGrid types
pub fn convert<TConverted, F>(&self, f: F) -> PrimitiveGrid<TConverted>
where
TConverted: PrimitiveGridType,
F: FnMut(&T) -> TConverted,
{
let data = self.data_ref().iter().map(f).collect::<Vec<_>>();
PrimitiveGrid::load(self.width(), self.height(), &*data)
}
} }
impl<T: PrimitiveGridType> Grid<T> for PrimitiveGrid<T> { impl<T: PrimitiveGridType> Grid<T> for PrimitiveGrid<T> {