Skip to content

Commit

Permalink
feat: Implement small int types U4 and U2 (#28)
Browse files Browse the repository at this point in the history
  • Loading branch information
MierenManz authored Feb 15, 2024
1 parent d7bb332 commit f0bb6b5
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 2 deletions.
2 changes: 0 additions & 2 deletions src/array/array.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,6 @@ export class ArrayType<T> extends UnsizedType<T[]> {
if (value.length !== this.length) {
throw new TypeError("T[].length !== ArrayType<T>.length");
}
if (value.length === 0) return;

const { type } = this;
for (let i = 0; i < value.length; i++) {
Expand All @@ -56,7 +55,6 @@ export class ArrayType<T> extends UnsizedType<T[]> {
if (value.length !== this.length) {
throw new TypeError("T[].length !== ArrayType<T>.length");
}
if (value.length === 0) return;

const { type } = this;
for (let i = 0; i < value.length; i++) {
Expand Down
49 changes: 49 additions & 0 deletions src/small_number/mod.ts
Original file line number Diff line number Diff line change
@@ -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<U2Number> {
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<U4Number> {
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();

0 comments on commit f0bb6b5

Please sign in to comment.