2023-01-16 06:38:55 +00:00
|
|
|
package safety
|
|
|
|
|
|
|
|
import "sync"
|
|
|
|
|
|
|
|
type Slice[T any] struct {
|
2024-06-11 16:14:07 +00:00
|
|
|
Var []T
|
|
|
|
mu sync.RWMutex
|
2023-01-16 06:38:55 +00:00
|
|
|
}
|
|
|
|
|
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]
|
|
|
|
}
|
2023-01-16 06:38:55 +00:00
|
|
|
return &Slice[T]{
|
2024-06-11 16:14:07 +00:00
|
|
|
s,
|
|
|
|
sync.RWMutex{},
|
2023-01-16 06:38:55 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
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
|
2023-01-16 06:38:55 +00:00
|
|
|
}
|