This repository has been archived by the owner on Mar 11, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 125
/
stack.go
110 lines (92 loc) · 1.63 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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
package redis
import (
"sync"
)
type Stack struct {
sync.Mutex
Key string
stack [][]byte
Chan chan *Stack
}
func (s *Stack) PopBack() []byte {
s.Lock()
defer s.Unlock()
if s.stack == nil || len(s.stack) == 0 {
return nil
}
var ret []byte
if len(s.stack)-1 == 0 {
ret, s.stack = s.stack[0], [][]byte{}
} else {
ret, s.stack = s.stack[len(s.stack)-1], s.stack[:len(s.stack)-1]
}
return ret
}
func (s *Stack) PushBack(val []byte) {
s.Lock()
defer s.Unlock()
if s.stack == nil {
s.stack = [][]byte{}
}
go func() {
if s.Chan != nil {
s.Chan <- s
}
}()
s.stack = append(s.stack, val)
}
func (s *Stack) PopFront() []byte {
s.Lock()
defer s.Unlock()
if s.stack == nil || len(s.stack) == 0 {
return nil
}
var ret []byte
if len(s.stack)-1 == 0 {
ret, s.stack = s.stack[0], [][]byte{}
} else {
ret, s.stack = s.stack[0], s.stack[1:]
}
return ret
}
func (s *Stack) PushFront(val []byte) {
s.Lock()
defer s.Unlock()
if s.stack == nil {
s.stack = [][]byte{}
}
s.stack = append([][]byte{val}, s.stack...)
go func() {
if s.Chan != nil {
s.Chan <- s
}
}()
}
// GetIndex return the element at the requested index.
// If no element correspond, return nil.
func (s *Stack) GetIndex(index int) []byte {
s.Lock()
defer s.Unlock()
if index < 0 {
if len(s.stack)+index >= 0 {
return s.stack[len(s.stack)+index]
}
return nil
}
if len(s.stack) > index {
return s.stack[index]
}
return nil
}
func (s *Stack) Len() int {
s.Lock()
defer s.Unlock()
return len(s.stack)
}
func NewStack(key string) *Stack {
return &Stack{
stack: [][]byte{},
Chan: make(chan *Stack),
Key: key,
}
}