-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathvarstack.rs
More file actions
88 lines (76 loc) · 2.47 KB
/
varstack.rs
File metadata and controls
88 lines (76 loc) · 2.47 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
use std::fmt::Debug;
pub trait VarStack : Debug {
type Item;
fn top(&self) -> Option<&Self::Item>;
fn pop(&mut self) -> Option<Self::Item>;
fn pop_many(&mut self, count: usize) -> Option<Vec<Self::Item>>;
fn push(&mut self, value: Self::Item);
fn pop_all_and_get_n_last(&mut self, nb: usize) -> Option<Vec<Self::Item>>;
fn pop_n_pairs(&mut self, nb: usize) -> Option<Vec<(Self::Item, Self::Item)>>;
fn peek(&self, nb: usize) -> Option<Vec<&Self::Item>>;
}
#[derive(Debug)]
pub struct VectorVarStack<Item: Sized> {
vector: Vec<Item>
}
impl<Item> VectorVarStack<Item> {
pub fn new() -> VectorVarStack<Item> {
VectorVarStack { vector: Vec::new() }
}
}
impl<Item> VectorVarStack<Item> {
pub fn iter(&self) -> ::std::slice::Iter<Item> {
self.vector.iter()
}
}
impl<Item: Clone> VarStack for VectorVarStack<Item> where Item: Debug {
type Item = Item;
fn top(&self) -> Option<&Self::Item> {
self.vector.last()
}
fn pop(&mut self) -> Option<Self::Item> {
self.vector.pop()
}
fn pop_many(&mut self, count: usize) -> Option<Vec<Self::Item>> {
if count > self.vector.len() {
None
}
else {
let length = self.vector.len();
Some(self.vector.drain((length-count)..length).into_iter().collect())
}
}
fn push(&mut self, value: Self::Item) {
self.vector.push(value)
}
fn pop_all_and_get_n_last(&mut self, nb: usize) -> Option<Vec<Self::Item>> {
if self.vector.len() < nb {
None
}
else {
self.vector.truncate(nb);
Some(self.vector.drain(..).collect())
}
}
fn pop_n_pairs(&mut self, nb: usize) -> Option<Vec<(Self::Item, Self::Item)>> {
self.pop_many(nb*2).map(|values| {
let mut pairs = Vec::<(Self::Item, Self::Item)>::new();
pairs.reserve(nb);
for chunk in values.chunks(2) {
assert!(chunk.len() == 2);
// TODO: remove clones. http://stackoverflow.com/q/37097395/539465
pairs.push((chunk.get(0).unwrap().clone(), chunk.get(1).unwrap().clone()));
}
pairs
})
}
fn peek(&self, nb: usize) -> Option<Vec<&Self::Item>> {
if nb > self.vector.len() {
None
}
else {
let length = self.vector.len();
Some(self.vector[(length-nb)..length].iter().collect())
}
}
}