github.com/songzhibin97/go-baseutils@v0.0.2-0.20240302024150-487d8ce9c082/structure/stacks/linkedliststack/linkedliststack_safe.go (about) 1 package linkedliststack 2 3 import ( 4 "github.com/songzhibin97/go-baseutils/structure/stacks" 5 "sync" 6 ) 7 8 var _ stacks.Stack[any] = (*StackSafe[any])(nil) 9 10 func NewSafe[E any]() *StackSafe[E] { 11 return &StackSafe[E]{ 12 unsafe: New[E](), 13 } 14 } 15 16 17 type StackSafe[E any] struct { 18 unsafe *Stack[E] 19 lock sync.Mutex 20 } 21 22 func (s *StackSafe[E]) Push(value E) { 23 s.lock.Lock() 24 defer s.lock.Unlock() 25 s.unsafe.Push(value) 26 27 } 28 29 func (s *StackSafe[E]) Pop() (E, bool) { 30 s.lock.Lock() 31 defer s.lock.Unlock() 32 return s.unsafe.Pop() 33 } 34 35 func (s *StackSafe[E]) Peek() (E, bool) { 36 s.lock.Lock() 37 defer s.lock.Unlock() 38 return s.unsafe.Peek() 39 } 40 41 func (s *StackSafe[E]) Empty() bool { 42 s.lock.Lock() 43 defer s.lock.Unlock() 44 return s.unsafe.Empty() 45 } 46 47 func (s *StackSafe[E]) Size() int { 48 s.lock.Lock() 49 defer s.lock.Unlock() 50 return s.unsafe.Size() 51 } 52 53 func (s *StackSafe[E]) Clear() { 54 s.lock.Lock() 55 defer s.lock.Unlock() 56 s.unsafe.Clear() 57 58 } 59 60 func (s *StackSafe[E]) Values() []E { 61 s.lock.Lock() 62 defer s.lock.Unlock() 63 return s.unsafe.Values() 64 } 65 66 func (s *StackSafe[E]) String() string { 67 s.lock.Lock() 68 defer s.lock.Unlock() 69 return s.unsafe.String() 70 } 71 72 func (s *StackSafe[E]) UnmarshalJSON(bytes []byte) error { 73 s.lock.Lock() 74 defer s.lock.Unlock() 75 return s.unsafe.UnmarshalJSON(bytes) 76 } 77 78 func (s *StackSafe[E]) MarshalJSON() ([]byte, error) { 79 s.lock.Lock() 80 defer s.lock.Unlock() 81 return s.unsafe.MarshalJSON() 82 }