github.com/go-board/x-go@v0.1.2-0.20220610024734-db1323f6cb15/xcontainer/maps/string_key_btree_map.go (about)

     1  package maps
     2  
     3  import (
     4  	"github.com/google/btree"
     5  )
     6  
     7  type entry struct {
     8  	key string
     9  	val interface{}
    10  }
    11  
    12  func (e *entry) Less(than btree.Item) bool {
    13  	return e.key < than.(*entry).key
    14  }
    15  
    16  type StringKeyBtreeMap struct {
    17  	tree *btree.BTree
    18  }
    19  
    20  func NewStringKeyBtreeMap() *StringKeyBtreeMap {
    21  	return &StringKeyBtreeMap{
    22  		tree: btree.New(64),
    23  	}
    24  }
    25  
    26  func (m *StringKeyBtreeMap) Set(key string, val interface{}) {
    27  	m.tree.ReplaceOrInsert(&entry{key: key, val: val})
    28  }
    29  
    30  func (m *StringKeyBtreeMap) GetOk(key string) (interface{}, bool) {
    31  	item := m.tree.Get(&entry{key: key})
    32  	if item == nil {
    33  		return nil, false
    34  	}
    35  	return item.(*entry).val, true
    36  }
    37  
    38  func (m *StringKeyBtreeMap) Remove(key string) {
    39  	m.tree.Delete(&entry{key: key})
    40  }
    41  
    42  func (m *StringKeyBtreeMap) RemoveAll() {
    43  	m.tree = btree.New(64)
    44  }
    45  
    46  func (m *StringKeyBtreeMap) RemoveIf(fn func(key string, val interface{}) bool) {
    47  	m.tree.Ascend(func(i btree.Item) bool {
    48  		entry := i.(*entry)
    49  		if fn(entry.key, entry.val) {
    50  			m.tree.Delete(entry)
    51  		}
    52  		return true
    53  	})
    54  }
    55  
    56  func (m *StringKeyBtreeMap) Exist(key string) bool {
    57  	return m.tree.Has(&entry{key: key})
    58  }
    59  
    60  func (m *StringKeyBtreeMap) Range(begin, end string, fn func(key string, val interface{}) bool) {
    61  	m.tree.AscendGreaterOrEqual(&entry{key: begin}, func(i btree.Item) bool {
    62  		entry := i.(*entry)
    63  		return entry.key <= end && fn(entry.key, entry.val)
    64  	})
    65  }
    66  
    67  func (m *StringKeyBtreeMap) RangeAll(fn func(key string, val interface{})) {
    68  	m.tree.Ascend(func(i btree.Item) bool {
    69  		entry := i.(*entry)
    70  		fn(entry.key, entry.val)
    71  		return true
    72  	})
    73  }