node-ctypes 2.2.0 → 2.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (38) hide show
  1. package/CHANGELOG.md +932 -0
  2. package/README.md +504 -99
  3. package/build/Release/ctypes-darwin-arm64.node +0 -0
  4. package/build/Release/ctypes-darwin-x64.node +0 -0
  5. package/build/Release/ctypes-linux-arm64-musl.node +0 -0
  6. package/build/Release/ctypes-linux-arm64.node +0 -0
  7. package/build/Release/ctypes-linux-x64-musl.node +0 -0
  8. package/build/Release/ctypes-linux-x64.node +0 -0
  9. package/build/Release/ctypes-win32-arm64.node +0 -0
  10. package/build/Release/ctypes-win32-x64.node +0 -0
  11. package/lib/core/Library.js +136 -109
  12. package/lib/core/callback.js +17 -20
  13. package/lib/core/conversions.js +376 -16
  14. package/lib/core/funcptr.js +148 -73
  15. package/lib/core/lazy-loader.js +10 -4
  16. package/lib/core/types.js +201 -98
  17. package/lib/index.d.ts +276 -83
  18. package/lib/index.js +44 -32
  19. package/lib/memory/buffer.js +82 -22
  20. package/lib/memory/operations.js +55 -45
  21. package/lib/memory/pointer.js +233 -57
  22. package/lib/platform/constants.js +0 -1
  23. package/lib/platform/errors.js +48 -4
  24. package/lib/platform/find_library.js +78 -19
  25. package/lib/platform/win_types.js +8 -3
  26. package/lib/structures/Structure.js +252 -203
  27. package/lib/structures/Union.js +10 -21
  28. package/lib/structures/helpers/array.js +102 -16
  29. package/lib/structures/helpers/bitfield.js +75 -150
  30. package/lib/structures/helpers/common.js +310 -21
  31. package/lib/structures/helpers/layout.js +145 -0
  32. package/lib/structures/helpers/struct.js +160 -419
  33. package/lib/structures/helpers/union.js +154 -155
  34. package/lib/structures/helpers/wrap.js +3 -15
  35. package/lib/types/SimpleCData.js +11 -32
  36. package/lib/types/primitives.js +160 -113
  37. package/lib/utils/cache.js +34 -2
  38. package/package.json +4 -1
@@ -1,3 +1,72 @@
1
+ import { flush, kMirrorBase, mirrorBase, mirroredPrototype, mirrorsActive, refresh } from "../../memory/mirror.js";
2
+ import { POINTER_SIZE } from "../../platform/constants.js";
3
+
4
+ const simpleTypes = new WeakSet();
5
+ export const byrefOwners = new WeakMap();
6
+
7
+ export function resolveParameter(value, owners) {
8
+ let seen;
9
+ for (let depth = 0; value !== null && (typeof value === "object" || typeof value === "function"); depth++) {
10
+ if (owners !== undefined) owners.push(value);
11
+ if (ArrayBuffer.isView(value) && !("_as_parameter_" in value)) return value;
12
+ if (value._isSimpleCDataInstance === true || value._pointerType !== undefined || value._arrayType !== undefined || value._structDef !== undefined || byrefOwners.has(value)) return value;
13
+ const parameter = value._as_parameter_;
14
+ if (parameter === undefined) return value;
15
+ if (depth >= 128) throw new RangeError("_as_parameter_ maximum depth exceeded");
16
+ seen ??= new Set();
17
+ if (seen.has(value)) throw new TypeError("_as_parameter_ cycle detected");
18
+ seen.add(value);
19
+ value = parameter;
20
+ }
21
+ return value;
22
+ }
23
+
24
+ export function sourceBytes(source, offset, size, name) {
25
+ const bytes = source !== null && typeof source === "object" && !ArrayBuffer.isView(source) && Buffer.isBuffer(source._buffer) ? source._buffer : source;
26
+ if (!ArrayBuffer.isView(bytes)) throw new TypeError(`${name}: source must be a Buffer, a typed array or a ctypes instance`);
27
+ if (!Number.isSafeInteger(offset)) throw new TypeError(`${name}: offset must be a safe integer`);
28
+ if (offset < 0) throw new RangeError(`${name}: offset cannot be negative`);
29
+ if (bytes.byteLength - offset < size) throw new RangeError(`${name}: Buffer size too small (${bytes.byteLength} instead of at least ${size + offset} bytes)`);
30
+ return bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes.buffer, bytes.byteOffset, bytes.byteLength);
31
+ }
32
+
33
+ export function registerSimpleType(type) {
34
+ simpleTypes.add(type);
35
+ }
36
+
37
+ export function isScalarSubclass(type) {
38
+ return typeof type === "function" && type._isSimpleCData === true && !simpleTypes.has(type);
39
+ }
40
+
41
+ export function scalarView(type, buffer, swapped = false) {
42
+ // C-owned representations must bypass application constructors and writers.
43
+ const base = mirrorsActive ? mirrorBase(buffer) : undefined;
44
+ const value = Object.create(base === undefined ? type.prototype : mirroredPrototype(type));
45
+ value._buffer = buffer;
46
+ if (base !== undefined) value[kMirrorBase] = base;
47
+ if (swapped && type._readerBE && type._writerBE) {
48
+ Object.defineProperty(value, "value", {
49
+ get() {
50
+ if (base !== undefined) refresh(buffer);
51
+ return type._readerBE(buffer, 0);
52
+ },
53
+ set(v) {
54
+ type._writerBE(buffer, 0, v);
55
+ if (base !== undefined) flush(buffer);
56
+ },
57
+ });
58
+ }
59
+ return value;
60
+ }
61
+
62
+ export function scalarReader(type, reader, swapped = false) {
63
+ return isScalarSubclass(type) ? (buffer, offset) => scalarView(type, buffer.subarray(offset, offset + type._size), swapped) : reader;
64
+ }
65
+
66
+ export function scalarOutparam() {
67
+ return isScalarSubclass(this.constructor) ? this : this.value;
68
+ }
69
+
1
70
  /**
2
71
  * @file helpers.js
3
72
  * @module structures/helpers
@@ -137,6 +206,50 @@ export function _isBitField(type) {
137
206
  return typeof type === "object" && type !== null && type._isBitField === true;
138
207
  }
139
208
 
209
+ /**
210
+ * Writer of a SimpleCData field of a struct/union. An instance assigned to the
211
+ * field (or given as positional initializer) is copied when it has the same
212
+ * type, as Python (pointers keep the instance alive); another SimpleCData type
213
+ * is "incompatible types" (c_void_p fields accept the pointer types).
214
+ *
215
+ * @param {Function} fieldType - SimpleCData class of the field
216
+ * @param {Function} writer - `(buf, offset, value)` writer
217
+ * @param {number} offset - Field offset
218
+ * @returns {Function} `(buf, value, relativeOffset = 0)` writer
219
+ */
220
+ export function simpleFieldWriter(fieldType, writer, offset) {
221
+ const pointerValued = fieldType._isPointerValued === true;
222
+ return (buf, val, relativeOffset = 0) => {
223
+ const fieldOffset = offset + relativeOffset;
224
+ if (typeof val === "object" && val !== null && val.constructor?._isSimpleCData === true) {
225
+ const T = val.constructor;
226
+ if (T._type === fieldType._type && T._size === fieldType._size && T._isBoolean === fieldType._isBoolean) {
227
+ if (!pointerValued) return writer(buf, fieldOffset, val.value);
228
+ copyInstance(buf, fieldOffset, T._size, val, 0, fieldType);
229
+ return;
230
+ }
231
+ if (!(fieldType._acceptsPointerValues === true && T._isPointerValued === true)) {
232
+ throw new TypeError(`incompatible types, ${T.name} instance instead of ${fieldType.name} instance`);
233
+ }
234
+ }
235
+ writer(buf, fieldOffset, val);
236
+ };
237
+ }
238
+
239
+ /**
240
+ * Python: a float is not an integer ("'float' object cannot be interpreted as
241
+ * an integer"); in JS, numbers that are not integral (or not finite).
242
+ *
243
+ * @throws {TypeError}
244
+ */
245
+ export function notIntegral() {
246
+ throw new TypeError("'float' object cannot be interpreted as an integer");
247
+ }
248
+
249
+ export function booleanValue(value) {
250
+ return !!(value !== null && typeof value === "object" && value._isSimpleCDataInstance === true ? value.value : value);
251
+ }
252
+
140
253
  /**
141
254
  * Address stored by a pointer field assignment: a pointer instance, a
142
255
  * CFUNCTYPE/callback object (`_as_parameter_`), a BigInt/number address,
@@ -148,10 +261,11 @@ export function _isBitField(type) {
148
261
  * @returns {bigint} Address to store
149
262
  */
150
263
  export function pointerFieldAddress(value, pointerSize) {
264
+ value = resolveParameter(value);
151
265
  if (typeof value === "bigint") return value;
152
266
  if (typeof value === "number") return BigInt(value);
153
267
  if (value === null || value === undefined) return 0n;
154
- if (typeof value === "object") {
268
+ if (typeof value === "object" || typeof value === "function") {
155
269
  if (typeof value.address === "bigint") return value.address;
156
270
  const param = value._as_parameter_;
157
271
  if (typeof param === "bigint") return param;
@@ -173,29 +287,152 @@ const funcPtrFieldTypes = new WeakMap();
173
287
  export function funcPtrFieldType(prototype) {
174
288
  let fieldType = funcPtrFieldTypes.get(prototype);
175
289
  if (fieldType === undefined) {
176
- fieldType = { _pointerTo: prototype, _isFuncPtrField: true, fromAddress: (address) => prototype(address) };
290
+ fieldType = {
291
+ _pointerTo: prototype,
292
+ _isFuncPtrField: true,
293
+ fromAddress: (address, owner) => keepFunctionOwner(prototype(address), owner),
294
+ };
177
295
  funcPtrFieldTypes.set(prototype, fieldType);
178
296
  }
179
297
  return fieldType;
180
298
  }
181
299
 
300
+ export function keepFunctionOwner(fn, owner) {
301
+ if (owner !== undefined) {
302
+ Object.defineProperty(fn, "_objects", { value: owner });
303
+ // AsyncWorker pins the native handle, not its public JS function.
304
+ Object.defineProperty(fn._ffi, "_objects", { value: owner });
305
+ }
306
+ return fn;
307
+ }
308
+
309
+ // Oggetti tenuti vivi dalla memoria che contiene i loro indirizzi, per
310
+ // ArrayBuffer e offset assoluto: tutte le view sulla stessa memoria (istanza,
311
+ // struct annidata, from_buffer) condividono la stessa tabella.
312
+ const keptObjects = new WeakMap();
313
+ const memoryOwners = new WeakMap();
314
+ // Address-backed aliases share the reference table of their known owner.
315
+ const memoryDomains = new WeakMap();
316
+ export const kPointerMemory = Symbol("pointerMemory");
317
+
318
+ export function memoryDomain(buf) {
319
+ return memoryDomains.get(buf.buffer) ?? { root: buf.buffer, offset: 0n };
320
+ }
321
+
322
+ function memoryPosition(buf, offset) {
323
+ return BigInt(buf.byteOffset + offset) + (memoryDomains.get(buf.buffer)?.offset ?? 0n);
324
+ }
325
+
326
+ export function shareMemory(buf, memory, position) {
327
+ memoryDomains.set(buf.buffer, { root: memory.root, offset: position - BigInt(buf.byteOffset) });
328
+ return keepMemoryOwner(buf, memory);
329
+ }
330
+
331
+ // Attach to the backing store, so subarrays and typed arrays keep the lease too.
332
+ export function keepMemoryOwner(buf, owner) {
333
+ if (owner === undefined || owner === null) return buf;
334
+ let owners = memoryOwners.get(buf.buffer);
335
+ if (owners === undefined) memoryOwners.set(buf.buffer, (owners = new Set()));
336
+ owners.add(owner);
337
+ return buf;
338
+ }
339
+
340
+ function storedAddress(buf, offset) {
341
+ return POINTER_SIZE === 8 ? buf.readBigUInt64LE(offset) : BigInt(buf.readUInt32LE(offset));
342
+ }
343
+
344
+ export function pointerOwner(buf, offset, address) {
345
+ const root = memoryDomains.get(buf.buffer)?.root ?? buf.buffer;
346
+ const kept = keptObjects.get(root);
347
+ if (kept === undefined) return buf;
348
+ const position = memoryPosition(buf, offset);
349
+ const reference = kept.get(position);
350
+ if (reference !== undefined && reference.address !== (address ?? storedAddress(buf, offset))) {
351
+ kept.delete(position);
352
+ return buf;
353
+ }
354
+ return reference?.owner ?? buf;
355
+ }
356
+
357
+ export function inDllBuffer(library, name, size, ptrToBuffer) {
358
+ const lib = library?._lib ?? library;
359
+ if (typeof lib?._symbolView !== "function") throw new TypeError("in_dll: first arg must be a Library (CDLL/WinDLL)");
360
+ const { address, owner } = lib._symbolView(name);
361
+ return keepMemoryOwner(ptrToBuffer(address, size), owner);
362
+ }
363
+
364
+ function pointerSlots(type, offset = 0, size) {
365
+ if (type?._isPointerValued || type?._isFuncPtr || type?._pointerTo !== undefined) return [[offset, type._size ?? type.size ?? size]];
366
+ if (type?._isArrayType) {
367
+ const slots = [];
368
+ const elementSize = type.length === 0 ? 0 : type.getSize() / type.length;
369
+ const elements = pointerSlots(type.elementType, 0, elementSize);
370
+ if (elements.length === 0) return slots;
371
+ for (let i = 0; i < type.length; i++) {
372
+ for (const [position, width] of elements) slots.push([offset + i * elementSize + position, width]);
373
+ }
374
+ return slots;
375
+ }
376
+ const def = typeof type?._buildStruct === "function" ? (type._structDef ?? type._buildStruct()) : type;
377
+ const slots = [];
378
+ for (const field of def?.fields ?? []) {
379
+ if (field.isPointer) slots.push([offset + field.offset, field.size]);
380
+ else slots.push(...pointerSlots(field.type, offset + field.offset, field.size));
381
+ }
382
+ return slots;
383
+ }
384
+
182
385
  /**
183
- * Keep `value` alive as long as `targetBuf`, like Python ctypes `_objects`:
184
- * an object whose address is stored in the buffer (pointer, callback) must
185
- * not be garbage collected while native code can still read that address.
186
- * Shares the slot table used for c_char_p / c_wchar_p fields.
386
+ * Keep `value` alive as long as the memory of `targetBuf`, like Python ctypes
387
+ * `_objects`: an object whose address is stored in the buffer (string,
388
+ * pointer, callback) must not be garbage collected while native code can
389
+ * still read that address. The table belongs to the memory, not to the view,
390
+ * so assigning through a nested structure keeps the object alive with the
391
+ * outer one.
187
392
  *
188
- * @param {Buffer} targetBuf - Buffer holding the address
189
- * @param {number} offset - Offset of the slot
393
+ * @param {Uint8Array} targetBuf - Buffer holding the address
394
+ * @param {number} offset - Offset of the slot in `targetBuf`
190
395
  * @param {*} value - Referenced object (or null to clear the slot)
191
396
  */
192
397
  export function keepAlive(targetBuf, offset, value) {
193
- let keep = targetBuf.__ctypesKeepalive;
194
- if (keep === undefined) {
195
- keep = Object.create(null);
196
- Object.defineProperty(targetBuf, "__ctypesKeepalive", { value: keep });
398
+ const position = memoryPosition(targetBuf, offset);
399
+ const root = memoryDomains.get(targetBuf.buffer)?.root ?? targetBuf.buffer;
400
+ let kept = keptObjects.get(root);
401
+ if (value === null || (typeof value !== "object" && typeof value !== "function")) {
402
+ kept?.delete(position);
403
+ return;
404
+ }
405
+ if (kept === undefined) {
406
+ kept = new Map();
407
+ keptObjects.set(root, kept);
408
+ }
409
+ // A pointer wrapper can later be repointed; retain its current memory.
410
+ if (value._pointerType !== undefined) value = value._buffer ?? value._objects ?? value;
411
+ else if (value._isSimpleCDataInstance && value.constructor._isPointerValued) value = pointerOwner(value._buffer, 0);
412
+ kept.set(position, { owner: value, address: storedAddress(targetBuf, offset) });
413
+ }
414
+
415
+ /**
416
+ * Object kept alive at `offset` of `buf` (see {@link keepAlive}).
417
+ *
418
+ * @param {Uint8Array} buf - Buffer
419
+ * @param {number} offset - Offset in `buf`
420
+ * @returns {*} The object, or undefined
421
+ */
422
+ export function keptObject(buf, offset) {
423
+ const root = memoryDomains.get(buf.buffer)?.root ?? buf.buffer;
424
+ return keptObjects.get(root)?.get(memoryPosition(buf, offset))?.owner;
425
+ }
426
+
427
+ export function clearKeepAlives(buf, offset, size) {
428
+ const root = memoryDomains.get(buf.buffer)?.root ?? buf.buffer;
429
+ const kept = keptObjects.get(root);
430
+ if (kept === undefined) return;
431
+ const start = BigInt(memoryPosition(buf, offset));
432
+ const end = start + BigInt(size);
433
+ for (const position of kept.keys()) {
434
+ if (position >= start && position < end) kept.delete(position);
197
435
  }
198
- keep[offset] = value !== null && typeof value === "object" ? value : undefined;
199
436
  }
200
437
 
201
438
  /**
@@ -214,6 +451,35 @@ export function writePointerField(buf, offset, value, pointerSize) {
214
451
  keepAlive(buf, offset, value);
215
452
  }
216
453
 
454
+ /**
455
+ * Fields given to struct() / union(): `[name, type]` pairs in declaration
456
+ * order (Structure._fieldMap; an object would put integer-like names such as
457
+ * "1" first), a Map or a `{ name: type }` object.
458
+ *
459
+ * @param {Array|Map|Object} fields - Field declarations
460
+ * @returns {Array} `[name, type]` pairs
461
+ */
462
+ export function fieldEntries(fields) {
463
+ if (Array.isArray(fields)) return fields;
464
+ if (fields instanceof Map) return [...fields];
465
+ return Object.entries(fields);
466
+ }
467
+
468
+ /**
469
+ * Fields of a value used as "name → value" map: a struct/union instance (its
470
+ * fields are accessors of its class, not own properties) becomes the object
471
+ * of its fields, any other value is returned as is.
472
+ *
473
+ * @param {*} value - Plain object or instance
474
+ * @returns {*} Object whose own properties are the fields
475
+ */
476
+ export function fieldsOf(value) {
477
+ if (value !== null && typeof value === "object" && Buffer.isBuffer(value._buffer) && typeof value.toObject === "function") {
478
+ return value.toObject();
479
+ }
480
+ return value;
481
+ }
482
+
217
483
  /**
218
484
  * Copy a struct/union instance into a nested field: the bytes (as Python
219
485
  * does) plus the objects it keeps alive (strings, pointers, callbacks), so
@@ -222,15 +488,38 @@ export function writePointerField(buf, offset, value, pointerSize) {
222
488
  * @param {Buffer} buf - Target buffer
223
489
  * @param {number} offset - Field offset
224
490
  * @param {number} size - Field size
225
- * @param {Object} value - Instance with a `_buffer`
491
+ * @param {Object|Buffer} value - Instance with a `_buffer`, or source bytes
492
+ * @param {number} [sourceOffset=0] - Byte offset in the source
493
+ * @param {Function|Object} [type] - Layout used to retain references into leased memory
226
494
  */
227
- export function copyInstance(buf, offset, size, value) {
228
- const source = value._buffer;
229
- source.copy(buf, offset, 0, size);
230
- const kept = source.__ctypesKeepalive;
231
- if (kept !== undefined) {
232
- for (const key of Object.keys(kept)) {
233
- if (Number(key) < size) keepAlive(buf, offset + Number(key), kept[key]);
495
+ export function copyInstance(buf, offset, size, value, sourceOffset = 0, type) {
496
+ const bytes = value._buffer ?? value;
497
+ const source = Buffer.isBuffer(bytes) ? bytes : Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength);
498
+ if (mirrorsActive) refresh(source, sourceOffset, size);
499
+ const start = memoryPosition(source, sourceOffset);
500
+ const sourceRoot = memoryDomains.get(source.buffer)?.root ?? source.buffer;
501
+ const sourceKept = keptObjects.get(sourceRoot);
502
+ const snapshot = new Map();
503
+ if (sourceKept !== undefined) {
504
+ for (const [position, reference] of sourceKept) {
505
+ if (position < start || position + BigInt(POINTER_SIZE) > start + BigInt(size)) continue;
506
+ const relative = Number(position - start);
507
+ if (reference.address === storedAddress(source, sourceOffset + relative)) snapshot.set(relative, reference.owner);
508
+ }
509
+ }
510
+ if (type !== undefined && memoryOwners.has(source.buffer)) {
511
+ for (const [position, width] of pointerSlots(type)) {
512
+ if (snapshot.has(position) || position + width > size) continue;
513
+ for (let i = 0; i < width; i++) {
514
+ if (source[sourceOffset + position + i] !== 0) {
515
+ snapshot.set(position, source);
516
+ break;
517
+ }
518
+ }
234
519
  }
235
520
  }
521
+ source.copy(buf, offset, sourceOffset, sourceOffset + size);
522
+ clearKeepAlives(buf, offset, size);
523
+ for (const [relative, object] of snapshot) keepAlive(buf, offset + relative, object);
524
+ if (mirrorsActive) flush(buf, offset, size);
236
525
  }
@@ -0,0 +1,145 @@
1
+ /**
2
+ * @file layout.js
3
+ * @module structures/helpers/layout
4
+ * @description Field layout of structures and unions, ported from CPython's
5
+ * `ctypes._layout.get_layout` (Python 3.14+), so that offsets, bitfields,
6
+ * `_pack_`, `_align_`, `_layout_` and inheritance give the same result as
7
+ * Python ctypes.
8
+ *
9
+ * Two layouts exist, as in Python:
10
+ * - `"gcc-sysv"` (default except on Windows): fields are placed bit by bit; a
11
+ * bitfield that would cross a boundary of its type moves to the next one.
12
+ * - `"ms"` (default on Windows, and whenever `_pack_` is set): adjacent
13
+ * bitfields share an allocation unit only if their types have the same size
14
+ * and the next one fits.
15
+ */
16
+
17
+ const roundDown = (n, multiple) => Math.floor(n / multiple) * multiple;
18
+ const roundUp = (n, multiple) => Math.ceil(n / multiple) * multiple;
19
+
20
+ export function normalizePack(value) {
21
+ if (value === null || value === undefined) return 0;
22
+ if (typeof value === "string") {
23
+ if (!/^[+-]?\d+$/.test(value.trim())) throw new TypeError("_pack_ must be convertible to an integer");
24
+ value = Number(value);
25
+ } else if (typeof value === "boolean" || typeof value === "bigint") {
26
+ value = Number(value);
27
+ }
28
+ if (typeof value !== "number" || !Number.isFinite(value)) throw new TypeError("_pack_ must be convertible to an integer");
29
+ const pack = Math.trunc(value);
30
+ if (pack < 0 || pack > 0x7fffffff) throw new RangeError("_pack_ must be between 0 and 2147483647");
31
+ return pack;
32
+ }
33
+
34
+ /**
35
+ * Layout mode of a class or definition, as Python: `_layout_` if given,
36
+ * otherwise `"ms"` on Windows or with `_pack_`, `"gcc-sysv"` elsewhere.
37
+ *
38
+ * @param {string|undefined} layout - `_layout_`
39
+ * @param {number} pack - `_pack_` (0 when absent)
40
+ * @returns {boolean} true for the gcc-sysv layout
41
+ */
42
+ export function isGccLayout(layout, pack, specified = pack !== 0) {
43
+ if (layout === undefined || layout === null) {
44
+ return process.platform !== "win32" && !specified;
45
+ }
46
+ if (layout === "ms") return false;
47
+ if (layout === "gcc-sysv") {
48
+ if (specified) throw new Error("_pack_ is not compatible with gcc-sysv layout");
49
+ return true;
50
+ }
51
+ throw new Error(`unknown _layout_: ${String(layout)}`);
52
+ }
53
+
54
+ /**
55
+ * Compute the layout of a structure or union.
56
+ *
57
+ * @param {Array<{size: number, align: number, bitSize?: number}>} fields -
58
+ * Size and alignment of each field type; `bitSize` for bitfields.
59
+ * @param {Object} options
60
+ * @param {boolean} options.isStruct - false for unions
61
+ * @param {boolean} options.gccLayout - see {@link isGccLayout}
62
+ * @param {number} [options.pack=0] - `_pack_` (ms layout only)
63
+ * @param {number} [options.align=1] - `_align_` (minimum alignment)
64
+ * @param {{size: number, alignment: number}} [options.base] - Layout of the base class
65
+ * @param {boolean} [options.bigEndian=false] - Bitfields laid out from the big end
66
+ * @returns {{offsets: Array<{offset: number, bitOffset?: number}>, size: number, alignment: number}}
67
+ */
68
+ export function computeLayout(fields, { isStruct, gccLayout, pack = 0, align = 1, base = null, bigEndian = false }) {
69
+ if (!Number.isInteger(align) || align < 0) throw new RangeError("_align_ must be a non-negative integer");
70
+ let alignment = Math.max(align, 1);
71
+ if (base) alignment = Math.max(base.alignment, alignment);
72
+
73
+ let lastFieldBitSize = 0; // ms layout only
74
+ // `8 * nextByteOffset + nextBitOffset` points to where the next field would start.
75
+ let nextBitOffset = 0;
76
+ let nextByteOffset = 0;
77
+ let structSize = 0;
78
+ let unionSize = 0;
79
+
80
+ if (base) {
81
+ structSize = base.size;
82
+ if (gccLayout) nextBitOffset = structSize * 8;
83
+ else nextByteOffset = structSize;
84
+ unionSize = isStruct ? 0 : base.size;
85
+ }
86
+
87
+ const offsets = [];
88
+ for (const field of fields) {
89
+ if (!isStruct) {
90
+ // Unions start fresh each time
91
+ lastFieldBitSize = 0;
92
+ nextBitOffset = 0;
93
+ nextByteOffset = 0;
94
+ }
95
+
96
+ const isBitField = field.bitSize !== undefined && field.bitSize !== null;
97
+ const typeSize = field.size;
98
+ const typeBitSize = typeSize * 8;
99
+ const bitSize = isBitField ? field.bitSize : typeBitSize;
100
+ if (isBitField && (!Number.isInteger(bitSize) || bitSize <= 0 || bitSize > typeBitSize)) {
101
+ throw new RangeError(`number of bits invalid for bit field ${JSON.stringify(field.name)}`);
102
+ }
103
+ let typeAlign = field.align || 1;
104
+ let offset;
105
+ let bitOffset;
106
+
107
+ if (gccLayout) {
108
+ const typeBitAlign = typeAlign * 8;
109
+ // The "slot" sized and aligned for the type that contains the start of
110
+ // the field must also contain its last bit, otherwise pad to the next one.
111
+ const slotEndBit = roundDown(nextBitOffset, typeBitAlign) + typeBitSize;
112
+ if (nextBitOffset + bitSize > slotEndBit) {
113
+ nextBitOffset = roundUp(nextBitOffset, typeBitAlign);
114
+ }
115
+ offset = roundDown(nextBitOffset, typeBitAlign) / 8;
116
+ if (isBitField) bitOffset = nextBitOffset - 8 * offset;
117
+ nextBitOffset += bitSize;
118
+ structSize = roundUp(nextBitOffset, 8) / 8;
119
+ } else {
120
+ if (pack) typeAlign = Math.min(pack, typeAlign);
121
+ // Close the previous bitfield (if any) and start a new allocation unit.
122
+ if (0 < nextBitOffset + bitSize || typeBitSize !== lastFieldBitSize) {
123
+ nextByteOffset = roundUp(nextByteOffset, typeAlign) + typeSize;
124
+ lastFieldBitSize = typeBitSize;
125
+ nextBitOffset = -lastFieldBitSize;
126
+ }
127
+ offset = nextByteOffset - lastFieldBitSize / 8;
128
+ if (isBitField) bitOffset = lastFieldBitSize + nextBitOffset;
129
+ nextBitOffset += bitSize;
130
+ structSize = nextByteOffset;
131
+ }
132
+
133
+ if (isBitField && bigEndian) {
134
+ // Bitfields of big-endian structures start from the big end.
135
+ bitOffset = typeBitSize - bitSize - bitOffset;
136
+ }
137
+
138
+ offsets.push(isBitField ? { offset, bitOffset } : { offset });
139
+ alignment = Math.max(alignment, typeAlign);
140
+ if (!isStruct) unionSize = Math.max(unionSize, structSize);
141
+ }
142
+
143
+ const totalSize = isStruct ? structSize : unionSize;
144
+ return { offsets, size: roundUp(totalSize, alignment), alignment };
145
+ }