wp-go/safety/slice.go

40 lines
530 B
Go
Raw Permalink Normal View History

package safety
import "sync"
type Slice[T any] struct {
2024-06-11 16:14:07 +00:00
Var []T
mu sync.RWMutex
}
2024-06-11 16:14:07 +00:00
func NewSlice[T any](a ...[]T) *Slice[T] {
var s []T
if len(a) > 0 {
s = a[0]
}
return &Slice[T]{
2024-06-11 16:14:07 +00:00
s,
sync.RWMutex{},
}
}
func (r *Slice[T]) Append(t ...T) {
r.mu.Lock()
2023-11-12 13:39:04 +00:00
defer r.mu.Unlock()
2024-06-11 16:14:07 +00:00
r.Var = append(r.Var, t...)
2024-06-11 14:10:34 +00:00
}
2024-06-11 16:14:07 +00:00
func (r *Slice[T]) Store(a []T) {
2024-06-11 14:10:34 +00:00
r.mu.Lock()
defer r.mu.Unlock()
2024-06-11 16:14:07 +00:00
r.Var = a
2024-06-11 14:10:34 +00:00
}
2023-11-12 13:39:04 +00:00
2024-06-11 14:10:34 +00:00
func (r *Slice[T]) Load() (a []T) {
2024-06-11 16:14:07 +00:00
r.mu.RLock()
defer r.mu.RUnlock()
a = make([]T, len(r.Var))
copy(a, r.Var)
2024-06-11 14:10:34 +00:00
return
}