import bool from "./bool"; import ISerializer, { InputOf, OutputOf, JSONOutputOf } from "./ISerializer"; type TInput = InputOf | null | undefined; type TOutput = OutputOf | null; type TJSONOutput = JSONOutputOf | null; export class OptionalSerializer extends ISerializer, TOutput, TJSONOutput> { constructor(public readonly serializer: T) { super(); } toJSON(value: TInput): TJSONOutput { if (value === null || value === undefined) return null; return this.serializer.toJSON(value); } fromJSON(value: TJSONOutput): TOutput { if (value === null) return null; return this.serializer.toJSON(value); } toBuffer(value: TInput): Buffer { const missing = value === null || value === undefined; const preres = bool.toBuffer(!missing); if (missing) return preres; return Buffer.concat([preres, this.serializer.toBuffer(value)]); } readFromBuffer(buffer: Buffer, offset: number = 0): { res: TOutput, newOffset: number } { const { res: provided, newOffset: from } = bool.readFromBuffer(buffer, offset); if (!provided) return { res: null, newOffset: from }; return this.serializer.readFromBuffer(buffer, from); } } export default function optional(serializer: T): OptionalSerializer { return new OptionalSerializer(serializer); }