use crate::{
Result,
Error,
ensure,
Position, Size
};
#[derive(Debug, Clone)]
pub struct Bounds {
pub origin: Position,
pub dim: Size
}
impl Bounds {
pub fn of(size: Size) -> Self {
Self {
origin: Position::default(),
dim: size
}
}
pub fn at_origin(mut self, origin: Position) -> Self {
self.origin = origin;
self
}
pub fn index_of(&self, pos: Position) -> Result<usize> {
ensure!(
pos.x() < self.dim.width() && pos.y() < self.dim.height(),
Error::OutOfBounds(pos.y(), pos.x(), self.clone())
);
let n = (pos.y() * self.dim.width()) + pos.x();
Ok(n as usize)
}
pub fn iter(&self) -> impl Iterator<Item = Position> + '_ {
self.dim.iter().map(move |pos| pos + self.origin)
}
}