github.com/matrixorigin/matrixone@v0.7.0/pkg/lockservice/btree_storage.go (about)

     1  // Copyright 2022 Matrix Origin
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //      http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package lockservice
    16  
    17  import (
    18  	"bytes"
    19  
    20  	"github.com/google/btree"
    21  )
    22  
    23  type treeItem struct {
    24  	key   []byte
    25  	value Lock
    26  }
    27  
    28  func (item treeItem) isEmpty() bool {
    29  	return len(item.key) == 0 &&
    30  		len(item.value.txnID) == 0
    31  }
    32  
    33  // Less returns true if the item key is less than the other.
    34  func (item treeItem) Less(other btree.Item) bool {
    35  	left := item.key
    36  	right := other.(treeItem).key
    37  	return bytes.Compare(right, left) > 0
    38  }
    39  
    40  type btreeBasedStorage struct {
    41  	tree *btree.BTreeG[treeItem]
    42  }
    43  
    44  func newBtreeBasedStorage() LockStorage {
    45  	return &btreeBasedStorage{
    46  		tree: btree.NewG(32, func(a, b treeItem) bool {
    47  			return bytes.Compare(a.key, b.key) < 0
    48  		}),
    49  	}
    50  }
    51  
    52  func (k *btreeBasedStorage) Add(key []byte, value Lock) {
    53  	k.tree.ReplaceOrInsert(treeItem{
    54  		key:   key,
    55  		value: value,
    56  	})
    57  }
    58  
    59  func (k *btreeBasedStorage) Get(key []byte) (Lock, bool) {
    60  	item, ok := k.tree.Get(treeItem{key: key})
    61  	return item.value, ok
    62  }
    63  
    64  func (k *btreeBasedStorage) Len() int {
    65  	return k.tree.Len()
    66  }
    67  
    68  func (k *btreeBasedStorage) Delete(key []byte) {
    69  	k.tree.Delete(treeItem{key: key})
    70  }
    71  
    72  func (k *btreeBasedStorage) Seek(key []byte) ([]byte, Lock, bool) {
    73  	var result treeItem
    74  	k.tree.AscendGreaterOrEqual(treeItem{key: key}, func(item treeItem) bool {
    75  		result = item
    76  		return false
    77  	})
    78  	return result.key, result.value, !result.isEmpty()
    79  }