All files Writer.ts

100% Statements 15/15
100% Branches 0/0
100% Functions 4/4
100% Lines 14/14

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  1x 1x   1x       2x 2x 2x       2x 8x 2x 2x 2x 8x 8x   2x              
import { ProtoTable } from './ProtoTable';
import { $$getShiftTable } from './proto';
import { toBinary } from './byte-table-builder';
 
export abstract class Writer<T, M> {
    private readonly instance: T;
    private readonly protoTable: ProtoTable;
 
    constructor(private C: { new(): T }){
        this.instance = new C();
        this.protoTable = (this.instance as any)[$$getShiftTable]();
    }
 
    public write(obj: T): M {
        const byteTable = toBinary(obj, this.protoTable, this.dynamicToBinary);
        const totalSize = byteTable.reduce((size, [_, shift]) => size + shift,0);
        const buffer = this.alloc(totalSize);
        let shift = 0;
        byteTable.forEach(([type, size, value]) => {
            this.writeAs(buffer, type, value, shift);
            shift += size as number;
        });
        return buffer;
    };
 
    protected abstract alloc(size: number): M;
    protected abstract dynamicToBinary(type: string, value: any): any;
    protected abstract writeAs(m: M, type: string, value: any, shift: number): any;
}