github.com/cockroachdb/cockroachdb-parser@v0.23.3-0.20240213214944-911057d40c9a/pkg/util/interval/llrb_based_interval.go (about)

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