Debian Codegraph @

gopls/internal/util/persistent/map.go

raw symbols SCIP
1 // Copyright 2022 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
4
5 // The persistent package defines various persistent data structures;
6 // that is, data structures that can be efficiently copied and modified
7 // in sublinear time.
8 package persistent
9
10 import (
11 "fmt"
12 "iter"
13 "math/rand"
14 "strings"
15 "sync/atomic"
16
17 "golang.org/x/tools/gopls/internal/util/constraints"
18 )
19
20 // Implementation details:
21 // * Each value is reference counted by nodes which hold it.
22 // * Each node is reference counted by its parent nodes.
23 // * Each map is considered a top-level parent node from reference counting perspective.
24 // * Each change does always effectively produce a new top level node.
25 //
26 // Functions which operate directly with nodes do have a notation in form of
27 // `foo(arg1:+n1, arg2:+n2) (ret1:+n3)`.
28 // Each argument is followed by a delta change to its reference counter.
29 // In case if no change is expected, the delta will be `-0`.
30 //
31 // TODO(rfindley): add Update(K, func(V, bool) V), as we have several instances
32 // of the Get-<check>-Set pattern that could be optimized.
33
34 // Map is an associative mapping from keys to values.
35 //
36 // Maps can be Cloned in constant time.
37 // Get, Set, and Delete operations are done on average in logarithmic time.
38 // Maps can be merged (via SetAll) in O(m log(n/m)) time for maps of size n and m, where m < n.
39 //
40 // Values are reference counted, and a client-supplied release function
41 // is called when a value is no longer referenced by a map or any clone.
42 //
43 // Internally the implementation is based on a randomized persistent treap:
44 // https://en.wikipedia.org/wiki/Treap.
45 //
46 // The zero value is ready to use.
47 type Map[K constraints.Ordered, V any] struct {
48 // Map is a generic wrapper around a non-generic implementation to avoid a
49 // significant increase in the size of the executable.
50 root *mapNode
51 }
52
53 func (*Map[K, V]) less(l, r any) bool {
54 return l.(K) < r.(K)
55 }
56
57 func (m *Map[K, V]) String() string {
58 var buf strings.Builder
59 buf.WriteByte('{')
60 var sep string
61 for k, v := range m.All() {
62 fmt.Fprintf(&buf, "%s%v: %v", sep, k, v)
63 sep = ", "
64 }
65 buf.WriteByte('}')
66 return buf.String()
67 }
68
69 type mapNode struct {
70 key any
71 value *refValue
72 weight uint64
73 refCount int32
74 left, right *mapNode
75 }
76
77 type refValue struct {
78 refCount int32
79 value any
80 release func(key, value any)
81 }
82
83 func newNodeWithRef[K constraints.Ordered, V any](key K, value V, release func(key, value any)) *mapNode {
84 return &mapNode{
85 key: key,
86 value: &refValue{
87 value: value,
88 release: release,
89 refCount: 1,
90 },
91 refCount: 1,
92 weight: rand.Uint64(),
93 }
94 }
95
96 func (node *mapNode) shallowCloneWithRef() *mapNode {
97 atomic.AddInt32(&node.value.refCount, 1)
98 return &mapNode{
99 key: node.key,
100 value: node.value,
101 weight: node.weight,
102 refCount: 1,
103 }
104 }
105
106 func (node *mapNode) incref() *mapNode {
107 if node != nil {
108 atomic.AddInt32(&node.refCount, 1)
109 }
110 return node
111 }
112
113 func (node *mapNode) decref() {
114 if node == nil {
115 return
116 }
117 if atomic.AddInt32(&node.refCount, -1) == 0 {
118 if atomic.AddInt32(&node.value.refCount, -1) == 0 {
119 if node.value.release != nil {
120 node.value.release(node.key, node.value.value)
121 }
122 node.value.value = nil
123 node.value.release = nil
124 }
125 node.left.decref()
126 node.right.decref()
127 }
128 }
129
130 // Clone returns a copy of the given map. It is a responsibility of the caller
131 // to Destroy it at later time.
132 func (pm *Map[K, V]) Clone() *Map[K, V] {
133 return &Map[K, V]{
134 root: pm.root.incref(),
135 }
136 }
137
138 // Destroy destroys the map.
139 //
140 // After Destroy, the Map should not be used again.
141 func (pm *Map[K, V]) Destroy() {
142 // The implementation of these two functions is the same,
143 // but their intent is different.
144 pm.Clear()
145 }
146
147 // Clear removes all entries from the map.
148 func (pm *Map[K, V]) Clear() {
149 pm.root.decref()
150 pm.root = nil
151 }
152
153 // Keys returns the ascending sequence of keys present in the map.
154 func (pm *Map[K, V]) Keys() iter.Seq[K] {
155 return func(yield func(K) bool) {
156 pm.root.forEach(func(k, _ any) bool {
157 return yield(k.(K))
158 })
159 }
160 }
161
162 // All returns the sequence of map entries in ascending key order.
163 func (pm *Map[K, V]) All() iter.Seq2[K, V] {
164 return func(yield func(K, V) bool) {
165 pm.root.forEach(func(k, v any) bool {
166 return yield(k.(K), v.(V))
167 })
168 }
169 }
170
171 func (node *mapNode) forEach(yield func(key, value any) bool) bool {
172 return node == nil ||
173 node.left.forEach(yield) &&
174 yield(node.key, node.value.value) &&
175 node.right.forEach(yield)
176 }
177
178 // Get returns the map value associated with the specified key.
179 // The ok result indicates whether an entry was found in the map.
180 func (pm *Map[K, V]) Get(key K) (V, bool) {
181 node := pm.root
182 for node != nil {
183 if key < node.key.(K) {
184 node = node.left
185 } else if node.key.(K) < key {
186 node = node.right
187 } else {
188 return node.value.value.(V), true
189 }
190 }
191 var zero V
192 return zero, false
193 }
194
195 // SetAll updates the map with key/value pairs from the other map, overwriting existing keys.
196 // It is equivalent to calling Set for each entry in the other map but is more efficient.
197 func (pm *Map[K, V]) SetAll(other *Map[K, V]) {
198 root := pm.root
199 pm.root = union(root, other.root, pm.less, true)
200 root.decref()
201 }
202
203 // Set updates the value associated with the specified key.
204 // If release is non-nil, it will be called with entry's key and value once the
205 // key is no longer contained in the map or any clone.
206 //
207 // TODO(adonovan): fix release, which has the wrong type.
208 func (pm *Map[K, V]) Set(key K, value V, release func(key, value any)) {
209 first := pm.root
210 second := newNodeWithRef(key, value, release)
211 pm.root = union(first, second, pm.less, true)
212 first.decref()
213 second.decref()
214 }
215
216 // union returns a new tree which is a union of first and second one.
217 // If overwrite is set to true, second one would override a value for any duplicate keys.
218 //
219 // union(first:-0, second:-0) (result:+1)
220 // Union borrows both subtrees without affecting their refcount and returns a
221 // new reference that the caller is expected to call decref.
222 func union(first, second *mapNode, less func(any, any) bool, overwrite bool) *mapNode {
223 if first == nil {
224 return second.incref()
225 }
226 if second == nil {
227 return first.incref()
228 }
229
230 if first.weight < second.weight {
231 second, first, overwrite = first, second, !overwrite
232 }
233
234 left, mid, right := split(second, first.key, less, false)
235 var result *mapNode
236 if overwrite && mid != nil {
237 result = mid.shallowCloneWithRef()
238 } else {
239 result = first.shallowCloneWithRef()
240 }
241 result.weight = first.weight
242 result.left = union(first.left, left, less, overwrite)
243 result.right = union(first.right, right, less, overwrite)
244 left.decref()
245 mid.decref()
246 right.decref()
247 return result
248 }
249
250 // split the tree midway by the key into three different ones.
251 // Return three new trees: left with all nodes with smaller than key, mid with
252 // the node matching the key, right with all nodes larger than key.
253 // If there are no nodes in one of trees, return nil instead of it.
254 // If requireMid is set (such as during deletion), then all return arguments
255 // are nil if mid is not found.
256 //
257 // split(n:-0) (left:+1, mid:+1, right:+1)
258 // Split borrows n without affecting its refcount, and returns three
259 // new references that the caller is expected to call decref.
260 func split(n *mapNode, key any, less func(any, any) bool, requireMid bool) (left, mid, right *mapNode) {
261 if n == nil {
262 return nil, nil, nil
263 }
264
265 if less(n.key, key) {
266 left, mid, right := split(n.right, key, less, requireMid)
267 if requireMid && mid == nil {
268 return nil, nil, nil
269 }
270 newN := n.shallowCloneWithRef()
271 newN.left = n.left.incref()
272 newN.right = left
273 return newN, mid, right
274 } else if less(key, n.key) {
275 left, mid, right := split(n.left, key, less, requireMid)
276 if requireMid && mid == nil {
277 return nil, nil, nil
278 }
279 newN := n.shallowCloneWithRef()
280 newN.left = right
281 newN.right = n.right.incref()
282 return left, mid, newN
283 }
284 mid = n.shallowCloneWithRef()
285 return n.left.incref(), mid, n.right.incref()
286 }
287
288 // Delete deletes the value for a key.
289 //
290 // The result reports whether the key was present in the map.
291 func (pm *Map[K, V]) Delete(key K) bool {
292 root := pm.root
293 left, mid, right := split(root, key, pm.less, true)
294 if mid == nil {
295 return false
296 }
297 pm.root = merge(left, right)
298 left.decref()
299 mid.decref()
300 right.decref()
301 root.decref()
302 return true
303 }
304
305 // merge two trees while preserving the weight invariant.
306 // All nodes in left must have smaller keys than any node in right.
307 //
308 // merge(left:-0, right:-0) (result:+1)
309 // Merge borrows its arguments without affecting their refcount
310 // and returns a new reference that the caller is expected to call decref.
311 func merge(left, right *mapNode) *mapNode {
312 switch {
313 case left == nil:
314 return right.incref()
315 case right == nil:
316 return left.incref()
317 case left.weight > right.weight:
318 root := left.shallowCloneWithRef()
319 root.left = left.left.incref()
320 root.right = merge(left.right, right)
321 return root
322 default:
323 root := right.shallowCloneWithRef()
324 root.left = merge(left, right.left)
325 root.right = right.right.incref()
326 return root
327 }
328 }