Skip to content

Instantly share code, notes, and snippets.

@greggman
Created November 13, 2024 08:16
Show Gist options
  • Save greggman/ca3542a1f626c8786f8eb430fdaa20b7 to your computer and use it in GitHub Desktop.
Save greggman/ca3542a1f626c8786f8eb430fdaa20b7 to your computer and use it in GitHub Desktop.
Incomplete structured setting - slow
const kTypedArrayConstructors = {
i8: Int8Array,
u8: Uint8Array,
i16: Int16Array,
u16: Uint16Array,
i32: Int32Array,
u32: Uint32Array,
f32: Float32Array,
f64: Float64Array,
i64: BigInt64Array,
u64: BigUint64Array,
};
class StructuredAccessorFactory {
constructor(layout) {
const typedArraysTypes = [...new Set(Object.values(layout).map(({type}) => type))];
this.create = function(buffer) {
const data = Object.fromEntries(typedArraysTypes.map(type => [type, new kTypedArrayConstructors[type](buffer)]));
const accessor = {};
Object.defineProperties(accessor, Object.fromEntries(Object.entries(layout).map(([key, {type, byteOffset}]) => {
const view = data[type];
const arrayOffset = byteOffset / view.BYTES_PER_ELEMENT;
return [key, {
enumerable: true,
get() {
return view[arrayOffset];
},
set(value) {
view[arrayOffset] = value;
},
}];
})));
return accessor;
};
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment