#![allow(deprecated)]
mod coord;
mod rect;
use alloc::vec::Vec;
pub use coord::Coord;
pub use rect::Rect;
#[deprecated(since = "0.1.4", note = "Use `DynamicGrid` instead")]
#[derive(Debug, Clone, Eq, PartialEq)]
pub struct Grid<T> {
cells: Vec<T>,
width: usize,
}
impl<T: Default> Grid<T> {
#[must_use]
pub fn new(width: usize, height: usize) -> Self {
Self::new_with(width, height, |_| T::default())
}
}
impl<T> Grid<T> {
#[must_use]
pub fn new_with(width: usize, height: usize, init_cell: impl FnMut(Coord) -> T) -> Self {
Self::from_row_major_iter(
width,
(0..(width * height))
.map(|i| Coord::from_index(width, i))
.map(init_cell),
)
}
#[must_use]
pub fn from_row_major_iter(width: usize, iter: impl IntoIterator<Item = T>) -> Self {
let cells = iter.into_iter().collect();
Self { cells, width }
}
#[must_use]
pub fn get(&self, coord: impl Into<Coord>) -> Option<&T> {
let index = coord.into().into_index(self.width)?;
self.cells.get(index)
}
pub fn get_mut(&mut self, coord: impl Into<Coord>) -> Option<&mut T> {
let index = coord.into().into_index(self.width)?;
self.cells.get_mut(index)
}
pub fn set(&mut self, coord: impl Into<Coord>, value: T) {
let cell = self.get_mut(coord).expect("coordinate is out-of-bounds");
*cell = value;
}
pub fn cells(&self) -> impl Iterator<Item = &T> {
self.cells.iter()
}
pub fn cells_in_rect(&self, rect: impl Into<Rect>) -> impl Iterator<Item = &T> {
rect.into().coords().filter_map(|c| self.get(c))
}
}