-
Notifications
You must be signed in to change notification settings - Fork 0
/
stack.go
85 lines (73 loc) · 1.21 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
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
package terminfo
import (
"errors"
)
var (
errStackEmpty = errors.New("stack: empty")
errStackNotEmpty = errors.New("stack: not empty")
errStackIllegalPopType = errors.New("stack: illegal pop type")
)
type stack struct {
e []interface{}
l int
}
func newStack() *stack {
return &stack{
e: make([]interface{}, 2),
l: 0,
}
}
func (s *stack) isEmpty() bool {
return s.l == 0
}
func (s *stack) push(e interface{}) {
if s.l < len(s.e) {
s.e[s.l] = e
} else {
s.e = append(s.e, e)
}
s.l++
}
func (s *stack) pop() (interface{}, error) {
if s.l <= 0 {
return nil, errStackEmpty
}
s.l--
return s.e[s.l], nil
}
func (s *stack) popI() (int, error) {
e, err := s.pop()
if err != nil {
return 0, err
}
i, ok := e.(int)
if !ok {
s.push(e)
return 0, errStackIllegalPopType
}
return i, nil
}
func (s *stack) popII() (int, int, error) {
i1, err := s.popI()
if err != nil {
return 0, 0, err
}
i2, err := s.popI()
if err != nil {
s.push(i1)
return 0, 0, err
}
return i1, i2, nil
}
func (s *stack) popS() (string, error) {
e, err := s.pop()
if err != nil {
return "", err
}
es, ok := e.(string)
if !ok {
s.push(e)
return "", errStackIllegalPopType
}
return es, nil
}