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
89
90
91
92
93
94
95
96
97
98
use instructions;
use std::fmt;
pub trait Stack<T> {
fn peek(&self, no_from_top: usize) -> &T;
fn swap_with_top(&mut self, no_from_top: usize);
fn has(&self, no_of_elems: usize) -> bool;
fn pop_back(&mut self) -> T;
fn pop_n(&mut self, no_of_elems: usize) -> &[T];
fn push(&mut self, elem: T);
fn size(&self) -> usize;
fn peek_top(&self, no_of_elems: usize) -> &[T];
}
pub struct VecStack<S> {
stack: Vec<S>,
logs: [S; instructions::MAX_NO_OF_TOPICS],
}
impl<S: Copy> VecStack<S> {
pub fn with_capacity(capacity: usize, zero: S) -> Self {
VecStack {
stack: Vec::with_capacity(capacity),
logs: [zero; instructions::MAX_NO_OF_TOPICS],
}
}
}
impl<S: fmt::Display> Stack<S> for VecStack<S> {
fn peek(&self, no_from_top: usize) -> &S {
&self.stack[self.stack.len() - no_from_top - 1]
}
fn swap_with_top(&mut self, no_from_top: usize) {
let len = self.stack.len();
self.stack.swap(len - no_from_top - 1, len - 1);
}
fn has(&self, no_of_elems: usize) -> bool {
self.stack.len() >= no_of_elems
}
fn pop_back(&mut self) -> S {
self.stack
.pop()
.expect("instruction validation prevents from popping too many items; qed")
}
fn pop_n(&mut self, no_of_elems: usize) -> &[S] {
assert!(no_of_elems <= instructions::MAX_NO_OF_TOPICS);
for i in 0..no_of_elems {
self.logs[i] = self.pop_back();
}
&self.logs[0..no_of_elems]
}
fn push(&mut self, elem: S) {
self.stack.push(elem);
}
fn size(&self) -> usize {
self.stack.len()
}
fn peek_top(&self, no_from_top: usize) -> &[S] {
assert!(
self.stack.len() >= no_from_top,
"peek_top asked for more items than exist."
);
&self.stack[self.stack.len() - no_from_top..self.stack.len()]
}
}