All files / lib/serialize Encoder.ts

18.75% Statements 3/16
0% Branches 0/6
0% Functions 0/2
18.75% Lines 3/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                                                          
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');
    }
  }
}