-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathslice.go
129 lines (95 loc) · 2.07 KB
/
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
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
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
package threadsafe
import (
"sync"
)
type Slice[T any] struct {
Data []T
lock sync.Mutex
}
// Append appends the value v into Slice.
func (s *Slice[T]) Append(v T) {
s.lock.Lock()
defer s.lock.Unlock()
s.Data = append(s.Data, v)
}
func (s *Slice[T]) Insert(index int, v T) {
s.lock.Lock()
defer s.lock.Unlock()
s.Data = append(s.Data[:index], append([]T{v}, s.Data[index:]...)...)
}
func (s *Slice[T]) SafeInsert(index int, v T) bool {
if index < 0 || index > len(s.Data) {
return false
}
s.lock.Lock()
defer s.lock.Unlock()
s.Data = append(s.Data[:index], append([]T{v}, s.Data[index:]...)...)
return true
}
func (s *Slice[T]) Replace(index int, v T) {
s.lock.Lock()
defer s.lock.Unlock()
s.Data[index] = v
}
func (s *Slice[T]) SafeReplace(index int, v T) bool {
s.lock.Lock()
defer s.lock.Unlock()
if index < 0 || index >= len(s.Data) {
return false
}
s.Data[index] = v
return true
}
func (s *Slice[T]) Get(index int) T {
s.lock.Lock()
defer s.lock.Unlock()
return s.Data[index]
}
func (s *Slice[T]) GetAll() []T {
s.lock.Lock()
defer s.lock.Unlock()
return s.Data
}
func (s *Slice[T]) SafeGet(index int) (T, bool) {
s.lock.Lock()
defer s.lock.Unlock()
if index < 0 || index >= len(s.Data) {
return *new(T), false
}
return s.Data[index], true
}
// Delete deletes the item at index i. Delete will panic if i is out of bounds. If a panic is undesired, use SafeDelete.
func (s *Slice[T]) Delete(index int) {
s.lock.Lock()
defer s.lock.Unlock()
s.Data = append(s.Data[:index], s.Data[index+1:]...)
}
func (s *Slice[T]) SafeDelete(index int) bool {
if index < 0 || index >= len(s.Data) {
return false
}
s.lock.Lock()
defer s.lock.Unlock()
s.Data = append(s.Data[:index], s.Data[index+1:]...)
return true
}
func (s *Slice[T]) Empty() {
s.lock.Lock()
s.Data = nil
s.lock.Unlock()
}
func (s *Slice[T]) IndexFunc(f func(T) bool) int {
s.lock.Lock()
defer s.lock.Unlock()
for i, v := range s.Data {
if f(v) {
return i
}
}
return -1
}
func (s *Slice[T]) Len() int {
s.lock.Lock()
defer s.lock.Unlock()
return len(s.Data)
}