UNPKG

@hazae41/binary

Version:

Zero-copy binary data types

1 lines 1.56 kB
{"version":3,"file":"index.mjs","sources":["../../../../../src/mods/binary/writable/index.ts"],"sourcesContent":["export * from \"./errors/index.js\"\n\nimport { Cursor } from \"@hazae41/cursor\"\nimport { WriteUnderflowError } from \"./errors/index.js\"\n\n/**\n * A writable binary data type\n */\nexport interface Writable {\n\n /**\n * Compute the amount of bytes to allocate\n */\n sizeOrThrow(): number\n\n /**\n * Write to a cursor\n * @param cursor \n */\n writeOrThrow(cursor: Cursor): void\n\n}\n\nexport namespace Writable {\n\n /**\n * Call writeOrThrow() on sizeOrThrow()-sized bytes and check for underflow\n * @throws whatever sizeOrThrow() or writeOrThrow() throws\n * @param writable \n * @returns \n */\n export function writeToBytesOrThrow(writable: Writable) {\n const size = writable.sizeOrThrow()\n\n const bytes = new Uint8Array(size)\n const cursor = new Cursor(bytes)\n\n writable.writeOrThrow(cursor)\n\n if (cursor.remaining)\n throw WriteUnderflowError.from(cursor)\n\n return bytes\n }\n\n}"],"names":[],"mappings":";;;;AAuBM,IAAW;AAAjB,CAAA,UAAiB,QAAQ,EAAA;AAEvB;;;;;AAKG;IACH,SAAgB,mBAAmB,CAAC,QAAkB,EAAA;AACpD,QAAA,MAAM,IAAI,GAAG,QAAQ,CAAC,WAAW,EAAE;AAEnC,QAAA,MAAM,KAAK,GAAG,IAAI,UAAU,CAAC,IAAI,CAAC;AAClC,QAAA,MAAM,MAAM,GAAG,IAAI,MAAM,CAAC,KAAK,CAAC;AAEhC,QAAA,QAAQ,CAAC,YAAY,CAAC,MAAM,CAAC;QAE7B,IAAI,MAAM,CAAC,SAAS;AAClB,YAAA,MAAM,mBAAmB,CAAC,IAAI,CAAC,MAAM,CAAC;AAExC,QAAA,OAAO,KAAK;;AAXE,IAAA,QAAA,CAAA,mBAAmB,sBAYlC;AAEH,CAAC,EAtBgB,QAAQ,KAAR,QAAQ,GAAA,EAAA,CAAA,CAAA;;;;"}