interval_tree.go 11 KB

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