/
rt.go
226 lines (187 loc) · 4.92 KB
/
rt.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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
/*
Copyright 2014 Workiva, LLC
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
//go:generate msgp -tests=false -io=false
package btree
import "sync"
// context is used to keep track of the nodes in this mutable
// that have been created. This is basically any node that had
// to be touched to perform mutations. Further mutations will visit
// this context first so we don't have to constantly copy if
// we don't need to.
type context struct {
lock sync.RWMutex
seenNodes map[string]*Node
}
func (c *context) nodeExists(id ID) bool {
c.lock.RLock()
defer c.lock.RUnlock()
_, ok := c.seenNodes[string(id)]
return ok
}
func (c *context) addNode(n *Node) {
c.lock.Lock()
defer c.lock.Unlock()
c.seenNodes[string(n.ID)] = n
}
func (c *context) getNode(id ID) *Node {
c.lock.RLock()
defer c.lock.RUnlock()
return c.seenNodes[string(id)]
}
func newContext() *context {
return &context{
seenNodes: make(map[string]*Node, 10),
}
}
// Tr itself is exported so that the code generated for serialization/deserialization
// works on Tr. Exported fields on Tr are those fields that need to be
// serialized.
type Tr struct {
UUID ID `msg:"u"`
Count int `msg:"c"`
config Config
Root ID `msg:"r"`
cacher *cacher
context *context
NodeWidth int `msg:"nw"`
mutable bool
}
func (t *Tr) createRoot() *Node {
n := newNode()
n.IsLeaf = true
return n
}
// contextOrCachedNode is a convenience function for either fetching
// a node from the context or persistence.
func (t *Tr) contextOrCachedNode(id ID, cache bool) (*Node, error) {
if t.context != nil {
n := t.context.getNode(id)
if n != nil {
return n, nil
}
}
return t.cacher.getNode(t, id, cache)
}
func (t *Tr) ID() ID {
return t.UUID
}
// toBytes encodes this tree into a byte array. Panics if unable
// as this error has to be fixed in code.
func (t *Tr) toBytes() []byte {
buf, err := t.MarshalMsg(nil)
if err != nil {
panic(`unable to encode tree`)
}
return buf
}
// reset is called on a tree to empty the context and clear the cache.
func (t *Tr) reset() {
t.cacher.clear()
t.context = nil
}
// commit will gather up all created nodes and serialize them into
// items that can be persisted.
func (t *Tr) commit() []*Payload {
items := make([]*Payload, 0, len(t.context.seenNodes))
for _, n := range t.context.seenNodes {
n.ChildValues, n.ChildKeys = n.flatten()
buf, err := n.MarshalMsg(nil)
if err != nil {
panic(`unable to encode node`)
}
n.ChildValues, n.ChildKeys = nil, nil
item := &Payload{n.ID, buf}
items = append(items, item)
}
return items
}
func (t *Tr) copyNode(n *Node) *Node {
if t.context.nodeExists(n.ID) {
return n
}
cp := n.copy()
t.context.addNode(cp)
return cp
}
func (t *Tr) Len() int {
return t.Count
}
func (t *Tr) AsMutable() MutableTree {
return &Tr{
Count: t.Count,
UUID: newID(),
Root: t.Root,
config: t.config,
cacher: t.cacher,
context: newContext(),
NodeWidth: t.NodeWidth,
mutable: true,
}
}
func (t *Tr) Commit() (ReadableTree, error) {
t.NodeWidth = t.config.NodeWidth
items := make([]*Payload, 0, len(t.context.seenNodes))
items = append(items, t.commit()...)
// save self
items = append(items, &Payload{t.ID(), t.toBytes()})
err := t.config.Persister.Save(items...)
if err != nil {
return nil, err
}
t.reset()
t.context = nil
return t, nil
}
func treeFromBytes(p Persister, data []byte, comparator Comparator) (*Tr, error) {
t := &Tr{}
_, err := t.UnmarshalMsg(data)
if err != nil {
return nil, err
}
cfg := DefaultConfig(p, comparator)
if t.NodeWidth > 0 {
cfg.NodeWidth = t.NodeWidth
}
t.config = cfg
t.cacher = newCacher(cfg.Persister)
return t, nil
}
func newTree(cfg Config) *Tr {
return &Tr{
config: cfg,
UUID: newID(),
cacher: newCacher(cfg.Persister),
}
}
// New creates a new ReadableTree using the provided config.
func New(cfg Config) ReadableTree {
return newTree(cfg)
}
// Load returns a ReadableTree from persistence. The provided
// config should contain a persister that can be used for this purpose.
// An error is returned if the tree could not be found or an error
// occurred in the persistence layer.
func Load(p Persister, id []byte, comparator Comparator) (ReadableTree, error) {
items, err := p.Load(id)
if err != nil {
return nil, err
}
if len(items) == 0 || items[0] == nil {
return nil, ErrTreeNotFound
}
rt, err := treeFromBytes(p, items[0].Payload, comparator)
if err != nil {
return nil, err
}
return rt, nil
}