github.com/gogf/gf/v2@v2.7.4/container/gtree/gtree_avltree.go (about)

     1  // Copyright GoFrame Author(https://goframe.org). All Rights Reserved.
     2  //
     3  // This Source Code Form is subject to the terms of the MIT License.
     4  // If a copy of the MIT was not distributed with this file,
     5  // You can obtain one at https://github.com/gogf/gf.
     6  
     7  package gtree
     8  
     9  import (
    10  	"fmt"
    11  
    12  	"github.com/emirpasic/gods/trees/avltree"
    13  	"github.com/gogf/gf/v2/container/gvar"
    14  	"github.com/gogf/gf/v2/internal/rwmutex"
    15  	"github.com/gogf/gf/v2/text/gstr"
    16  	"github.com/gogf/gf/v2/util/gconv"
    17  )
    18  
    19  var _ iTree = (*AVLTree)(nil)
    20  
    21  // AVLTree holds elements of the AVL tree.
    22  type AVLTree struct {
    23  	mu         rwmutex.RWMutex
    24  	root       *AVLTreeNode
    25  	comparator func(v1, v2 interface{}) int
    26  	tree       *avltree.Tree
    27  }
    28  
    29  // AVLTreeNode is a single element within the tree.
    30  type AVLTreeNode struct {
    31  	Key   interface{}
    32  	Value interface{}
    33  }
    34  
    35  // NewAVLTree instantiates an AVL tree with the custom key comparator.
    36  // The parameter `safe` is used to specify whether using tree in concurrent-safety,
    37  // which is false in default.
    38  func NewAVLTree(comparator func(v1, v2 interface{}) int, safe ...bool) *AVLTree {
    39  	return &AVLTree{
    40  		mu:         rwmutex.Create(safe...),
    41  		comparator: comparator,
    42  		tree:       avltree.NewWith(comparator),
    43  	}
    44  }
    45  
    46  // NewAVLTreeFrom instantiates an AVL tree with the custom key comparator and data map.
    47  // The parameter `safe` is used to specify whether using tree in concurrent-safety,
    48  // which is false in default.
    49  func NewAVLTreeFrom(comparator func(v1, v2 interface{}) int, data map[interface{}]interface{}, safe ...bool) *AVLTree {
    50  	tree := NewAVLTree(comparator, safe...)
    51  	for k, v := range data {
    52  		tree.doSet(k, v)
    53  	}
    54  	return tree
    55  }
    56  
    57  // Clone returns a new tree with a copy of current tree.
    58  func (tree *AVLTree) Clone() *AVLTree {
    59  	newTree := NewAVLTree(tree.comparator, tree.mu.IsSafe())
    60  	newTree.Sets(tree.Map())
    61  	return newTree
    62  }
    63  
    64  // Set inserts node into the tree.
    65  func (tree *AVLTree) Set(key interface{}, value interface{}) {
    66  	tree.mu.Lock()
    67  	defer tree.mu.Unlock()
    68  	tree.doSet(key, value)
    69  }
    70  
    71  // Sets batch sets key-values to the tree.
    72  func (tree *AVLTree) Sets(data map[interface{}]interface{}) {
    73  	tree.mu.Lock()
    74  	defer tree.mu.Unlock()
    75  	for key, value := range data {
    76  		tree.doSet(key, value)
    77  	}
    78  }
    79  
    80  // SetIfNotExist sets `value` to the map if the `key` does not exist, and then returns true.
    81  // It returns false if `key` exists, and `value` would be ignored.
    82  func (tree *AVLTree) SetIfNotExist(key interface{}, value interface{}) bool {
    83  	tree.mu.Lock()
    84  	defer tree.mu.Unlock()
    85  	if _, ok := tree.doGet(key); !ok {
    86  		tree.doSet(key, value)
    87  		return true
    88  	}
    89  	return false
    90  }
    91  
    92  // SetIfNotExistFunc sets value with return value of callback function `f`, and then returns true.
    93  // It returns false if `key` exists, and `value` would be ignored.
    94  func (tree *AVLTree) SetIfNotExistFunc(key interface{}, f func() interface{}) bool {
    95  	tree.mu.Lock()
    96  	defer tree.mu.Unlock()
    97  	if _, ok := tree.doGet(key); !ok {
    98  		tree.doSet(key, f())
    99  		return true
   100  	}
   101  	return false
   102  }
   103  
   104  // SetIfNotExistFuncLock sets value with return value of callback function `f`, and then returns true.
   105  // It returns false if `key` exists, and `value` would be ignored.
   106  //
   107  // SetIfNotExistFuncLock differs with SetIfNotExistFunc function is that
   108  // it executes function `f` with mutex.Lock of the hash map.
   109  func (tree *AVLTree) SetIfNotExistFuncLock(key interface{}, f func() interface{}) bool {
   110  	tree.mu.Lock()
   111  	defer tree.mu.Unlock()
   112  	if _, ok := tree.doGet(key); !ok {
   113  		tree.doSet(key, f)
   114  		return true
   115  	}
   116  	return false
   117  }
   118  
   119  // Get searches the node in the tree by `key` and returns its value or nil if key is not found in tree.
   120  func (tree *AVLTree) Get(key interface{}) (value interface{}) {
   121  	value, _ = tree.Search(key)
   122  	return
   123  }
   124  
   125  // GetOrSet returns the value by key,
   126  // or sets value with given `value` if it does not exist and then returns this value.
   127  func (tree *AVLTree) GetOrSet(key interface{}, value interface{}) interface{} {
   128  	tree.mu.Lock()
   129  	defer tree.mu.Unlock()
   130  	if v, ok := tree.doGet(key); !ok {
   131  		return tree.doSet(key, value)
   132  	} else {
   133  		return v
   134  	}
   135  }
   136  
   137  // GetOrSetFunc returns the value by key,
   138  // or sets value with returned value of callback function `f` if it does not exist
   139  // and then returns this value.
   140  func (tree *AVLTree) GetOrSetFunc(key interface{}, f func() interface{}) interface{} {
   141  	tree.mu.Lock()
   142  	defer tree.mu.Unlock()
   143  	if v, ok := tree.doGet(key); !ok {
   144  		return tree.doSet(key, f())
   145  	} else {
   146  		return v
   147  	}
   148  }
   149  
   150  // GetOrSetFuncLock returns the value by key,
   151  // or sets value with returned value of callback function `f` if it does not exist
   152  // and then returns this value.
   153  //
   154  // GetOrSetFuncLock differs with GetOrSetFunc function is that it executes function `f`
   155  // with mutex.Lock of the hash map.
   156  func (tree *AVLTree) GetOrSetFuncLock(key interface{}, f func() interface{}) interface{} {
   157  	tree.mu.Lock()
   158  	defer tree.mu.Unlock()
   159  	if v, ok := tree.doGet(key); !ok {
   160  		return tree.doSet(key, f)
   161  	} else {
   162  		return v
   163  	}
   164  }
   165  
   166  // GetVar returns a gvar.Var with the value by given `key`.
   167  // The returned gvar.Var is un-concurrent safe.
   168  func (tree *AVLTree) GetVar(key interface{}) *gvar.Var {
   169  	return gvar.New(tree.Get(key))
   170  }
   171  
   172  // GetVarOrSet returns a gvar.Var with result from GetVarOrSet.
   173  // The returned gvar.Var is un-concurrent safe.
   174  func (tree *AVLTree) GetVarOrSet(key interface{}, value interface{}) *gvar.Var {
   175  	return gvar.New(tree.GetOrSet(key, value))
   176  }
   177  
   178  // GetVarOrSetFunc returns a gvar.Var with result from GetOrSetFunc.
   179  // The returned gvar.Var is un-concurrent safe.
   180  func (tree *AVLTree) GetVarOrSetFunc(key interface{}, f func() interface{}) *gvar.Var {
   181  	return gvar.New(tree.GetOrSetFunc(key, f))
   182  }
   183  
   184  // GetVarOrSetFuncLock returns a gvar.Var with result from GetOrSetFuncLock.
   185  // The returned gvar.Var is un-concurrent safe.
   186  func (tree *AVLTree) GetVarOrSetFuncLock(key interface{}, f func() interface{}) *gvar.Var {
   187  	return gvar.New(tree.GetOrSetFuncLock(key, f))
   188  }
   189  
   190  // Search searches the tree with given `key`.
   191  // Second return parameter `found` is true if key was found, otherwise false.
   192  func (tree *AVLTree) Search(key interface{}) (value interface{}, found bool) {
   193  	tree.mu.RLock()
   194  	defer tree.mu.RUnlock()
   195  	if node, found := tree.doGet(key); found {
   196  		return node, true
   197  	}
   198  	return nil, false
   199  }
   200  
   201  // Contains checks whether `key` exists in the tree.
   202  func (tree *AVLTree) Contains(key interface{}) bool {
   203  	tree.mu.RLock()
   204  	defer tree.mu.RUnlock()
   205  	_, ok := tree.doGet(key)
   206  	return ok
   207  }
   208  
   209  // Size returns number of nodes in the tree.
   210  func (tree *AVLTree) Size() int {
   211  	tree.mu.RLock()
   212  	defer tree.mu.RUnlock()
   213  	return tree.tree.Size()
   214  }
   215  
   216  // IsEmpty returns true if tree does not contain any nodes.
   217  func (tree *AVLTree) IsEmpty() bool {
   218  	tree.mu.RLock()
   219  	defer tree.mu.RUnlock()
   220  	return tree.tree.Size() == 0
   221  }
   222  
   223  // Remove removes the node from the tree by key.
   224  // Key should adhere to the comparator's type assertion, otherwise method panics.
   225  func (tree *AVLTree) Remove(key interface{}) (value interface{}) {
   226  	tree.mu.Lock()
   227  	defer tree.mu.Unlock()
   228  	return tree.doRemove(key)
   229  }
   230  
   231  // Removes batch deletes values of the tree by `keys`.
   232  func (tree *AVLTree) Removes(keys []interface{}) {
   233  	tree.mu.Lock()
   234  	defer tree.mu.Unlock()
   235  	for _, key := range keys {
   236  		tree.doRemove(key)
   237  	}
   238  }
   239  
   240  // Clear removes all nodes from the tree.
   241  func (tree *AVLTree) Clear() {
   242  	tree.mu.Lock()
   243  	defer tree.mu.Unlock()
   244  	tree.tree.Clear()
   245  }
   246  
   247  // Keys returns all keys in asc order.
   248  func (tree *AVLTree) Keys() []interface{} {
   249  	tree.mu.RLock()
   250  	defer tree.mu.RUnlock()
   251  	return tree.tree.Keys()
   252  }
   253  
   254  // Values returns all values in asc order based on the key.
   255  func (tree *AVLTree) Values() []interface{} {
   256  	tree.mu.RLock()
   257  	defer tree.mu.RUnlock()
   258  	return tree.tree.Values()
   259  }
   260  
   261  // Replace the data of the tree with given `data`.
   262  func (tree *AVLTree) Replace(data map[interface{}]interface{}) {
   263  	tree.mu.Lock()
   264  	defer tree.mu.Unlock()
   265  	tree.tree.Clear()
   266  	for k, v := range data {
   267  		tree.doSet(k, v)
   268  	}
   269  }
   270  
   271  // Print prints the tree to stdout.
   272  func (tree *AVLTree) Print() {
   273  	fmt.Println(tree.String())
   274  }
   275  
   276  // String returns a string representation of container
   277  func (tree *AVLTree) String() string {
   278  	tree.mu.RLock()
   279  	defer tree.mu.RUnlock()
   280  	return gstr.Replace(tree.tree.String(), "AVLTree\n", "")
   281  }
   282  
   283  // MarshalJSON implements the interface MarshalJSON for json.Marshal.
   284  func (tree *AVLTree) MarshalJSON() (jsonBytes []byte, err error) {
   285  	tree.mu.RLock()
   286  	defer tree.mu.RUnlock()
   287  	return tree.tree.MarshalJSON()
   288  }
   289  
   290  // Map returns all key-value items as map.
   291  func (tree *AVLTree) Map() map[interface{}]interface{} {
   292  	tree.mu.RLock()
   293  	defer tree.mu.RUnlock()
   294  	m := make(map[interface{}]interface{}, tree.Size())
   295  	tree.IteratorAsc(func(key, value interface{}) bool {
   296  		m[key] = value
   297  		return true
   298  	})
   299  	return m
   300  }
   301  
   302  // MapStrAny returns all key-value items as map[string]interface{}.
   303  func (tree *AVLTree) MapStrAny() map[string]interface{} {
   304  	tree.mu.RLock()
   305  	defer tree.mu.RUnlock()
   306  	m := make(map[string]interface{}, tree.Size())
   307  	tree.IteratorAsc(func(key, value interface{}) bool {
   308  		m[gconv.String(key)] = value
   309  		return true
   310  	})
   311  	return m
   312  }
   313  
   314  // Iterator is alias of IteratorAsc.
   315  func (tree *AVLTree) Iterator(f func(key, value interface{}) bool) {
   316  	tree.IteratorAsc(f)
   317  }
   318  
   319  // IteratorFrom is alias of IteratorAscFrom.
   320  func (tree *AVLTree) IteratorFrom(key interface{}, match bool, f func(key, value interface{}) bool) {
   321  	tree.IteratorAscFrom(key, match, f)
   322  }
   323  
   324  // IteratorAsc iterates the tree readonly in ascending order with given callback function `f`.
   325  // If `f` returns true, then it continues iterating; or false to stop.
   326  func (tree *AVLTree) IteratorAsc(f func(key, value interface{}) bool) {
   327  	tree.mu.RLock()
   328  	defer tree.mu.RUnlock()
   329  	it := tree.tree.Iterator()
   330  	for it.Begin(); it.Next(); {
   331  		index, value := it.Key(), it.Value()
   332  		if ok := f(index, value); !ok {
   333  			break
   334  		}
   335  	}
   336  }
   337  
   338  // IteratorAscFrom iterates the tree readonly in ascending order with given callback function `f`.
   339  // The parameter `key` specifies the start entry for iterating. The `match` specifies whether
   340  // starting iterating if the `key` is fully matched, or else using index searching iterating.
   341  // If `f` returns true, then it continues iterating; or false to stop.
   342  func (tree *AVLTree) IteratorAscFrom(key interface{}, match bool, f func(key, value interface{}) bool) {
   343  	tree.mu.RLock()
   344  	defer tree.mu.RUnlock()
   345  	var keys = tree.tree.Keys()
   346  	index, isIterator := tree.iteratorFromGetIndex(key, keys, match)
   347  	if !isIterator {
   348  		return
   349  	}
   350  	for ; index < len(keys); index++ {
   351  		f(keys[index], tree.Get(keys[index]))
   352  	}
   353  }
   354  
   355  // IteratorDesc iterates the tree readonly in descending order with given callback function `f`.
   356  // If `f` returns true, then it continues iterating; or false to stop.
   357  func (tree *AVLTree) IteratorDesc(f func(key, value interface{}) bool) {
   358  	tree.mu.RLock()
   359  	defer tree.mu.RUnlock()
   360  	it := tree.tree.Iterator()
   361  	for it.End(); it.Prev(); {
   362  		index, value := it.Key(), it.Value()
   363  		if ok := f(index, value); !ok {
   364  			break
   365  		}
   366  	}
   367  }
   368  
   369  // IteratorDescFrom iterates the tree readonly in descending order with given callback function `f`.
   370  // The parameter `key` specifies the start entry for iterating. The `match` specifies whether
   371  // starting iterating if the `key` is fully matched, or else using index searching iterating.
   372  // If `f` returns true, then it continues iterating; or false to stop.
   373  func (tree *AVLTree) IteratorDescFrom(key interface{}, match bool, f func(key, value interface{}) bool) {
   374  	tree.mu.RLock()
   375  	defer tree.mu.RUnlock()
   376  	var keys = tree.tree.Keys()
   377  	index, isIterator := tree.iteratorFromGetIndex(key, keys, match)
   378  	if !isIterator {
   379  		return
   380  	}
   381  	for ; index >= 0; index-- {
   382  		f(keys[index], tree.Get(keys[index]))
   383  	}
   384  }
   385  
   386  // Left returns the minimum element of the AVL tree
   387  // or nil if the tree is empty.
   388  func (tree *AVLTree) Left() *AVLTreeNode {
   389  	tree.mu.RLock()
   390  	defer tree.mu.RUnlock()
   391  	node := tree.tree.Left()
   392  	if node == nil {
   393  		return nil
   394  	}
   395  	return &AVLTreeNode{
   396  		Key:   node.Key,
   397  		Value: node.Value,
   398  	}
   399  }
   400  
   401  // Right returns the maximum element of the AVL tree
   402  // or nil if the tree is empty.
   403  func (tree *AVLTree) Right() *AVLTreeNode {
   404  	tree.mu.RLock()
   405  	defer tree.mu.RUnlock()
   406  	node := tree.tree.Right()
   407  	if node == nil {
   408  		return nil
   409  	}
   410  	return &AVLTreeNode{
   411  		Key:   node.Key,
   412  		Value: node.Value,
   413  	}
   414  }
   415  
   416  // Floor Finds floor node of the input key, return the floor node or nil if no floor node is found.
   417  // Second return parameter is true if floor was found, otherwise false.
   418  //
   419  // Floor node is defined as the largest node that is smaller than or equal to the given node.
   420  // A floor node may not be found, either because the tree is empty, or because
   421  // all nodes in the tree is larger than the given node.
   422  //
   423  // Key should adhere to the comparator's type assertion, otherwise method panics.
   424  func (tree *AVLTree) Floor(key interface{}) (floor *AVLTreeNode, found bool) {
   425  	tree.mu.RLock()
   426  	defer tree.mu.RUnlock()
   427  	node, found := tree.tree.Floor(key)
   428  	if !found {
   429  		return nil, false
   430  	}
   431  	return &AVLTreeNode{
   432  		Key:   node.Key,
   433  		Value: node.Value,
   434  	}, true
   435  }
   436  
   437  // Ceiling finds ceiling node of the input key, return the ceiling node or nil if no ceiling node is found.
   438  // Second return parameter is true if ceiling was found, otherwise false.
   439  //
   440  // Ceiling node is defined as the smallest node that is larger than or equal to the given node.
   441  // A ceiling node may not be found, either because the tree is empty, or because
   442  // all nodes in the tree is smaller than the given node.
   443  //
   444  // Key should adhere to the comparator's type assertion, otherwise method panics.
   445  func (tree *AVLTree) Ceiling(key interface{}) (ceiling *AVLTreeNode, found bool) {
   446  	tree.mu.RLock()
   447  	defer tree.mu.RUnlock()
   448  	node, found := tree.tree.Ceiling(key)
   449  	if !found {
   450  		return nil, false
   451  	}
   452  	return &AVLTreeNode{
   453  		Key:   node.Key,
   454  		Value: node.Value,
   455  	}, true
   456  }
   457  
   458  // Flip exchanges key-value of the tree to value-key.
   459  // Note that you should guarantee the value is the same type as key,
   460  // or else the comparator would panic.
   461  //
   462  // If the type of value is different with key, you pass the new `comparator`.
   463  func (tree *AVLTree) Flip(comparator ...func(v1, v2 interface{}) int) {
   464  	var t = new(AVLTree)
   465  	if len(comparator) > 0 {
   466  		t = NewAVLTree(comparator[0], tree.mu.IsSafe())
   467  	} else {
   468  		t = NewAVLTree(tree.comparator, tree.mu.IsSafe())
   469  	}
   470  	tree.IteratorAsc(func(key, value interface{}) bool {
   471  		t.doSet(value, key)
   472  		return true
   473  	})
   474  	tree.Clear()
   475  	tree.Sets(t.Map())
   476  }
   477  
   478  // doSet sets key-value pair to the tree.
   479  func (tree *AVLTree) doSet(key, value interface{}) interface{} {
   480  	if f, ok := value.(func() interface{}); ok {
   481  		value = f()
   482  	}
   483  	if value == nil {
   484  		return value
   485  	}
   486  	tree.tree.Put(key, value)
   487  	return value
   488  }
   489  
   490  // doGet retrieves and returns the value of given key from tree.
   491  func (tree *AVLTree) doGet(key interface{}) (value interface{}, found bool) {
   492  	return tree.tree.Get(key)
   493  }
   494  
   495  // doRemove removes key from tree.
   496  func (tree *AVLTree) doRemove(key interface{}) (value interface{}) {
   497  	value, _ = tree.tree.Get(key)
   498  	tree.tree.Remove(key)
   499  	return
   500  }
   501  
   502  // iteratorFromGetIndex returns the index of the key in the keys slice.
   503  // The parameter `match` specifies whether starting iterating if the `key` is fully matched,
   504  // or else using index searching iterating.
   505  // If `isIterator` is true, iterator is available; or else not.
   506  func (tree *AVLTree) iteratorFromGetIndex(key interface{}, keys []interface{}, match bool) (index int, isIterator bool) {
   507  	if match {
   508  		for i, k := range keys {
   509  			if k == key {
   510  				isIterator = true
   511  				index = i
   512  			}
   513  		}
   514  	} else {
   515  		if i, ok := key.(int); ok {
   516  			isIterator = true
   517  			index = i
   518  		}
   519  	}
   520  	return
   521  }