Created
January 22, 2020 10:57
-
-
Save NishanthSpShetty/213561fc9fb9733fd01ce823f1ea04b6 to your computer and use it in GitHub Desktop.
Implement runtime stack for Stack-VM
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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