forked from skx/go.vm
-
Notifications
You must be signed in to change notification settings - Fork 0
/
stack.go
54 lines (42 loc) · 1.02 KB
/
stack.go
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
// This file contains the implementation of the stack the CPU uses.
//
// Note that the stack is used for storing integers only.
package cpu
import "errors"
// Stack holds return-addresses when the `call` operation is being
// completed. It can also be used for storing ints.
type Stack struct {
// The entries on our stack
entries []int
}
//
// Stack functions
//
// NewStack creates a new stack object.
func NewStack() *Stack {
return &Stack{}
}
// Empty returns true if the stack is empty.
func (s *Stack) Empty() bool {
return (len(s.entries) <= 0)
}
// Size retrieves the length of the stack.
func (s *Stack) Size() int {
return (len(s.entries))
}
// Push adds a value to the stack.
func (s *Stack) Push(value int) {
s.entries = append(s.entries, value)
}
// Pop removes a value from the stack.
func (s *Stack) Pop() (int, error) {
if s.Empty() {
return 0, errors.New("Pop from an empty stack")
}
// get top
l := len(s.entries)
top := s.entries[l-1]
// truncate
s.entries = s.entries[:l-1]
return top, nil
}