You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
72 lines
1.6 KiB
72 lines
1.6 KiB
2 years ago
|
|
||
|
|
||
|
pub trait Locatable {
|
||
|
fn get_xy(&self) -> (usize, usize);
|
||
|
}
|
||
|
|
||
|
pub trait LocatableFactory<T:Locatable> {
|
||
|
fn create(x:usize, y:usize) -> T;
|
||
|
}
|
||
|
|
||
|
#[derive(Clone)]
|
||
|
pub struct LocatableVec<T:Locatable + std::marker::Copy> {
|
||
|
arr: [Option<T>; 81],
|
||
|
len: usize,
|
||
|
}
|
||
|
|
||
|
pub struct LocatableVecIter<'a, T:Locatable + std::marker::Copy> {
|
||
|
vec : &'a LocatableVec<T>,
|
||
|
idx: usize,
|
||
|
} // (&'a LocatableVec<T>, usize);
|
||
|
|
||
|
|
||
|
impl<T:Locatable + std::marker::Copy> LocatableVec<T> {
|
||
|
|
||
|
pub fn new() -> LocatableVec<T> {
|
||
|
LocatableVec{arr: [None; 81], len: 0}
|
||
|
}
|
||
|
|
||
|
pub fn iter(&self) -> LocatableVecIter<'_, T> {
|
||
|
LocatableVecIter{vec: self, idx: 0}
|
||
|
}
|
||
|
|
||
|
pub fn len(&self) -> usize {
|
||
|
self.len
|
||
|
}
|
||
|
|
||
|
pub fn put(&mut self, value : T) {
|
||
|
let (x,y) = value.get_xy();
|
||
|
let idx = y * 9 + x;
|
||
|
if self.arr[idx].is_none() {
|
||
|
self.len += 1;
|
||
|
}
|
||
|
self.arr[idx] = Some(value);
|
||
|
}
|
||
|
|
||
|
pub fn remove(&mut self, value : &T) -> bool{
|
||
|
let (x,y) = value.get_xy();
|
||
|
let idx = y * 9 + x;
|
||
|
if self.arr[idx].is_some() {
|
||
|
self.arr[idx] = None;
|
||
|
self.len -= 1;
|
||
|
return true;
|
||
|
}
|
||
|
false
|
||
|
}
|
||
|
|
||
|
}
|
||
|
|
||
|
impl<'a, T:Locatable + std::marker::Copy> Iterator for LocatableVecIter<'a, T> {
|
||
|
type Item = &'a T;
|
||
|
|
||
|
fn next(&mut self) -> Option<Self::Item> {
|
||
|
for i in self.idx..self.vec.arr.len() {
|
||
|
let pos = &self.vec.arr[i];
|
||
|
if pos.is_some() {
|
||
|
self.idx = i + 1;
|
||
|
return pos.as_ref();
|
||
|
}
|
||
|
}
|
||
|
None
|
||
|
}
|
||
|
}
|