labast/src/stack.rs

78 lines
1.5 KiB
Rust

use std::ops::Deref;
use crate::errors::StackError;
#[derive(Clone, Debug)]
pub struct Instruction {
pub name: String,
pub arg: String,
pub data: u16,
pub ispiped: bool,
pub isdrained: bool
}
pub struct Stack {
pub program: Vec<Instruction>,
pub program_counter: u16,
pub labels: [Option<i16>; 256],
pub memory: StackVec,
}
impl Stack {
pub fn new(stack_size: usize) -> Stack {
return Stack {
program: Vec::new(),
program_counter: 0,
labels: [None; 256],
memory: StackVec::new(stack_size),
};
}
}
pub struct StackVec {
data: Vec<u16>,
max_size: usize,
}
impl StackVec {
fn new(max_size: usize) -> Self {
StackVec {
data: Vec::new(),
max_size,
}
}
pub fn size(&self) -> usize {
self.max_size
}
pub fn push(&mut self, item: u16) {
if self.data.len() + 1 > self.max_size {
panic!("{}", StackError::StackOverflow);
} else {
self.data.push(item);
}
}
pub fn pop(&mut self) -> u16 {
self.data
.pop()
.expect(&format!("{}", StackError::StackUnderflow))
}
pub fn last(&mut self) -> u16 {
*self
.data
.last()
.expect(&format!("{}", StackError::StackUnderflow))
}
}
impl Deref for StackVec {
type Target = Vec<u16>;
fn deref(&self) -> &Self::Target {
&self.data
}
}