Skip to content

Instantly share code, notes, and snippets.

@NishanthSpShetty
Created January 22, 2020 10:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save NishanthSpShetty/213561fc9fb9733fd01ce823f1ea04b6 to your computer and use it in GitHub Desktop.
Save NishanthSpShetty/213561fc9fb9733fd01ce823f1ea04b6 to your computer and use it in GitHub Desktop.
Implement runtime stack for Stack-VM
pub struct VMStack {
internal_stack: Vec<i32>,
capacity: usize,
top: usize, //also size
}
impl VMStack {
pub fn new(stack_size: usize) -> VMStack {
VMStack { capacity: stack_size, top: 0, internal_stack: Vec::with_capacity(stack_size) }
}
pub fn push(&mut self, data: i32) {
if self.top == self.capacity {
panic!("Stack overflow Capacity {} , Size {} ", self.capacity, self.top)
}
self.internal_stack.push(data);
self.top += 1;
}
pub fn pop(&mut self) -> i32 {
if self.top == 0 {
panic!("Stack underflow")
}
self.top-=1;
self.internal_stack.pop().unwrap()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment