use std::ops::{Deref, DerefMut};
#[derive(Debug, Clone)]
pub struct ArrayMap<T> {
nodes: Vec<T>,
available_indexes: Vec<usize>,
}
impl<T> ArrayMap<T> {
pub fn new(initial_capacity: usize) -> ArrayMap<T> {
let nodes: Vec<T> = Vec::with_capacity(initial_capacity);
let mut available_indexes: Vec<usize> = Vec::with_capacity(initial_capacity);
for i in 0..initial_capacity {
available_indexes.push(initial_capacity - 1 - i);
}
ArrayMap {
nodes,
available_indexes,
}
}
pub fn push(&mut self, node: T) -> usize {
match self.available_indexes.pop() {
Some(index) => match self.nodes.get(index) {
Some(_) => {
self.nodes[index] = node;
index
}
None => {
self.nodes.push(node);
index
}
},
None => {
self.nodes.push(node);
self.nodes.len() - 1
}
}
}
pub fn remove(&mut self, index: usize) {
let _ = self
.nodes
.get(index)
.expect("ERROR: Was expecting a node in this position");
self.available_indexes.push(index);
}
pub fn node_number(&self) -> usize {
self.nodes.len()
}
}
impl<T> Deref for ArrayMap<T> {
type Target = Vec<T>;
fn deref(&self) -> &Vec<T> {
&self.nodes
}
}
impl<T> DerefMut for ArrayMap<T> {
fn deref_mut(&mut self) -> &mut Vec<T> {
&mut self.nodes
}
}