-
Notifications
You must be signed in to change notification settings - Fork 0
/
stack.go
109 lines (85 loc) · 1.83 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
package safe
import (
"encoding/json"
"sync"
)
// Stack ...
type Stack[V any] struct {
sync.RWMutex
data []V
}
// NewStack returns a new safe stack
func NewStack[V any]() *Stack[V] {
return &Stack[V]{
data: make([]V, 0),
}
}
// Push adds an element to the end of the stack
func (m *Stack[V]) Push(key string, value V) {
m.Lock()
defer m.Unlock()
m.data = append(m.data, value)
}
// Pop removes and returns the last element of the stack
func (m *Stack[V]) Pop(key string) V {
m.Lock()
defer m.Unlock()
if len(m.data) == 0 {
var v V
return v
}
value := m.data[len(m.data)-1]
m.data = m.data[:len(m.data)-1]
return value
}
// Size returns the number of elements in the stack
func (m *Stack[V]) Size(key string) int {
m.RLock()
defer m.RUnlock()
return len(m.data)
}
// IsEmpty returns true if the stack is empty
func (m *Stack[V]) IsEmpty(key string) bool {
return m.Size(key) == 0
}
// Clear removes all elements from the stack
func (m *Stack[V]) Clear(key string) {
m.Lock()
defer m.Unlock()
m.data = make([]V, 0)
}
// Peek returns the last element of the stack
func (m *Stack[V]) Peek(key string) V {
m.RLock()
defer m.RUnlock()
if len(m.data) == 0 {
var v V
return v
}
return m.data[len(m.data)-1]
}
// String returns a string representation of the stack
func (m *Stack[V]) String() string {
bytes, err := m.MarshalJSON()
if err != nil {
return err.Error()
}
return string(bytes)
}
// MarshalJSON returns the JSON encoding of the stack
func (m *Stack[V]) MarshalJSON() ([]byte, error) {
m.RLock()
defer m.RUnlock()
return json.Marshal(m.data)
}
// UnmarshalJSON decodes the JSON encoding of the stack
func (m *Stack[V]) UnmarshalJSON(data []byte) error {
var values []V
if err := json.Unmarshal(data, &values); err != nil {
return err
}
m.Lock()
defer m.Unlock()
m.data = values
return nil
}