From acecce292fac38c8f84900ba01a2afbd946e561f Mon Sep 17 00:00:00 2001 From: Skye Date: Sun, 3 Mar 2024 23:33:05 +0100 Subject: [PATCH] implement prefixed_length strings --- src/string/prefixed_length.ts | 65 +++++++++++++++++++++++++++++++++++ 1 file changed, 65 insertions(+) create mode 100644 src/string/prefixed_length.ts diff --git a/src/string/prefixed_length.ts b/src/string/prefixed_length.ts new file mode 100644 index 0000000..8c8455a --- /dev/null +++ b/src/string/prefixed_length.ts @@ -0,0 +1,65 @@ +import { UnsizedType, u8 } from "../mod.ts"; +import { Options } from "../types/_common.ts"; +import { TEXT_DECODER, TEXT_ENCODER } from "./_common.ts"; + +export class PrefixedLengthString extends UnsizedType { + #prefixCodec: UnsizedType; + + constructor(prefixCodec: UnsizedType = u8) { + super(1); + this.#prefixCodec = prefixCodec; + } + + writePacked(value: string, dt: DataView, options: Options = { byteOffset: 0 }): void { + this.#prefixCodec.writePacked(value.length, dt, options); + + const view = new Uint8Array( + dt.buffer, + dt.byteOffset + options.byteOffset, + value.length + ); + + TEXT_ENCODER.encodeInto(value, view); + super.incrementOffset(options, value.length); + } + + write(value: string, dt: DataView, options: Options = { byteOffset: 0 }): void { + this.#prefixCodec.write(value.length, dt, options); + super.alignOffset(options); + + const view = new Uint8Array( + dt.buffer, + dt.byteLength + options.byteOffset, + value.length, + ); + + TEXT_ENCODER.encodeInto(value, view); + super.incrementOffset(options, value.length); + } + + readPacked(dt: DataView, options: Options = { byteOffset: 0 }): string { + const length = this.#prefixCodec.readPacked(dt, options); + const view = new Uint8Array( + dt.buffer, + dt.byteOffset + options.byteOffset, + length, + ); + + super.incrementOffset(options, length); + return TEXT_DECODER.decode(view); + } + + read(dt: DataView, options: Options = { byteOffset: 0 }): string { + const length = this.#prefixCodec.read(dt, options); + super.alignOffset(options); + + const view = new Uint8Array( + dt.buffer, + dt.byteOffset + options.byteOffset, + length, + ); + + super.incrementOffset(options, length); + return TEXT_DECODER.decode(view); + } +} \ No newline at end of file