Skip to content

Commit

Permalink
feat: Additional string codecs (#29)
Browse files Browse the repository at this point in the history
  • Loading branch information
MierenManz authored Mar 5, 2024
1 parent f0bb6b5 commit a598ac0
Show file tree
Hide file tree
Showing 2 changed files with 76 additions and 3 deletions.
6 changes: 3 additions & 3 deletions src/string/fixed_length.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { type Options, SizedType } from "../types/mod.ts";
import { TEXT_DECODER, TEXT_ENCODER } from "./_common.ts";

export class FixedLength extends SizedType<string> {
export class FixedLengthString extends SizedType<string> {
constructor(length: number) {
super(length, 1);
}
Expand Down Expand Up @@ -38,5 +38,5 @@ export class FixedLength extends SizedType<string> {
}
}

export const asciiChar = new FixedLength(1);
export const utf8Char = new FixedLength(4);
export const asciiChar = new FixedLengthString(1);
export const utf8Char = new FixedLengthString(4);
73 changes: 73 additions & 0 deletions src/string/prefixed_length.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
import { u8, UnsizedType } from "../mod.ts";
import { Options } from "../types/_common.ts";
import { TEXT_DECODER, TEXT_ENCODER } from "./_common.ts";

export class PrefixedString extends UnsizedType<string> {
#prefixCodec: UnsizedType<number>;

constructor(prefixCodec: UnsizedType<number> = 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);
}
}

0 comments on commit a598ac0

Please sign in to comment.