factorio_blueprint/src/misc/map.rs

66 lines
1.5 KiB
Rust

#[derive(Clone, Debug)]
pub struct Map<T> {
pub width: usize,
pub height: usize,
data: Vec<T>,
}
impl<T> Map<T>
where
T: Default,
{
pub fn new(width: usize, height: usize) -> Self {
let mut data = Vec::new();
for _ in 0..(width * height) {
data.push(T::default());
}
Self {
width,
height,
data,
}
}
fn index(&self, x: usize, y: usize) -> usize {
x + y * self.width
}
pub fn get(&self, x: usize, y: usize) -> &T {
assert!(
x < self.width,
"assertion failed: x < self.width; x: {}, self.width: {}",
x,
self.width
);
assert!(
y < self.height,
"assertion failed: y < self.height; y: {}, self.height: {}",
y,
self.height
);
let i = self.index(x, y);
self.data.get(i).unwrap()
}
pub fn get_mut(&mut self, x: usize, y: usize) -> &mut T {
assert!(
x < self.width,
"assertion failed: x < self.width; x: {}, self.width: {}",
x,
self.width
);
assert!(
y < self.height,
"assertion failed: y < self.height; y: {}, self.height: {}",
y,
self.height
);
let i = self.index(x, y);
self.data.get_mut(i).unwrap()
}
pub fn set(&mut self, x: usize, y: usize, item: T) {
*self.get_mut(x, y) = item;
}
}