interval_tree.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709
  1. // Copyright 2016 The etcd Authors
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package adt
  15. import (
  16. "bytes"
  17. "fmt"
  18. "math"
  19. "strings"
  20. )
  21. // Comparable is an interface for trichotomic comparisons.
  22. type Comparable interface {
  23. // Compare gives the result of a 3-way comparison
  24. // a.Compare(b) = 1 => a > b
  25. // a.Compare(b) = 0 => a == b
  26. // a.Compare(b) = -1 => a < b
  27. Compare(c Comparable) int
  28. }
  29. type rbcolor int
  30. const (
  31. black rbcolor = iota
  32. red
  33. )
  34. func (c rbcolor) String() string {
  35. switch c {
  36. case black:
  37. return "black"
  38. case red:
  39. return "black"
  40. default:
  41. panic(fmt.Errorf("unknown color %d", c))
  42. }
  43. }
  44. // Interval implements a Comparable interval [begin, end)
  45. // TODO: support different sorts of intervals: (a,b), [a,b], (a, b]
  46. type Interval struct {
  47. Begin Comparable
  48. End Comparable
  49. }
  50. // Compare on an interval gives == if the interval overlaps.
  51. func (ivl *Interval) Compare(c Comparable) int {
  52. ivl2 := c.(*Interval)
  53. ivbCmpBegin := ivl.Begin.Compare(ivl2.Begin)
  54. ivbCmpEnd := ivl.Begin.Compare(ivl2.End)
  55. iveCmpBegin := ivl.End.Compare(ivl2.Begin)
  56. // ivl is left of ivl2
  57. if ivbCmpBegin < 0 && iveCmpBegin <= 0 {
  58. return -1
  59. }
  60. // iv is right of iv2
  61. if ivbCmpEnd >= 0 {
  62. return 1
  63. }
  64. return 0
  65. }
  66. type intervalNode struct {
  67. // iv is the interval-value pair entry.
  68. iv IntervalValue
  69. // max endpoint of all descendent nodes.
  70. max Comparable
  71. // left and right are sorted by low endpoint of key interval
  72. left, right *intervalNode
  73. // parent is the direct ancestor of the node
  74. parent *intervalNode
  75. c rbcolor
  76. }
  77. func (x *intervalNode) color() rbcolor {
  78. if x == nil {
  79. return black
  80. }
  81. return x.c
  82. }
  83. func (x *intervalNode) height() int {
  84. if x == nil {
  85. return 0
  86. }
  87. ld := x.left.height()
  88. rd := x.right.height()
  89. if ld < rd {
  90. return rd + 1
  91. }
  92. return ld + 1
  93. }
  94. func (x *intervalNode) min() *intervalNode {
  95. for x.left != nil {
  96. x = x.left
  97. }
  98. return x
  99. }
  100. // successor is the next in-order node in the tree
  101. func (x *intervalNode) successor() *intervalNode {
  102. if x.right != nil {
  103. return x.right.min()
  104. }
  105. y := x.parent
  106. for y != nil && x == y.right {
  107. x = y
  108. y = y.parent
  109. }
  110. return y
  111. }
  112. // updateMax updates the maximum values for a node and its ancestors
  113. func (x *intervalNode) updateMax() {
  114. for x != nil {
  115. oldmax := x.max
  116. max := x.iv.Ivl.End
  117. if x.left != nil && x.left.max.Compare(max) > 0 {
  118. max = x.left.max
  119. }
  120. if x.right != nil && x.right.max.Compare(max) > 0 {
  121. max = x.right.max
  122. }
  123. if oldmax.Compare(max) == 0 {
  124. break
  125. }
  126. x.max = max
  127. x = x.parent
  128. }
  129. }
  130. type nodeVisitor func(n *intervalNode) bool
  131. // visit will call a node visitor on each node that overlaps the given interval
  132. func (x *intervalNode) visit(iv *Interval, nv nodeVisitor) bool {
  133. if x == nil {
  134. return true
  135. }
  136. v := iv.Compare(&x.iv.Ivl)
  137. switch {
  138. case v < 0:
  139. if !x.left.visit(iv, nv) {
  140. return false
  141. }
  142. case v > 0:
  143. maxiv := Interval{x.iv.Ivl.Begin, x.max}
  144. if maxiv.Compare(iv) == 0 {
  145. if !x.left.visit(iv, nv) || !x.right.visit(iv, nv) {
  146. return false
  147. }
  148. }
  149. default:
  150. if !x.left.visit(iv, nv) || !nv(x) || !x.right.visit(iv, nv) {
  151. return false
  152. }
  153. }
  154. return true
  155. }
  156. // IntervalValue represents a range tree node that contains a range and a value.
  157. type IntervalValue struct {
  158. Ivl Interval
  159. Val interface{}
  160. }
  161. // IntervalTree represents a (mostly) textbook implementation of the
  162. // "Introduction to Algorithms" (Cormen et al, 3rd ed.) chapter 13 red-black tree
  163. // and chapter 14.3 interval tree with search supporting "stabbing queries".
  164. type IntervalTree interface {
  165. // Insert adds a node with the given interval into the tree.
  166. Insert(ivl Interval, val interface{})
  167. // Delete removes the node with the given interval from the tree, returning
  168. // true if a node is in fact removed.
  169. Delete(ivl Interval) bool
  170. // Len gives the number of elements in the tree.
  171. Len() int
  172. // Height is the number of levels in the tree; one node has height 1.
  173. Height() int
  174. // MaxHeight is the expected maximum tree height given the number of nodes.
  175. MaxHeight() int
  176. // Visit calls a visitor function on every tree node intersecting the given interval.
  177. // It will visit each interval [x, y) in ascending order sorted on x.
  178. Visit(ivl Interval, ivv IntervalVisitor)
  179. // Find gets the IntervalValue for the node matching the given interval
  180. Find(ivl Interval) *IntervalValue
  181. // Intersects returns true if there is some tree node intersecting the given interval.
  182. Intersects(iv Interval) bool
  183. // Contains returns true if the interval tree's keys cover the entire given interval.
  184. Contains(ivl Interval) bool
  185. // Stab returns a slice with all elements in the tree intersecting the interval.
  186. Stab(iv Interval) []*IntervalValue
  187. // Union merges a given interval tree into the receiver.
  188. Union(inIvt IntervalTree, ivl Interval)
  189. }
  190. // NewIntervalTree returns a new interval tree.
  191. func NewIntervalTree() IntervalTree {
  192. return &intervalTree{}
  193. }
  194. type intervalTree struct {
  195. root *intervalNode
  196. count int
  197. }
  198. // Delete removes the node with the given interval from the tree, returning
  199. // true if a node is in fact removed.
  200. func (ivt *intervalTree) Delete(ivl Interval) bool {
  201. z := ivt.find(ivl)
  202. if z == nil {
  203. return false
  204. }
  205. y := z
  206. if z.left != nil && z.right != nil {
  207. y = z.successor()
  208. }
  209. x := y.left
  210. if x == nil {
  211. x = y.right
  212. }
  213. if x != nil {
  214. x.parent = y.parent
  215. }
  216. if y.parent == nil {
  217. ivt.root = x
  218. } else {
  219. if y == y.parent.left {
  220. y.parent.left = x
  221. } else {
  222. y.parent.right = x
  223. }
  224. y.parent.updateMax()
  225. }
  226. if y != z {
  227. z.iv = y.iv
  228. z.updateMax()
  229. }
  230. if y.color() == black && x != nil {
  231. ivt.deleteFixup(x)
  232. }
  233. ivt.count--
  234. return true
  235. }
  236. func (ivt *intervalTree) deleteFixup(x *intervalNode) {
  237. for x != ivt.root && x.color() == black && x.parent != nil {
  238. if x == x.parent.left {
  239. w := x.parent.right
  240. if w.color() == red {
  241. w.c = black
  242. x.parent.c = red
  243. ivt.rotateLeft(x.parent)
  244. w = x.parent.right
  245. }
  246. if w == nil {
  247. break
  248. }
  249. if w.left.color() == black && w.right.color() == black {
  250. w.c = red
  251. x = x.parent
  252. } else {
  253. if w.right.color() == black {
  254. w.left.c = black
  255. w.c = red
  256. ivt.rotateRight(w)
  257. w = x.parent.right
  258. }
  259. w.c = x.parent.color()
  260. x.parent.c = black
  261. w.right.c = black
  262. ivt.rotateLeft(x.parent)
  263. x = ivt.root
  264. }
  265. } else {
  266. // same as above but with left and right exchanged
  267. w := x.parent.left
  268. if w.color() == red {
  269. w.c = black
  270. x.parent.c = red
  271. ivt.rotateRight(x.parent)
  272. w = x.parent.left
  273. }
  274. if w == nil {
  275. break
  276. }
  277. if w.left.color() == black && w.right.color() == black {
  278. w.c = red
  279. x = x.parent
  280. } else {
  281. if w.left.color() == black {
  282. w.right.c = black
  283. w.c = red
  284. ivt.rotateLeft(w)
  285. w = x.parent.left
  286. }
  287. w.c = x.parent.color()
  288. x.parent.c = black
  289. w.left.c = black
  290. ivt.rotateRight(x.parent)
  291. x = ivt.root
  292. }
  293. }
  294. }
  295. if x != nil {
  296. x.c = black
  297. }
  298. }
  299. // Insert adds a node with the given interval into the tree.
  300. func (ivt *intervalTree) Insert(ivl Interval, val interface{}) {
  301. var y *intervalNode
  302. z := &intervalNode{iv: IntervalValue{ivl, val}, max: ivl.End, c: red}
  303. x := ivt.root
  304. for x != nil {
  305. y = x
  306. if z.iv.Ivl.Begin.Compare(x.iv.Ivl.Begin) < 0 {
  307. x = x.left
  308. } else {
  309. x = x.right
  310. }
  311. }
  312. z.parent = y
  313. if y == nil {
  314. ivt.root = z
  315. } else {
  316. if z.iv.Ivl.Begin.Compare(y.iv.Ivl.Begin) < 0 {
  317. y.left = z
  318. } else {
  319. y.right = z
  320. }
  321. y.updateMax()
  322. }
  323. z.c = red
  324. ivt.insertFixup(z)
  325. ivt.count++
  326. }
  327. func (ivt *intervalTree) insertFixup(z *intervalNode) {
  328. for z.parent != nil && z.parent.parent != nil && z.parent.color() == red {
  329. if z.parent == z.parent.parent.left {
  330. y := z.parent.parent.right
  331. if y.color() == red {
  332. y.c = black
  333. z.parent.c = black
  334. z.parent.parent.c = red
  335. z = z.parent.parent
  336. } else {
  337. if z == z.parent.right {
  338. z = z.parent
  339. ivt.rotateLeft(z)
  340. }
  341. z.parent.c = black
  342. z.parent.parent.c = red
  343. ivt.rotateRight(z.parent.parent)
  344. }
  345. } else {
  346. // same as then with left/right exchanged
  347. y := z.parent.parent.left
  348. if y.color() == red {
  349. y.c = black
  350. z.parent.c = black
  351. z.parent.parent.c = red
  352. z = z.parent.parent
  353. } else {
  354. if z == z.parent.left {
  355. z = z.parent
  356. ivt.rotateRight(z)
  357. }
  358. z.parent.c = black
  359. z.parent.parent.c = red
  360. ivt.rotateLeft(z.parent.parent)
  361. }
  362. }
  363. }
  364. ivt.root.c = black
  365. }
  366. // rotateLeft moves x so it is left of its right child
  367. func (ivt *intervalTree) rotateLeft(x *intervalNode) {
  368. y := x.right
  369. x.right = y.left
  370. if y.left != nil {
  371. y.left.parent = x
  372. }
  373. x.updateMax()
  374. ivt.replaceParent(x, y)
  375. y.left = x
  376. y.updateMax()
  377. }
  378. // rotateRight moves x so it is right of its left child
  379. func (ivt *intervalTree) rotateRight(x *intervalNode) {
  380. if x == nil {
  381. return
  382. }
  383. y := x.left
  384. x.left = y.right
  385. if y.right != nil {
  386. y.right.parent = x
  387. }
  388. x.updateMax()
  389. ivt.replaceParent(x, y)
  390. y.right = x
  391. y.updateMax()
  392. }
  393. // replaceParent replaces x's parent with y
  394. func (ivt *intervalTree) replaceParent(x *intervalNode, y *intervalNode) {
  395. y.parent = x.parent
  396. if x.parent == nil {
  397. ivt.root = y
  398. } else {
  399. if x == x.parent.left {
  400. x.parent.left = y
  401. } else {
  402. x.parent.right = y
  403. }
  404. x.parent.updateMax()
  405. }
  406. x.parent = y
  407. }
  408. // Len gives the number of elements in the tree
  409. func (ivt *intervalTree) Len() int { return ivt.count }
  410. // Height is the number of levels in the tree; one node has height 1.
  411. func (ivt *intervalTree) Height() int { return ivt.root.height() }
  412. // MaxHeight is the expected maximum tree height given the number of nodes
  413. func (ivt *intervalTree) MaxHeight() int {
  414. return int((2 * math.Log2(float64(ivt.Len()+1))) + 0.5)
  415. }
  416. // IntervalVisitor is used on tree searches; return false to stop searching.
  417. type IntervalVisitor func(n *IntervalValue) bool
  418. // Visit calls a visitor function on every tree node intersecting the given interval.
  419. // It will visit each interval [x, y) in ascending order sorted on x.
  420. func (ivt *intervalTree) Visit(ivl Interval, ivv IntervalVisitor) {
  421. ivt.root.visit(&ivl, func(n *intervalNode) bool { return ivv(&n.iv) })
  422. }
  423. // find the exact node for a given interval
  424. func (ivt *intervalTree) find(ivl Interval) (ret *intervalNode) {
  425. f := func(n *intervalNode) bool {
  426. if n.iv.Ivl != ivl {
  427. return true
  428. }
  429. ret = n
  430. return false
  431. }
  432. ivt.root.visit(&ivl, f)
  433. return ret
  434. }
  435. // Find gets the IntervalValue for the node matching the given interval
  436. func (ivt *intervalTree) Find(ivl Interval) (ret *IntervalValue) {
  437. n := ivt.find(ivl)
  438. if n == nil {
  439. return nil
  440. }
  441. return &n.iv
  442. }
  443. // Intersects returns true if there is some tree node intersecting the given interval.
  444. func (ivt *intervalTree) Intersects(iv Interval) bool {
  445. x := ivt.root
  446. for x != nil && iv.Compare(&x.iv.Ivl) != 0 {
  447. if x.left != nil && x.left.max.Compare(iv.Begin) > 0 {
  448. x = x.left
  449. } else {
  450. x = x.right
  451. }
  452. }
  453. return x != nil
  454. }
  455. // Contains returns true if the interval tree's keys cover the entire given interval.
  456. func (ivt *intervalTree) Contains(ivl Interval) bool {
  457. var maxEnd, minBegin Comparable
  458. isContiguous := true
  459. ivt.Visit(ivl, func(n *IntervalValue) bool {
  460. if minBegin == nil {
  461. minBegin = n.Ivl.Begin
  462. maxEnd = n.Ivl.End
  463. return true
  464. }
  465. if maxEnd.Compare(n.Ivl.Begin) < 0 {
  466. isContiguous = false
  467. return false
  468. }
  469. if n.Ivl.End.Compare(maxEnd) > 0 {
  470. maxEnd = n.Ivl.End
  471. }
  472. return true
  473. })
  474. return isContiguous && minBegin != nil && maxEnd.Compare(ivl.End) >= 0 && minBegin.Compare(ivl.Begin) <= 0
  475. }
  476. // Stab returns a slice with all elements in the tree intersecting the interval.
  477. func (ivt *intervalTree) Stab(iv Interval) (ivs []*IntervalValue) {
  478. if ivt.count == 0 {
  479. return nil
  480. }
  481. f := func(n *IntervalValue) bool { ivs = append(ivs, n); return true }
  482. ivt.Visit(iv, f)
  483. return ivs
  484. }
  485. // Union merges a given interval tree into the receiver.
  486. func (ivt *intervalTree) Union(inIvt IntervalTree, ivl Interval) {
  487. f := func(n *IntervalValue) bool {
  488. ivt.Insert(n.Ivl, n.Val)
  489. return true
  490. }
  491. inIvt.Visit(ivl, f)
  492. }
  493. type visitedInterval struct {
  494. root Interval
  495. left Interval
  496. right Interval
  497. color rbcolor
  498. depth int
  499. }
  500. func (vi visitedInterval) String() string {
  501. bd := new(strings.Builder)
  502. bd.WriteString(fmt.Sprintf("root [%v,%v,%v], left [%v,%v], right [%v,%v], depth %d",
  503. vi.root.Begin, vi.root.End, vi.color,
  504. vi.left.Begin, vi.left.End,
  505. vi.right.Begin, vi.right.End,
  506. vi.depth,
  507. ))
  508. return bd.String()
  509. }
  510. // visitLevel traverses tree in level order.
  511. // used for testing
  512. func (ivt *intervalTree) visitLevel() []visitedInterval {
  513. if ivt.root == nil {
  514. return nil
  515. }
  516. rs := make([]visitedInterval, 0, ivt.Len())
  517. type pair struct {
  518. node *intervalNode
  519. depth int
  520. }
  521. queue := []pair{{ivt.root, 0}}
  522. for len(queue) > 0 {
  523. f := queue[0]
  524. queue = queue[1:]
  525. ivt := visitedInterval{
  526. root: f.node.iv.Ivl,
  527. color: f.node.color(),
  528. depth: f.depth,
  529. }
  530. if f.node.left != nil {
  531. ivt.left = f.node.left.iv.Ivl
  532. queue = append(queue, pair{f.node.left, f.depth + 1})
  533. }
  534. if f.node.right != nil {
  535. ivt.right = f.node.right.iv.Ivl
  536. queue = append(queue, pair{f.node.right, f.depth + 1})
  537. }
  538. rs = append(rs, ivt)
  539. }
  540. return rs
  541. }
  542. type StringComparable string
  543. func (s StringComparable) Compare(c Comparable) int {
  544. sc := c.(StringComparable)
  545. if s < sc {
  546. return -1
  547. }
  548. if s > sc {
  549. return 1
  550. }
  551. return 0
  552. }
  553. func NewStringInterval(begin, end string) Interval {
  554. return Interval{StringComparable(begin), StringComparable(end)}
  555. }
  556. func NewStringPoint(s string) Interval {
  557. return Interval{StringComparable(s), StringComparable(s + "\x00")}
  558. }
  559. // StringAffineComparable treats "" as > all other strings
  560. type StringAffineComparable string
  561. func (s StringAffineComparable) Compare(c Comparable) int {
  562. sc := c.(StringAffineComparable)
  563. if len(s) == 0 {
  564. if len(sc) == 0 {
  565. return 0
  566. }
  567. return 1
  568. }
  569. if len(sc) == 0 {
  570. return -1
  571. }
  572. if s < sc {
  573. return -1
  574. }
  575. if s > sc {
  576. return 1
  577. }
  578. return 0
  579. }
  580. func NewStringAffineInterval(begin, end string) Interval {
  581. return Interval{StringAffineComparable(begin), StringAffineComparable(end)}
  582. }
  583. func NewStringAffinePoint(s string) Interval {
  584. return NewStringAffineInterval(s, s+"\x00")
  585. }
  586. func NewInt64Interval(a int64, b int64) Interval {
  587. return Interval{Int64Comparable(a), Int64Comparable(b)}
  588. }
  589. func newInt64EmptyInterval() Interval {
  590. return Interval{Begin: nil, End: nil}
  591. }
  592. func NewInt64Point(a int64) Interval {
  593. return Interval{Int64Comparable(a), Int64Comparable(a + 1)}
  594. }
  595. type Int64Comparable int64
  596. func (v Int64Comparable) Compare(c Comparable) int {
  597. vc := c.(Int64Comparable)
  598. cmp := v - vc
  599. if cmp < 0 {
  600. return -1
  601. }
  602. if cmp > 0 {
  603. return 1
  604. }
  605. return 0
  606. }
  607. // BytesAffineComparable treats empty byte arrays as > all other byte arrays
  608. type BytesAffineComparable []byte
  609. func (b BytesAffineComparable) Compare(c Comparable) int {
  610. bc := c.(BytesAffineComparable)
  611. if len(b) == 0 {
  612. if len(bc) == 0 {
  613. return 0
  614. }
  615. return 1
  616. }
  617. if len(bc) == 0 {
  618. return -1
  619. }
  620. return bytes.Compare(b, bc)
  621. }
  622. func NewBytesAffineInterval(begin, end []byte) Interval {
  623. return Interval{BytesAffineComparable(begin), BytesAffineComparable(end)}
  624. }
  625. func NewBytesAffinePoint(b []byte) Interval {
  626. be := make([]byte, len(b)+1)
  627. copy(be, b)
  628. be[len(b)] = 0
  629. return NewBytesAffineInterval(b, be)
  630. }