import { printString } from "./debug"; import { Packer, Encoder, Decoder } from "./serializer" import { Utils } from "./utils" export class Optional implements Packer { value: T | null; constructor( value: T | null = null ) { this.value = value; } pack(enc: Encoder): usize { let oldPos = enc.getPos(); if (this.value) { enc.packNumber(1); enc.pack(this.value!); } else { enc.packNumber(0); } return enc.getPos() - oldPos; } unpack(data: u8[]): usize { let dec = new Decoder(data) let hasValue = dec.unpackNumber(); if (!hasValue) { this.value = null; return 1; } let obj = instantiate(); dec.unpack(obj); this.value = obj; return dec.getPos(); } getSize(): usize { if (!this.value) { return 1; } return 1 + this.value!.getSize(); } } export class OptionalNumber implements Packer { value: T; hasValue: bool; constructor( value: T = 0, hasValue: bool = true ) { if (hasValue) { this.value = value; } this.hasValue = hasValue; } pack(enc: Encoder): usize { let oldPos = enc.getPos(); if (this.value) { enc.packNumber(1); enc.packNumber(this.value); } else { enc.packNumber(0); } return enc.getPos() - oldPos; } unpack(data: u8[]): usize { let dec = new Decoder(data); let hasValue = dec.unpackNumber(); if (!hasValue) { this.hasValue = false; this.value = 0; return 1; } this.hasValue = true; this.value = dec.unpackNumber(); return dec.getPos(); } getSize(): usize { if (!this.value) { return 1; } return 1 + sizeof(); } } export class OptionalString implements Packer { value: string = ""; hasValue: bool; constructor( value: string="", hasValue: bool=true ) { this.value = value; this.hasValue = hasValue; } pack(enc: Encoder): usize { let oldPos = enc.getPos(); if (this.hasValue) { enc.packNumber(1); enc.packString(this.value); } else { enc.packNumber(0); } return enc.getPos() - oldPos; } unpack(data: u8[]): usize { let dec = new Decoder(data) let hasValue = dec.unpackNumber(); if (!hasValue) { this.hasValue = false; this.value = ""; return 1; } this.hasValue = true; this.value = dec.unpackString(); return dec.getPos(); } getSize(): usize { if (!this.hasValue) { return 1; } return 1 + Utils.calcPackedStringLength(this.value); } }