github.com/songzhibin97/go-baseutils@v0.0.2-0.20240302024150-487d8ce9c082/structure/trees/binaryheap/binaryheap_safe.go (about) 1 package binaryheap 2 3 import ( 4 "github.com/songzhibin97/go-baseutils/base/bcomparator" 5 "github.com/songzhibin97/go-baseutils/structure/trees" 6 "sync" 7 ) 8 9 var _ trees.Tree[any] = (*HeapSafe[any])(nil) 10 11 func NewSafeWith[E any](comparator bcomparator.Comparator[E]) *HeapSafe[E] { 12 return &HeapSafe[E]{ 13 unsafe: NewWith[E](comparator), 14 } 15 } 16 17 func NewSafeWithIntComparator() *HeapSafe[int] { 18 return &HeapSafe[int]{ 19 unsafe: NewWithIntComparator(), 20 } 21 } 22 23 func NewSafeWithStringComparator() *HeapSafe[string] { 24 return &HeapSafe[string]{ 25 unsafe: NewWithStringComparator(), 26 } 27 } 28 29 type HeapSafe[E any] struct { 30 unsafe *Heap[E] 31 lock sync.Mutex 32 } 33 34 func (s *HeapSafe[E]) Push(values ...E) { 35 s.lock.Lock() 36 defer s.lock.Unlock() 37 s.unsafe.Push(values...) 38 39 } 40 41 func (s *HeapSafe[E]) Pop() (E, bool) { 42 s.lock.Lock() 43 defer s.lock.Unlock() 44 return s.unsafe.Pop() 45 } 46 47 func (s *HeapSafe[E]) Peek() (E, bool) { 48 s.lock.Lock() 49 defer s.lock.Unlock() 50 return s.unsafe.Peek() 51 } 52 53 func (s *HeapSafe[E]) Empty() bool { 54 s.lock.Lock() 55 defer s.lock.Unlock() 56 return s.unsafe.Empty() 57 } 58 59 func (s *HeapSafe[E]) Size() int { 60 s.lock.Lock() 61 defer s.lock.Unlock() 62 return s.unsafe.Size() 63 } 64 65 func (s *HeapSafe[E]) Clear() { 66 s.lock.Lock() 67 defer s.lock.Unlock() 68 s.unsafe.Clear() 69 70 } 71 72 func (s *HeapSafe[E]) Values() []E { 73 s.lock.Lock() 74 defer s.lock.Unlock() 75 return s.unsafe.Values() 76 } 77 78 func (s *HeapSafe[E]) String() string { 79 s.lock.Lock() 80 defer s.lock.Unlock() 81 return s.unsafe.String() 82 } 83 84 func (s *HeapSafe[E]) UnmarshalJSON(bytes []byte) error { 85 s.lock.Lock() 86 defer s.lock.Unlock() 87 return s.unsafe.UnmarshalJSON(bytes) 88 } 89 90 func (s *HeapSafe[E]) MarshalJSON() ([]byte, error) { 91 s.lock.Lock() 92 defer s.lock.Unlock() 93 return s.unsafe.MarshalJSON() 94 }