forked from miaokobot/miaospeed
-
Notifications
You must be signed in to change notification settings - Fork 4
/
asyncarr.go
71 lines (55 loc) · 1.12 KB
/
asyncarr.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
package structs
import "sync"
type AsyncArr[T any] struct {
lock sync.Mutex
store []T
}
func NewAsyncArr[T any]() *AsyncArr[T] {
return &AsyncArr[T]{
store: make([]T, 0),
}
}
func (aa *AsyncArr[T]) ForEach() []T {
aa.lock.Lock()
defer aa.lock.Unlock()
return aa.store[:]
}
func (aa *AsyncArr[T]) Get(idx int) (*T, bool) {
aa.lock.Lock()
defer aa.lock.Unlock()
if idx >= 0 && idx < len(aa.store) {
return &aa.store[idx], true
}
return nil, false
}
func (aa *AsyncArr[T]) MustGet(idx int) *T {
t, _ := aa.Get(idx)
return t
}
func (aa *AsyncArr[T]) Set(idx int, val T) bool {
aa.lock.Lock()
defer aa.lock.Unlock()
if idx >= 0 && idx < len(aa.store) {
aa.store[idx] = val
return true
}
return false
}
func (aa *AsyncArr[T]) Push(val T) {
aa.lock.Lock()
defer aa.lock.Unlock()
aa.store = append(aa.store, val)
}
func (aa *AsyncArr[T]) Del(idx int) *T {
aa.lock.Lock()
defer aa.lock.Unlock()
if idx >= 0 && idx < len(aa.store) {
del := aa.store[idx]
aa.store = append(aa.store[:idx], aa.store[idx+1:]...)
return &del
}
return nil
}
func (aa *AsyncArr[T]) Take(idx int) *T {
return aa.Del(idx)
}