/
threadsafe_stack.go
86 lines (66 loc) · 1.7 KB
/
threadsafe_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
package stack
import (
"sync"
)
// threadSafeStack implements a thread safe Stack.
type threadSafeStack struct {
sync.RWMutex
elements []interface{}
}
// newThreadSafeStack returns a new thread safe Stack.
func newThreadSafeStack() *threadSafeStack {
return &threadSafeStack{}
}
// Push pushes an element onto the top of this Stack.
func (s *threadSafeStack) Push(element interface{}) {
s.Lock()
defer s.Unlock()
s.elements = append(s.elements, element)
}
// Pop removes and returns the top element of this Stack.
func (s *threadSafeStack) Pop() interface{} {
s.Lock()
defer s.Unlock()
if len(s.elements) == 0 {
return nil
}
index := len(s.elements) - 1
element := s.elements[index]
// erase element to avoid memory leaks for long lasting stacks
s.elements[index] = nil
s.elements = s.elements[:index]
return element
}
// Peek returns the top element of this Stack without removing it.
func (s *threadSafeStack) Peek() interface{} {
s.RLock()
defer s.RUnlock()
if len(s.elements) == 0 {
return nil
}
return s.elements[len(s.elements)-1]
}
// Clear removes all elements from this Stack.
func (s *threadSafeStack) Clear() {
s.Lock()
defer s.Unlock()
// erase elements to avoid memory leaks for long lasting stacks
for index := range s.elements {
s.elements[index] = nil
}
s.elements = s.elements[:0]
}
// Size returns the amount of elements in this Stack.
func (s *threadSafeStack) Size() int {
s.RLock()
defer s.RUnlock()
return len(s.elements)
}
// IsEmpty checks if this Stack is empty.
func (s *threadSafeStack) IsEmpty() bool {
s.RLock()
defer s.RUnlock()
return len(s.elements) == 0
}
// code contract - make sure the type implements the interface
var _ Stack = &threadSafeStack{}