Last active
August 24, 2017 04:41
-
-
Save Archina/612de166242694f9e9e3ccb6f1bdb4ac to your computer and use it in GitHub Desktop.
Implementing a simple Stack within Rust
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
use std::boxed::Box; | |
use std::mem; | |
enum CellarState<S>{ | |
Empty, | |
Value (S,Box<CellarState<S>>), | |
} | |
pub struct Cellar<S>{ | |
// The Cellar of the Automaton | |
cellar: CellarState<S>, | |
} | |
impl <S> Cellar<S>{ | |
fn push(&mut self, next_state: S) -> (){ | |
let tmp_cellar = mem::replace(&mut self.cellar,CellarState::Empty); | |
self.cellar = CellarState::Value(next_state,Box::new(tmp_cellar)); | |
} | |
fn pop(&mut self)->Option<S>{ | |
match mem::replace(&mut self.cellar,CellarState::Empty){ | |
CellarState::Empty => None, | |
CellarState::Value(state,tmp_cellar) => { | |
self.cellar = *tmp_cellar; | |
Some(state) | |
}, | |
} | |
} | |
fn top(&self)->Option<&S>{ | |
match self.cellar{ | |
CellarState::Empty => None, | |
CellarState::Value(ref state,_) => { | |
Some(state) | |
}, | |
} | |
} | |
} | |
impl <S> Default for Cellar<S>{ | |
fn default() -> Cellar<S>{ | |
return Cellar{ | |
cellar: CellarState::Empty, | |
} | |
} | |
} | |
#[test] | |
fn validate() { | |
let mut pda : Cellar<i32> = Cellar::default(); | |
// New cellar. | |
assert!(pda.top().is_none()); | |
// Fill empty cellar. | |
pda.push(10); | |
assert!(pda.top().is_some()); | |
// Fill full cellar a bit more. | |
pda.push(22); | |
pda.push(15); | |
pda.push(39); | |
assert!(pda.top().is_some()); | |
// Assure correct top. | |
assert_eq!(39,*pda.top().unwrap()); | |
// Remove from filled cellar. | |
pda.pop(); | |
assert!(pda.top().is_some()); | |
assert_eq!(15,*pda.top().unwrap()); | |
// Empty out cellar. | |
pda.pop(); | |
pda.pop(); | |
pda.pop(); | |
assert!(pda.top().is_none()); | |
// Remove from already empty cellar. | |
pda.pop(); | |
assert!(pda.top().is_none()); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment