All files / json-crdt-extensions/peritext/util ChunkSlice.ts

61.29% Statements 19/31
28.57% Branches 2/7
66.66% Functions 4/6
61.29% Lines 19/31

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 6959x 59x 59x           59x         6325x   6325x   6325x               598x 598x 598x                     5795x 5795x         6325x     7x 7x 7x 7x 7x 7x                                
import {CONST, updateNum} from '../../../json-hash';
import {updateId} from '../../../json-crdt/hash';
import {type ITimestampStruct, Timestamp, printTs} from '../../../json-crdt-patch/clock';
import type {IChunkSlice} from './types';
import type {Stateful} from '../types';
import type {Printable} from 'tree-dump/lib/types';
import type {Chunk} from '../../../json-crdt/nodes/rga';
 
export class ChunkSlice<T = string> implements IChunkSlice<T>, Stateful, Printable {
  constructor(
    /** Chunk from which slice is computed. */
    chunk: Chunk<T>,
    /** Start offset of the slice within the chunk. */
    public off: number,
    /** Length of the slice. */
    public len: number,
  ) {
    this.chunk = chunk;
  }
 
  // -------------------------------------------------------------- IChunkSlice
 
  public readonly chunk: Chunk<T>;
 
  public id(): ITimestampStruct {
    const id = this.chunk.id;
    const off = this.off;
    return !off ? id : new Timestamp(id.sid, id.time + off);
  }
 
  public key(): string {
    const id = this.chunk.id;
    const sid = id.sid;
    const time = id.time + this.off;
    return sid.toString(36) + time.toString(36);
  }
 
  public view(): T {
    const offset = this.off;
    return this.chunk.view().slice(offset, offset + this.len);
  }
 
  // ----------------------------------------------------------------- Stateful
 
  public hash: number = 0;
 
  public refresh(): number {
    const {chunk, off, len} = this;
    const delOffLenState = (((off << 16) + len) << 1) + +chunk.del;
    let state = CONST.START_STATE;
    state = updateId(state, chunk.id);
    state = updateNum(state, delOffLenState);
    return (this.hash = state);
  }
 
  // ---------------------------------------------------------------- Printable
 
  public toString(tab: string = ''): string {
    const name = 'ChunkSlice';
    const off = this.off;
    const len = this.len;
    const str = this.view() + '';
    const truncate = str.length > 32;
    const view = JSON.stringify(truncate ? str.slice(0, 32) : str) + (truncate ? ' …' : '');
    const id = printTs(this.chunk.id);
    return `${name} ${id} [${off}..${off + len}) ${view}`;
  }
}