diff --git a/showbits-common/src/buffer.rs b/showbits-common/src/buffer.rs new file mode 100644 index 0000000..c4ae863 --- /dev/null +++ b/showbits-common/src/buffer.rs @@ -0,0 +1,56 @@ +use crate::Vec2; + +#[derive(Clone)] +pub struct Buffer { + size: Vec2, + data: Vec, +} + +impl Buffer { + pub fn new(size: Vec2, color: C) -> Self + where + C: Copy, + { + assert!(size.x >= 0); + assert!(size.y >= 0); + + let len = (size.x * size.y) as usize; + let data = vec![color; len]; + + Self { size, data } + } + + pub fn size(&self) -> Vec2 { + self.size + } + + fn index(&self, pos: Vec2) -> Option { + let in_bounds_x = pos.x >= 0 || pos.x < self.size.x; + let in_bounds_y = pos.y >= 0 || pos.y < self.size.y; + let in_bounds = in_bounds_x && in_bounds_y; + + if in_bounds { + Some((pos.y * self.size.x + pos.x) as usize) + } else { + None + } + } + + pub fn at(&self, pos: Vec2) -> Option<&C> { + let index = self.index(pos)?; + let pixel = self.data.get(index)?; + Some(pixel) + } + + pub fn at_mut(&mut self, pos: Vec2) -> Option<&mut C> { + let index = self.index(pos)?; + let pixel = self.data.get_mut(index)?; + Some(pixel) + } + + pub fn set(&mut self, pos: Vec2, color: C) { + if let Some(pixel) = self.at_mut(pos) { + *pixel = color; + } + } +} diff --git a/showbits-common/src/lib.rs b/showbits-common/src/lib.rs index e63189e..b5eac6e 100644 --- a/showbits-common/src/lib.rs +++ b/showbits-common/src/lib.rs @@ -1,3 +1,4 @@ -pub use crate::vec2::Vec2; +pub use crate::{buffer::Buffer, vec2::Vec2}; +mod buffer; mod vec2;