forked from n3tael/labast
обновление 1.0.5
* стек теперь не бесконечный. задать можно через аргумент cli (максимум 65535, дефолт: 256)
This commit is contained in:
+49
-4
@@ -1,3 +1,7 @@
|
||||
use std::ops::Deref;
|
||||
|
||||
use crate::errors::StackError;
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Instruction {
|
||||
pub name: String,
|
||||
@@ -5,21 +9,62 @@ pub struct Instruction {
|
||||
pub data: u16
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Stack {
|
||||
pub program: Vec<Instruction>,
|
||||
pub program_counter: u16,
|
||||
pub labels: [Option<i16>; 256],
|
||||
pub memory: Vec<u16>
|
||||
pub memory: StackVec
|
||||
}
|
||||
|
||||
impl Stack {
|
||||
pub fn new() -> Stack {
|
||||
pub fn new(stack_size: usize) -> Stack {
|
||||
return Stack {
|
||||
program: Vec::new(),
|
||||
program_counter: 0,
|
||||
labels: [None; 256],
|
||||
memory: Vec::new()
|
||||
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
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user