interval_tree.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590
  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. "math"
  18. )
  19. // Comparable is an interface for trichotomic comparisons.
  20. type Comparable interface {
  21. // Compare gives the result of a 3-way comparison
  22. // a.Compare(b) = 1 => a > b
  23. // a.Compare(b) = 0 => a == b
  24. // a.Compare(b) = -1 => a < b
  25. Compare(c Comparable) int
  26. }
  27. type rbcolor int
  28. const (
  29. black rbcolor = iota
  30. red
  31. )
  32. // Interval implements a Comparable interval [begin, end)
  33. // TODO: support different sorts of intervals: (a,b), [a,b], (a, b]
  34. type Interval struct {
  35. Begin Comparable
  36. End Comparable
  37. }
  38. // Compare on an interval gives == if the interval overlaps.
  39. func (ivl *Interval) Compare(c Comparable) int {
  40. ivl2 := c.(*Interval)
  41. ivbCmpBegin := ivl.Begin.Compare(ivl2.Begin)
  42. ivbCmpEnd := ivl.Begin.Compare(ivl2.End)
  43. iveCmpBegin := ivl.End.Compare(ivl2.Begin)
  44. // ivl is left of ivl2
  45. if ivbCmpBegin < 0 && iveCmpBegin <= 0 {
  46. return -1
  47. }
  48. // iv is right of iv2
  49. if ivbCmpEnd >= 0 {
  50. return 1
  51. }
  52. return 0
  53. }
  54. type intervalNode struct {
  55. // iv is the interval-value pair entry.
  56. iv IntervalValue
  57. // max endpoint of all descendent nodes.
  58. max Comparable
  59. // left and right are sorted by low endpoint of key interval
  60. left, right *intervalNode
  61. // parent is the direct ancestor of the node
  62. parent *intervalNode
  63. c rbcolor
  64. }
  65. func (x *intervalNode) color() rbcolor {
  66. if x == nil {
  67. return black
  68. }
  69. return x.c
  70. }
  71. func (n *intervalNode) height() int {
  72. if n == nil {
  73. return 0
  74. }
  75. ld := n.left.height()
  76. rd := n.right.height()
  77. if ld < rd {
  78. return rd + 1
  79. }
  80. return ld + 1
  81. }
  82. func (x *intervalNode) min() *intervalNode {
  83. for x.left != nil {
  84. x = x.left
  85. }
  86. return x
  87. }
  88. // successor is the next in-order node in the tree
  89. func (x *intervalNode) successor() *intervalNode {
  90. if x.right != nil {
  91. return x.right.min()
  92. }
  93. y := x.parent
  94. for y != nil && x == y.right {
  95. x = y
  96. y = y.parent
  97. }
  98. return y
  99. }
  100. // updateMax updates the maximum values for a node and its ancestors
  101. func (x *intervalNode) updateMax() {
  102. for x != nil {
  103. oldmax := x.max
  104. max := x.iv.Ivl.End
  105. if x.left != nil && x.left.max.Compare(max) > 0 {
  106. max = x.left.max
  107. }
  108. if x.right != nil && x.right.max.Compare(max) > 0 {
  109. max = x.right.max
  110. }
  111. if oldmax.Compare(max) == 0 {
  112. break
  113. }
  114. x.max = max
  115. x = x.parent
  116. }
  117. }
  118. type nodeVisitor func(n *intervalNode) bool
  119. // visit will call a node visitor on each node that overlaps the given interval
  120. func (x *intervalNode) visit(iv *Interval, nv nodeVisitor) bool {
  121. if x == nil {
  122. return true
  123. }
  124. v := iv.Compare(&x.iv.Ivl)
  125. switch {
  126. case v < 0:
  127. if !x.left.visit(iv, nv) {
  128. return false
  129. }
  130. case v > 0:
  131. maxiv := Interval{x.iv.Ivl.Begin, x.max}
  132. if maxiv.Compare(iv) == 0 {
  133. if !x.left.visit(iv, nv) || !x.right.visit(iv, nv) {
  134. return false
  135. }
  136. }
  137. default:
  138. if !x.left.visit(iv, nv) || !nv(x) || !x.right.visit(iv, nv) {
  139. return false
  140. }
  141. }
  142. return true
  143. }
  144. type IntervalValue struct {
  145. Ivl Interval
  146. Val interface{}
  147. }
  148. // IntervalTree represents a (mostly) textbook implementation of the
  149. // "Introduction to Algorithms" (Cormen et al, 2nd ed.) chapter 13 red-black tree
  150. // and chapter 14.3 interval tree with search supporting "stabbing queries".
  151. type IntervalTree struct {
  152. root *intervalNode
  153. count int
  154. }
  155. // Delete removes the node with the given interval from the tree, returning
  156. // true if a node is in fact removed.
  157. func (ivt *IntervalTree) Delete(ivl Interval) bool {
  158. z := ivt.find(ivl)
  159. if z == nil {
  160. return false
  161. }
  162. y := z
  163. if z.left != nil && z.right != nil {
  164. y = z.successor()
  165. }
  166. x := y.left
  167. if x == nil {
  168. x = y.right
  169. }
  170. if x != nil {
  171. x.parent = y.parent
  172. }
  173. if y.parent == nil {
  174. ivt.root = x
  175. } else {
  176. if y == y.parent.left {
  177. y.parent.left = x
  178. } else {
  179. y.parent.right = x
  180. }
  181. y.parent.updateMax()
  182. }
  183. if y != z {
  184. z.iv = y.iv
  185. z.updateMax()
  186. }
  187. if y.color() == black && x != nil {
  188. ivt.deleteFixup(x)
  189. }
  190. ivt.count--
  191. return true
  192. }
  193. func (ivt *IntervalTree) deleteFixup(x *intervalNode) {
  194. for x != ivt.root && x.color() == black && x.parent != nil {
  195. if x == x.parent.left {
  196. w := x.parent.right
  197. if w.color() == red {
  198. w.c = black
  199. x.parent.c = red
  200. ivt.rotateLeft(x.parent)
  201. w = x.parent.right
  202. }
  203. if w == nil {
  204. break
  205. }
  206. if w.left.color() == black && w.right.color() == black {
  207. w.c = red
  208. x = x.parent
  209. } else {
  210. if w.right.color() == black {
  211. w.left.c = black
  212. w.c = red
  213. ivt.rotateRight(w)
  214. w = x.parent.right
  215. }
  216. w.c = x.parent.color()
  217. x.parent.c = black
  218. w.right.c = black
  219. ivt.rotateLeft(x.parent)
  220. x = ivt.root
  221. }
  222. } else {
  223. // same as above but with left and right exchanged
  224. w := x.parent.left
  225. if w.color() == red {
  226. w.c = black
  227. x.parent.c = red
  228. ivt.rotateRight(x.parent)
  229. w = x.parent.left
  230. }
  231. if w == nil {
  232. break
  233. }
  234. if w.left.color() == black && w.right.color() == black {
  235. w.c = red
  236. x = x.parent
  237. } else {
  238. if w.left.color() == black {
  239. w.right.c = black
  240. w.c = red
  241. ivt.rotateLeft(w)
  242. w = x.parent.left
  243. }
  244. w.c = x.parent.color()
  245. x.parent.c = black
  246. w.left.c = black
  247. ivt.rotateRight(x.parent)
  248. x = ivt.root
  249. }
  250. }
  251. }
  252. if x != nil {
  253. x.c = black
  254. }
  255. }
  256. // Insert adds a node with the given interval into the tree.
  257. func (ivt *IntervalTree) Insert(ivl Interval, val interface{}) {
  258. var y *intervalNode
  259. z := &intervalNode{iv: IntervalValue{ivl, val}, max: ivl.End, c: red}
  260. x := ivt.root
  261. for x != nil {
  262. y = x
  263. if z.iv.Ivl.Begin.Compare(x.iv.Ivl.Begin) < 0 {
  264. x = x.left
  265. } else {
  266. x = x.right
  267. }
  268. }
  269. z.parent = y
  270. if y == nil {
  271. ivt.root = z
  272. } else {
  273. if z.iv.Ivl.Begin.Compare(y.iv.Ivl.Begin) < 0 {
  274. y.left = z
  275. } else {
  276. y.right = z
  277. }
  278. y.updateMax()
  279. }
  280. z.c = red
  281. ivt.insertFixup(z)
  282. ivt.count++
  283. }
  284. func (ivt *IntervalTree) insertFixup(z *intervalNode) {
  285. for z.parent != nil && z.parent.parent != nil && z.parent.color() == red {
  286. if z.parent == z.parent.parent.left {
  287. y := z.parent.parent.right
  288. if y.color() == red {
  289. y.c = black
  290. z.parent.c = black
  291. z.parent.parent.c = red
  292. z = z.parent.parent
  293. } else {
  294. if z == z.parent.right {
  295. z = z.parent
  296. ivt.rotateLeft(z)
  297. }
  298. z.parent.c = black
  299. z.parent.parent.c = red
  300. ivt.rotateRight(z.parent.parent)
  301. }
  302. } else {
  303. // same as then with left/right exchanged
  304. y := z.parent.parent.left
  305. if y.color() == red {
  306. y.c = black
  307. z.parent.c = black
  308. z.parent.parent.c = red
  309. z = z.parent.parent
  310. } else {
  311. if z == z.parent.left {
  312. z = z.parent
  313. ivt.rotateRight(z)
  314. }
  315. z.parent.c = black
  316. z.parent.parent.c = red
  317. ivt.rotateLeft(z.parent.parent)
  318. }
  319. }
  320. }
  321. ivt.root.c = black
  322. }
  323. // rotateLeft moves x so it is left of its right child
  324. func (ivt *IntervalTree) rotateLeft(x *intervalNode) {
  325. y := x.right
  326. x.right = y.left
  327. if y.left != nil {
  328. y.left.parent = x
  329. }
  330. x.updateMax()
  331. ivt.replaceParent(x, y)
  332. y.left = x
  333. y.updateMax()
  334. }
  335. // rotateLeft moves x so it is right of its left child
  336. func (ivt *IntervalTree) rotateRight(x *intervalNode) {
  337. if x == nil {
  338. return
  339. }
  340. y := x.left
  341. x.left = y.right
  342. if y.right != nil {
  343. y.right.parent = x
  344. }
  345. x.updateMax()
  346. ivt.replaceParent(x, y)
  347. y.right = x
  348. y.updateMax()
  349. }
  350. // replaceParent replaces x's parent with y
  351. func (ivt *IntervalTree) replaceParent(x *intervalNode, y *intervalNode) {
  352. y.parent = x.parent
  353. if x.parent == nil {
  354. ivt.root = y
  355. } else {
  356. if x == x.parent.left {
  357. x.parent.left = y
  358. } else {
  359. x.parent.right = y
  360. }
  361. x.parent.updateMax()
  362. }
  363. x.parent = y
  364. }
  365. // Len gives the number of elements in the tree
  366. func (ivt *IntervalTree) Len() int { return ivt.count }
  367. // Height is the number of levels in the tree; one node has height 1.
  368. func (ivt *IntervalTree) Height() int { return ivt.root.height() }
  369. // MaxHeight is the expected maximum tree height given the number of nodes
  370. func (ivt *IntervalTree) MaxHeight() int {
  371. return int((2 * math.Log2(float64(ivt.Len()+1))) + 0.5)
  372. }
  373. // IntervalVisitor is used on tree searches; return false to stop searching.
  374. type IntervalVisitor func(n *IntervalValue) bool
  375. // Visit calls a visitor function on every tree node intersecting the given interval.
  376. // It will visit each interval [x, y) in ascending order sorted on x.
  377. func (ivt *IntervalTree) Visit(ivl Interval, ivv IntervalVisitor) {
  378. ivt.root.visit(&ivl, func(n *intervalNode) bool { return ivv(&n.iv) })
  379. }
  380. // find the exact node for a given interval
  381. func (ivt *IntervalTree) find(ivl Interval) (ret *intervalNode) {
  382. f := func(n *intervalNode) bool {
  383. if n.iv.Ivl != ivl {
  384. return true
  385. }
  386. ret = n
  387. return false
  388. }
  389. ivt.root.visit(&ivl, f)
  390. return ret
  391. }
  392. // Find gets the IntervalValue for the node matching the given interval
  393. func (ivt *IntervalTree) Find(ivl Interval) (ret *IntervalValue) {
  394. n := ivt.find(ivl)
  395. if n == nil {
  396. return nil
  397. }
  398. return &n.iv
  399. }
  400. // Intersects returns true if there is some tree node intersecting the given interval.
  401. func (ivt *IntervalTree) Intersects(iv Interval) bool {
  402. x := ivt.root
  403. for x != nil && iv.Compare(&x.iv.Ivl) != 0 {
  404. if x.left != nil && x.left.max.Compare(iv.Begin) > 0 {
  405. x = x.left
  406. } else {
  407. x = x.right
  408. }
  409. }
  410. return x != nil
  411. }
  412. // Contains returns true if the interval tree's keys cover the entire given interval.
  413. func (ivt *IntervalTree) Contains(ivl Interval) bool {
  414. var maxEnd, minBegin Comparable
  415. isContiguous := true
  416. ivt.Visit(ivl, func(n *IntervalValue) bool {
  417. if minBegin == nil {
  418. minBegin = n.Ivl.Begin
  419. maxEnd = n.Ivl.End
  420. return true
  421. }
  422. if maxEnd.Compare(n.Ivl.Begin) < 0 {
  423. isContiguous = false
  424. return false
  425. }
  426. if n.Ivl.End.Compare(maxEnd) > 0 {
  427. maxEnd = n.Ivl.End
  428. }
  429. return true
  430. })
  431. return isContiguous && minBegin != nil && maxEnd.Compare(ivl.End) >= 0 && minBegin.Compare(ivl.Begin) <= 0
  432. }
  433. // Stab returns a slice with all elements in the tree intersecting the interval.
  434. func (ivt *IntervalTree) Stab(iv Interval) (ivs []*IntervalValue) {
  435. if ivt.count == 0 {
  436. return nil
  437. }
  438. f := func(n *IntervalValue) bool { ivs = append(ivs, n); return true }
  439. ivt.Visit(iv, f)
  440. return ivs
  441. }
  442. type StringComparable string
  443. func (s StringComparable) Compare(c Comparable) int {
  444. sc := c.(StringComparable)
  445. if s < sc {
  446. return -1
  447. }
  448. if s > sc {
  449. return 1
  450. }
  451. return 0
  452. }
  453. func NewStringInterval(begin, end string) Interval {
  454. return Interval{StringComparable(begin), StringComparable(end)}
  455. }
  456. func NewStringPoint(s string) Interval {
  457. return Interval{StringComparable(s), StringComparable(s + "\x00")}
  458. }
  459. // StringAffineComparable treats "" as > all other strings
  460. type StringAffineComparable string
  461. func (s StringAffineComparable) Compare(c Comparable) int {
  462. sc := c.(StringAffineComparable)
  463. if len(s) == 0 {
  464. if len(sc) == 0 {
  465. return 0
  466. }
  467. return 1
  468. }
  469. if len(sc) == 0 {
  470. return -1
  471. }
  472. if s < sc {
  473. return -1
  474. }
  475. if s > sc {
  476. return 1
  477. }
  478. return 0
  479. }
  480. func NewStringAffineInterval(begin, end string) Interval {
  481. return Interval{StringAffineComparable(begin), StringAffineComparable(end)}
  482. }
  483. func NewStringAffinePoint(s string) Interval {
  484. return NewStringAffineInterval(s, s+"\x00")
  485. }
  486. func NewInt64Interval(a int64, b int64) Interval {
  487. return Interval{Int64Comparable(a), Int64Comparable(b)}
  488. }
  489. func NewInt64Point(a int64) Interval {
  490. return Interval{Int64Comparable(a), Int64Comparable(a + 1)}
  491. }
  492. type Int64Comparable int64
  493. func (v Int64Comparable) Compare(c Comparable) int {
  494. vc := c.(Int64Comparable)
  495. cmp := v - vc
  496. if cmp < 0 {
  497. return -1
  498. }
  499. if cmp > 0 {
  500. return 1
  501. }
  502. return 0
  503. }
  504. // BytesAffineComparable treats empty byte arrays as > all other byte arrays
  505. type BytesAffineComparable []byte
  506. func (b BytesAffineComparable) Compare(c Comparable) int {
  507. bc := c.(BytesAffineComparable)
  508. if len(b) == 0 {
  509. if len(bc) == 0 {
  510. return 0
  511. }
  512. return 1
  513. }
  514. if len(bc) == 0 {
  515. return -1
  516. }
  517. return bytes.Compare(b, bc)
  518. }
  519. func NewBytesAffineInterval(begin, end []byte) Interval {
  520. return Interval{BytesAffineComparable(begin), BytesAffineComparable(end)}
  521. }
  522. func NewBytesAffinePoint(b []byte) Interval {
  523. be := make([]byte, len(b)+1)
  524. copy(be, b)
  525. be[len(b)] = 0
  526. return NewBytesAffineInterval(b, be)
  527. }