github.com/songzhibin97/go-baseutils@v0.0.2-0.20240302024150-487d8ce9c082/structure/trees/redblacktree/redblacktree_safe.go (about) 1 package redblacktree 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] = (*TreeSafe[any, any])(nil) 10 11 func NewSafeWith[K, V any](comparator bcomparator.Comparator[K]) *TreeSafe[K, V] { 12 return &TreeSafe[K, V]{ 13 unsafe: NewWith[K, V](comparator), 14 } 15 } 16 17 func NewSafeWithIntComparator[V any]() *TreeSafe[int, V] { 18 return &TreeSafe[int, V]{ 19 unsafe: NewWithIntComparator[V](), 20 } 21 } 22 23 func NewSafeWithStringComparator[V any]() *TreeSafe[string, V] { 24 return &TreeSafe[string, V]{ 25 unsafe: NewWithStringComparator[V](), 26 } 27 } 28 29 type TreeSafe[K, V any] struct { 30 unsafe *Tree[K, V] 31 lock sync.Mutex 32 } 33 34 func (s *TreeSafe[K, V]) Put(key K, value V) { 35 s.lock.Lock() 36 defer s.lock.Unlock() 37 s.unsafe.Put(key, value) 38 39 } 40 41 func (s *TreeSafe[K, V]) Get(key K) (V, bool) { 42 s.lock.Lock() 43 defer s.lock.Unlock() 44 return s.unsafe.Get(key) 45 } 46 47 func (s *TreeSafe[K, V]) GetNode(key K) *Node[K, V] { 48 s.lock.Lock() 49 defer s.lock.Unlock() 50 return s.unsafe.GetNode(key) 51 } 52 53 func (s *TreeSafe[K, V]) Remove(key K) { 54 s.lock.Lock() 55 defer s.lock.Unlock() 56 s.unsafe.Remove(key) 57 58 } 59 60 func (s *TreeSafe[K, V]) Empty() bool { 61 s.lock.Lock() 62 defer s.lock.Unlock() 63 return s.unsafe.Empty() 64 } 65 66 func (s *TreeSafe[K, V]) Size() int { 67 s.lock.Lock() 68 defer s.lock.Unlock() 69 return s.unsafe.Size() 70 } 71 72 func (s *TreeSafe[K, V]) Keys() []K { 73 s.lock.Lock() 74 defer s.lock.Unlock() 75 return s.unsafe.Keys() 76 } 77 78 func (s *TreeSafe[K, V]) Values() []V { 79 s.lock.Lock() 80 defer s.lock.Unlock() 81 return s.unsafe.Values() 82 } 83 84 func (s *TreeSafe[K, V]) Left() *Node[K, V] { 85 s.lock.Lock() 86 defer s.lock.Unlock() 87 return s.unsafe.Left() 88 } 89 90 func (s *TreeSafe[K, V]) Right() *Node[K, V] { 91 s.lock.Lock() 92 defer s.lock.Unlock() 93 return s.unsafe.Right() 94 } 95 96 func (s *TreeSafe[K, V]) Floor(key K) (*Node[K, V], bool) { 97 s.lock.Lock() 98 defer s.lock.Unlock() 99 return s.unsafe.Floor(key) 100 } 101 102 func (s *TreeSafe[K, V]) Ceiling(key K) (*Node[K, V], bool) { 103 s.lock.Lock() 104 defer s.lock.Unlock() 105 return s.unsafe.Ceiling(key) 106 } 107 108 func (s *TreeSafe[K, V]) Clear() { 109 s.lock.Lock() 110 defer s.lock.Unlock() 111 s.unsafe.Clear() 112 113 } 114 115 func (s *TreeSafe[K, V]) String() string { 116 s.lock.Lock() 117 defer s.lock.Unlock() 118 return s.unsafe.String() 119 } 120 121 func (s *TreeSafe[K, V]) UnmarshalJSON(bytes []byte) error { 122 s.lock.Lock() 123 defer s.lock.Unlock() 124 return s.unsafe.UnmarshalJSON(bytes) 125 } 126 127 func (s *TreeSafe[K, V]) MarshalJSON() ([]byte, error) { 128 s.lock.Lock() 129 defer s.lock.Unlock() 130 return s.unsafe.MarshalJSON() 131 }