All files / lib/serialize Encoder.ts

87.5% Statements 14/16
66.67% Branches 4/6
100% Functions 2/2
87.5% Lines 14/16

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 331x 1x   1x     13x   7x 7x   6x 6x       13x       14x 14x 14x   6x   8x            
import { EncodingType } from "./EncodingType";
import { ZlibEncoder } from "./ZlibEncoder";
 
export class Encoder {
    public encode(encoding: EncodingType, data: Buffer): Buffer {
        let encoded: Buffer;
        switch (encoding) {
            case EncodingType.Raw:
                encoded = data;
                break;
            case EncodingType.ZlibDeflate:
                encoded = new ZlibEncoder().encode(data);
                break;
            default:
                throw new Error("Unknown encoding type");
        }
        return Buffer.concat([Buffer.from([encoding]), encoded]);
    }
 
    public decode(buffer: Buffer): Buffer {
        const encoding = buffer.readUInt8(0);
        const raw = buffer.slice(1);
        switch (encoding) {
            case EncodingType.Raw:
                return raw;
            case EncodingType.ZlibDeflate:
                return new ZlibEncoder().decode(raw);
            default:
                throw new Error("Unknown encoding type");
        }
    }
}