All files / json-crdt/nodes/rga AbstractRga.ts

96.83% Statements 673/695
93.79% Branches 257/274
96.49% Functions 55/57
97.87% Lines 600/613

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 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973180x                   180x 180x 180x 180x 180x 180x 180x 180x                                                                                       180x 14907205x 14907205x 14907205x     180x 5688623x 5688623x 5688623x     180x 1967232x 1967232x 1967232x     180x 1956820x 10685297x 10685297x       180x 13673815x 13673815x 6879292x   6879292x 6879292x   6794523x 6794523x 6967015x 6967015x   6794523x     180x 4319226x 4319226x 2839914x   2839914x 2839914x   1479312x 1479312x 851679x 851679x   1479312x           180x 310076x 310076x 310076x           310076x         910798x 910798x 910798x   910798x 910798x 190863x 190863x   719935x 719935x 719935x 5532220x 5532220x 5532220x 1347453x 4184767x 933426x 933426x   3251341x 3251341x 1565404x 1685937x 1414826x 1414826x   271111x 271111x       719935x 719934x 719934x 719934x 719934x 719934x 719934x 719934x 719933x 719933x       834161x 16147x 16147x 16147x   818014x 818014x 818014x 818014x 818014x 818014x 818014x       207010x 207010x 207010x 98121x   46327x 23814x                     1537947x 1537947x 1537947x 1537947x 1537947x 1537947x 1537947x 370940x 370940x 370940x 366298x 366049x 366049x 366049x     1167256x 1167256x       760699x 4265664x 760699x       4265664x 4265664x 4265664x 4265664x 4265664x 4265662x 4265662x 4265662x 5663279x 5663279x 5663279x 5663279x 5663279x 5663279x 4779330x 1332010x 1332010x   883949x 883949x 883949x 617741x 617741x 462353x 462353x 462353x   155388x 155388x 155388x 155388x 155388x 155388x   266208x 266208x 266208x 221956x 221956x 221956x 221956x 221956x 221956x   44252x 44252x 44252x 44252x 44252x 44252x 44252x     65609x   4265662x       192030x 192030x 696635x 696635x   696635x 396748x 41765x 41765x 354983x 178015x 178015x 178015x   176968x 176968x     14015x       820298x 820298x 1172537x 1172537x   1172537x 987876x 77430x 77430x 910446x 820293x   90153x 90153x     5x       295285x 295285x 286687x 286687x 286687x 3719913x 3719913x 2341406x 1340737x 1340737x 1000669x 286686x 286686x   713983x 713983x     286687x 286686x 236153x 236153x 236153x   50533x 50533x 50533x 50533x 50533x 50533x 50529x 1420121x 485522x 485522x 485522x 49881x 49881x   435641x 435641x   648x         6071x 6071x 13990x 13990x   6071x                                           66492x 66492x 66492x 66492x 59045x 59045x 59045x 26116x 26116x 26116x   32929x 32929x   7447x   39640x 39640x 172967x   172967x 29184x 29184x   143783x 143783x   10456x           762356x 762356x 1959888x 1959888x 613416x   148940x       29x 29x 55x 55x 29x                               2786052x           53557x         643067x 643067x         127271x         955057x 955057x 955057x 631936x 631936x 631936x 419854x 419854x           108911x 108911x 108911x       51915x 51915x 51915x 51915x 51915x 51915x       51915x 51915x 51915x 51915x       269046x 269046x 269046x 269046x 269046x 269046x 146087x 146087x   269046x 269046x 269046x 269046x       1191070x 1191070x 1191070x 1191070x 1191070x 1354946x 1354946x 1354946x 1082878x 1082878x   1354946x 1354946x 1339058x 1339058x 1339058x 1339058x 341179x 191032x 20797x   163876x   1020835x 751910x 751910x 268925x       751910x 751910x 751910x 751910x 751910x       366049x 366049x 366049x 366049x 366049x 366049x 366049x 366049x 366049x 366049x 366049x 366049x 164094x 164094x   201955x 201955x 201955x 201955x 201955x 201955x 201955x   366049x 164934x 164934x   201115x 201115x 201115x 201115x 201115x 201115x 201115x   366049x 340720x 170142x 366049x 366049x 366049x 366049x 366049x 366049x 366049x 366049x 2029423x 2029423x     366049x 366049x 366049x       465848x 465848x 465848x 465848x 465848x 465848x 465848x 465848x 465848x 465848x 465848x       11714031x 7551674x 7551674x 7551674x 1877571x 316542x 316542x 316542x 316542x       4265662x 4265662x 7560843x 7560843x 7480701x 7480701x 7277423x             7277423x     4265662x 4265662x       74x 74x 74x 212x 212x   191x       316735x 316735x 316735x 316735x 316735x   316735x 92859x   92804x 84561x   223876x 19403x 19403x 19403x 19403x 19403x   19403x 19403x 123x 123x   19280x 10104x 19280x   19403x 27206x 27206x     204473x 204473x 204473x 204454x 190542x         2352807x 2352807x 2352807x       366049x 366049x       316735x 316735x       4493434x 4493434x 4493434x 4493434x 4493434x 47759017x 47759017x 47759017x 8392350x 39366667x 7492907x 7492907x   31873760x 31873760x 15014082x 16859678x 12884151x 12884151x   3975527x 3975527x       4493434x 4479919x 4479919x 4479919x 4479919x 4479919x 4475163x 4474763x 4474763x 4474759x               20x 20x 20x 20x 7x 7x 5x 5x 5x       15x 15x 15x 15x 15x 15x 15x 10x 10x 10x 10x 10x   5x 5x 5x 5x     5x 8x 8x 6x 4x 4x 4x   2x   4x 4x   5x           3187678x 3187678x 1967232x 1967232x 1967232x 312867x 165688x 312867x 312867x 312867x 312867x   1654365x 1654365x 835950x 408270x   427680x     818415x 310071x   508344x     1654365x 1654365x 1654365x 1654365x           49361x 49361x 416217x 416217x 416217x         178108x 171090x 171090x 1091036x 1091036x 1091036x 1091036x 1091036x 523548x 523548x   1091036x 1091036x 1091036x         1091036x 1091036x 1091036x 1091036x 1091036x 542733x 542733x   1091036x 1091036x 377213x 377213x   1091036x   1091036x 1091036x                   3776x 3776x 3776x 2556x 2513x 3776x 3776x       76167x     41509x 30927x           76434x 76434x 76434x   10340x 7076x   6909x 6909x     76434x      
import {
  compare,
  tick,
  type ITimestampStruct,
  type ITimespanStruct,
  tss,
  printTs,
  containsId,
  Timestamp,
} from '../../../json-crdt-patch/clock';
import {isUint8Array} from '@jsonjoy.com/util/lib/buffers/isUint8Array';
import {rSplay, lSplay, llSplay, rrSplay, lrSplay, rlSplay} from 'sonic-forest/lib/splay/util';
import {splay2} from 'sonic-forest/lib/splay/util2';
import {insert2, remove2} from 'sonic-forest/lib/util2';
import {ORIGIN} from '../../../json-crdt-patch/constants';
import {printTree} from 'tree-dump/lib/printTree';
import {printBinary} from 'tree-dump/lib/printBinary';
import {printOctets} from '@jsonjoy.com/util/lib/buffers/printOctets';
 
/**
 * @category CRDT Node
 */
export interface Chunk<T> {
  /** Unique sortable ID of this chunk and its span. */
  id: ITimestampStruct;
  /** Length of the logical clock interval of this chunk. */
  span: number;
  /** Whether this chunk is deleted. */
  del: boolean;
  /** Actual content of the chunk, may be undefined if chunk is deleted. */
  data: T | undefined;
  /** Length of content in this subtree (this node and its children). */
  len: number;
  /** Parent. */
  p: Chunk<T> | undefined;
  /** Left. */
  l: Chunk<T> | undefined;
  /** Right. */
  r: Chunk<T> | undefined;
  /** Parent 2. */
  p2: Chunk<T> | undefined;
  /** Left 2. */
  l2: Chunk<T> | undefined;
  /** Right 2. */
  r2: Chunk<T> | undefined;
  /** Split link, next chunk which was split from this chunk. */
  s: Chunk<T> | undefined;
  /** Add more content to this chunk. */
  merge(content: T): void;
  /**
   * Split this chunk after given clock ticks. Minimal `ticks` is 1.
   */
  split(ticks: number): Chunk<T>;
  /** Mark chunk as deleted. */
  delete(): void;
  /** Return a deep copy of itself. */
  clone(): Chunk<T>;
  /** Return the data of the chunk, if not deleted. */
  view(): T & {slice: (start: number, end: number) => T};
}
 
const compareById = (c1: Chunk<unknown>, c2: Chunk<unknown>): number => {
  const ts1 = c1.id;
  const ts2 = c2.id;
  return ts1.sid - ts2.sid || ts1.time - ts2.time;
};
 
const updateLenOne = (chunk: Chunk<unknown>): void => {
  const l = chunk.l;
  const r = chunk.r;
  chunk.len = (chunk.del ? 0 : chunk.span) + (l ? l.len : 0) + (r ? r.len : 0);
};
 
const updateLenOneLive = (chunk: Chunk<unknown>): void => {
  const l = chunk.l;
  const r = chunk.r;
  chunk.len = chunk.span + (l ? l.len : 0) + (r ? r.len : 0);
};
 
const dLen = (chunk: Chunk<unknown> | undefined, delta: number): void => {
  while (chunk) {
    chunk.len += delta;
    chunk = chunk.p;
  }
};
 
const next = <T>(curr: Chunk<T>): Chunk<T> | undefined => {
  const r = curr.r;
  if (r) {
    curr = r;
    let tmp: Chunk<T> | undefined;
    while ((tmp = curr.l)) curr = tmp;
    return curr;
  }
  let p = curr.p;
  while (p && p.r === curr) {
    curr = p;
    p = p.p;
  }
  return p;
};
 
const prev = <T>(curr: Chunk<T>): Chunk<T> | undefined => {
  const l = curr.l;
  if (l) {
    curr = l;
    let tmp: Chunk<T> | undefined;
    while ((tmp = curr.r)) curr = tmp;
    return curr;
  }
  let p = curr.p;
  while (p && p.l === curr) {
    curr = p;
    p = p.p;
  }
  return p;
};
 
/**
 * @category CRDT Node
 */
export abstract class AbstractRga<T> {
  public root: Chunk<T> | undefined = undefined;
  public ids: Chunk<T> | undefined = undefined;
  public count: number = 0;
 
  public abstract view(): unknown;
  protected abstract createChunk(id: ITimestampStruct, content: T | undefined): Chunk<T>;
  protected abstract onChange(): void;
 
  constructor(public readonly id: ITimestampStruct) {}
 
  // --------------------------------------------------------------- Public API
 
  public ins(after: ITimestampStruct, id: ITimestampStruct, content: T): void {
    const rootId = this.id;
    const afterTime = after.time;
    const afterSid = after.sid;
    // TODO: perf: sid equality check is redundant? As it is implied by time equality.
    const isRootInsert = rootId.time === afterTime && rootId.sid === afterSid;
    if (isRootInsert) {
      this.insAfterRoot(after, id, content);
      return;
    }
    let curr: Chunk<T> | undefined = this.ids;
    let chunk: Chunk<T> | undefined = curr;
    while (curr) {
      const currId = curr.id;
      const currIdSid = currId.sid;
      if (currIdSid > afterSid) {
        curr = curr.l2;
      } else if (currIdSid < afterSid) {
        chunk = curr;
        curr = curr.r2;
      } else {
        const currIdTime = currId.time;
        if (currIdTime > afterTime) {
          curr = curr.l2;
        } else if (currIdTime < afterTime) {
          chunk = curr;
          curr = curr.r2;
        } else {
          chunk = curr;
          break;
        }
      }
    }
    if (!chunk) return;
    const atId = chunk.id;
    const atIdTime = atId.time;
    const atIdSid = atId.sid;
    const atSpan = chunk.span;
    Iif (atIdSid !== afterSid) return;
    const offset = afterTime - atIdTime;
    if (offset >= atSpan) return;
    const offsetInInsertAtChunk = afterTime - atIdTime;
    this.insAfterChunk(after, chunk, offsetInInsertAtChunk, id, content);
  }
 
  public insAt(position: number, id: ITimestampStruct, content: T): ITimestampStruct | undefined {
    if (!position) {
      const rootId = this.id;
      this.insAfterRoot(rootId, id, content);
      return rootId;
    }
    const found = this.findChunk(position - 1);
    Iif (!found) return undefined;
    const [at, offset] = found;
    const atId = at.id;
    const after = offset === 0 ? atId : new Timestamp(atId.sid, atId.time + offset);
    this.insAfterChunk(after, at, offset, id, content);
    return after;
  }
 
  protected insAfterRoot(after: ITimestampStruct, id: ITimestampStruct, content: T): void {
    const chunk = this.createChunk(id, content);
    const first = this.first();
    if (!first) this.setRoot(chunk);
    else if (compare(first.id, id) < 0) this.insertBefore(chunk, first);
    else {
      if (containsId(first.id, first.span, id)) return;
      this.insertAfterRef(chunk, after, first);
    }
  }
 
  protected insAfterChunk(
    after: ITimestampStruct,
    chunk: Chunk<T>,
    chunkOffset: number,
    id: ITimestampStruct,
    content: T,
  ): void {
    const atId = chunk.id;
    const atIdTime = atId.time;
    const atIdSid = atId.sid;
    const atSpan = chunk.span;
    const newChunk = this.createChunk(id, content);
    const needsSplit = chunkOffset + 1 < atSpan;
    if (needsSplit) {
      const idSid = id.sid;
      const idTime = id.time;
      if (atIdSid === idSid && atIdTime <= idTime && atIdTime + atSpan - 1 >= idTime) return;
      if (idTime > after.time + 1 || idSid > after.sid) {
        this.insertInside(newChunk, chunk, chunkOffset + 1);
        this.splay(newChunk);
        return;
      }
    }
    this.insertAfterRef(newChunk, after, chunk);
    this.splay(newChunk);
  }
 
  public delete(spans: ITimespanStruct[]): void {
    const length = spans.length;
    for (let i = 0; i < length; i++) this.deleteSpan(spans[i]);
    this.onChange();
  }
 
  protected deleteSpan(span: ITimespanStruct): void {
    const len = span.span;
    const t1 = span.time;
    const t2 = t1 + len - 1;
    const start = this.findById(span);
    if (!start) return;
    let chunk: Chunk<T> | undefined = start;
    let last: Chunk<T> | undefined = chunk;
    while (chunk) {
      last = chunk;
      const id = chunk.id;
      const chunkSpan = chunk.span;
      const c1 = id.time;
      const c2 = c1 + chunkSpan - 1;
      if (chunk.del) {
        if (c2 >= t2) break;
        chunk = chunk.s;
        continue;
      }
      const deleteStartsFromLeft = t1 <= c1;
      const deleteStartsInTheMiddle = t1 <= c2;
      if (deleteStartsFromLeft) {
        const deleteFullyContainsChunk = t2 >= c2;
        if (deleteFullyContainsChunk) {
          chunk.delete();
          dLen(chunk, -chunk.span);
          if (t2 <= c2) break;
        } else {
          const range = t2 - c1 + 1;
          const newChunk = this.split(chunk, range);
          chunk.delete();
          updateLenOne(newChunk);
          dLen(chunk, -chunk.span);
          break;
        }
      } else if (deleteStartsInTheMiddle) {
        const deleteContainsRightSide = t2 >= c2;
        if (deleteContainsRightSide) {
          const offset = t1 - c1;
          const newChunk = this.split(chunk, offset);
          newChunk.delete();
          newChunk.len = newChunk.r ? newChunk.r.len : 0;
          dLen(chunk, -newChunk.span);
          if (t2 <= c2) break;
        } else {
          const right = this.split(chunk, t2 - c1 + 1);
          const mid = this.split(chunk, t1 - c1);
          mid.delete();
          updateLenOne(right);
          updateLenOne(mid);
          dLen(chunk, -mid.span);
          break;
        }
      }
      chunk = chunk.s;
    }
    if (last) this.mergeTombstones2(start, last);
  }
 
  public find(position: number): undefined | ITimestampStruct {
    let curr = this.root;
    while (curr) {
      const l = curr.l;
      const leftLength = l ? l.len : 0;
      let span: number;
      if (position < leftLength) curr = l;
      else if (curr.del) {
        position -= leftLength;
        curr = curr.r;
      } else if (position < leftLength + (span = curr.span)) {
        const ticks = position - leftLength;
        const id = curr.id;
        return !ticks ? id : new Timestamp(id.sid, id.time + ticks);
      } else {
        position -= leftLength + span;
        curr = curr.r;
      }
    }
    return;
  }
 
  public findChunk(position: number): undefined | [chunk: Chunk<T>, offset: number] {
    let curr = this.root;
    while (curr) {
      const l = curr.l;
      const leftLength = l ? l.len : 0;
      let span: number;
      if (position < leftLength) curr = l;
      else if (curr.del) {
        position -= leftLength;
        curr = curr.r;
      } else if (position < leftLength + (span = curr.span)) {
        return [curr, position - leftLength];
      } else {
        position -= leftLength + span;
        curr = curr.r;
      }
    }
    return;
  }
 
  public findInterval(position: number, length: number): ITimespanStruct[] {
    const ranges: ITimespanStruct[] = [];
    if (!length) return ranges;
    let curr = this.root;
    let offset: number = 0;
    while (curr) {
      const leftLength = curr.l ? curr.l.len : 0;
      if (position < leftLength) curr = curr.l;
      else if (curr.del) {
        position -= leftLength;
        curr = curr.r;
      } else if (position < leftLength + curr.span) {
        offset = position - leftLength;
        break;
      } else {
        position -= leftLength + curr.span;
        curr = curr.r;
      }
    }
    if (!curr) return ranges;
    if (curr.span >= length + offset) {
      const id = curr.id;
      ranges.push(tss(id.sid, id.time + offset, length));
      return ranges;
    }
    const len = curr.span - offset;
    const id = curr.id;
    ranges.push(tss(id.sid, id.time + offset, len));
    length -= len;
    curr = next(curr);
    if (!curr) return ranges;
    do {
      if (curr.del) continue;
      const id = curr.id;
      const span = curr.span;
      if (length <= span) {
        ranges.push(tss(id.sid, id.time, length));
        return ranges;
      }
      ranges.push(tss(id.sid, id.time, span));
      length -= span;
    } while ((curr = next(curr)) && length > 0);
    return ranges;
  }
 
  /** Rename to .rangeX() method? */
  public findInterval2(from: ITimestampStruct, to: ITimestampStruct): ITimespanStruct[] {
    const ranges: ITimespanStruct[] = [];
    this.range0(undefined, from, to, (chunk, off, len) => {
      const id = chunk.id;
      ranges.push(tss(id.sid, id.time + off, len));
    });
    return ranges;
  }
 
  /**
   * @note All ".rangeX()" method are not performance optimized. For hot paths
   * it is better to hand craft the loop.
   *
   * @param startChunk Chunk from which to start the range. If undefined, the
   *                   chunk containing `from` will be used. This is an optimization
   *                   to avoid a lookup.
   * @param from ID of the first element in the range.
   * @param to ID of the last element in the range.
   * @param callback Function to call for each chunk slice in the range. If it
   *     returns truthy value, the iteration will stop.
   * @returns Reference to the last chunk in the range.
   */
  public range0(
    startChunk: Chunk<T> | undefined,
    from: ITimestampStruct,
    to: ITimestampStruct,
    callback: (chunk: Chunk<T>, off: number, len: number) => boolean | void,
  ): Chunk<T> | void {
    let chunk: Chunk<T> | undefined = startChunk ? startChunk : this.findById(from);
    if (startChunk) while (chunk && !containsId(chunk.id, chunk.span, from)) chunk = next(chunk);
    Iif (!chunk) return;
    if (!chunk.del) {
      const off: number = from.time - chunk.id.time;
      const toContainedInChunk = containsId(chunk.id, chunk.span, to);
      if (toContainedInChunk) {
        const len = to.time - from.time + 1;
        callback(chunk, off, len);
        return chunk;
      }
      const len = chunk.span - off;
      if (callback(chunk, off, len)) return chunk;
    } else {
      if (containsId(chunk.id, chunk.span, to)) return;
    }
    chunk = next(chunk);
    while (chunk) {
      const toContainedInChunk = containsId(chunk.id, chunk.span, to);
      // TODO: fast path for chunk.del
      if (toContainedInChunk) {
        if (!chunk.del) Iif (callback(chunk, 0, to.time - chunk.id.time + 1)) return chunk;
        return chunk;
      }
      if (!chunk.del) Iif (callback(chunk, 0, chunk.span)) return chunk;
      chunk = next(chunk);
    }
    return chunk;
  }
 
  // ---------------------------------------------------------------- Retrieval
 
  public first(): Chunk<T> | undefined {
    let curr = this.root;
    while (curr) {
      const l = curr.l;
      if (l) curr = l;
      else return curr;
    }
    return curr;
  }
 
  public last(): Chunk<T> | undefined {
    let curr = this.root;
    while (curr) {
      const r = curr.r;
      if (r) curr = r;
      else return curr;
    }
    return curr;
  }
 
  public lastId(): ITimestampStruct | undefined {
    const chunk = this.last();
    Iif (!chunk) return undefined;
    const id = chunk.id;
    const span = chunk.span;
    return span === 1 ? id : new Timestamp(id.sid, id.time + span - 1);
  }
 
  /** @todo Maybe use implementation from tree utils, if does not impact performance. */
  /** @todo Or better remove this method completely, as it does not require "this". */
  public next(curr: Chunk<T>): Chunk<T> | undefined {
    return next(curr);
  }
 
  /** @todo Maybe use implementation from tree utils, if does not impact performance. */
  /** @todo Or better remove this method completely, as it does not require "this". */
  public prev(curr: Chunk<T>): Chunk<T> | undefined {
    return prev(curr);
  }
 
  /** Content length. */
  public length(): number {
    const root = this.root;
    return root ? root.len : 0;
  }
 
  /** Number of chunks. */
  public size(): number {
    return this.count;
  }
 
  /** Returns the position of the first element in the chunk. */
  public pos(chunk: Chunk<T>): number {
    const p = chunk.p;
    const l = chunk.l;
    if (!p) return l ? l.len : 0;
    const parentPos = this.pos(p);
    const isRightChild = p.r === chunk;
    if (isRightChild) return parentPos + (p.del ? 0 : p.span) + (l ? l.len : 0);
    const r = chunk.r;
    return parentPos - (chunk.del ? 0 : chunk.span) - (r ? r.len : 0);
  }
 
  // --------------------------------------------------------------- Insertions
 
  public setRoot(chunk: Chunk<T>): void {
    this.root = chunk;
    this.insertId(chunk);
    this.onChange();
  }
 
  public insertBefore(chunk: Chunk<T>, before: Chunk<T>): void {
    const l = before.l;
    before.l = chunk;
    chunk.l = l;
    chunk.p = before;
    let lLen = 0;
    Iif (l) {
      l.p = chunk;
      lLen = l.len;
    }
    chunk.len = chunk.span + lLen;
    dLen(before, chunk.span);
    this.insertId(chunk);
    this.onChange();
  }
 
  public insertAfter(chunk: Chunk<T>, after: Chunk<T>): void {
    const r = after.r;
    after.r = chunk;
    chunk.r = r;
    chunk.p = after;
    let rLen = 0;
    if (r) {
      r.p = chunk;
      rLen = r.len;
    }
    chunk.len = chunk.span + rLen;
    dLen(after, chunk.span);
    this.insertId(chunk);
    this.onChange();
  }
 
  protected insertAfterRef(chunk: Chunk<T>, ref: ITimestampStruct, left: Chunk<T>): void {
    const id = chunk.id;
    const sid = id.sid;
    const time = id.time;
    let isSplit: boolean = false;
    for (;;) {
      const leftId = left.id;
      const leftNextTick = leftId.time + left.span;
      if (!left.s) {
        isSplit = leftId.sid === sid && leftNextTick === time && leftNextTick - 1 === ref.time;
        if (isSplit) left.s = chunk;
      }
      const right = next(left);
      if (!right) break;
      const rightId = right.id;
      const rightIdTime = rightId.time;
      const rightIdSid = rightId.sid;
      if (rightIdTime < time) break;
      if (rightIdTime === time) {
        if (rightIdSid === sid) return;
        if (rightIdSid < sid) break;
      }
      left = right;
    }
    if (isSplit && !left.del) {
      this.mergeContent(left, chunk.data!);
      left.s = undefined;
    } else this.insertAfter(chunk, left);
  }
 
  protected mergeContent(chunk: Chunk<T>, content: T): void {
    const span1 = chunk.span;
    chunk.merge(content);
    dLen(chunk, chunk.span - span1);
    this.onChange();
    return;
  }
 
  protected insertInside(chunk: Chunk<T>, at: Chunk<T>, offset: number): void {
    const p = at.p;
    const l = at.l;
    const r = at.r;
    const s = at.s;
    const len = at.len;
    const at2 = at.split(offset);
    at.s = at2;
    at2.s = s;
    at.l = at.r = at2.l = at2.r = undefined;
    at2.l = undefined;
    chunk.p = p;
    if (!l) {
      chunk.l = at;
      at.p = chunk;
    } else {
      chunk.l = l;
      l.p = chunk;
      const a = l.r;
      l.r = at;
      at.p = l;
      at.l = a;
      if (a) a.p = at;
    }
    if (!r) {
      chunk.r = at2;
      at2.p = chunk;
    } else {
      chunk.r = r;
      r.p = chunk;
      const b = r.l;
      r.l = at2;
      at2.p = r;
      at2.r = b;
      if (b) b.p = at2;
    }
    if (!p) this.root = chunk;
    else if (p.l === at) p.l = chunk;
    else p.r = chunk;
    updateLenOne(at);
    updateLenOne(at2);
    if (l) l.len = (l.l ? l.l.len : 0) + at.len + (l.del ? 0 : l.span);
    if (r) r.len = (r.r ? r.r.len : 0) + at2.len + (r.del ? 0 : r.span);
    chunk.len = len + chunk.span;
    const span = chunk.span;
    let curr = chunk.p;
    while (curr) {
      curr.len += span;
      curr = curr.p;
    }
    // TODO: perf: could insert these two ids in one go
    this.insertId(at2);
    this.insertIdFast(chunk);
    this.onChange();
  }
 
  protected split(chunk: Chunk<T>, ticks: number): Chunk<T> {
    const s = chunk.s;
    const newChunk = chunk.split(ticks);
    const r = chunk.r;
    chunk.s = newChunk;
    newChunk.r = r;
    newChunk.s = s;
    chunk.r = newChunk;
    newChunk.p = chunk;
    this.insertId(newChunk);
    if (r) r.p = newChunk;
    return newChunk;
  }
 
  protected mergeTombstones(ch1: Chunk<T>, ch2: Chunk<T>): boolean {
    if (!ch1.del || !ch2.del) return false;
    const id1 = ch1.id;
    const id2 = ch2.id;
    if (id1.sid !== id2.sid) return false;
    if (id1.time + ch1.span !== id2.time) return false;
    ch1.s = ch2.s;
    ch1.span += ch2.span;
    this.deleteChunk(ch2);
    return true;
  }
 
  protected mergeTombstones2(start: Chunk<T>, end: Chunk<T>): void {
    let curr: Chunk<T> | undefined = start;
    while (curr) {
      const nextCurr = next(curr);
      if (!nextCurr) break;
      const merged = this.mergeTombstones(curr, nextCurr);
      if (!merged) {
        Iif (nextCurr === end) {
          Iif (nextCurr) {
            const n = next(nextCurr);
            Iif (n) this.mergeTombstones(nextCurr, n);
          }
          break;
        }
        curr = curr.s;
      }
    }
    const left = prev(start);
    if (left) this.mergeTombstones(left, start);
  }
 
  public removeTombstones(): void {
    let curr = this.first();
    const list: Chunk<T>[] = [];
    while (curr) {
      if (curr.del) list.push(curr);
      curr = next(curr);
    }
    for (let i = 0; i < list.length; i++) this.deleteChunk(list[i]);
  }
 
  public deleteChunk(chunk: Chunk<T>): void {
    this.deleteId(chunk);
    const p = chunk.p;
    const l = chunk.l;
    const r = chunk.r;
    chunk.id = ORIGIN; // mark chunk as disposed
    // TODO: perf: maybe set .p, .l, .r to undefined to help GC?
    if (!l && !r) {
      if (!p) this.root = undefined;
      else {
        if (p.l === chunk) p.l = undefined;
        else p.r = undefined;
      }
    } else if (l && r) {
      let mostRightChildFromLeft = l;
      while (mostRightChildFromLeft.r) mostRightChildFromLeft = mostRightChildFromLeft.r;
      mostRightChildFromLeft.r = r;
      r.p = mostRightChildFromLeft;
      const rLen = r.len;
      let curr: undefined | Chunk<T>;
      curr = mostRightChildFromLeft;
      if (!p) {
        this.root = l;
        l.p = undefined;
      } else {
        if (p.l === chunk) p.l = l;
        else p.r = l;
        l.p = p;
      }
      while (curr && curr !== p) {
        curr.len += rLen;
        curr = curr.p;
      }
    } else {
      const child = (l || r)!;
      child.p = p;
      if (!p) this.root = child;
      else if (p.l === chunk) p.l = child;
      else p.r = child;
    }
  }
 
  public insertId(chunk: Chunk<T>): void {
    this.ids = insert2(this.ids, chunk, compareById);
    this.count++;
    this.ids = splay2(this.ids, chunk);
  }
 
  public insertIdFast(chunk: Chunk<T>): void {
    this.ids = insert2(this.ids, chunk, compareById);
    this.count++;
  }
 
  protected deleteId(chunk: Chunk<T>): void {
    this.ids = remove2(this.ids, chunk);
    this.count--;
  }
 
  public findById(after: ITimestampStruct): Chunk<T> | undefined {
    const afterSid = after.sid;
    const afterTime = after.time;
    let curr: Chunk<T> | undefined = this.ids;
    let chunk: Chunk<T> | undefined = curr;
    while (curr) {
      const currId = curr.id;
      const currIdSid = currId.sid;
      if (currIdSid > afterSid) {
        curr = curr.l2;
      } else if (currIdSid < afterSid) {
        chunk = curr;
        curr = curr.r2;
      } else {
        const currIdTime = currId.time;
        if (currIdTime > afterTime) {
          curr = curr.l2;
        } else if (currIdTime < afterTime) {
          chunk = curr;
          curr = curr.r2;
        } else {
          chunk = curr;
          break;
        }
      }
    }
    if (!chunk) return;
    const atId = chunk.id;
    const atIdTime = atId.time;
    const atIdSid = atId.sid;
    const atSpan = chunk.span;
    if (atIdSid !== afterSid) return;
    if (afterTime < atIdTime) return;
    const offset = afterTime - atIdTime;
    if (offset >= atSpan) return;
    return chunk;
  }
 
  /**
   * @param id ID of character to start the search from.
   * @returns Previous ID in the RGA sequence.
   */
  public prevId(id: ITimestampStruct): ITimestampStruct | undefined {
    let chunk = this.findById(id);
    Iif (!chunk) return;
    const time = id.time;
    if (chunk.id.time < time) return new Timestamp(id.sid, time - 1);
    chunk = prev(chunk);
    if (!chunk) return;
    const prevId = chunk.id;
    const span = chunk.span;
    return span > 1 ? new Timestamp(prevId.sid, prevId.time + chunk.span - 1) : prevId;
  }
 
  public spanView(span: ITimespanStruct): T[] {
    const view: T[] = [];
    let remaining = span.span;
    const time = span.time;
    let chunk = this.findById(span);
    Iif (!chunk) return view;
    if (!chunk.del) {
      if (chunk.span >= remaining + time - chunk.id.time) {
        const offset = time - chunk.id.time;
        const end = offset + remaining;
        const viewChunk = chunk.view().slice(offset, end);
        view.push(viewChunk);
        return view;
      } else {
        const offset = time - chunk.id.time;
        const viewChunk = chunk.view().slice(offset, span.span);
        remaining -= chunk.span - offset;
        view.push(viewChunk);
      }
    }
    while ((chunk = chunk.s)) {
      const chunkSpan = chunk.span;
      if (!chunk.del) {
        if (chunkSpan > remaining) {
          const viewChunk = chunk.view().slice(0, remaining);
          view.push(viewChunk);
          break;
        }
        view.push(chunk.data!);
      }
      remaining -= chunkSpan;
      if (remaining <= 0) break;
    }
    return view;
  }
 
  // ---------------------------------------------------------- Splay balancing
 
  public splay(chunk: Chunk<T>): void {
    const p = chunk.p;
    if (!p) return;
    const pp = p.p;
    const l2 = p.l === chunk;
    if (!pp) {
      if (l2) rSplay(chunk, p);
      else lSplay(chunk, p);
      this.root = chunk;
      updateLenOne(p);
      updateLenOneLive(chunk);
      return;
    }
    const l1 = pp.l === p;
    if (l1) {
      if (l2) {
        this.root = llSplay(this.root!, chunk, p, pp);
      } else {
        this.root = lrSplay(this.root!, chunk, p, pp);
      }
    } else {
      if (l2) {
        this.root = rlSplay(this.root!, chunk, p, pp);
      } else {
        this.root = rrSplay(this.root!, chunk, p, pp);
      }
    }
    updateLenOne(pp);
    updateLenOne(p);
    updateLenOneLive(chunk);
    this.splay(chunk);
  }
 
  // ---------------------------------------------------------- Export / Import
 
  public iterator(): () => Chunk<T> | undefined {
    let curr = this.first();
    return () => {
      const res = curr;
      if (curr) curr = next(curr);
      return res;
    };
  }
 
  public ingest(size: number, next: () => Chunk<T>): void {
    if (size < 1) return;
    const splitLeftChunks = new Map<string, Chunk<T>>();
    this.root = this._ingest(size, () => {
      const chunk = next();
      const id = chunk.id;
      const key = id.sid + '.' + id.time;
      const split = splitLeftChunks.get(key);
      if (split) {
        split.s = chunk;
        splitLeftChunks.delete(key);
      }
      const nextStampAfterSpan = tick(id, chunk.span);
      splitLeftChunks.set(nextStampAfterSpan.sid + '.' + nextStampAfterSpan.time, chunk);
      return chunk;
    });
  }
 
  private _ingest(size: number, next: () => Chunk<T>): Chunk<T> {
    const leftSize = size >> 1;
    const rightSize = size - leftSize - 1;
    const c1 = leftSize > 0 ? this._ingest(leftSize, next) : undefined;
    const c2 = next();
    if (c1) {
      c2.l = c1;
      c1.p = c2;
    }
    const c3 = rightSize > 0 ? this._ingest(rightSize, next) : undefined;
    if (c3) {
      c2.r = c3;
      c3.p = c2;
    }
    updateLenOne(c2);
    // TODO: perf: splay only nodes with hight clock values and which are not tombstones?
    this.insertId(c2);
    return c2;
  }
 
  // ---------------------------------------------------------------- Printable
 
  protected toStringName(): string {
    return 'AbstractRga';
  }
 
  public toString(tab: string = ''): string {
    const view = this.view();
    let value = '';
    if (isUint8Array(view)) value += ` { ${printOctets(view) || '∅'} }`;
    else if (typeof view === 'string')
      value += `{ ${view.length > 32 ? JSON.stringify(view.substring(0, 32)) + ' …' : JSON.stringify(view)} }`;
    const header = `${this.toStringName()} ${printTs(this.id)} ${value}`;
    return header + printTree(tab, [(tab) => (this.root ? this.printChunk(tab, this.root) : '∅')]);
  }
 
  protected printChunk(tab: string, chunk: Chunk<T>): string {
    return (
      this.formatChunk(chunk) +
      printBinary(tab, [
        chunk.l ? (tab) => this.printChunk(tab, chunk.l!) : null,
        chunk.r ? (tab) => this.printChunk(tab, chunk.r!) : null,
      ])
    );
  }
 
  protected formatChunk(chunk: Chunk<T>): string {
    const id = printTs(chunk.id);
    let str = `chunk ${id}:${chunk.span} .${chunk.len}.`;
    if (chunk.del) str += ` [${chunk.span}]`;
    else {
      if (isUint8Array(chunk.data)) str += ` { ${printOctets(chunk.data) || '∅'} }`;
      else if (typeof chunk.data === 'string') {
        const data =
          chunk.data.length > 32 ? JSON.stringify(chunk.data.substring(0, 32)) + ' …' : JSON.stringify(chunk.data);
        str += ` { ${data} }`;
      }
    }
    return str;
  }
}