All files / src/internal/engines ordered-tree.ts

100% Statements 350/350
100% Branches 171/171
100% Functions 42/42
100% Lines 310/310

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712                                                106x                                               40x 36x 15x                   764307x 764307x 764307x 764307x     764307x         3488601x         3046554x 3046554x 3046554x         182765x 182765x 182765x                 5342431x 2866444x 2866444x 2866444x 2393072x 2393072x   2866444x                 247241x 144028x 144028x 144028x 91331x 91331x   144028x         68061x 98660x 68061x                                                   162164x   162164x               162164x 162164x     162164x 162164x 162164x                   3937289x 2185223x   2185223x 2177947x   1752066x 1752066x 1752066x                 21656246x 21117189x 21117189x 21117031x       2580348x 32x                     227020x 227020x             814847x         114167x               1806474x 1806474x 21682652x     21682652x 21671876x 20286063x   409885x               1540626x 1540626x         537818x 537818x 7544636x 7544636x 7065512x   3825167x     1074x 657x 3824093x   58277x               618979x 618979x 618979x 618979x 13839252x 13839252x 13820041x 13820041x   12835126x   766x 648x 12834360x 13819923x   599650x 599650x 599650x         598598x                           507199x 507199x 507199x 1685432x 1685432x 1407889x 715874x 345188x 345188x   370686x   692015x 345876x 345876x   346139x     229656x                   145083x 145083x 127939x 127939x                 292441x 292441x 292441x 292441x 291852x 907490x 907490x 864406x 864406x   248768x               243931x       842529x 842529x 762668x 585086x 842529x 842529x                 106716x 106716x 68061x 68061x 68061x 488141x 488141x 210040x 210040x 488141x 488141x 488141x 141979x 91741x 210040x 210040x 210040x   68061x               51285x 32213x 32213x 484830x 484830x 484830x 484830x 484830x 484830x 452617x 226255x 484830x 484830x   32213x             6821x 6821x               335091x     335091x 302991x 302991x 302991x 32100x 11057x 11057x 11057x   21043x 21043x 21043x 21043x 12195x   8848x 8848x 8848x 8848x   21043x 21043x 21043x 21043x   335091x 335091x 335091x 335091x 335091x             955710x 955710x 802202x 574988x 955710x       511714x 511714x 511714x 511714x 511714x 511714x       100057x 100057x 100057x 100057x 100057x 100057x       842529x 842529x 1052651x   1052651x 1052651x 120754x 120754x 62039x 62039x 62039x 62039x   58715x 28815x 28815x 28815x   58715x 58715x 58715x     931897x 931897x 468464x 468464x 468464x 468464x   463433x 27225x 27225x 27225x   463433x 463433x 463433x       842529x               221586x 221586x 221586x 150377x   131890x 131890x 2718x 2718x 2718x 2718x   131890x 118566x 118566x 118566x   13324x 5062x 5062x 5062x 5062x   13324x 13324x 13324x 13324x 13324x 13324x     18487x 18487x 1653x 1653x 1653x 1653x   18487x 11085x 11085x 11085x   7402x 3424x 3424x 3424x 3424x   7402x 7402x 7402x 7402x 7402x 7402x       221586x                                                 748561x 748561x 748561x 748561x 748561x       5341841x 5341841x 4604923x 5341841x                                 99903x                           99903x 99903x 99903x 99903x 99903x 99903x       379958x       140706x 140706x 140706x 140706x       101691x 101691x 101691x      
// The ordered tree behind `TreeSet` and `TreeMap`: an iterative red-black tree with parent pointers. Nothing here
// recurses, so the depth of the call stack never grows with the size of the tree.
//
// Every operation finds first and writes after: a descent from the root makes all the comparisons
// an operation needs, and only then is a node linked or unlinked. Rebalancing (rotations and
// recolouring) and removal never compare, so a comparator that throws, returns an invalid result
// or changes the tree leaves it exactly as it was. Removal moves nodes rather than values, so a
// node keeps its value for as long as it is in the tree and cursors can hold on to nodes.
//
// In natural order a tree holds values of one kind only, since a value that does not compare with
// the stored ones is refused. So when the root and the value searched for are both numbers, or
// both strings, every value in the tree is of that kind, no user code can run and no comparison
// can fail: `findPlain` and `locatePlain` descend with `<` and `===`, in the order `compareNatural`
// gives (`NaN` last and equal to itself, `-0` equal to `0`), one comparison per level as `find`.
 
import { ConcurrentModificationError } from '../../errors/errors'
import type { Comparator } from '../../functions/comparators'
import type { Cursor } from '../../interfaces/collection'
import { guardedCompare } from '../compare'
import { done, FailFastCursor, FailFastIterator } from '../iteration'
import { compareNatural, compareNaturalOrAbsent, isPlainKind } from '../natural-order'
import type { ChangeCounter } from '../revision'
 
/** What a lenient comparison returns when, in natural order, the values cannot be compared. */
export const ABSENT = 2
 
/** -1, 0 or 1, or `ABSENT`. */
export type Comparison = -1 | 0 | 1 | typeof ABSENT
 
/**
 * Where a value belongs in the tree: the node that compares equal to it, or else the parent a new
 * node hangs from (`null` for the root) and on which side.
 *
 * @internal
 */
export interface Place<E> {
  readonly node: TreeNode<E> | null
  readonly parent: TreeNode<E> | null
  readonly left: boolean
}
 
/**
 * Returns a function that orders values in the reverse of `order` (natural order when
 * `undefined`).
 *
 * @internal
 */
export function reversing<E>(order: Comparator<E> | undefined): Comparator<E> {
  return order === undefined
    ? (a: E, b: E) => compareNatural(b, a, 'naturalOrder')
    : (a: E, b: E) => order(b, a)
}
 
/**
 * A node of the tree.
 *
 * @internal
 */
export class TreeNode<E> {
  value: E
  left: TreeNode<E> | null = null
  right: TreeNode<E> | null = null
  parent: TreeNode<E> | null = null
  red = true
 
  constructor(value: E) {
    this.value = value
  }
}
 
function isRed<E>(node: TreeNode<E> | null): boolean {
  return node === null ? false : node.red
}
 
/** The leftmost node under `node`. */
function leftmost<E>(node: TreeNode<E>): TreeNode<E> {
  let n = node
  while (n.left !== null) n = n.left
  return n
}
 
/** The rightmost node under `node`. */
function rightmost<E>(node: TreeNode<E>): TreeNode<E> {
  let n = node
  while (n.right !== null) n = n.right
  return n
}
 
/**
 * The node after `node` in ascending order, or `null`.
 *
 * @internal
 */
export function successor<E>(node: TreeNode<E>): TreeNode<E> | null {
  if (node.right !== null) return leftmost(node.right)
  let child = node
  let parent = node.parent
  while (parent !== null && child === parent.right) {
    child = parent
    parent = parent.parent
  }
  return parent
}
 
/**
 * The node before `node` in ascending order, or `null`.
 *
 * @internal
 */
export function predecessor<E>(node: TreeNode<E>): TreeNode<E> | null {
  if (node.left !== null) return rightmost(node.left)
  let child = node
  let parent = node.parent
  while (parent !== null && child === parent.left) {
    child = parent
    parent = parent.parent
  }
  return parent
}
 
/** The level whose nodes are red when `size` sorted values are built into a balanced tree. */
function redLevel(size: number): number {
  let level = 0
  for (let m = size - 1; m >= 0; m = Math.floor(m / 2) - 1) level++
  return level
}
 
/** A pending piece of the bottom-up build: values `lo..hi` hang under `parent` on one side. */
interface BuildFrame<E> {
  readonly lo: number
  readonly hi: number
  readonly level: number
  readonly parent: TreeNode<E> | null
  readonly left: boolean
}
 
/** A pending piece of a copy: `source`'s subtree is cloned under `parent` on one side. */
interface CopyFrame<E> {
  readonly source: TreeNode<E>
  readonly parent: TreeNode<E> | null
  readonly left: boolean
}
 
/**
 * A red-black tree of distinct values (distinct under its order) with parent pointers. It records
 * no changes itself: the collections that use it record each change in `changes` after it is made.
 *
 * @internal
 */
export class OrderedTree<E> {
  root: TreeNode<E> | null = null
  /** The number of nodes. */
  count = 0
  /** The comparator, or `undefined` for natural order. */
  readonly order: Comparator<E> | undefined
  /** The change counter of the collection the tree belongs to, shared with its views. */
  readonly changes: ChangeCounter
  /** What the collection is called in messages: `set` or `map`. */
  private readonly noun: string
  /** Where `locatePlain` found that a new node would hang: its parent and side. */
  private plainParent: TreeNode<E> | null = null
  private plainLeft = false
 
  constructor(order: Comparator<E> | undefined, changes: ChangeCounter, noun = 'set') {
    this.order = order
    this.changes = changes
    this.noun = noun
  }
 
  // ── Comparing ──
 
  /**
   * Compares `a` with `b` under the tree's order, then checks that the call did not add or remove
   * members: `expected` is the structure count when the outer operation started.
   */
  compare(a: E, b: E, where: string, expected: number): -1 | 0 | 1 {
    if (this.order === undefined) {
      const result = compareNatural(a, b, where)
      // Two numbers or two strings run no user code, so nothing can have changed the tree.
      if (!isPlainKind(a, b)) this.checkStructure(where, expected)
      return result
    }
    const result = guardedCompare(this.order, a, b, where)
    this.checkStructure(where, expected)
    return result
  }
 
  /**
   * As `compare`, but in natural order a value that cannot be compared (`null`, `undefined`, no
   * natural order, another kind) gives `ABSENT` instead of an error. Errors from a comparator or a
   * `[compareSymbol]` method still propagate.
   */
  compareLenient(a: E, b: E, where: string, expected: number): Comparison {
    if (this.order !== undefined) return this.compare(a, b, where, expected)
    const result = compareNaturalOrAbsent(a, b, where)
    if (!isPlainKind(a, b)) this.checkStructure(where, expected)
    return result === undefined ? ABSENT : result
  }
 
  private checkStructure(where: string, expected: number): void {
    if (this.changes.structure !== expected) {
      throw new ConcurrentModificationError(
        `${where}: the ${this.noun} was changed by the comparator`,
      )
    }
  }
 
  /**
   * Compares `value` with a member (or with itself when the tree is empty), so in natural order a
   * value that cannot join the tree is refused before anything changes.
   */
  checkNatural(value: E, where: string, expected: number): void {
    const other = this.root === null ? value : this.root.value
    this.compare(value, other, where, expected)
  }
 
  // ── Finding ──
 
  /** The least node, or `null`. No comparisons. */
  first(): TreeNode<E> | null {
    return this.root === null ? null : leftmost(this.root)
  }
 
  /** The greatest node, or `null`. No comparisons. */
  last(): TreeNode<E> | null {
    return this.root === null ? null : rightmost(this.root)
  }
 
  /**
   * The node whose value compares equal to `value`, or `null`; one comparison per level. With
   * `lenient`, a value natural order cannot compare is not found instead of refused.
   */
  find(value: E, where: string, expected: number, lenient: boolean): TreeNode<E> | null {
    let node = this.root
    while (node !== null) {
      const c = lenient
        ? this.compareLenient(value, node.value, where, expected)
        : this.compare(value, node.value, where, expected)
      if (c === ABSENT) return null
      if (c === 0) return node
      node = c < 0 ? node.left : node.right
    }
    return null
  }
 
  /**
   * Whether the plain descent applies to `value`: natural order, a non-empty tree, and `value` and
   * the root both numbers or both strings.
   */
  plain(value: E): boolean {
    const root = this.root
    return this.order === undefined && root !== null && isPlainKind(value, root.value)
  }
 
  /** As `find` for a value `plain` accepts: the node equal to `value`, or `null`. */
  findPlain(value: E): TreeNode<E> | null {
    let node = this.root
    while (node !== null) {
      const other = node.value
      if (value === other) return node
      if (value < other) node = node.left
      // biome-ignore lint/suspicious/noSelfCompare: `x !== x` is true only for NaN.
      else if (other !== other) {
        // `other` is NaN: equal to a NaN value, after every other number.
        // biome-ignore lint/suspicious/noSelfCompare: as above.
        if (value !== value) return node
        node = node.left
      } else node = node.right
    }
    return null
  }
 
  /**
   * As `locate` for a value `plain` accepts: the node equal to `value`, or `null` after recording
   * where a new node would hang, for `linkPlain`.
   */
  locatePlain(value: E): TreeNode<E> | null {
    let parent: TreeNode<E> | null = null
    let left = false
    let node = this.root
    while (node !== null) {
      const other = node.value
      if (value === other) return node
      parent = node
      if (value < other) left = true
      // biome-ignore lint/suspicious/noSelfCompare: `x !== x` is true only for NaN.
      else if (other !== other) {
        // biome-ignore lint/suspicious/noSelfCompare: as above.
        if (value !== value) return node
        left = true
      } else left = false
      node = left ? node.left : node.right
    }
    this.plainParent = parent
    this.plainLeft = left
    return null
  }
 
  /** Links `added` where the last `locatePlain` (with no change since) said it hangs. */
  linkPlain(added: TreeNode<E>): void {
    this.linkAt(added, this.plainParent, this.plainLeft)
  }
 
  /**
   * The greatest node before `value` (`below`) or the least node after it, counting a node equal to
   * `value` when `inclusive`; one comparison per level.
   */
  nearest(
    value: E,
    below: boolean,
    inclusive: boolean,
    where: string,
    expected: number,
  ): TreeNode<E> | null {
    let node = this.root
    let best: TreeNode<E> | null = null
    while (node !== null) {
      const c = this.compare(value, node.value, where, expected)
      if (c === 0 && inclusive) return node
      if (below) {
        if (c > 0) {
          best = node
          node = node.right
        } else {
          node = node.left
        }
      } else if (c < 0) {
        best = node
        node = node.left
      } else {
        node = node.right
      }
    }
    return best
  }
 
  // ── Adding ──
 
  /**
   * Adds `value` unless a node compares equal to it; returns whether it was added. In natural
   * order, a value added to an empty tree is compared with itself first.
   */
  insert(value: E, where: string, expected: number): boolean {
    const place = this.locate(value, where, expected)
    if (place.node !== null) return false
    this.link(new TreeNode(value), place)
    return true
  }
 
  /**
   * Finds where `value` belongs, making every comparison an insertion needs: the node equal to it,
   * or where a new node would hang. In natural order, a value meeting an empty tree is compared
   * with itself.
   */
  locate(value: E, where: string, expected: number): Place<E> {
    let parent: TreeNode<E> | null = null
    let c: -1 | 0 | 1 = 0
    let node = this.root
    if (node === null && this.order === undefined) this.compare(value, value, where, expected)
    while (node !== null) {
      c = this.compare(value, node.value, where, expected)
      if (c === 0) return { node, parent: null, left: false }
      parent = node
      node = c < 0 ? node.left : node.right
    }
    return { node: null, parent, left: c < 0 }
  }
 
  /**
   * Links the new node `added` at `place` (found by `locate` with no change since) and
   * rebalances. No comparisons, so nothing here can fail.
   */
  link(added: TreeNode<E>, place: Place<E>): void {
    this.linkAt(added, place.parent, place.left)
  }
 
  private linkAt(added: TreeNode<E>, parent: TreeNode<E> | null, left: boolean): void {
    added.parent = parent
    if (parent === null) this.root = added
    else if (left) parent.left = added
    else parent.right = added
    this.count++
    this.fixAfterInsert(added)
  }
 
  /**
   * Fills an empty tree with `values`, which must be in strictly ascending order, as a balanced
   * tree. No comparisons. `make(index)` makes the node of `values[index]`; a plain node by
   * default.
   */
  buildSorted(values: readonly E[], make?: (index: number) => TreeNode<E>): void {
    const size = values.length
    if (size === 0) return
    const red = redLevel(size)
    const stack: BuildFrame<E>[] = [{ lo: 0, hi: size - 1, level: 0, parent: null, left: false }]
    while (stack.length > 0) {
      const frame = stack.pop() as BuildFrame<E>
      if (frame.hi < frame.lo) continue
      const mid = (frame.lo + frame.hi) >>> 1
      const node = make === undefined ? new TreeNode(values[mid] as E) : make(mid)
      node.red = frame.level === red
      node.parent = frame.parent
      if (frame.parent === null) this.root = node
      else if (frame.left) frame.parent.left = node
      else frame.parent.right = node
      const level = frame.level + 1
      stack.push({ lo: frame.lo, hi: mid - 1, level, parent: node, left: true })
      stack.push({ lo: mid + 1, hi: frame.hi, level, parent: node, left: false })
    }
    this.count = size
  }
 
  /**
   * Fills an empty tree with a node-for-node copy of `source`'s tree. No comparisons.
   * `clone(node)` makes the copy of a node; a plain node with the same value by default.
   */
  copyFrom(source: OrderedTree<E>, clone?: (node: TreeNode<E>) => TreeNode<E>): void {
    if (source.root === null) return
    const stack: CopyFrame<E>[] = [{ source: source.root, parent: null, left: false }]
    while (stack.length > 0) {
      const frame = stack.pop() as CopyFrame<E>
      const from = frame.source
      const node = clone === undefined ? new TreeNode(from.value) : clone(from)
      node.red = from.red
      node.parent = frame.parent
      if (frame.parent === null) this.root = node
      else if (frame.left) frame.parent.left = node
      else frame.parent.right = node
      if (from.left !== null) stack.push({ source: from.left, parent: node, left: true })
      if (from.right !== null) stack.push({ source: from.right, parent: node, left: false })
    }
    this.count = source.count
  }
 
  // ── Removing ──
 
  /** Removes every node. */
  clear(): void {
    this.root = null
    this.count = 0
  }
 
  /**
   * Unlinks `node` and rebalances. No comparisons. A node with two children is replaced by its
   * successor node, which moves with its value, so every other node keeps its value.
   */
  remove(node: TreeNode<E>): void {
    let removedRed = node.red
    let child: TreeNode<E> | null
    let childParent: TreeNode<E> | null
    if (node.left === null) {
      child = node.right
      childParent = node.parent
      this.transplant(node, node.right)
    } else if (node.right === null) {
      child = node.left
      childParent = node.parent
      this.transplant(node, node.left)
    } else {
      const next = leftmost(node.right)
      removedRed = next.red
      child = next.right
      if (next.parent === node) {
        childParent = next
      } else {
        childParent = next.parent
        this.transplant(next, next.right)
        next.right = node.right
        next.right.parent = next
      }
      this.transplant(node, next)
      next.left = node.left
      next.left.parent = next
      next.red = node.red
    }
    node.left = null
    node.right = null
    node.parent = null
    this.count--
    if (!removedRed) this.fixAfterRemove(child, childParent)
  }
 
  // ── Rebalancing (no comparisons) ──
 
  /** Puts `replacement` where `node` hangs from its parent. */
  private transplant(node: TreeNode<E>, replacement: TreeNode<E> | null): void {
    const parent = node.parent
    if (parent === null) this.root = replacement
    else if (node === parent.left) parent.left = replacement
    else parent.right = replacement
    if (replacement !== null) replacement.parent = parent
  }
 
  private rotateLeft(node: TreeNode<E>): void {
    const pivot = node.right as TreeNode<E>
    node.right = pivot.left
    if (pivot.left !== null) pivot.left.parent = node
    this.transplant(node, pivot)
    pivot.left = node
    node.parent = pivot
  }
 
  private rotateRight(node: TreeNode<E>): void {
    const pivot = node.left as TreeNode<E>
    node.left = pivot.right
    if (pivot.right !== null) pivot.right.parent = node
    this.transplant(node, pivot)
    pivot.right = node
    node.parent = pivot
  }
 
  private fixAfterInsert(added: TreeNode<E>): void {
    let node = added
    while (isRed(node.parent)) {
      let parent = node.parent as TreeNode<E>
      // A red parent is never the root, so the grandparent exists.
      const grand = parent.parent as TreeNode<E>
      if (parent === grand.left) {
        const uncle = grand.right
        if (isRed(uncle)) {
          parent.red = false
          ;(uncle as TreeNode<E>).red = false
          grand.red = true
          node = grand
        } else {
          if (node === parent.right) {
            node = parent
            this.rotateLeft(node)
            parent = node.parent as TreeNode<E>
          }
          parent.red = false
          grand.red = true
          this.rotateRight(grand)
        }
      } else {
        const uncle = grand.left
        if (isRed(uncle)) {
          parent.red = false
          ;(uncle as TreeNode<E>).red = false
          grand.red = true
          node = grand
        } else {
          if (node === parent.left) {
            node = parent
            this.rotateRight(node)
            parent = node.parent as TreeNode<E>
          }
          parent.red = false
          grand.red = true
          this.rotateLeft(grand)
        }
      }
    }
    ;(this.root as TreeNode<E>).red = false
  }
 
  /**
   * Restores the black heights after a black node was removed: `node` (possibly `null`) carries an
   * extra black and hangs under `parent`.
   */
  private fixAfterRemove(start: TreeNode<E> | null, startParent: TreeNode<E> | null): void {
    let node = start
    let parent = startParent
    while (node !== this.root && !isRed(node) && parent !== null) {
      if (node === parent.left) {
        // The sibling of a doubly black node always exists.
        let sibling = parent.right as TreeNode<E>
        if (sibling.red) {
          sibling.red = false
          parent.red = true
          this.rotateLeft(parent)
          sibling = parent.right as TreeNode<E>
        }
        if (!isRed(sibling.left) && !isRed(sibling.right)) {
          sibling.red = true
          node = parent
          parent = node.parent
        } else {
          if (!isRed(sibling.right)) {
            ;(sibling.left as TreeNode<E>).red = false
            sibling.red = true
            this.rotateRight(sibling)
            sibling = parent.right as TreeNode<E>
          }
          sibling.red = parent.red
          parent.red = false
          ;(sibling.right as TreeNode<E>).red = false
          this.rotateLeft(parent)
          node = this.root
          parent = null
        }
      } else {
        let sibling = parent.left as TreeNode<E>
        if (sibling.red) {
          sibling.red = false
          parent.red = true
          this.rotateRight(parent)
          sibling = parent.left as TreeNode<E>
        }
        if (!isRed(sibling.left) && !isRed(sibling.right)) {
          sibling.red = true
          node = parent
          parent = node.parent
        } else {
          if (!isRed(sibling.left)) {
            ;(sibling.right as TreeNode<E>).red = false
            sibling.red = true
            this.rotateLeft(sibling)
            sibling = parent.left as TreeNode<E>
          }
          sibling.red = parent.red
          parent.red = false
          ;(sibling.left as TreeNode<E>).red = false
          this.rotateRight(parent)
          node = this.root
          parent = null
        }
      }
    }
    if (node !== null) node.red = false
  }
}
 
/**
 * A fail-fast iterator over the nodes from `start` up to, but not including, `end`, in ascending
 * order or, when `descending`, in descending order. It yields `project(node)`: the node's value
 * by default.
 *
 * @internal
 */
export class TreeIterator<E, T = E> extends FailFastIterator<T> {
  private node: TreeNode<E> | null
  private readonly end: TreeNode<E> | null
  private readonly descending: boolean
  private readonly project: ((node: TreeNode<E>) => T) | undefined
 
  constructor(
    start: TreeNode<E> | null,
    end: TreeNode<E> | null,
    descending: boolean,
    changes: ChangeCounter,
    where: string,
    project?: (node: TreeNode<E>) => T,
  ) {
    super(changes, where)
    this.node = start
    this.end = end
    this.descending = descending
    this.project = project
  }
 
  protected step(): IteratorResult<T> {
    const node = this.node
    if (node === null || node === this.end) return done()
    this.node = this.descending ? predecessor(node) : successor(node)
    return {
      done: false,
      value: this.project === undefined ? (node.value as unknown as T) : this.project(node),
    }
  }
}
 
/**
 * A fail-fast cursor over the nodes from `start` up to, but not including, `end`; `remove()`
 * unlinks the node `next()` last returned. The next node is found before anything is removed, and
 * removal moves nodes rather than values, so the cursor carries on from where it was. It returns
 * `project(node)`: the node's value by default.
 *
 * @internal
 */
export class TreeCursor<E, T = E> extends FailFastCursor<T> implements Cursor<T> {
  private next_: TreeNode<E> | null
  private last: TreeNode<E> | null = null
  private readonly end: TreeNode<E> | null
  private readonly descending: boolean
  private readonly tree: OrderedTree<E>
  private readonly project: ((node: TreeNode<E>) => T) | undefined
 
  constructor(
    tree: OrderedTree<E>,
    start: TreeNode<E> | null,
    end: TreeNode<E> | null,
    descending: boolean,
    where: string,
    project?: (node: TreeNode<E>) => T,
  ) {
    super(tree.changes, where)
    this.tree = tree
    this.next_ = start
    this.end = end
    this.descending = descending
    this.project = project
  }
 
  protected hasMore(): boolean {
    return this.next_ !== null && this.next_ !== this.end
  }
 
  protected advance(): T {
    const node = this.next_ as TreeNode<E>
    this.last = node
    this.next_ = this.descending ? predecessor(node) : successor(node)
    return this.project === undefined ? (node.value as unknown as T) : this.project(node)
  }
 
  protected removeLast(): void {
    this.tree.remove(this.last as TreeNode<E>)
    this.last = null
    this.tree.changes.structural()
  }
}