github.com/songzhibin97/go-baseutils@v0.0.2-0.20240302024150-487d8ce9c082/structure/lists/arraylist/arraylist_safe.go (about) 1 package arraylist 2 3 import ( 4 "github.com/songzhibin97/go-baseutils/base/bcomparator" 5 "github.com/songzhibin97/go-baseutils/structure/lists" 6 "sync" 7 ) 8 9 var _ lists.List[any] = (*ListSafe[any])(nil) 10 11 func NewSafe[E any](values ...E) *ListSafe[E] { 12 return &ListSafe[E]{ 13 unsafe: New(values...), 14 } 15 } 16 17 type ListSafe[E any] struct { 18 unsafe *List[E] 19 lock sync.Mutex 20 } 21 22 func (s *ListSafe[E]) Add(values ...E) { 23 s.lock.Lock() 24 defer s.lock.Unlock() 25 s.unsafe.Add(values...) 26 27 } 28 29 func (s *ListSafe[E]) Get(index int) (E, bool) { 30 s.lock.Lock() 31 defer s.lock.Unlock() 32 return s.unsafe.Get(index) 33 } 34 35 func (s *ListSafe[E]) Remove(index int) { 36 s.lock.Lock() 37 defer s.lock.Unlock() 38 s.unsafe.Remove(index) 39 40 } 41 42 func (s *ListSafe[E]) Contains(values ...E) bool { 43 s.lock.Lock() 44 defer s.lock.Unlock() 45 return s.unsafe.Contains(values...) 46 } 47 48 func (s *ListSafe[E]) Values() []E { 49 s.lock.Lock() 50 defer s.lock.Unlock() 51 return s.unsafe.Values() 52 } 53 54 func (s *ListSafe[E]) IndexOf(value E) int { 55 s.lock.Lock() 56 defer s.lock.Unlock() 57 return s.unsafe.IndexOf(value) 58 } 59 60 func (s *ListSafe[E]) Empty() bool { 61 s.lock.Lock() 62 defer s.lock.Unlock() 63 return s.unsafe.Empty() 64 } 65 66 func (s *ListSafe[E]) Size() int { 67 s.lock.Lock() 68 defer s.lock.Unlock() 69 return s.unsafe.Size() 70 } 71 72 func (s *ListSafe[E]) Clear() { 73 s.lock.Lock() 74 defer s.lock.Unlock() 75 s.unsafe.Clear() 76 77 } 78 79 func (s *ListSafe[E]) Sort(comparator bcomparator.Comparator[E]) { 80 s.lock.Lock() 81 defer s.lock.Unlock() 82 s.unsafe.Sort(comparator) 83 84 } 85 86 func (s *ListSafe[E]) Swap(i int, j int) { 87 s.lock.Lock() 88 defer s.lock.Unlock() 89 s.unsafe.Swap(i, j) 90 91 } 92 93 func (s *ListSafe[E]) Insert(index int, values ...E) { 94 s.lock.Lock() 95 defer s.lock.Unlock() 96 s.unsafe.Insert(index, values...) 97 98 } 99 100 func (s *ListSafe[E]) Set(index int, value E) { 101 s.lock.Lock() 102 defer s.lock.Unlock() 103 s.unsafe.Set(index, value) 104 105 } 106 107 func (s *ListSafe[E]) String() string { 108 s.lock.Lock() 109 defer s.lock.Unlock() 110 return s.unsafe.String() 111 } 112 113 func (s *ListSafe[E]) UnmarshalJSON(bytes []byte) error { 114 s.lock.Lock() 115 defer s.lock.Unlock() 116 return s.unsafe.UnmarshalJSON(bytes) 117 } 118 119 func (s *ListSafe[E]) MarshalJSON() ([]byte, error) { 120 s.lock.Lock() 121 defer s.lock.Unlock() 122 return s.unsafe.MarshalJSON() 123 }