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.

148 lines
3.4 KiB

pub trait Locatable {
fn get_xy(&self) -> (usize, usize);
}
#[derive(Clone)]
pub struct LocatableVec<T:Locatable + Copy, const COUNT: usize> {
arr: [Option<T>; COUNT],
len: usize,
}
pub struct LocatableVecIter<'a, T:Locatable + Copy, const COUNT: usize> {
vec : &'a LocatableVec<T, COUNT>,
idx: usize,
cnt: usize,
}
impl<T:Locatable + Copy, const COUNT: usize> LocatableVec<T, COUNT> {
pub fn new() -> LocatableVec<T, COUNT> {
LocatableVec{arr: [None; COUNT], len: 0}
}
pub fn iter(&self) -> LocatableVecIter<'_, T, COUNT> {
LocatableVecIter{vec: self, idx: 0, cnt: 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 + Copy, const COUNT: usize> Iterator for LocatableVecIter<'a, T, COUNT> {
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;
self.cnt += 1;
return pos.as_ref();
}
}
None
}
fn size_hint(&self) -> (usize, Option<usize>) {
(self.vec.len - self.cnt, Some(self.vec.arr.len() - self.idx))
}
}
impl<'a, L:Locatable + Copy, const COUNT: usize> FromIterator<L> for LocatableVec<L, COUNT> {
fn from_iter<T: IntoIterator<Item = L>>(iter: T) -> Self {
let mut x = LocatableVec{arr: [None; COUNT], len: 0};
for p in iter {
x.put(p);
}
x
}
}
pub struct FsVec<T: Copy + Sized + Default, const COUNT: usize> {
arr: [T; COUNT],
len: usize
}
pub struct FsVecIter<'a, T:Copy + Sized + Default, const COUNT: usize> {
vec : &'a FsVec<T, COUNT>,
idx: usize,
}
impl<T: Sized + Copy + Default, const COUNT: usize> FsVec<T, COUNT> {
pub fn new() -> FsVec<T, COUNT> {
FsVec{arr: [Default::default(); COUNT], len: 0}
}
pub fn len(&self) -> usize {
self.len
}
pub fn append(&mut self, value : T) {
self.arr[self.len] = value;
self.len += 1;
}
pub fn iter(&self) -> FsVecIter<'_, T, COUNT> {
FsVecIter{vec: self, idx: 0}
}
}
impl<'a, T:Sized + Copy + Default, const COUNT: usize> Iterator for FsVecIter<'a, T, COUNT> {
type Item = &'a T;
fn next(&mut self) -> Option<Self::Item> {
if self.idx >= self.vec.len {
return None
}
let result = Some(&self.vec.arr[self.idx]);
self.idx += 1;
result
}
fn size_hint(&self) -> (usize, Option<usize>) {
(self.vec.len() - self.idx, Some(self.vec.len() - self.idx))
}
}
impl<'a, L:Sized + Copy + Default, const COUNT: usize> FromIterator<L> for FsVec<L, COUNT> {
fn from_iter<T: IntoIterator<Item = L>>(iter: T) -> Self {
let mut x = FsVec::new();
for elem in iter {
x.append(elem);
}
x
}
}