github.com/matrixorigin/matrixone@v1.2.0/pkg/txn/storage/memorystorage/memorytable/btree.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 memorytable
    16  
    17  import (
    18  	"github.com/tidwall/btree"
    19  )
    20  
    21  type BTree[
    22  	K Ordered[K],
    23  	V any,
    24  ] struct {
    25  	rows *btree.BTreeG[TreeNode[K, V]]
    26  }
    27  
    28  func NewBTree[
    29  	K Ordered[K],
    30  	V any,
    31  ]() *BTree[K, V] {
    32  	return &BTree[K, V]{
    33  		rows: btree.NewBTreeG(compareTreeNode[K, V]),
    34  	}
    35  }
    36  
    37  var _ Tree[Int, int] = new(BTree[Int, int])
    38  
    39  func (b *BTree[K, V]) Copy() Tree[K, V] {
    40  	return &BTree[K, V]{
    41  		rows: b.rows.Copy(),
    42  	}
    43  }
    44  
    45  func (b *BTree[K, V]) Get(pivot TreeNode[K, V]) (TreeNode[K, V], bool) {
    46  	return b.rows.Get(pivot)
    47  }
    48  
    49  func (b *BTree[K, V]) Set(pair TreeNode[K, V]) (TreeNode[K, V], bool) {
    50  	return b.rows.Set(pair)
    51  }
    52  
    53  func (b *BTree[K, V]) Delete(pivot TreeNode[K, V]) {
    54  	b.rows.Delete(pivot)
    55  }
    56  
    57  type btreeKVIter[
    58  	K Ordered[K],
    59  	V any,
    60  ] struct {
    61  	iter btree.IterG[TreeNode[K, V]]
    62  }
    63  
    64  func (b *BTree[K, V]) Iter() TreeIter[K, V] {
    65  	iter := b.rows.Iter()
    66  	return &btreeKVIter[K, V]{
    67  		iter: iter,
    68  	}
    69  }
    70  
    71  func (b *btreeKVIter[K, V]) Close() error {
    72  	b.iter.Release()
    73  	return nil
    74  }
    75  
    76  func (b *btreeKVIter[K, V]) First() bool {
    77  	return b.iter.First()
    78  }
    79  
    80  func (b *btreeKVIter[K, V]) Next() bool {
    81  	return b.iter.Next()
    82  }
    83  
    84  func (b *btreeKVIter[K, V]) Read() (TreeNode[K, V], error) {
    85  	return b.iter.Item(), nil
    86  }
    87  
    88  func (b *btreeKVIter[K, V]) Seek(pivot TreeNode[K, V]) bool {
    89  	return b.iter.Seek(pivot)
    90  }