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

96.69% Statements 672/695
93.43% Branches 256/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 973181x                   181x 181x 181x 181x 181x 181x 181x 181x                                                                                       181x 14974306x 14974306x 14974306x     181x 5668812x 5668812x 5668812x     181x 1967300x 1967300x 1967300x     181x 1968069x 10712596x 10712596x       181x 11809556x 11809556x 5953080x   5953080x 5953080x   5856476x 5856476x 5853705x 5853705x   5856476x     181x 3196253x 3196253x 1978084x   1978084x 1978084x   1218169x 1218169x 739762x 739762x   1218169x           181x 297278x 297278x 297278x           297278x         923279x 923279x 923279x   923279x 923279x 195290x 195290x   727989x 727989x 727989x 5274003x 5274003x 5274003x 1180380x 4093623x 954436x 954436x   3139187x 3139187x 1455956x 1683231x 1410066x 1410066x   273165x 273165x       727989x 727988x 727988x 727988x 727988x 727988x 727988x 727988x 727987x 727987x       834057x 16219x 16219x 16219x   817838x 817838x 817838x 817838x 817838x 817838x 817838x       211509x 211509x 211509x 101949x   50065x 27556x                     1545825x 1545825x 1545825x 1545825x 1545825x 1545825x 1545825x 375202x 375202x 375202x 370708x 370464x 370464x 370464x     1170867x 1170867x       758635x 3143858x 758635x       3143858x 3143858x 3143858x 3143858x 3143858x 3143856x 3143856x 3143856x 4147241x 4147241x 4147241x 4147241x 4147241x 4147241x 3257670x 937484x 937484x   889571x 889571x 889571x 617647x 617647x 459219x 459219x 459219x   158428x 158428x 158428x 158428x 158428x 158428x   271924x 271924x 271924x 226620x 226620x 226620x 226620x 226620x 226620x   45304x 45304x 45304x 45304x 45304x 45304x 45304x     65903x   3143856x       193111x 193111x 702588x 702588x   702588x 399715x 42282x 42282x 357433x 178736x 178736x 178736x   178697x 178697x     14375x       820165x 820165x 1171992x 1171992x   1171992x 987414x 77307x 77307x 910107x 820160x   89947x 89947x     5x       295311x 295311x 286520x 286520x 286520x 3712455x 3712455x 2339490x 1340644x 1340644x 998846x 286519x 286519x   712327x 712327x     286520x 286519x 236162x 236162x 236162x   50357x 50357x 50357x 50357x 50357x 50357x 50353x 1019093x 371238x 371238x 371238x 49705x 49705x   321533x 321533x   648x         6020x 6020x 13730x 13730x   6020x                                           65850x 65850x 65850x 65850x 58340x 58340x 58340x 25649x 25649x 25649x   32691x 32691x   7510x   39438x 39438x 170121x   170121x 29032x 29032x   141089x 141089x   10406x           749167x 749167x 1959688x 1959688x 600044x   149123x       29x 29x 55x 55x 29x                               2770873x           52390x         642979x 642979x         126313x         952565x 952565x 952565x 634347x 634347x 634347x 426278x 426278x           109582x 109582x 109582x       52005x 52005x 52005x 52005x 52005x 52005x       52005x 52005x 52005x 52005x       274657x 274657x 274657x 274657x 274657x 274657x 147642x 147642x   274657x 274657x 274657x 274657x       1198423x 1198423x 1198423x 1198423x 1198423x 1412591x 1412591x 1412591x 1136098x 1136098x   1412591x 1412591x 1396665x 1396665x 1396665x 1396665x 395028x 195994x 23943x   214168x   1026372x 751836x 751836x 274536x       751836x 751836x 751836x 751836x 751836x       370464x 370464x 370464x 370464x 370464x 370464x 370464x 370464x 370464x 370464x 370464x 370464x 167739x 167739x   202725x 202725x 202725x 202725x 202725x 202725x 202725x   370464x 166967x 166967x   203497x 203497x 203497x 203497x 203497x 203497x 203497x   370464x 345261x 172778x 370464x 370464x 370464x 370464x 370464x 370464x 370464x 370464x 2028211x 2028211x     370464x 370464x 370464x       475656x 475656x 475656x 475656x 475656x 475656x 475656x 475656x 475656x 475656x 475656x       9100224x 5442914x 5442914x 5442914x 1636231x 319293x 319293x 319293x 319293x       3143856x 3143856x 6069725x 6069725x 5988309x 5988309x 5783983x             5783983x     3143856x 3143856x       70x 70x 70x 202x 202x   188x       319483x 319483x 319483x 319483x 319483x   319483x 94061x   94004x 85529x   225422x 19924x 19924x 19924x 19924x 19924x   19924x 19924x 125x 125x   19799x 10387x 19799x   19924x 27895x 27895x     205498x 205498x 205498x 205464x 191251x         2342071x 2342071x 2342071x       370464x 370464x       319483x 319483x       3369130x 3369130x 3369130x 3369130x 3369130x 31402378x 31402378x 31402378x 5318414x 26083964x 4927156x 4927156x   21156808x 21156808x 9953072x 11203736x 8351442x 8351442x   2852294x 2852294x       3369130x 3356305x 3356305x 3356305x 3356305x 3356305x 3351546x 3351146x 3351146x 3351146x               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           3193182x 3193182x 1967300x 1967300x 1967300x 315457x 166788x 315457x 315457x 315457x 315457x   1651843x 1651843x 835324x 407218x   428106x     816519x 306214x   510305x     1651843x 1651843x 1651843x 1651843x           46898x 46898x 401940x 401940x 401940x         164992x 158108x 158108x 1059705x 1059705x 1059705x 1059705x 1059705x 519211x 519211x   1059705x 1059705x 1059705x         1059705x 1059705x 1059705x 1059705x 1059705x 532130x 532130x   1059705x 1059705x 369467x 369467x   1059705x   1059705x 1059705x                   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;
    Iif (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;
  }
}