-
Notifications
You must be signed in to change notification settings - Fork 0
/
slice.go
59 lines (47 loc) · 880 Bytes
/
slice.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
package do
import (
"sync"
)
type Slice[T any] struct {
mu sync.Mutex
items []T
}
func NewSlice[T any](lenAndCap ...int) *Slice[T] {
l, cap := getLenAndCap(lenAndCap...)
return &Slice[T]{
items: make([]T, l, cap),
}
}
func (s *Slice[T]) Index(i int) T {
s.mu.Lock()
item := s.items[i]
s.mu.Unlock()
return item
}
func (s *Slice[T]) Append(values ...T) {
s.mu.Lock()
s.items = append(s.items, values...)
s.mu.Unlock()
}
func (s *Slice[T]) Range(f func(item T, index int)) {
s.mu.Lock()
defer s.mu.Unlock()
for i, v := range s.items {
f(v, i)
}
}
func (s *Slice[T]) Reset(lenAndCap ...int) {
s.mu.Lock()
defer s.mu.Unlock()
l, c := getLenAndCap(lenAndCap...)
s.items = make([]T, l, c)
}
func getLenAndCap(lenAndCap ...int) (l, c int) {
if len(lenAndCap) >= 1 {
l = lenAndCap[0]
}
if len(lenAndCap) >= 2 {
c = lenAndCap[1]
}
return
}