diff --git a/src/array/array.ts b/src/array/array.ts index 14291a8..44ceedb 100644 --- a/src/array/array.ts +++ b/src/array/array.ts @@ -39,7 +39,6 @@ export class ArrayType extends UnsizedType { if (value.length !== this.length) { throw new TypeError("T[].length !== ArrayType.length"); } - if (value.length === 0) return; const { type } = this; for (let i = 0; i < value.length; i++) { @@ -56,7 +55,6 @@ export class ArrayType extends UnsizedType { if (value.length !== this.length) { throw new TypeError("T[].length !== ArrayType.length"); } - if (value.length === 0) return; const { type } = this; for (let i = 0; i < value.length; i++) { diff --git a/src/small_number/mod.ts b/src/small_number/mod.ts new file mode 100644 index 0000000..c4321f2 --- /dev/null +++ b/src/small_number/mod.ts @@ -0,0 +1,49 @@ +import { type Options, SizedType } from "../mod.ts"; + +type U2Number = 0 | 1 | 2 | 3; +type U4Number = U2Number | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15; + +export class U2 extends SizedType { + constructor() { + super(1, 1); + } + + readPacked(dt: DataView, options: Options = { byteOffset: 0 }): U2Number { + const v = dt.getUint8(options.byteOffset) & 0b11; + super.incrementOffset(options); + return v as U2Number; + } + + writePacked( + value: U2Number, + dt: DataView, + options: Options = { byteOffset: 0 }, + ): void { + dt.setUint8(options.byteOffset, value & 0b11); + super.incrementOffset(options); + } +} + +export class U4 extends SizedType { + constructor() { + super(1, 1); + } + + readPacked(dt: DataView, options: Options = { byteOffset: 0 }): U4Number { + const v = dt.getUint8(options.byteOffset) & 0b1111; + super.incrementOffset(options); + return v as U4Number; + } + + writePacked( + value: U4Number, + dt: DataView, + options: Options = { byteOffset: 0 }, + ): void { + dt.setUint8(options.byteOffset, value & 0b1111); + super.incrementOffset(options); + } +} + +export const u2 = new U2(); +export const u4 = new U4();