forked from cockroachdb/cockroach
-
Notifications
You must be signed in to change notification settings - Fork 0
/
interval.go
758 lines (669 loc) · 18.2 KB
/
interval.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
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
// Copyright ©2012 The bíogo Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package interval implements an interval tree based on an augmented
// Left-Leaning Red Black tree.
package interval
import (
"bytes"
"errors"
"fmt"
"github.com/biogo/store/llrb"
)
// Operation mode of the underlying LLRB tree.
const (
TD234 = iota
BU23
)
func init() {
if Mode != TD234 && Mode != BU23 {
panic("interval: unknown mode")
}
}
// ErrInvertedRange is returned if an interval is used where the start value is greater
// than the end value.
var ErrInvertedRange = errors.New("interval: inverted range")
// ErrEmptyRange is returned if an interval is used where the start value is equal
// to the end value.
var ErrEmptyRange = errors.New("interval: empty range")
func rangeError(r Range) error {
switch r.Start.Compare(r.End) {
case 1:
return ErrInvertedRange
case 0:
return ErrEmptyRange
default:
return nil
}
}
// A Range is a type that describes the basic characteristics of an interval.
type Range struct {
Start, End Comparable
}
// OverlapInclusive returns whether the two provided ranges overlap. It
// defines overlapping as a pair of ranges that share a segment, with both
// start and end keys treated as inclusive values.
func (r Range) OverlapInclusive(other Range) bool {
return r.End.Compare(other.Start) >= 0 && r.Start.Compare(other.End) <= 0
}
// OverlapExclusive returns whether the two provided ranges overlap. It defines
// overlapping as a pair of ranges that share a segment of the keyspace, with the
// start keys treated as inclusive and the end keys treated as exclusive.
func (r Range) OverlapExclusive(other Range) bool {
return r.End.Compare(other.Start) > 0 && r.Start.Compare(other.End) < 0
}
var _ = Range{}.Equal
// Equal returns whether the two ranges are equal.
func (r Range) Equal(other Range) bool {
return r.End.Equal(other.Start) && r.Start.Equal(other.End)
}
// String implements the Stringer interface.
func (r Range) String() string {
return fmt.Sprintf("[%x-%x)", r.Start, r.End)
}
// An Interface is a type that can be inserted into a Tree.
type Interface interface {
Range() Range
// Returns a unique ID for the element.
// TODO(nvanbenschoten): Should this be changed to an int64?
ID() uintptr
}
// A Comparable is a type that describes the ends of a Range.
type Comparable []byte
// Compare returns a value indicating the sort order relationship between the
// receiver and the parameter.
//
// Given c = a.Compare(b):
// c < 0 if a < b;
// c == 0 if a == b; and
// c > 0 if a > b.
//
func (c Comparable) Compare(o Comparable) int {
return bytes.Compare(c, o)
}
var _ = Comparable(nil).Equal
// Equal returns a boolean indicating if the given comparables are equal to
// each other. Note that this has measurably better performance than
// Compare() == 0, so it should be used when only equality state is needed.
func (c Comparable) Equal(o Comparable) bool {
return bytes.Equal(c, o)
}
// A Node represents a node in a Tree.
type Node struct {
Elem Interface
Range Range
Left, Right *Node
Color llrb.Color
}
// A Tree manages the root node of an interval tree. Public methods are exposed through this type.
type Tree struct {
Root *Node // root node of the tree.
Count int // number of elements stored.
Overlapper func(Range, Range) bool // determines how to define Range overlap.
}
// Helper methods
// color returns the effect color of a Node. A nil node returns black.
func (n *Node) color() llrb.Color {
if n == nil {
return llrb.Black
}
return n.Color
}
// maxRange returns the furthest right position held by the subtree
// rooted at root, assuming that the left and right nodes have correct
// range extents.
func maxRange(root, left, right *Node) Comparable {
end := root.Elem.Range().End
if left != nil && left.Range.End.Compare(end) > 0 {
end = left.Range.End
}
if right != nil && right.Range.End.Compare(end) > 0 {
end = right.Range.End
}
return end
}
// (a,c)b -rotL-> ((a,)b,)c
func (n *Node) rotateLeft() (root *Node) {
// Assumes: n has a right child.
root = n.Right
n.Right = root.Left
root.Left = n
root.Color = n.Color
n.Color = llrb.Red
root.Left.Range.End = maxRange(root.Left, root.Left.Left, root.Left.Right)
if root.Left == nil {
root.Range.Start = root.Elem.Range().Start
} else {
root.Range.Start = root.Left.Range.Start
}
root.Range.End = maxRange(root, root.Left, root.Right)
return
}
// (a,c)b -rotR-> (,(,c)b)a
func (n *Node) rotateRight() (root *Node) {
// Assumes: n has a left child.
root = n.Left
n.Left = root.Right
root.Right = n
root.Color = n.Color
n.Color = llrb.Red
if root.Right.Left == nil {
root.Right.Range.Start = root.Right.Elem.Range().Start
} else {
root.Right.Range.Start = root.Right.Left.Range.Start
}
root.Right.Range.End = maxRange(root.Right, root.Right.Left, root.Right.Right)
root.Range.End = maxRange(root, root.Left, root.Right)
return
}
// (aR,cR)bB -flipC-> (aB,cB)bR | (aB,cB)bR -flipC-> (aR,cR)bB
func (n *Node) flipColors() {
// Assumes: n has two children.
n.Color = !n.Color
n.Left.Color = !n.Left.Color
n.Right.Color = !n.Right.Color
}
// fixUp ensures that black link balance is correct, that red nodes lean left,
// and that 4 nodes are split in the case of BU23 and properly balanced in TD234.
func (n *Node) fixUp(fast bool) *Node {
if !fast {
n.adjustRange()
}
if n.Right.color() == llrb.Red {
if Mode == TD234 && n.Right.Left.color() == llrb.Red {
n.Right = n.Right.rotateRight()
}
n = n.rotateLeft()
}
if n.Left.color() == llrb.Red && n.Left.Left.color() == llrb.Red {
n = n.rotateRight()
}
if Mode == BU23 && n.Left.color() == llrb.Red && n.Right.color() == llrb.Red {
n.flipColors()
}
return n
}
// adjustRange sets the Range to the maximum extent of the children's Range
// spans and the node's Elem span.
func (n *Node) adjustRange() {
if n.Left == nil {
n.Range.Start = n.Elem.Range().Start
} else {
n.Range.Start = n.Left.Range.Start
}
n.Range.End = maxRange(n, n.Left, n.Right)
}
func (n *Node) moveRedLeft() *Node {
n.flipColors()
if n.Right.Left.color() == llrb.Red {
n.Right = n.Right.rotateRight()
n = n.rotateLeft()
n.flipColors()
if Mode == TD234 && n.Right.Right.color() == llrb.Red {
n.Right = n.Right.rotateLeft()
}
}
return n
}
func (n *Node) moveRedRight() *Node {
n.flipColors()
if n.Left.Left.color() == llrb.Red {
n = n.rotateRight()
n.flipColors()
}
return n
}
// Len returns the number of intervals stored in the Tree.
func (t *Tree) Len() int {
return t.Count
}
// Get returns a slice of Interfaces that overlap r in the Tree.
func (t *Tree) Get(r Range) (o []Interface) {
return t.GetWithOverlapper(r, t.Overlapper)
}
// GetWithOverlapper returns a slice of Interfaces that overlap r
// in the Tree using the provided overlapper function.
func (t *Tree) GetWithOverlapper(r Range, overlapper func(Range, Range) bool) (o []Interface) {
if t.Root != nil && overlapper(r, t.Root.Range) {
t.Root.doMatch(func(e Interface) (done bool) { o = append(o, e); return }, r, overlapper)
}
return
}
// AdjustRanges fixes range fields for all Nodes in the Tree. This must be called
// before Get or DoMatching* is used if fast insertion or deletion has been performed.
func (t *Tree) AdjustRanges() {
if t.Root == nil {
return
}
t.Root.adjustRanges()
}
func (n *Node) adjustRanges() {
if n.Left != nil {
n.Left.adjustRanges()
}
if n.Right != nil {
n.Right.adjustRanges()
}
n.adjustRange()
}
// Insert inserts the Interface e into the Tree. Insertions may replace
// existing stored intervals.
func (t *Tree) Insert(e Interface, fast bool) (err error) {
r := e.Range()
if err := rangeError(r); err != nil {
return err
}
var d int
t.Root, d = t.Root.insert(e, r.Start, e.ID(), fast)
t.Count += d
t.Root.Color = llrb.Black
return
}
func (n *Node) insert(e Interface, min Comparable, id uintptr, fast bool) (root *Node, d int) {
if n == nil {
return &Node{Elem: e, Range: e.Range()}, 1
} else if n.Elem == nil {
n.Elem = e
if !fast {
n.adjustRange()
}
return n, 1
}
if Mode == TD234 {
if n.Left.color() == llrb.Red && n.Right.color() == llrb.Red {
n.flipColors()
}
}
switch c := min.Compare(n.Elem.Range().Start); {
case c == 0:
switch eid := n.Elem.ID(); {
case id == eid:
n.Elem = e
if !fast {
n.Range.End = e.Range().End
}
case id < eid:
n.Left, d = n.Left.insert(e, min, id, fast)
default:
n.Right, d = n.Right.insert(e, min, id, fast)
}
case c < 0:
n.Left, d = n.Left.insert(e, min, id, fast)
default:
n.Right, d = n.Right.insert(e, min, id, fast)
}
if n.Right.color() == llrb.Red && n.Left.color() == llrb.Black {
n = n.rotateLeft()
}
if n.Left.color() == llrb.Red && n.Left.Left.color() == llrb.Red {
n = n.rotateRight()
}
if Mode == BU23 {
if n.Left.color() == llrb.Red && n.Right.color() == llrb.Red {
n.flipColors()
}
}
if !fast {
n.adjustRange()
}
root = n
return
}
var _ = (*Tree)(nil).DeleteMin
// DeleteMin deletes the left-most interval.
func (t *Tree) DeleteMin(fast bool) {
if t.Root == nil {
return
}
var d int
t.Root, d = t.Root.deleteMin(fast)
t.Count += d
if t.Root == nil {
return
}
t.Root.Color = llrb.Black
}
func (n *Node) deleteMin(fast bool) (root *Node, d int) {
if n.Left == nil {
return nil, -1
}
if n.Left.color() == llrb.Black && n.Left.Left.color() == llrb.Black {
n = n.moveRedLeft()
}
n.Left, d = n.Left.deleteMin(fast)
if n.Left == nil {
n.Range.Start = n.Elem.Range().Start
}
root = n.fixUp(fast)
return
}
var _ = (*Tree)(nil).DeleteMax
// DeleteMax deletes the right-most interval.
func (t *Tree) DeleteMax(fast bool) {
if t.Root == nil {
return
}
var d int
t.Root, d = t.Root.deleteMax(fast)
t.Count += d
if t.Root == nil {
return
}
t.Root.Color = llrb.Black
}
func (n *Node) deleteMax(fast bool) (root *Node, d int) {
if n.Left != nil && n.Left.color() == llrb.Red {
n = n.rotateRight()
}
if n.Right == nil {
return nil, -1
}
if n.Right.color() == llrb.Black && n.Right.Left.color() == llrb.Black {
n = n.moveRedRight()
}
n.Right, d = n.Right.deleteMax(fast)
if n.Right == nil {
n.Range.End = n.Elem.Range().End
}
root = n.fixUp(fast)
return
}
// Delete deletes the element e if it exists in the Tree.
func (t *Tree) Delete(e Interface, fast bool) (err error) {
r := e.Range()
if err := rangeError(r); err != nil {
return err
}
if t.Root == nil || !t.Overlapper(r, t.Root.Range) {
return
}
var d int
t.Root, d = t.Root.delete(r.Start, e.ID(), fast)
t.Count += d
if t.Root == nil {
return
}
t.Root.Color = llrb.Black
return
}
func (n *Node) delete(min Comparable, id uintptr, fast bool) (root *Node, d int) {
if p := min.Compare(n.Elem.Range().Start); p < 0 || (p == 0 && id < n.Elem.ID()) {
if n.Left != nil {
if n.Left.color() == llrb.Black && n.Left.Left.color() == llrb.Black {
n = n.moveRedLeft()
}
n.Left, d = n.Left.delete(min, id, fast)
if n.Left == nil {
n.Range.Start = n.Elem.Range().Start
}
}
} else {
if n.Left.color() == llrb.Red {
n = n.rotateRight()
}
if n.Right == nil && id == n.Elem.ID() {
return nil, -1
}
if n.Right != nil {
if n.Right.color() == llrb.Black && n.Right.Left.color() == llrb.Black {
n = n.moveRedRight()
}
if id == n.Elem.ID() {
n.Elem = n.Right.min().Elem
n.Right, d = n.Right.deleteMin(fast)
} else {
n.Right, d = n.Right.delete(min, id, fast)
}
if n.Right == nil {
n.Range.End = n.Elem.Range().End
}
}
}
root = n.fixUp(fast)
return
}
var _ = (*Tree)(nil).Min
// Min returns the left-most interval stored in the tree.
func (t *Tree) Min() Interface {
if t.Root == nil {
return nil
}
return t.Root.min().Elem
}
func (n *Node) min() *Node {
for ; n.Left != nil; n = n.Left {
}
return n
}
var _ = (*Tree)(nil).Max
// Max returns the right-most interval stored in the tree.
func (t *Tree) Max() Interface {
if t.Root == nil {
return nil
}
return t.Root.max().Elem
}
func (n *Node) max() *Node {
for ; n.Right != nil; n = n.Right {
}
return n
}
var _ = (*Tree)(nil).Floor
// Floor returns the largest value equal to or less than the query q according to
// q.Start.Compare(), with ties broken by comparison of ID() values.
func (t *Tree) Floor(q Interface) (o Interface, err error) {
if t.Root == nil {
return
}
n := t.Root.floor(q.Range().Start, q.ID())
if n == nil {
return
}
return n.Elem, nil
}
func (n *Node) floor(m Comparable, id uintptr) *Node {
if n == nil {
return nil
}
switch c := m.Compare(n.Elem.Range().Start); {
case c == 0:
switch eid := n.Elem.ID(); {
case id == eid:
return n
case id < eid:
return n.Left.floor(m, id)
default:
if r := n.Right.floor(m, id); r != nil {
return r
}
}
case c < 0:
return n.Left.floor(m, id)
default:
if r := n.Right.floor(m, id); r != nil {
return r
}
}
return n
}
var _ = (*Tree)(nil).Ceil
// Ceil returns the smallest value equal to or greater than the query q according to
// q.Start.Compare(), with ties broken by comparison of ID() values.
func (t *Tree) Ceil(q Interface) (o Interface, err error) {
if t.Root == nil {
return
}
n := t.Root.ceil(q.Range().Start, q.ID())
if n == nil {
return
}
return n.Elem, nil
}
func (n *Node) ceil(m Comparable, id uintptr) *Node {
if n == nil {
return nil
}
switch c := m.Compare(n.Elem.Range().Start); {
case c == 0:
switch eid := n.Elem.ID(); {
case id == eid:
return n
case id > eid:
return n.Right.ceil(m, id)
default:
if l := n.Left.ceil(m, id); l != nil {
return l
}
}
case c > 0:
return n.Right.ceil(m, id)
default:
if l := n.Left.ceil(m, id); l != nil {
return l
}
}
return n
}
// An Operation is a function that operates on an Interface. If done is returned true, the
// Operation is indicating that no further work needs to be done and so the Do function should
// traverse no further.
type Operation func(Interface) (done bool)
// Do performs fn on all intervals stored in the tree. A boolean is returned indicating whether the
// Do traversal was interrupted by an Operation returning true. If fn alters stored intervals' sort
// relationships, future tree operation behaviors are undefined.
func (t *Tree) Do(fn Operation) bool {
if t.Root == nil {
return false
}
return t.Root.do(fn)
}
func (n *Node) do(fn Operation) (done bool) {
if n.Left != nil {
done = n.Left.do(fn)
if done {
return
}
}
done = fn(n.Elem)
if done {
return
}
if n.Right != nil {
done = n.Right.do(fn)
}
return
}
var _ = (*Tree)(nil).DoReverse
// DoReverse performs fn on all intervals stored in the tree, but in reverse of sort order. A boolean
// is returned indicating whether the Do traversal was interrupted by an Operation returning true.
// If fn alters stored intervals' sort relationships, future tree operation behaviors are undefined.
func (t *Tree) DoReverse(fn Operation) bool {
if t.Root == nil {
return false
}
return t.Root.doReverse(fn)
}
func (n *Node) doReverse(fn Operation) (done bool) {
if n.Right != nil {
done = n.Right.doReverse(fn)
if done {
return
}
}
done = fn(n.Elem)
if done {
return
}
if n.Left != nil {
done = n.Left.doReverse(fn)
}
return
}
// DoMatching performs fn on all intervals stored in the tree that match r according to
// t.Overlapper, with Overlapper() used to guide tree traversal, so DoMatching() will
// outperform Do() with a called conditional function if the condition is based on sort
// order, but can not be reliably used if the condition is independent of sort order. A
// boolean is returned indicating whether the Do traversal was interrupted by an Operation
// returning true. If fn alters stored intervals' sort relationships, future tree operation
// behaviors are undefined.
func (t *Tree) DoMatching(fn Operation, r Range) bool {
if t.Root != nil && t.Overlapper(r, t.Root.Range) {
return t.Root.doMatch(fn, r, t.Overlapper)
}
return false
}
func (n *Node) doMatch(fn Operation, r Range, overlaps func(Range, Range) bool) (done bool) {
if n.Left != nil && overlaps(r, n.Left.Range) {
done = n.Left.doMatch(fn, r, overlaps)
if done {
return
}
}
if overlaps(r, n.Elem.Range()) {
done = fn(n.Elem)
if done {
return
}
}
if n.Right != nil && overlaps(r, n.Right.Range) {
done = n.Right.doMatch(fn, r, overlaps)
}
return
}
var _ = (*Tree)(nil).DoMatchingReverse
// DoMatchingReverse performs fn on all intervals stored in the tree that match r according to
// t.Overlapper, with Overlapper() used to guide tree traversal, so DoMatching() will outperform
// Do() with a called conditional function if the condition is based on sort order, but can not
// be reliably used if the condition is independent of sort order. A boolean is returned indicating
// whether the Do traversal was interrupted by an Operation returning true. If fn alters stored
// intervals' sort relationships, future tree operation behaviors are undefined.
func (t *Tree) DoMatchingReverse(fn Operation, r Range) bool {
if t.Root != nil && t.Overlapper(r, t.Root.Range) {
return t.Root.doMatchReverse(fn, r, t.Overlapper)
}
return false
}
func (n *Node) doMatchReverse(fn Operation, r Range, overlaps func(Range, Range) bool) (done bool) {
if n.Right != nil && overlaps(r, n.Right.Range) {
done = n.Right.doMatchReverse(fn, r, overlaps)
if done {
return
}
}
if overlaps(r, n.Elem.Range()) {
done = fn(n.Elem)
if done {
return
}
}
if n.Left != nil && overlaps(r, n.Left.Range) {
done = n.Left.doMatchReverse(fn, r, overlaps)
}
return
}
// TreeIterator iterates over all intervals stored in the Tree, in-order.
type TreeIterator struct {
stack []*Node
}
// Next moves the iterator to the next Node in the Tree and returns the node's
// Elem. The method returns false if no Nodes remain in the Tree.
func (ti *TreeIterator) Next() (i Interface, ok bool) {
if len(ti.stack) == 0 {
return nil, false
}
n := ti.stack[len(ti.stack)-1]
ti.stack = ti.stack[:len(ti.stack)-1]
for r := n.Right; r != nil; r = r.Left {
ti.stack = append(ti.stack, r)
}
return n.Elem, true
}
// Iterator creates an iterator to iterate over all intervals stored in the
// tree, in-order.
func (t *Tree) Iterator() TreeIterator {
var ti TreeIterator
for n := t.Root; n != nil; n = n.Left {
ti.stack = append(ti.stack, n)
}
return ti
}