-
-
Notifications
You must be signed in to change notification settings - Fork 7
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat: Additional string codecs (#29)
- Loading branch information
1 parent
f0bb6b5
commit a598ac0
Showing
2 changed files
with
76 additions
and
3 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | ||
} | ||
} |