Debian Codegraph @

interval/interval.go

raw symbols SCIP
1 // Copyright ©2012 The bíogo 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 // Package interval implements an interval tree based on an augmented
6 // Left-Leaning Red Black tree.
7 package interval
8
9 import (
10 "errors"
11
12 "github.com/biogo/store/llrb"
13 )
14
15 // Operation mode of the underlying LLRB tree.
16 const (
17 TD234 = iota
18 BU23
19 )
20
21 func init() {
22 if Mode != TD234 && Mode != BU23 {
23 panic("interval: unknown mode")
24 }
25 }
26
27 // ErrInvertedRange is returned if an interval is used where the start value is greater
28 // than the end value.
29 var ErrInvertedRange = errors.New("interval: inverted range")
30
31 // An Overlapper can determine whether it overlaps a range.
32 type Overlapper interface {
33 // Overlap returns a boolean indicating whether the receiver overlaps the parameter.
34 Overlap(Range) bool
35 }
36
37 // A Range is a type that describes the basic characteristics of an interval.
38 type Range interface {
39 // Return a Comparable equal to the start value of the Overlapper.
40 Start() Comparable
41 // Return a Comparable equal to the end value of the Overlapper.
42 End() Comparable
43 }
44
45 // An Interface is a type that can be inserted into a Tree.
46 type Interface interface {
47 Overlapper
48 Range
49 ID() uintptr // Returns a unique ID for the element.
50 NewMutable() Mutable // Returns an mutable copy of the Interface's range.
51 }
52
53 // A Mutable is a Range that can have its range altered.
54 type Mutable interface {
55 Range
56 SetStart(Comparable) // Set the start value.
57 SetEnd(Comparable) // Set the end value.
58 }
59
60 // A Comparable is a type that describes the ends of an Overlapper.
61 type Comparable interface {
62 // Compare returns a value indicating the sort order relationship between the
63 // receiver and the parameter.
64 //
65 // Given c = a.Compare(b):
66 // c < 0 if a < b;
67 // c == 0 if a == b; and
68 // c > 0 if a > b.
69 //
70 Compare(Comparable) int
71 }
72
73 // A Node represents a node in a Tree.
74 type Node struct {
75 Elem Interface
76 Range Mutable
77 Left, Right *Node
78 Color llrb.Color
79 }
80
81 // A Tree manages the root node of an interval tree. Public methods are exposed through this type.
82 type Tree struct {
83 Root *Node // Root node of the tree.
84 Count int // Number of elements stored.
85 }
86
87 // Helper methods
88
89 // color returns the effect color of a Node. A nil node returns black.
90 func (n *Node) color() llrb.Color {
91 if n == nil {
92 return llrb.Black
93 }
94 return n.Color
95 }
96
97 // maxRange returns the furthest right position held by the subtree
98 // rooted at root, assuming that the left and right nodes have correct
99 // range extents.
100 func maxRange(root, left, right *Node) Comparable {
101 end := root.Elem.End()
102 if left != nil && left.Range.End().Compare(end) > 0 {
103 end = left.Range.End()
104 }
105 if right != nil && right.Range.End().Compare(end) > 0 {
106 end = right.Range.End()
107 }
108 return end
109 }
110
111 // (a,c)b -rotL-> ((a,)b,)c
112 func (n *Node) rotateLeft() (root *Node) {
113 // Assumes: n has a right child.
114 root = n.Right
115 n.Right = root.Left
116 root.Left = n
117 root.Color = n.Color
118 n.Color = llrb.Red
119
120 root.Left.Range.SetEnd(maxRange(root.Left, root.Left.Left, root.Left.Right))
121 if root.Left == nil {
122 root.Range.SetStart(root.Elem.Start())
123 } else {
124 root.Range.SetStart(root.Left.Range.Start())
125 }
126 root.Range.SetEnd(maxRange(root, root.Left, root.Right))
127
128 return
129 }
130
131 // (a,c)b -rotR-> (,(,c)b)a
132 func (n *Node) rotateRight() (root *Node) {
133 // Assumes: n has a left child.
134 root = n.Left
135 n.Left = root.Right
136 root.Right = n
137 root.Color = n.Color
138 n.Color = llrb.Red
139
140 if root.Right.Left == nil {
141 root.Right.Range.SetStart(root.Right.Elem.Start())
142 } else {
143 root.Right.Range.SetStart(root.Right.Left.Range.Start())
144 }
145 root.Right.Range.SetEnd(maxRange(root.Right, root.Right.Left, root.Right.Right))
146 root.Range.SetEnd(maxRange(root, root.Left, root.Right))
147
148 return
149 }
150
151 // (aR,cR)bB -flipC-> (aB,cB)bR | (aB,cB)bR -flipC-> (aR,cR)bB
152 func (n *Node) flipColors() {
153 // Assumes: n has two children.
154 n.Color = !n.Color
155 n.Left.Color = !n.Left.Color
156 n.Right.Color = !n.Right.Color
157 }
158
159 // fixUp ensures that black link balance is correct, that red nodes lean left,
160 // and that 4 nodes are split in the case of BU23 and properly balanced in TD234.
161 func (n *Node) fixUp(fast bool) *Node {
162 if !fast {
163 n.adjustRange()
164 }
165 if n.Right.color() == llrb.Red {
166 if Mode == TD234 && n.Right.Left.color() == llrb.Red {
167 n.Right = n.Right.rotateRight()
168 }
169 n = n.rotateLeft()
170 }
171 if n.Left.color() == llrb.Red && n.Left.Left.color() == llrb.Red {
172 n = n.rotateRight()
173 }
174 if Mode == BU23 && n.Left.color() == llrb.Red && n.Right.color() == llrb.Red {
175 n.flipColors()
176 }
177
178 return n
179 }
180
181 // adjustRange sets the Range to the maximum extent of the childrens' Range
182 // spans and the node's Elem span.
183 func (n *Node) adjustRange() {
184 if n.Left == nil {
185 n.Range.SetStart(n.Elem.Start())
186 } else {
187 n.Range.SetStart(n.Left.Range.Start())
188 }
189 n.Range.SetEnd(maxRange(n, n.Left, n.Right))
190 }
191
192 func (n *Node) moveRedLeft() *Node {
193 n.flipColors()
194 if n.Right.Left.color() == llrb.Red {
195 n.Right = n.Right.rotateRight()
196 n = n.rotateLeft()
197 n.flipColors()
198 if Mode == TD234 && n.Right.Right.color() == llrb.Red {
199 n.Right = n.Right.rotateLeft()
200 }
201 }
202 return n
203 }
204
205 func (n *Node) moveRedRight() *Node {
206 n.flipColors()
207 if n.Left.Left.color() == llrb.Red {
208 n = n.rotateRight()
209 n.flipColors()
210 }
211 return n
212 }
213
214 // Len returns the number of intervals stored in the Tree.
215 func (t *Tree) Len() int {
216 return t.Count
217 }
218
219 // Get returns a slice of Interfaces that overlap q in the Tree according
220 // to q.Overlap().
221 func (t *Tree) Get(q Overlapper) (o []Interface) {
222 if t.Root != nil && q.Overlap(t.Root.Range) {
223 t.Root.doMatch(func(e Interface) (done bool) { o = append(o, e); return }, q)
224 }
225 return
226 }
227
228 // AdjustRanges fixes range fields for all Nodes in the Tree. This must be called
229 // before Get or DoMatching* is used if fast insertion or deletion has been performed.
230 func (t *Tree) AdjustRanges() {
231 if t.Root == nil {
232 return
233 }
234 t.Root.adjustRanges()
235 }
236
237 func (n *Node) adjustRanges() {
238 if n.Left != nil {
239 n.Left.adjustRanges()
240 }
241 if n.Right != nil {
242 n.Right.adjustRanges()
243 }
244 n.adjustRange()
245 }
246
247 // Insert inserts the Interface e into the Tree. Insertions may replace
248 // existing stored intervals.
249 func (t *Tree) Insert(e Interface, fast bool) (err error) {
250 if e.Start().Compare(e.End()) > 0 {
251 return ErrInvertedRange
252 }
253 var d int
254 t.Root, d = t.Root.insert(e, e.Start(), e.ID(), fast)
255 t.Count += d
256 t.Root.Color = llrb.Black
257 return
258 }
259
260 func (n *Node) insert(e Interface, min Comparable, id uintptr, fast bool) (root *Node, d int) {
261 if n == nil {
262 return &Node{Elem: e, Range: e.NewMutable()}, 1
263 } else if n.Elem == nil {
264 n.Elem = e
265 if !fast {
266 n.adjustRange()
267 }
268 return n, 1
269 }
270
271 if Mode == TD234 {
272 if n.Left.color() == llrb.Red && n.Right.color() == llrb.Red {
273 n.flipColors()
274 }
275 }
276
277 switch c := min.Compare(n.Elem.Start()); {
278 case c == 0:
279 switch {
280 case id == n.Elem.ID():
281 n.Elem = e
282 if !fast {
283 n.Range.SetEnd(e.End())
284 }
285 case id < n.Elem.ID():
286 n.Left, d = n.Left.insert(e, min, id, fast)
287 default:
288 n.Right, d = n.Right.insert(e, min, id, fast)
289 }
290 case c < 0:
291 n.Left, d = n.Left.insert(e, min, id, fast)
292 default:
293 n.Right, d = n.Right.insert(e, min, id, fast)
294 }
295
296 if n.Right.color() == llrb.Red && n.Left.color() == llrb.Black {
297 n = n.rotateLeft()
298 }
299 if n.Left.color() == llrb.Red && n.Left.Left.color() == llrb.Red {
300 n = n.rotateRight()
301 }
302
303 if Mode == BU23 {
304 if n.Left.color() == llrb.Red && n.Right.color() == llrb.Red {
305 n.flipColors()
306 }
307 }
308
309 if !fast {
310 n.adjustRange()
311 }
312 root = n
313
314 return
315 }
316
317 // DeleteMin deletes the left-most interval.
318 func (t *Tree) DeleteMin(fast bool) {
319 if t.Root == nil {
320 return
321 }
322 var d int
323 t.Root, d = t.Root.deleteMin(fast)
324 t.Count += d
325 if t.Root == nil {
326 return
327 }
328 t.Root.Color = llrb.Black
329 }
330
331 func (n *Node) deleteMin(fast bool) (root *Node, d int) {
332 if n.Left == nil {
333 return nil, -1
334 }
335 if n.Left.color() == llrb.Black && n.Left.Left.color() == llrb.Black {
336 n = n.moveRedLeft()
337 }
338 n.Left, d = n.Left.deleteMin(fast)
339 if n.Left == nil {
340 n.Range.SetStart(n.Elem.Start())
341 }
342
343 root = n.fixUp(fast)
344
345 return
346 }
347
348 // DeleteMax deletes the right-most interval.
349 func (t *Tree) DeleteMax(fast bool) {
350 if t.Root == nil {
351 return
352 }
353 var d int
354 t.Root, d = t.Root.deleteMax(fast)
355 t.Count += d
356 if t.Root == nil {
357 return
358 }
359 t.Root.Color = llrb.Black
360 }
361
362 func (n *Node) deleteMax(fast bool) (root *Node, d int) {
363 if n.Left != nil && n.Left.color() == llrb.Red {
364 n = n.rotateRight()
365 }
366 if n.Right == nil {
367 return nil, -1
368 }
369 if n.Right.color() == llrb.Black && n.Right.Left.color() == llrb.Black {
370 n = n.moveRedRight()
371 }
372 n.Right, d = n.Right.deleteMax(fast)
373 if n.Right == nil {
374 n.Range.SetEnd(n.Elem.End())
375 }
376
377 root = n.fixUp(fast)
378
379 return
380 }
381
382 // Delete deletes the element e if it exists in the Tree.
383 func (t *Tree) Delete(e Interface, fast bool) (err error) {
384 if e.Start().Compare(e.End()) > 0 {
385 return ErrInvertedRange
386 }
387 if t.Root == nil || !e.Overlap(t.Root.Range) {
388 return
389 }
390 var d int
391 t.Root, d = t.Root.delete(e.Start(), e.ID(), fast)
392 t.Count += d
393 if t.Root == nil {
394 return
395 }
396 t.Root.Color = llrb.Black
397 return
398 }
399
400 func (n *Node) delete(min Comparable, id uintptr, fast bool) (root *Node, d int) {
401 if p := min.Compare(n.Elem.Start()); p < 0 || (p == 0 && id < n.Elem.ID()) {
402 if n.Left != nil {
403 if n.Left.color() == llrb.Black && n.Left.Left.color() == llrb.Black {
404 n = n.moveRedLeft()
405 }
406 n.Left, d = n.Left.delete(min, id, fast)
407 if n.Left == nil {
408 n.Range.SetStart(n.Elem.Start())
409 }
410 }
411 } else {
412 if n.Left.color() == llrb.Red {
413 n = n.rotateRight()
414 }
415 if n.Right == nil && id == n.Elem.ID() {
416 return nil, -1
417 }
418 if n.Right != nil {
419 if n.Right.color() == llrb.Black && n.Right.Left.color() == llrb.Black {
420 n = n.moveRedRight()
421 }
422 if id == n.Elem.ID() {
423 n.Elem = n.Right.min().Elem
424 n.Right, d = n.Right.deleteMin(fast)
425 } else {
426 n.Right, d = n.Right.delete(min, id, fast)
427 }
428 if n.Right == nil {
429 n.Range.SetEnd(n.Elem.End())
430 }
431 }
432 }
433
434 root = n.fixUp(fast)
435
436 return
437 }
438
439 // Return the left-most interval stored in the tree.
440 func (t *Tree) Min() Interface {
441 if t.Root == nil {
442 return nil
443 }
444 return t.Root.min().Elem
445 }
446
447 func (n *Node) min() *Node {
448 for ; n.Left != nil; n = n.Left {
449 }
450 return n
451 }
452
453 // Return the right-most interval stored in the tree.
454 func (t *Tree) Max() Interface {
455 if t.Root == nil {
456 return nil
457 }
458 return t.Root.max().Elem
459 }
460
461 func (n *Node) max() *Node {
462 for ; n.Right != nil; n = n.Right {
463 }
464 return n
465 }
466
467 // Floor returns the largest value equal to or less than the query q according to
468 // q.Start().Compare(), with ties broken by comparison of ID() values.
469 func (t *Tree) Floor(q Interface) (o Interface, err error) {
470 if t.Root == nil {
471 return
472 }
473 n := t.Root.floor(q.Start(), q.ID())
474 if n == nil {
475 return
476 }
477 return n.Elem, nil
478 }
479
480 func (n *Node) floor(m Comparable, id uintptr) *Node {
481 if n == nil {
482 return nil
483 }
484 switch c := m.Compare(n.Elem.Start()); {
485 case c == 0:
486 switch {
487 case id == n.Elem.ID():
488 return n
489 case id < n.Elem.ID():
490 return n.Left.floor(m, id)
491 default:
492 if r := n.Right.floor(m, id); r != nil {
493 return r
494 }
495 }
496 case c < 0:
497 return n.Left.floor(m, id)
498 default:
499 if r := n.Right.floor(m, id); r != nil {
500 return r
501 }
502 }
503 return n
504 }
505
506 // Ceil returns the smallest value equal to or greater than the query q according to
507 // q.Start().Compare(), with ties broken by comparison of ID() values.
508 func (t *Tree) Ceil(q Interface) (o Interface, err error) {
509 if t.Root == nil {
510 return
511 }
512 n := t.Root.ceil(q.Start(), q.ID())
513 if n == nil {
514 return
515 }
516 return n.Elem, nil
517 }
518
519 func (n *Node) ceil(m Comparable, id uintptr) *Node {
520 if n == nil {
521 return nil
522 }
523 switch c := m.Compare(n.Elem.Start()); {
524 case c == 0:
525 switch {
526 case id == n.Elem.ID():
527 return n
528 case id > n.Elem.ID():
529 return n.Right.ceil(m, id)
530 default:
531 if l := n.Left.ceil(m, id); l != nil {
532 return l
533 }
534 }
535 case c > 0:
536 return n.Right.ceil(m, id)
537 default:
538 if l := n.Left.ceil(m, id); l != nil {
539 return l
540 }
541 }
542 return n
543 }
544
545 // An Operation is a function that operates on an Interface. If done is returned true, the
546 // Operation is indicating that no further work needs to be done and so the Do function should
547 // traverse no further.
548 type Operation func(Interface) (done bool)
549
550 // Do performs fn on all intervals stored in the tree. A boolean is returned indicating whether the
551 // Do traversal was interrupted by an Operation returning true. If fn alters stored intervals' sort
552 // relationships, future tree operation behaviors are undefined.
553 func (t *Tree) Do(fn Operation) bool {
554 if t.Root == nil {
555 return false
556 }
557 return t.Root.do(fn)
558 }
559
560 func (n *Node) do(fn Operation) (done bool) {
561 if n.Left != nil {
562 done = n.Left.do(fn)
563 if done {
564 return
565 }
566 }
567 done = fn(n.Elem)
568 if done {
569 return
570 }
571 if n.Right != nil {
572 done = n.Right.do(fn)
573 }
574 return
575 }
576
577 // DoReverse performs fn on all intervals stored in the tree, but in reverse of sort order. A boolean
578 // is returned indicating whether the Do traversal was interrupted by an Operation returning true.
579 // If fn alters stored intervals' sort relationships, future tree operation behaviors are undefined.
580 func (t *Tree) DoReverse(fn Operation) bool {
581 if t.Root == nil {
582 return false
583 }
584 return t.Root.doReverse(fn)
585 }
586
587 func (n *Node) doReverse(fn Operation) (done bool) {
588 if n.Right != nil {
589 done = n.Right.doReverse(fn)
590 if done {
591 return
592 }
593 }
594 done = fn(n.Elem)
595 if done {
596 return
597 }
598 if n.Left != nil {
599 done = n.Left.doReverse(fn)
600 }
601 return
602 }
603
604 // DoMatch performs fn on all intervals stored in the tree that match q according to Overlap, with
605 // q.Overlap() used to guide tree traversal, so DoMatching() will out perform Do() with a called
606 // conditional function if the condition is based on sort order, but can not be reliably used if
607 // the condition is independent of sort order. A boolean is returned indicating whether the Do
608 // traversal was interrupted by an Operation returning true. If fn alters stored intervals' sort
609 // relationships, future tree operation behaviors are undefined.
610 func (t *Tree) DoMatching(fn Operation, q Overlapper) bool {
611 if t.Root != nil && q.Overlap(t.Root.Range) {
612 return t.Root.doMatch(fn, q)
613 }
614 return false
615 }
616
617 func (n *Node) doMatch(fn Operation, q Overlapper) (done bool) {
618 if n.Left != nil && q.Overlap(n.Left.Range) {
619 done = n.Left.doMatch(fn, q)
620 if done {
621 return
622 }
623 }
624 if q.Overlap(n.Elem) {
625 done = fn(n.Elem)
626 if done {
627 return
628 }
629 }
630 if n.Right != nil && q.Overlap(n.Right.Range) {
631 done = n.Right.doMatch(fn, q)
632 }
633 return
634 }
635
636 // DoMatchReverse performs fn on all intervals stored in the tree that match q according to Overlap,
637 // with q.Overlap() used to guide tree traversal, so DoMatching() will out perform Do() with a called
638 // conditional function if the condition is based on sort order, but can not be reliably used if
639 // the condition is independent of sort order. A boolean is returned indicating whether the Do
640 // traversal was interrupted by an Operation returning true. If fn alters stored intervals' sort
641 // relationships, future tree operation behaviors are undefined.
642 func (t *Tree) DoMatchingReverse(fn Operation, q Overlapper) bool {
643 if t.Root != nil && q.Overlap(t.Root.Range) {
644 return t.Root.doMatch(fn, q)
645 }
646 return false
647 }
648
649 func (n *Node) doMatchReverse(fn Operation, q Overlapper) (done bool) {
650 if n.Right != nil && q.Overlap(n.Right.Range) {
651 done = n.Right.doMatchReverse(fn, q)
652 if done {
653 return
654 }
655 }
656 if q.Overlap(n.Elem) {
657 done = fn(n.Elem)
658 if done {
659 return
660 }
661 }
662 if n.Left != nil && q.Overlap(n.Left.Range) {
663 done = n.Left.doMatchReverse(fn, q)
664 }
665 return
666 }