-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgeneric.go
48 lines (41 loc) · 852 Bytes
/
generic.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
package filo
import (
"sync"
)
// GenericStack stack first in last out
// safe for concurrent usage
type GenericStack struct {
items []interface{}
mu *sync.RWMutex
}
// Push pushes new interface{} to the stack
func (g *GenericStack) Push(j interface{}) {
g.mu.Lock()
g.items = append(g.items, j)
g.mu.Unlock()
}
// Pop pops the last interface{} from the stack
func (g *GenericStack) Pop() interface{} {
g.mu.Lock()
defer g.mu.Unlock()
ln := len(g.items)
if ln == 0 {
return nil
}
tail := g.items[ln-1]
g.items = g.items[:ln-1]
return tail
}
// Len gets the number of items pushed
// into the stack
func (g *GenericStack) Len() int {
g.mu.RLock()
defer g.mu.RUnlock()
return len(g.items)
}
// NewGenericStack creates new GenericStack
func NewGenericStack() *GenericStack {
return &GenericStack{
mu: &sync.RWMutex{},
}
}