Skip to content

Commit

Permalink
Tweaked DataView
Browse files Browse the repository at this point in the history
  • Loading branch information
AlexanderOMara committed Nov 22, 2024
1 parent 6fadd79 commit 9dbe43c
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 8 deletions.
7 changes: 6 additions & 1 deletion struct.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,8 +32,13 @@ Deno.test('byteOffset', () => {
assertEquals(new Test(data, 3.14).byteOffset, 3);
assertEquals(new Test(data, 3.99).byteOffset, 3);
assertEquals(new Test(data, 32).byteOffset, 32);

// Negative offset throws immediately.
assertThrows(() => new Test(data, -1), RangeError);
assertThrows(() => new Test(data, 33), RangeError);

// Offset over buffer size throws lazy.
const over = new Test(data, 33);
assertThrows(() => over.dataView, RangeError);
});

Deno.test('dataView', () => {
Expand Down
28 changes: 21 additions & 7 deletions struct.ts
Original file line number Diff line number Diff line change
Expand Up @@ -66,15 +66,25 @@ export class Struct implements ArrayBufferView {
declare public readonly ['constructor']: typeof Struct;

/**
* Data view of buffer.
* Buffer data.
*/
readonly #dataView: DataView;
readonly #buffer: StructBuffer;

/**
* Byte offset into buffer.
*/
readonly #byteOffset: number;

/**
* Little endian, or not.
*/
readonly #littleEndian: boolean;

/**
* Data view of buffer, lazy init.
*/
#dataView?: DataView;

/**
* Blob constructor.
*
Expand All @@ -87,15 +97,19 @@ export class Struct implements ArrayBufferView {
byteOffset = 0,
littleEndian: boolean | null = null,
) {
this.#dataView = new DataView(buffer, byteOffset);
this.#littleEndian = littleEndian ?? LITTLE_ENDIAN;
if ((byteOffset |= 0) < 0) {
new DataView(buffer, byteOffset);
}
this.#buffer = buffer;
this.#byteOffset = byteOffset;
this.#littleEndian = !!(littleEndian ?? LITTLE_ENDIAN);
}

/**
* @inheritdoc
*/
public get buffer(): ArrayBuffer {
return this.#dataView.buffer;
return this.#buffer;
}

/**
Expand All @@ -109,7 +123,7 @@ export class Struct implements ArrayBufferView {
* @inheritdoc
*/
public get byteOffset(): number {
return this.#dataView.byteOffset;
return this.#byteOffset;
}

/**
Expand All @@ -118,7 +132,7 @@ export class Struct implements ArrayBufferView {
* @returns Data view of buffer.
*/
public get dataView(): DataView {
return this.#dataView;
return this.#dataView ??= new DataView(this.#buffer, this.byteOffset);
}

/**
Expand Down

0 comments on commit 9dbe43c

Please sign in to comment.