Skip to content

Commit

Permalink
Kind of added support for unions
Browse files Browse the repository at this point in the history
  • Loading branch information
james-pre committed Dec 13, 2024
1 parent a74dfcb commit 4fade5e
Show file tree
Hide file tree
Showing 2 changed files with 5 additions and 2 deletions.
1 change: 1 addition & 0 deletions src/internal/struct.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ export const init: typeof Symbol.struct_init = Symbol.struct_init;
export interface Options {
align: number;
bigEndian: boolean;
isUnion: boolean;
}

export interface Member {
Expand Down
6 changes: 4 additions & 2 deletions src/struct.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,11 +45,12 @@ export function struct(options: Partial<Options> = {}) {
throw new TypeError('Not a valid type: ' + type);
}
members.set(name, {
offset: size,
offset: options.isUnion ? 0 : size,
type: primitive.isValid(type) ? primitive.normalize(type) : type,
length,
});
size += sizeof(type) * (length || 1);
const memberSize = sizeof(type) * (length || 1);
size = options.isUnion ? Math.max(size, memberSize) : size + memberSize;
size = align(size, options.align || 1);
}

Expand Down Expand Up @@ -90,6 +91,7 @@ export function serialize(instance: unknown): Uint8Array {
const buffer = new Uint8Array(sizeof(instance));
const view = new DataView(buffer.buffer);

// for unions we should write members in ascending last modified order, but we don't have that info.
for (const [name, { type, length, offset }] of members) {
for (let i = 0; i < (length || 1); i++) {
const iOff = offset + sizeof(type) * i;
Expand Down

0 comments on commit 4fade5e

Please sign in to comment.