Debian Codegraph @

server/avl/seqset.go

raw
1 // Copyright 2023-2025 The NATS Authors
2 // Licensed under the Apache License, Version 2.0 (the "License");
3 // you may not use this file except in compliance with the License.
4 // You may obtain a copy of the License at
5 //
6 // http://www.apache.org/licenses/LICENSE-2.0
7 //
8 // Unless required by applicable law or agreed to in writing, software
9 // distributed under the License is distributed on an "AS IS" BASIS,
10 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 // See the License for the specific language governing permissions and
12 // limitations under the License.
13
14 package avl
15
16 import (
17 "cmp"
18 "encoding/binary"
19 "errors"
20 "math/bits"
21 "slices"
22 )
23
24 // SequenceSet is a memory and encoding optimized set for storing unsigned ints.
25 //
26 // SequenceSet is ~80-100 times more efficient memory wise than a map[uint64]struct{}.
27 // SequenceSet is ~1.75 times slower at inserts than the same map.
28 // SequenceSet is not thread safe.
29 //
30 // We use an AVL tree with nodes that hold bitmasks for set membership.
31 //
32 // Encoding will convert to a space optimized encoding using bitmasks.
33 type SequenceSet struct {
34 root *node // root node
35 size int // number of items
36 nodes int // number of nodes
37 // Having this here vs on the stack in Insert/Delete
38 // makes a difference in memory usage.
39 changed bool
40 }
41
42 // Insert will insert the sequence into the set.
43 // The tree will be balanced inline.
44 func (ss *SequenceSet) Insert(seq uint64) {
45 // If a node covering seq already exists, setting a bit can not change the
46 // tree shape, so skip the recursive descent and rebalance checks.
47 for n := ss.root; n != nil; {
48 if seq < n.base {
49 n = n.l
50 } else if seq >= n.base+numEntries {
51 n = n.r
52 } else {
53 n.set(seq, &ss.changed)
54 if ss.changed {
55 ss.changed = false
56 ss.size++
57 }
58 return
59 }
60 }
61 if ss.root = ss.root.insert(seq, &ss.changed, &ss.nodes); ss.changed {
62 ss.changed = false
63 ss.size++
64 }
65 }
66
67 // Exists will return true iff the sequence is a member of this set.
68 func (ss *SequenceSet) Exists(seq uint64) bool {
69 for n := ss.root; n != nil; {
70 if seq < n.base {
71 n = n.l
72 continue
73 } else if seq >= n.base+numEntries {
74 n = n.r
75 continue
76 }
77 return n.exists(seq)
78 }
79 return false
80 }
81
82 // SetInitialMin should be used to set the initial minimum sequence when known.
83 // This will more effectively utilize space versus self selecting.
84 // The set should be empty.
85 func (ss *SequenceSet) SetInitialMin(min uint64) error {
86 if !ss.IsEmpty() {
87 return ErrSetNotEmpty
88 }
89 ss.root, ss.nodes = &node{base: min, h: 1}, 1
90 return nil
91 }
92
93 // Delete will remove the sequence from the set.
94 // Will optionally remove nodes and rebalance.
95 // Returns where the sequence was set.
96 func (ss *SequenceSet) Delete(seq uint64) bool {
97 if ss == nil || ss.root == nil {
98 return false
99 }
100 ss.root = ss.root.delete(seq, &ss.changed, &ss.nodes)
101 if ss.changed {
102 ss.changed = false
103 ss.size--
104 if ss.size == 0 {
105 ss.Empty()
106 }
107 return true
108 }
109 return false
110 }
111
112 // Size returns the number of items in the set.
113 func (ss *SequenceSet) Size() int {
114 return ss.size
115 }
116
117 // Nodes returns the number of nodes in the tree.
118 func (ss *SequenceSet) Nodes() int {
119 return ss.nodes
120 }
121
122 // Empty will clear all items from a set.
123 func (ss *SequenceSet) Empty() {
124 ss.root = nil
125 ss.size = 0
126 ss.nodes = 0
127 }
128
129 // IsEmpty is a fast check of the set being empty.
130 func (ss *SequenceSet) IsEmpty() bool {
131 if ss == nil || ss.root == nil {
132 return true
133 }
134 return false
135 }
136
137 // Range will invoke the given function for each item in the set.
138 // They will range over the set in ascending order.
139 // If the callback returns false we terminate the iteration.
140 func (ss *SequenceSet) Range(f func(uint64) bool) {
141 ss.root.iter(f)
142 }
143
144 // Heights returns the left and right heights of the tree.
145 func (ss *SequenceSet) Heights() (l, r int) {
146 if ss.root == nil {
147 return 0, 0
148 }
149 if ss.root.l != nil {
150 l = ss.root.l.h
151 }
152 if ss.root.r != nil {
153 r = ss.root.r.h
154 }
155 return l, r
156 }
157
158 // Returns min, max and number of set items.
159 func (ss *SequenceSet) State() (min, max, num uint64) {
160 if ss == nil || ss.root == nil {
161 return 0, 0, 0
162 }
163 min, max = ss.MinMax()
164 return min, max, uint64(ss.Size())
165 }
166
167 // MinMax will return the minunum and maximum values in the set.
168 func (ss *SequenceSet) MinMax() (min, max uint64) {
169 if ss.root == nil {
170 return 0, 0
171 }
172 for l := ss.root; l != nil; l = l.l {
173 if l.l == nil {
174 min = l.min()
175 }
176 }
177 for r := ss.root; r != nil; r = r.r {
178 if r.r == nil {
179 max = r.max()
180 }
181 }
182 return min, max
183 }
184
185 func clone(src *node, target **node) {
186 if src == nil {
187 return
188 }
189 n := &node{base: src.base, bits: src.bits, h: src.h}
190 *target = n
191 clone(src.l, &n.l)
192 clone(src.r, &n.r)
193 }
194
195 // Clone will return a clone of the given SequenceSet.
196 func (ss *SequenceSet) Clone() *SequenceSet {
197 if ss == nil {
198 return nil
199 }
200 css := &SequenceSet{nodes: ss.nodes, size: ss.size}
201 clone(ss.root, &css.root)
202
203 return css
204 }
205
206 // Equal returns whether the two sets contain exactly the same sequences.
207 func (ss *SequenceSet) Equal(other *SequenceSet) bool {
208 if ss.IsEmpty() || other.IsEmpty() {
209 return ss.IsEmpty() && other.IsEmpty()
210 }
211 if ss.size != other.size {
212 return false
213 }
214 // Sizes are equal, so a one-way membership check suffices.
215 equal := true
216 ss.Range(func(seq uint64) bool {
217 equal = other.Exists(seq)
218 return equal
219 })
220 return equal
221 }
222
223 // Union will union this SequenceSet with ssa.
224 func (ss *SequenceSet) Union(ssa ...*SequenceSet) {
225 for _, sa := range ssa {
226 sa.root.nodeIter(func(n *node) {
227 for nb, b := range n.bits {
228 base := n.base + uint64(nb)*bitsPerBucket
229 for b != 0 {
230 ss.Insert(base + uint64(bits.TrailingZeros64(b)))
231 b &= b - 1
232 }
233 }
234 })
235 }
236 }
237
238 // Union will return a union of all sets.
239 func Union(ssa ...*SequenceSet) *SequenceSet {
240 if len(ssa) == 0 {
241 return nil
242 }
243 // Sort so we can clone largest.
244 slices.SortFunc(ssa, func(i, j *SequenceSet) int { return -cmp.Compare(i.Size(), j.Size()) }) // reverse order
245 ss := ssa[0].Clone()
246
247 // Insert the rest through range call.
248 for i := 1; i < len(ssa); i++ {
249 ssa[i].Range(func(n uint64) bool {
250 ss.Insert(n)
251 return true
252 })
253 }
254 return ss
255 }
256
257 const (
258 // Magic is used to identify the encode binary state..
259 magic = uint8(22)
260 // Version
261 version = uint8(2)
262 // hdrLen
263 hdrLen = 2
264 // minimum length of an encoded SequenceSet.
265 minLen = 2 + 8 // magic + version + num nodes + num entries.
266 )
267
268 // EncodeLen returns the bytes needed for encoding.
269 func (ss SequenceSet) EncodeLen() int {
270 return minLen + (ss.Nodes() * ((numBuckets+1)*8 + 2))
271 }
272
273 func (ss SequenceSet) Encode(buf []byte) []byte {
274 nn, encLen := ss.Nodes(), ss.EncodeLen()
275
276 if cap(buf) < encLen {
277 buf = make([]byte, encLen)
278 } else {
279 buf = buf[:encLen]
280 }
281
282 // TODO(dlc) - Go 1.19 introduced Append to not have to keep track.
283 // Once 1.20 is out we could change this over.
284 // Also binary.Write() is way slower, do not use.
285
286 var le = binary.LittleEndian
287 buf[0], buf[1] = magic, version
288 i := hdrLen
289 le.PutUint32(buf[i:], uint32(nn))
290 le.PutUint32(buf[i+4:], uint32(ss.size))
291 i += 8
292 ss.root.nodeIter(func(n *node) {
293 le.PutUint64(buf[i:], n.base)
294 i += 8
295 for _, b := range n.bits {
296 le.PutUint64(buf[i:], b)
297 i += 8
298 }
299 le.PutUint16(buf[i:], uint16(n.h))
300 i += 2
301 })
302 return buf[:i]
303 }
304
305 // ErrBadEncoding is returned when we can not decode properly.
306 var (
307 ErrBadEncoding = errors.New("ss: bad encoding")
308 ErrBadVersion = errors.New("ss: bad version")
309 ErrSetNotEmpty = errors.New("ss: set not empty")
310 )
311
312 // Decode returns the sequence set and number of bytes read from the buffer on success.
313 func Decode(buf []byte) (*SequenceSet, int, error) {
314 if len(buf) < minLen || buf[0] != magic {
315 return nil, -1, ErrBadEncoding
316 }
317
318 switch v := buf[1]; v {
319 case 1:
320 return decodev1(buf)
321 case 2:
322 return decodev2(buf)
323 default:
324 return nil, -1, ErrBadVersion
325 }
326 }
327
328 // Helper to decode v2.
329 func decodev2(buf []byte) (*SequenceSet, int, error) {
330 var le = binary.LittleEndian
331 index := 2
332 nn := int(le.Uint32(buf[index:]))
333 sz := int(le.Uint32(buf[index+4:]))
334 index += 8
335
336 // nn is decoded as a uint32 but held in an int. On 32-bit builds a value
337 // above MaxInt32 turns negative and nn*perNode below overflows, so the
338 // length check would pass for a short buffer and the following make/reads
339 // run off the end. Compare with division so the bound holds on every arch.
340 if nn < 0 || nn > (len(buf)-minLen)/((numBuckets+1)*8+2) {
341 return nil, -1, ErrBadEncoding
342 }
343
344 ss, nodes := SequenceSet{size: sz}, make([]node, nn)
345
346 for i := 0; i < nn; i++ {
347 n := &nodes[i]
348 n.base = le.Uint64(buf[index:])
349 index += 8
350 for bi := range n.bits {
351 n.bits[bi] = le.Uint64(buf[index:])
352 index += 8
353 }
354 n.h = int(le.Uint16(buf[index:]))
355 index += 2
356 ss.insertNode(n)
357 }
358
359 return &ss, index, nil
360 }
361
362 // Helper to decode v1 into v2 which has fixed buckets of 32 vs 64 originally.
363 func decodev1(buf []byte) (*SequenceSet, int, error) {
364 var le = binary.LittleEndian
365 index := 2
366 nn := int(le.Uint32(buf[index:]))
367 sz := int(le.Uint32(buf[index+4:]))
368 index += 8
369
370 const v1NumBuckets = 64
371
372 // See decodev2: guard the node count without overflowing the multiply so
373 // the bound stays correct on 32-bit builds too.
374 if nn < 0 || nn > (len(buf)-minLen)/((v1NumBuckets+1)*8+2) {
375 return nil, -1, ErrBadEncoding
376 }
377
378 var ss SequenceSet
379 for i := 0; i < nn; i++ {
380 base := le.Uint64(buf[index:])
381 index += 8
382 for nb := uint64(0); nb < v1NumBuckets; nb++ {
383 n := le.Uint64(buf[index:])
384 // Walk all set bits and insert sequences manually for this decode from v1.
385 for n != 0 {
386 ss.Insert(base + (nb * uint64(bitsPerBucket)) + uint64(bits.TrailingZeros64(n)))
387 n &= n - 1
388 }
389 index += 8
390 }
391 // Skip over encoded height.
392 index += 2
393 }
394
395 // Sanity check.
396 if ss.Size() != sz {
397 return nil, -1, ErrBadEncoding
398 }
399
400 return &ss, index, nil
401
402 }
403
404 // insertNode places a decoded node into the tree.
405 // These should be done in tree order as defined by Encode()
406 // This allows us to not have to calculate height or do rebalancing.
407 // So much better performance this way.
408 func (ss *SequenceSet) insertNode(n *node) {
409 ss.nodes++
410
411 if ss.root == nil {
412 ss.root = n
413 return
414 }
415 // Walk our way to the insertion point.
416 for p := ss.root; p != nil; {
417 if n.base < p.base {
418 if p.l == nil {
419 p.l = n
420 return
421 }
422 p = p.l
423 } else {
424 if p.r == nil {
425 p.r = n
426 return
427 }
428 p = p.r
429 }
430 }
431 }
432
433 const (
434 bitsPerBucket = 64 // bits in uint64
435 numBuckets = 32
436 numEntries = numBuckets * bitsPerBucket
437 )
438
439 type node struct {
440 //v dvalue
441 base uint64
442 bits [numBuckets]uint64
443 l *node
444 r *node
445 h int
446 }
447
448 // Set the proper bit.
449 // seq should have already been qualified and inserted should be non nil.
450 func (n *node) set(seq uint64, inserted *bool) {
451 seq -= n.base
452 i := seq / bitsPerBucket
453 mask := uint64(1) << (seq % bitsPerBucket)
454 if (n.bits[i] & mask) == 0 {
455 n.bits[i] |= mask
456 *inserted = true
457 }
458 }
459
460 func (n *node) insert(seq uint64, inserted *bool, nodes *int) *node {
461 if n == nil {
462 base := (seq / numEntries) * numEntries
463 n := &node{base: base, h: 1}
464 n.set(seq, inserted)
465 *nodes++
466 return n
467 }
468
469 if seq < n.base {
470 n.l = n.l.insert(seq, inserted, nodes)
471 } else if seq >= n.base+numEntries {
472 n.r = n.r.insert(seq, inserted, nodes)
473 } else {
474 n.set(seq, inserted)
475 }
476
477 n.h = maxH(n) + 1
478
479 // Don't make a function, impacts performance.
480 if bf := balanceF(n); bf > 1 {
481 // Left unbalanced.
482 if balanceF(n.l) < 0 {
483 n.l = n.l.rotateL()
484 }
485 return n.rotateR()
486 } else if bf < -1 {
487 // Right unbalanced.
488 if balanceF(n.r) > 0 {
489 n.r = n.r.rotateR()
490 }
491 return n.rotateL()
492 }
493 return n
494 }
495
496 func (n *node) rotateL() *node {
497 r := n.r
498 if r != nil {
499 n.r = r.l
500 r.l = n
501 n.h = maxH(n) + 1
502 r.h = maxH(r) + 1
503 } else {
504 n.r = nil
505 n.h = maxH(n) + 1
506 }
507 return r
508 }
509
510 func (n *node) rotateR() *node {
511 l := n.l
512 if l != nil {
513 n.l = l.r
514 l.r = n
515 n.h = maxH(n) + 1
516 l.h = maxH(l) + 1
517 } else {
518 n.l = nil
519 n.h = maxH(n) + 1
520 }
521 return l
522 }
523
524 func balanceF(n *node) int {
525 if n == nil {
526 return 0
527 }
528 var lh, rh int
529 if n.l != nil {
530 lh = n.l.h
531 }
532 if n.r != nil {
533 rh = n.r.h
534 }
535 return lh - rh
536 }
537
538 func maxH(n *node) int {
539 if n == nil {
540 return 0
541 }
542 var lh, rh int
543 if n.l != nil {
544 lh = n.l.h
545 }
546 if n.r != nil {
547 rh = n.r.h
548 }
549 if lh > rh {
550 return lh
551 }
552 return rh
553 }
554
555 // Clear the proper bit.
556 // seq should have already been qualified and deleted should be non nil.
557 // Will return true if this node is now empty.
558 func (n *node) clear(seq uint64, deleted *bool) bool {
559 seq -= n.base
560 i := seq / bitsPerBucket
561 mask := uint64(1) << (seq % bitsPerBucket)
562 if (n.bits[i] & mask) == 0 {
563 // Nothing cleared, and nodes in the tree are never empty,
564 // so no need to scan the buckets.
565 return false
566 }
567 n.bits[i] &^= mask
568 *deleted = true
569 for _, b := range n.bits {
570 if b != 0 {
571 return false
572 }
573 }
574 return true
575 }
576
577 func (n *node) delete(seq uint64, deleted *bool, nodes *int) *node {
578 if n == nil {
579 return nil
580 }
581
582 if seq < n.base {
583 n.l = n.l.delete(seq, deleted, nodes)
584 } else if seq >= n.base+numEntries {
585 n.r = n.r.delete(seq, deleted, nodes)
586 } else if empty := n.clear(seq, deleted); empty {
587 *nodes--
588 if n.l == nil {
589 n = n.r
590 } else if n.r == nil {
591 n = n.l
592 } else {
593 // We have both children.
594 n.r = n.r.insertNodePrev(n.l)
595 n = n.r
596 }
597 }
598
599 if n != nil {
600 n.h = maxH(n) + 1
601 }
602
603 // Check balance.
604 if bf := balanceF(n); bf > 1 {
605 // Left unbalanced.
606 if balanceF(n.l) < 0 {
607 n.l = n.l.rotateL()
608 }
609 return n.rotateR()
610 } else if bf < -1 {
611 // right unbalanced.
612 if balanceF(n.r) > 0 {
613 n.r = n.r.rotateR()
614 }
615 return n.rotateL()
616 }
617
618 return n
619 }
620
621 // Will insert nn into the node assuming it is less than all other nodes in n.
622 // Will re-calculate height and balance.
623 func (n *node) insertNodePrev(nn *node) *node {
624 if n.l == nil {
625 n.l = nn
626 } else {
627 n.l = n.l.insertNodePrev(nn)
628 }
629 n.h = maxH(n) + 1
630
631 // Check balance.
632 if bf := balanceF(n); bf > 1 {
633 // Left unbalanced.
634 if balanceF(n.l) < 0 {
635 n.l = n.l.rotateL()
636 }
637 return n.rotateR()
638 } else if bf < -1 {
639 // right unbalanced.
640 if balanceF(n.r) > 0 {
641 n.r = n.r.rotateR()
642 }
643 return n.rotateL()
644 }
645 return n
646 }
647
648 func (n *node) exists(seq uint64) bool {
649 seq -= n.base
650 i := seq / bitsPerBucket
651 mask := uint64(1) << (seq % bitsPerBucket)
652 return n.bits[i]&mask != 0
653 }
654
655 // Return minimum sequence in the set.
656 // This node can not be empty.
657 func (n *node) min() uint64 {
658 for i, b := range n.bits {
659 if b != 0 {
660 return n.base +
661 uint64(i*bitsPerBucket) +
662 uint64(bits.TrailingZeros64(b))
663 }
664 }
665 return 0
666 }
667
668 // Return maximum sequence in the set.
669 // This node can not be empty.
670 func (n *node) max() uint64 {
671 for i := numBuckets - 1; i >= 0; i-- {
672 if b := n.bits[i]; b != 0 {
673 return n.base +
674 uint64(i*bitsPerBucket) +
675 uint64(bitsPerBucket-bits.LeadingZeros64(b>>1))
676 }
677 }
678 return 0
679 }
680
681 // This is done in tree order.
682 func (n *node) nodeIter(f func(n *node)) {
683 if n == nil {
684 return
685 }
686 f(n)
687 n.l.nodeIter(f)
688 n.r.nodeIter(f)
689 }
690
691 // iter will iterate through the set's items in this node.
692 // If the supplied function returns false we terminate the iteration.
693 func (n *node) iter(f func(uint64) bool) bool {
694 if n == nil {
695 return true
696 }
697
698 if ok := n.l.iter(f); !ok {
699 return false
700 }
701 for i, b := range n.bits {
702 base := n.base + uint64(i)*bitsPerBucket
703 for b != 0 {
704 if ok := f(base + uint64(bits.TrailingZeros64(b))); !ok {
705 return false
706 }
707 b &= b - 1
708 }
709 }
710 if ok := n.r.iter(f); !ok {
711 return false
712 }
713
714 return true
715 }