Initial commit
This commit is contained in:
commit
7d47a10acf
18 changed files with 1545 additions and 0 deletions
52
src/misc/arena.rs
Normal file
52
src/misc/arena.rs
Normal file
|
|
@ -0,0 +1,52 @@
|
|||
#[derive(Debug)]
|
||||
pub struct Arena<T> {
|
||||
data: Vec<Option<T>>,
|
||||
free: Vec<usize>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct ArenaKey(usize);
|
||||
|
||||
impl Default for ArenaKey {
|
||||
fn default() -> Self {
|
||||
ArenaKey(usize::MAX)
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> Arena<T> {
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
data: Vec::new(),
|
||||
free: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn insert(&mut self, item: T) -> ArenaKey {
|
||||
if let Some(i) = self.free.pop() {
|
||||
self.data[i] = Some(item);
|
||||
ArenaKey(i)
|
||||
} else {
|
||||
self.data.push(Some(item));
|
||||
ArenaKey(self.data.len() - 1)
|
||||
}
|
||||
}
|
||||
|
||||
pub fn get(&self, key: &ArenaKey) -> &T {
|
||||
self.data.get(key.0).unwrap().as_ref().unwrap()
|
||||
}
|
||||
|
||||
pub fn get_mut(&mut self, key: &ArenaKey) -> &mut T {
|
||||
self.data.get_mut(key.0).unwrap().as_mut().unwrap()
|
||||
}
|
||||
|
||||
pub fn remove(&mut self, key: ArenaKey) -> T {
|
||||
self.free.push(key.0);
|
||||
self.data[key.0].take().unwrap()
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> Default for Arena<T> {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
45
src/misc/map.rs
Normal file
45
src/misc/map.rs
Normal file
|
|
@ -0,0 +1,45 @@
|
|||
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);
|
||||
assert!(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);
|
||||
assert!(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;
|
||||
}
|
||||
}
|
||||
5
src/misc/mod.rs
Normal file
5
src/misc/mod.rs
Normal file
|
|
@ -0,0 +1,5 @@
|
|||
pub mod arena;
|
||||
pub mod map;
|
||||
|
||||
pub use arena::*;
|
||||
pub use map::*;
|
||||
Loading…
Add table
Add a link
Reference in a new issue