forked from 0xPolygonHermez/zkevm-node
-
Notifications
You must be signed in to change notification settings - Fork 0
/
stack.go
44 lines (35 loc) · 842 Bytes
/
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
package state
import (
"errors"
"sync"
)
// ErrStackEmpty returned when Pop is called and the stack is empty
var ErrStackEmpty = errors.New("Empty Stack")
// Stack is a thread safe stack data structure implementation implementing generics
type Stack[T any] struct {
lock sync.Mutex
items []T
}
// NewStack creates a new stack
func NewStack[T any]() *Stack[T] {
return &Stack[T]{sync.Mutex{}, make([]T, 0)}
}
// Push adds an item to the stack
func (s *Stack[T]) Push(v T) {
s.lock.Lock()
defer s.lock.Unlock()
s.items = append(s.items, v)
}
// Pop removes and returns the last item added to the stack
func (s *Stack[T]) Pop() (T, error) {
s.lock.Lock()
defer s.lock.Unlock()
size := len(s.items)
if size == 0 {
var r T
return r, ErrStackEmpty
}
res := s.items[size-1]
s.items = s.items[:size-1]
return res, nil
}