From 6fbc06d4e127aee438d48ad4a9d30a690fc912bb Mon Sep 17 00:00:00 2001 From: Bill Thiede Date: Wed, 22 Dec 2021 12:46:30 -0800 Subject: [PATCH] advent: add helper image class (not currently used). --- src/image.rs | 95 ++++++++++++++++++++++++++++++++++++++++++++++++++++ src/lib.rs | 5 +++ 2 files changed, 100 insertions(+) create mode 100644 src/image.rs diff --git a/src/image.rs b/src/image.rs new file mode 100644 index 0000000..6f651c5 --- /dev/null +++ b/src/image.rs @@ -0,0 +1,95 @@ +use crate::prelude::*; + +pub struct Image { + width: usize, + height: usize, + pixels: Vec, +} + +impl Image { + fn kernel3x3(&mut self, (x, y): (usize, usize), func: F) + where + F: Fn(u8) -> u8, + { + if x > 0 { + self[(x - 1, y)] = func(self[(x - 1, y)]); + if y > 0 { + self[(x - 1, y - 1)] = func(self[(x - 1, y - 1)]); + } + if y < self.height - 1 { + self[(x - 1, y + 1)] = func(self[(x - 1, y + 1)]); + } + } + + if y > 0 { + self[(x, y - 1)] = func(self[(x, y - 1)]); + } + self[(x, y)] = func(self[(x, y)]); + if y < self.height - 1 { + self[(x, y + 1)] = func(self[(x, y + 1)]); + } + + if x < self.width - 1 { + self[(x + 1, y)] = func(self[(x + 1, y)]); + if y > 0 { + self[(x + 1, y - 1)] = func(self[(x + 1, y - 1)]); + } + if y < self.height - 1 { + self[(x + 1, y + 1)] = func(self[(x + 1, y + 1)]); + } + } + } +} + +impl PartialEq for Image { + fn eq(&self, other: &Self) -> bool { + self.width == other.width && self.height == other.height && self.pixels == other.pixels + } +} + +impl Debug for Image { + fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error> { + writeln!(f)?; + for y in 0..self.height { + for x in 0..self.width { + write!(f, "{:2}", self[(x, y)] as char)?; + } + writeln!(f)?; + } + Ok(()) + } +} + +impl FromStr for Image { + type Err = Infallible; + + fn from_str(s: &str) -> Result { + let rows: Vec<_> = s.lines().collect(); + let width = rows[0].len(); + let height = rows.len(); + let pixels = rows + .iter() + .flat_map(|row| row.as_bytes().iter()) + .map(|b| *b) + .collect(); + + Ok(Image { + width, + height, + pixels, + }) + } +} + +impl Index<(usize, usize)> for Image { + type Output = u8; + fn index(&self, (x, y): (usize, usize)) -> &Self::Output { + &self.pixels[x + y * self.width] + } +} + +impl IndexMut<(usize, usize)> for Image { + fn index_mut(&mut self, (x, y): (usize, usize)) -> &mut Self::Output { + &mut self.pixels[x + y * self.width] + } +} diff --git a/src/lib.rs b/src/lib.rs index 878b20e..50cdd48 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,5 +1,6 @@ pub mod prelude { pub use std::{ + collections::{HashMap, HashSet}, convert::Infallible, fmt::{Debug, Display, Error, Formatter}, io::Read, @@ -10,4 +11,8 @@ pub mod prelude { pub use anyhow::Result; pub use thiserror::Error; + + pub use crate::image::Image; } + +mod image;