@ain1084/array-buffer-partitioner
Version:
Partition an ArrayBuffer into multiple TypedArray views efficiently.
51 lines • 2.14 kB
JavaScript
/**
* Creates multiple TypedArray views on a single ArrayBuffer or SharedArrayBuffer.
* The function takes a constructor (either ArrayBuffer or SharedArrayBuffer) and a configuration object,
* then allocates the buffer and returns the specified TypedArray views.
*
* @typeParam T - A record specifying the TypedArray types and sizes.
* @param BufferType - The constructor for the buffer, either ArrayBuffer or SharedArrayBuffer.
* @param config - An object specifying the desired views. Each key represents the name of the view, and the value is a tuple where:
* - The first element is the TypedArray class name (e.g., Float32Array, Uint32Array).
* - The second element is the number of elements for that view.
*
* @returns An object containing the views, with each key corresponding to the provided configuration.
*
* @example
* ```typescript
* import { createArrayBufferViews } from '@ain1084/array-buffer-partitioner';
*
* const views = createArrayBufferViews(ArrayBuffer, {
* data: [Float32Array, 1024],
* index: [Uint32Array, 1],
* flag: [Uint8Array, 1]
* });
*
* console.log(views.data.length); // 1024
* console.log(views.data.byteOffset); // 0
* console.log(views.index.length); // 1
* console.log(views.flag.length); // 1
* console.log(views.flag.byteOffset); // 4100
* console.log(views.data.buffer.byteLength); // 4104
* ```
*/
export function createArrayBufferViews(BufferType, config) {
const alignTo = (value, alignment) => (value + alignment - 1) & ~(alignment - 1);
let totalSize = 0;
for (const [, [type, size]] of Object.entries(config)) {
const alignment = type.BYTES_PER_ELEMENT;
totalSize = alignTo(totalSize, alignment) + (alignment * size);
}
const buffer = new BufferType(totalSize);
const result = {};
let offset = 0;
for (const key in config) {
const [type, size] = config[key];
const alignment = type.BYTES_PER_ELEMENT;
offset = alignTo(offset, alignment);
result[key] = new type(buffer, offset, size);
offset += alignment * size;
}
return result;
}
//# sourceMappingURL=index.js.map