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