forked from gofor-little/ts
-
Notifications
You must be signed in to change notification settings - Fork 0
/
slice.go
58 lines (46 loc) · 1.19 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
package ts
import (
"sync"
)
// Slice wraps a standard slice and a sync.RWMutex.
type Slice struct {
elements []interface{}
mutex sync.RWMutex
}
// Add adds the passed elements to the underlying slice.
func (s *Slice) Add(elements ...interface{}) {
s.mutex.Lock()
defer s.mutex.Unlock()
s.elements = append(s.elements, elements...)
}
// Remove removes the passed elements from the underlying slice.
func (s *Slice) Remove(elements ...interface{}) {
s.mutex.Lock()
defer s.mutex.Unlock()
for _, element := range elements {
for i, e := range s.elements {
if element == e {
s.elements[i] = s.elements[len(s.elements)-1]
s.elements = s.elements[:len(s.elements)-1]
}
}
}
}
// GetElement returns the element from the underlying slice at the passed index.
func (s *Slice) GetElement(index int) interface{} {
s.mutex.Lock()
defer s.mutex.Unlock()
return s.elements[index]
}
// GetElements returns the underlying slice.
func (s *Slice) GetElements() []interface{} {
s.mutex.Lock()
defer s.mutex.Unlock()
return s.elements
}
// Length returns the length of the underlying slice.
func (s *Slice) Length() int {
s.mutex.Lock()
defer s.mutex.Unlock()
return len(s.elements)
}