Added SimpleVector
This commit is contained in:
107
src/webee/simpleVector.rs
Normal file
107
src/webee/simpleVector.rs
Normal file
@@ -0,0 +1,107 @@
|
|||||||
|
|
||||||
|
|
||||||
|
#[derive(Copy, Clone, Debug)]
|
||||||
|
pub struct SimpleVec {
|
||||||
|
items: [VecItem; 128]
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
#[derive(Copy, Clone, Debug)]
|
||||||
|
pub struct VecItem {
|
||||||
|
value: u8,
|
||||||
|
indexed: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
impl VecItem {
|
||||||
|
fn new() -> Self {
|
||||||
|
Self {
|
||||||
|
value: 0,
|
||||||
|
indexed: false,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl SimpleVec {
|
||||||
|
|
||||||
|
pub fn new() -> Self {
|
||||||
|
Self { items: [VecItem { value: 0, indexed: false}; 128] }
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn len(&self) -> usize {
|
||||||
|
|
||||||
|
let mut len = 0;
|
||||||
|
for i in &self.items {
|
||||||
|
if i.indexed { len = len + 1 };
|
||||||
|
};
|
||||||
|
|
||||||
|
len
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
pub fn push(&mut self, value: u8) {
|
||||||
|
|
||||||
|
let index = if self.len() < 0 { self.len() + 1 } else { 0 };
|
||||||
|
|
||||||
|
let vec_item = VecItem {
|
||||||
|
value,
|
||||||
|
indexed: true,
|
||||||
|
};
|
||||||
|
|
||||||
|
let mut items = self.items;
|
||||||
|
{
|
||||||
|
let (left, right) = items.split_at_mut(self.len());
|
||||||
|
right[index] = vec_item;
|
||||||
|
}
|
||||||
|
|
||||||
|
self.items = items;
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn pop(&mut self) {
|
||||||
|
|
||||||
|
let index = if self.len() > 0 { self.len() - 1 } else { 0 };
|
||||||
|
|
||||||
|
let mut items = self.items;
|
||||||
|
{
|
||||||
|
let (left, right) = items.split_at_mut(self.len());
|
||||||
|
left[index] = VecItem::new();
|
||||||
|
}
|
||||||
|
|
||||||
|
self.items = items;
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn items(&self) -> [u8; 128] {
|
||||||
|
self.items.map(|i| i.value)
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
pub fn from_slice(slice: &[u8]) -> Self {
|
||||||
|
|
||||||
|
let mut simple_array = Self::new();
|
||||||
|
for i in slice {
|
||||||
|
simple_array.push(*i);
|
||||||
|
};
|
||||||
|
simple_array
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
fn main() {
|
||||||
|
|
||||||
|
let mut myarr = SimpleVec::new();
|
||||||
|
myarr.push(15);
|
||||||
|
println!("{:?}", myarr.items());
|
||||||
|
myarr.push(122);
|
||||||
|
println!("{:?}", myarr.items());
|
||||||
|
myarr.pop();
|
||||||
|
println!("{:?}", myarr.items());
|
||||||
|
|
||||||
|
let mut anotherarr = SimpleVec::from_slice(&[1,2,3]);
|
||||||
|
println!("{:?}", anotherarr);
|
||||||
|
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user