All files / json-crdt/nodes/vec VecNode.ts

96.77% Statements 90/93
92.1% Branches 35/38
88.23% Functions 15/17
96% Lines 72/75

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 208174x 174x 174x 174x                               174x       27097x           27097x 27097x       2x                   125004x                   132861x 132861x 131563x             125004x 125003x 125003x 125001x 125001x 82215x 125001x               27097x               6239x 3205x 3205x 3205x 2208x 2208x 2205x 2205x             5x               3205x 2320x 2320x 2313x 2313x 2313x 105x 2208x                               130x             153415x 153415x 153415x 153415x 717047x 717047x 717011x 717011x             27097x           2003x 2003x 988x 988x 988x 988x 988x 988x 988x 3475x 3475x 3475x 3475x 3475x   988x           27097x     13x           7x 7x 7x     7x 7x       20x 20x                  
import {ConNode} from '../const/ConNode';
import {CRDT_CONSTANTS} from '../../constants';
import {printTree} from 'tree-dump/lib/printTree';
import {compare, type ITimestampStruct, printTs} from '../../../json-crdt-patch/clock';
import type {Model} from '../../model';
import type {JsonNode, JsonNodeView} from '..';
import type {Printable} from 'tree-dump/lib/types';
import type {ExtNode} from '../../extensions/ExtNode';
import type {VecNodeExtensionData} from '../../schema/types';
 
/**
 * Represents a `vec` JSON CRDT node, which is a LWW array.
 *
 * Vector is, usually a fixed length, last-write-wins array. Each element
 * in the array is a reference to another JSON CRDT node. The vector
 * can be extended by adding new elements to the end of the array.
 *
 * @category CRDT Node
 */
export class VecNode<Value extends JsonNode[] = JsonNode[]> implements JsonNode<JsonNodeView<Value>>, Printable {
  /**
   * @ignore
   */
  public readonly elements: (ITimestampStruct | undefined)[] = [];
 
  constructor(
    /**
     * @ignore
     */
    public readonly doc: Model<any>,
    public readonly id: ITimestampStruct,
  ) {}
 
  public length(): number {
    return this.elements.length;
  }
 
  /**
   * Retrieves the ID of an element at the given index.
   *
   * @param index Index of the element to get.
   * @returns ID of the element at the given index, if any.
   */
  public val(index: number): ITimestampStruct | undefined {
    return this.elements[index] as ITimestampStruct | undefined;
  }
 
  /**
   * Retrieves the JSON CRDT node at the given index.
   *
   * @param index Index of the element to get.
   * @returns JSON CRDT node at the given index, if any.
   */
  public get<Index extends number>(index: Index): Value[Index] | undefined {
    const id = this.elements[index] as ITimestampStruct | undefined;
    if (!id) return undefined;
    return this.doc.index.get(id);
  }
 
  /**
   * @ignore
   */
  public put(index: number, id: ITimestampStruct): ITimestampStruct | undefined {
    if (index > CRDT_CONSTANTS.MAX_TUPLE_LENGTH) throw new Error('OUT_OF_BOUNDS');
    const currentId = this.val(index);
    if (currentId && compare(currentId, id) >= 0) return;
    if (index > this.elements.length) for (let i = this.elements.length; i < index; i++) this.elements.push(undefined);
    if (index < this.elements.length) this.elements[index] = id;
    else this.elements.push(id);
    return currentId;
  }
 
  // ----------------------------------------------------------------- extension
 
  /**
   * @ignore
   */
  private __extNode: VecNodeExtensionData<Value> = <any>undefined;
 
  /**
   * @ignore
   * @returns Returns the extension data node if this is an extension node,
   *          otherwise `undefined`. The node is cached after the first access.
   */
  public ext(): VecNodeExtensionData<Value> {
    if (this.__extNode) return this.__extNode;
    const extensionId = this.getExtId();
    const isExtension = extensionId >= 0;
    if (!isExtension) return <any>undefined;
    const extension = this.doc.ext.get(extensionId);
    if (!extension) return <any>undefined;
    this.__extNode = new extension.Node(this.get(1)!);
    return this.__extNode;
  }
 
  /**
   * @ignore
   */
  public isExt(): boolean {
    return !!this.ext();
  }
 
  /**
   * @ignore
   * @returns Returns extension ID if this is an extension node, otherwise -1.
   */
  public getExtId(): number {
    if (this.elements.length !== 2) return -1;
    const type = this.get(0);
    if (!(type instanceof ConNode)) return -1;
    const buf = type.val;
    const id = this.id;
    if (!(buf instanceof Uint8Array) || buf.length !== 3 || buf[1] !== id.sid % 256 || buf[2] !== id.time % 256)
      return -1;
    return buf[0];
  }
 
  /** ------------------------------------------------------ {@link JsonNode} */
 
  /**
   * @ignore
   */
  public child(): ExtNode<JsonNode> | undefined {
    return this.ext();
  }
 
  /**
   * @ignore
   */
  public container(): JsonNode | undefined {
    return this;
  }
 
  /**
   * @ignore
   */
  public children(callback: (node: JsonNode) => void) {
    const elements = this.elements;
    const length = elements.length;
    const index = this.doc.index;
    for (let i = 0; i < length; i++) {
      const id = elements[i];
      if (!id) continue;
      const node = index.get(id);
      if (node) callback(node);
    }
  }
 
  /**
   * @ignore
   */
  private _view = [] as JsonNodeView<Value>;
 
  /**
   * @ignore
   */
  public view(): JsonNodeView<Value> {
    const extNode = this.ext();
    if (extNode) return extNode.view() as any;
    let useCache = true;
    const _view = this._view;
    const arr = [] as JsonNodeView<Value>;
    const index = this.doc.index;
    const elements = this.elements;
    const length = elements.length;
    for (let i = 0; i < length; i++) {
      const id = elements[i];
      const node = id ? index.get(id) : undefined;
      const value = node ? node.view() : undefined;
      if (_view[i] !== value) useCache = false;
      arr.push(value);
    }
    return useCache ? _view : (this._view = arr);
  }
 
  /**
   * @ignore
   */
  public api: undefined | unknown = undefined;
 
  public name(): string {
    return 'vec';
  }
 
  /** ----------------------------------------------------- {@link Printable} */
 
  public toString(tab: string = ''): string {
    const extNode = this.ext();
    const header = this.name() + ' ' + printTs(this.id) + (extNode ? ` { extension = ${this.getExtId()} }` : '');
    Iif (extNode) {
      return this.child()!.toString(tab, this.id);
    }
    const index = this.doc.index;
    return (
      header +
      printTree(tab, [
        ...this.elements.map(
          (id, i) => (tab: string) =>
            `${i}: ${
              !id ? 'nil' : index.get(id) ? index.get(id)!.toString(tab + '  ' + ' '.repeat(('' + i).length)) : 'nil'
            }`,
        ),
        ...(extNode ? [(tab: string) => `${this.child()!.toString(tab)}`] : []),
      ])
    );
  }
}