-
Notifications
You must be signed in to change notification settings - Fork 46
Expand file tree
/
Copy pathsync_slice.go
More file actions
77 lines (62 loc) · 1.88 KB
/
sync_slice.go
File metadata and controls
77 lines (62 loc) · 1.88 KB
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
package sliceutil
import "sync"
// SyncSlice provides a thread-safe slice for elements of any comparable type.
type SyncSlice[K comparable] struct {
Slice []K
mu *sync.RWMutex
}
// NewSyncSlice initializes a new instance of SyncSlice.
func NewSyncSlice[K comparable]() *SyncSlice[K] {
return &SyncSlice[K]{mu: &sync.RWMutex{}}
}
// Append adds elements to the end of the slice in a thread-safe manner.
func (ss *SyncSlice[K]) Append(items ...K) {
ss.mu.Lock()
defer ss.mu.Unlock()
ss.Slice = append(ss.Slice, items...)
}
// Each iterates over all elements in the slice and applies the function f to each element.
// Iteration is done in a read-locked context to prevent data race.
func (ss *SyncSlice[K]) Each(f func(i int, k K) error) {
ss.mu.RLock()
defer ss.mu.RUnlock()
for i, k := range ss.Slice {
if err := f(i, k); err != nil {
break
}
}
}
// Empty clears the slice by reinitializing it in a thread-safe manner.
func (ss *SyncSlice[K]) Empty() {
ss.mu.Lock()
defer ss.mu.Unlock()
ss.Slice = make([]K, 0)
}
// Len returns the number of elements in the slice in a thread-safe manner.
func (ss *SyncSlice[K]) Len() int {
ss.mu.RLock()
defer ss.mu.RUnlock()
return len(ss.Slice)
}
// Get retrieves an element by index from the slice safely.
// Returns the element and true if index is within bounds, otherwise returns zero value and false.
func (ss *SyncSlice[K]) Get(index int) (K, bool) {
ss.mu.RLock()
defer ss.mu.RUnlock()
if index < 0 || index >= len(ss.Slice) {
var zero K
return zero, false
}
return ss.Slice[index], true
}
// Put updates the element at the specified index in the slice in a thread-safe manner.
// Returns true if the index is within bounds, otherwise false.
func (ss *SyncSlice[K]) Put(index int, value K) bool {
ss.mu.Lock()
defer ss.mu.Unlock()
if index < 0 || index >= len(ss.Slice) {
return false
}
ss.Slice[index] = value
return true
}