From 4fade5e5829161722275a4d161f301fad3308643 Mon Sep 17 00:00:00 2001 From: James Prevett Date: Fri, 13 Dec 2024 15:36:08 -0600 Subject: [PATCH] Kind of added support for unions --- src/internal/struct.ts | 1 + src/struct.ts | 6 ++++-- 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/src/internal/struct.ts b/src/internal/struct.ts index 75cd2df..23958c8 100644 --- a/src/internal/struct.ts +++ b/src/internal/struct.ts @@ -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 { diff --git a/src/struct.ts b/src/struct.ts index eb82799..fdf01ef 100644 --- a/src/struct.ts +++ b/src/struct.ts @@ -45,11 +45,12 @@ export function struct(options: Partial = {}) { 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); } @@ -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;