slice.go (979B)
1 package syncx 2 3 import ( 4 "iter" 5 "slices" 6 ) 7 8 // Slice is a mutex protected slice. 9 type Slice[T any] struct { 10 Value Mutex[[]T] 11 } 12 13 func (s *Slice[T]) Append(v T) { 14 s.Value.Update(func(list []T) []T { 15 return append(list, v) 16 }) 17 } 18 19 func (s *Slice[T]) Prepend(v T) { 20 s.Value.Update(func(list []T) []T { 21 return append([]T{v}, list...) 22 }) 23 } 24 25 func (s *Slice[T]) Delete(start, end int) { 26 s.Value.Update(func(list []T) []T { 27 return slices.Delete(list, start, end) 28 }) 29 } 30 31 func (s *Slice[T]) Contains(fn func(T) bool) bool { 32 return s.Index(fn) > -1 33 } 34 35 func (s *Slice[T]) Index(fn func(T) bool) int { 36 _, ii := s.Find(fn) 37 return ii 38 } 39 40 func (s *Slice[T]) Find(fn func(T) bool) (T, int) { 41 for ii, v := range s.Iter() { 42 if fn(v) { 43 return v, ii 44 } 45 } 46 return *new(T), -1 47 } 48 49 func (s *Slice[T]) Iter() iter.Seq2[int, T] { 50 return func(yield func(int, T) bool) { 51 s.Value.With(func(list []T) { 52 for ii, v := range list { 53 if !yield(ii, v) { 54 break 55 } 56 } 57 }) 58 } 59 }