-
Notifications
You must be signed in to change notification settings - Fork 5
/
btree.go
91 lines (79 loc) · 1.6 KB
/
btree.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
package block_stm
import (
"sync/atomic"
"github.com/tidwall/btree"
)
// BTree wraps an atomic pointer to an unsafe btree.BTreeG
type BTree[T any] struct {
atomic.Pointer[btree.BTreeG[T]]
}
// NewBTree returns a new BTree.
func NewBTree[T any](less func(a, b T) bool, degree int) *BTree[T] {
tree := btree.NewBTreeGOptions(less, btree.Options{
NoLocks: true,
ReadOnly: true,
Degree: degree,
})
t := &BTree[T]{}
t.Store(tree)
return t
}
func (bt *BTree[T]) Get(item T) (result T, ok bool) {
return bt.Load().Get(item)
}
func (bt *BTree[T]) GetOrDefault(item T, fillDefaults func(*T)) T {
for {
t := bt.Load()
result, ok := t.Get(item)
if ok {
return result
}
fillDefaults(&item)
c := t.Copy()
c.Set(item)
c.Freeze()
if bt.CompareAndSwap(t, c) {
return item
}
}
}
func (bt *BTree[T]) Set(item T) (prev T, ok bool) {
for {
t := bt.Load()
c := t.Copy()
prev, ok = c.Set(item)
c.Freeze()
if bt.CompareAndSwap(t, c) {
return
}
}
}
func (bt *BTree[T]) Delete(item T) (prev T, ok bool) {
for {
t := bt.Load()
c := t.Copy()
prev, ok = c.Delete(item)
c.Freeze()
if bt.CompareAndSwap(t, c) {
return
}
}
}
func (bt *BTree[T]) Scan(iter func(item T) bool) {
bt.Load().Scan(iter)
}
func (bt *BTree[T]) Max() (T, bool) {
return bt.Load().Max()
}
func (bt *BTree[T]) Iter() btree.IterG[T] {
return bt.Load().Iter()
}
// ReverseSeek returns the first item that is less than or equal to the pivot
func (bt *BTree[T]) ReverseSeek(pivot T) (result T, ok bool) {
bt.Load().Descend(pivot, func(item T) bool {
result = item
ok = true
return false
})
return
}