node-ctypes 2.2.0 → 2.3.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.
@@ -106,6 +106,7 @@
106
106
  */
107
107
  import { encodeWide, decodeWide } from "../../memory/buffer.js";
108
108
  import { funcPtrFieldType, writePointerField } from "./common.js";
109
+ import { buildWrapper } from "./wrap.js";
109
110
  import { flush, isMirror, mirrorsActive, refresh } from "../../memory/mirror.js";
110
111
 
111
112
  // Python: gli array di c_char / c_wchar (anche come campi struct) hanno un
@@ -130,6 +131,54 @@ function setCharArrayValue(buf, charKind, wcharSize, value, message) {
130
131
  }
131
132
  }
132
133
 
134
+ // Metodi di Array che sul proxy operano sugli elementi (Python: arr[1:3],
135
+ // x in arr, list(arr)), non sui byte del Buffer: le versioni generiche di
136
+ // Array.prototype usano `length` e gli indici del proxy. I metodi propri di
137
+ // Buffer/TypedArray (readInt32LE, subarray, copy, ...) restano sui byte.
138
+ const elementMethods = new Map(
139
+ [
140
+ "at",
141
+ "copyWithin",
142
+ "entries",
143
+ "every",
144
+ "fill",
145
+ "filter",
146
+ "find",
147
+ "findIndex",
148
+ "findLast",
149
+ "findLastIndex",
150
+ "forEach",
151
+ "includes",
152
+ "indexOf",
153
+ "join",
154
+ "keys",
155
+ "lastIndexOf",
156
+ "map",
157
+ "reduce",
158
+ "reduceRight",
159
+ "reverse",
160
+ "slice",
161
+ "some",
162
+ "sort",
163
+ "toLocaleString",
164
+ "toReversed",
165
+ "toSorted",
166
+ "values",
167
+ "with",
168
+ ]
169
+ .filter((name) => typeof Array.prototype[name] === "function")
170
+ .map((name) => [name, Array.prototype[name]]),
171
+ );
172
+
173
+ function elementsToJSON() {
174
+ return Array.from(this);
175
+ }
176
+
177
+ // Python: lo slice di c_char * n / c_wchar * n è bytes / str.
178
+ function charSlice(...args) {
179
+ return Array.prototype.slice.apply(this, args).join("");
180
+ }
181
+
133
182
  export function array(elementType, count, sizeof, alloc, readValue, writeValue, Structure, Union, ArrayType, voidPointerType, ptrToBuffer) {
134
183
  // Validate elementType: accept SimpleCData classes, Structure/Union classes,
135
184
  // or native CType-like objects.
@@ -137,10 +186,12 @@ export function array(elementType, count, sizeof, alloc, readValue, writeValue,
137
186
  const isStruct = typeof elementType === "function" && (elementType.prototype instanceof Structure || elementType.prototype instanceof Union);
138
187
  // Array di puntatori (Python: POINTER(T) * n, CFUNCTYPE * n).
139
188
  const isPointerElem = (typeof elementType === "object" && elementType !== null && elementType._pointerTo !== undefined) || (typeof elementType === "function" && elementType._isFuncPtr === true);
140
- const isNativeTypeObj = !isPointerElem && typeof elementType === "object" && elementType !== null && (typeof elementType.getSize === "function" || elementType.size !== undefined);
189
+ // Definizione di struct()/union(): come una classe Structure/Union.
190
+ const isStructDef = !isPointerElem && typeof elementType === "object" && elementType !== null && elementType._isStructType === true;
191
+ const isNativeTypeObj = !isPointerElem && !isStructDef && typeof elementType === "object" && elementType !== null && (typeof elementType.getSize === "function" || elementType.size !== undefined);
141
192
  // Array di array (Python: (c_int * 2) * 3).
142
193
  const isArrayElem = typeof elementType === "function" && elementType._isArrayType === true;
143
- if (!isSimple && !isStruct && !isNativeTypeObj && !isArrayElem && !isPointerElem) {
194
+ if (!isSimple && !isStruct && !isStructDef && !isNativeTypeObj && !isArrayElem && !isPointerElem) {
144
195
  throw new TypeError("array elementType must be a SimpleCData class or a Structure/Union class");
145
196
  }
146
197
 
@@ -148,7 +199,7 @@ export function array(elementType, count, sizeof, alloc, readValue, writeValue,
148
199
  // Array alignment == element alignment (C standard), NOT element size.
149
200
  // For Structure/Union: ask the class. For SimpleCData: alignment == size
150
201
  // (each primitive is self-aligned on all platforms we target).
151
- const elementAlignment = isStruct ? (elementType.alignment ?? elementSize) : isArrayElem ? elementType.getAlignment() : elementSize;
202
+ const elementAlignment = isStruct ? (elementType.alignment ?? elementSize) : isStructDef ? elementType.alignment : isArrayElem ? elementType.getAlignment() : elementSize;
152
203
  let nativeArray;
153
204
  if (isPointerElem && ArrayType && voidPointerType) {
154
205
  nativeArray = new ArrayType(voidPointerType._type, count);
@@ -214,6 +265,10 @@ export function array(elementType, count, sizeof, alloc, readValue, writeValue,
214
265
  if (isStructElem) {
215
266
  return new elementType(target.subarray(off, off + elementSize));
216
267
  }
268
+ if (isStructDef) {
269
+ const view = target.subarray(off, off + elementSize);
270
+ return new Proxy(view, buildWrapper(elementType, { instanceTag: "NestedStructInstance", exposeAnonymous: true, mirrored: isMirror(view) }));
271
+ }
217
272
  if (isArrayElem) {
218
273
  return elementType.wrap(target.subarray(off, off + elementSize));
219
274
  }
@@ -255,7 +310,7 @@ export function array(elementType, count, sizeof, alloc, readValue, writeValue,
255
310
  // scalare o puntatore si rilegge prima di leggerlo e si ricopia dopo averlo
256
311
  // scritto (viene sovrascritto per intero). Gli elementi struct e array sono
257
312
  // istanze che si sincronizzano da sole.
258
- const scalarElem = !isStructElem && !isArrayElem;
313
+ const scalarElem = !isStructElem && !isStructDef && !isArrayElem;
259
314
  const mirroredReadAt = (target, index) => {
260
315
  if (scalarElem && index >= 0 && index < count) refresh(target, index * elementSize, elementSize);
261
316
  return readAt(target, index);
@@ -319,6 +374,11 @@ export function array(elementType, count, sizeof, alloc, readValue, writeValue,
319
374
  if (prop === "_buffer") {
320
375
  return target;
321
376
  }
377
+ // Tipo dell'array (controllo degli argomenti: Python accetta solo
378
+ // istanze dello stesso tipo array).
379
+ if (prop === "_arrayType") {
380
+ return ArrayCType;
381
+ }
322
382
 
323
383
  // Python ctypes parity: `len(arr)` ritorna il numero di elementi,
324
384
  // non la dimensione in byte del buffer. Senza questo trap,
@@ -363,6 +423,10 @@ export function array(elementType, count, sizeof, alloc, readValue, writeValue,
363
423
  return readAt(target, index);
364
424
  }
365
425
 
426
+ const method = elementMethods.get(prop);
427
+ if (method !== undefined) return charKind !== undefined && prop === "slice" ? charSlice : method;
428
+ if (prop === "toJSON") return elementsToJSON;
429
+
366
430
  // For everything else, use the normal buffer
367
431
  const value = Reflect.get(target, prop, target);
368
432
  // If it's a function, bind it to the target
@@ -414,6 +478,9 @@ export function array(elementType, count, sizeof, alloc, readValue, writeValue,
414
478
  for (let i = 0; i < Math.min(values.length, count); i++) {
415
479
  writeAt(buffer, i, values[i]);
416
480
  }
481
+ } else if (typeof values === "string" && setValue !== undefined) {
482
+ // c_char * n / c_wchar * n: stessa codifica di `.value` (UTF-8 / wchar_t).
483
+ setValue(buffer, values);
417
484
  } else if (typeof values === "string") {
418
485
  for (let i = 0; i < Math.min(values.length, count); i++) {
419
486
  writeAt(buffer, i, values.charCodeAt(i));
@@ -1,165 +1,81 @@
1
1
  /**
2
- * @file bitfield-helpers.js
3
- * @module structures/bitfield-helpers
4
- * @description Helper functions for reading and writing bitfield values in structs.
2
+ * @file bitfield.js
3
+ * @module structures/helpers/bitfield
4
+ * @description Readers and writers of bitfields in structs and unions.
5
5
  *
6
- * This module provides low-level bitfield manipulation functions used by struct
7
- * and union implementations to pack multiple small integer values into single bytes.
8
- *
9
- * @example
10
- * ```javascript
11
- * import { _readBitField, _writeBitField } from './structures/bitfield-helpers.js';
12
- *
13
- * const buf = Buffer.alloc(4);
14
- * _writeBitField(buf, 0, c_uint32, 0, 3, 5); // Write 5 to bits 0-2
15
- * const value = _readBitField(buf, 0, c_uint32, 0, 3); // Read bits 0-2
16
- * ```
17
- */
18
-
19
- /**
20
- * Reads an unsigned integer value from a buffer.
21
- *
22
- * @param {Buffer} buf - Buffer to read from
23
- * @param {number} offset - Byte offset in buffer
24
- * @param {number} byteSize - Size in bytes (1, 2, 4, or 8)
25
- * @param {Function} sizeof - sizeof function reference
26
- * @returns {number|bigint} Value read from buffer
27
- * @throws {Error} If byteSize is not supported
28
- * @private
6
+ * A bitfield is `bitSize` bits at `bitOffset` inside an allocation unit of
7
+ * its base type (`baseSize` bytes at `offset`), as computed by layout.js.
8
+ * Values are truncated to the field width on write; signed base types are
9
+ * sign-extended on read, as in Python ctypes. Fields up to 53 bits read as
10
+ * numbers, wider ones (only possible with 64-bit base types) as BigInt.
29
11
  */
30
- export function _readUintFromBuffer(buf, offset, byteSize) {
31
- switch (byteSize) {
32
- case 1:
33
- return buf.readUInt8(offset);
34
- case 2:
35
- return buf.readUInt16LE(offset);
36
- case 4:
37
- return buf.readUInt32LE(offset);
38
- case 8:
39
- return buf.readBigUInt64LE(offset);
40
- default:
41
- throw new Error(`Unsupported byte size: ${byteSize}`);
42
- }
43
- }
44
12
 
45
- /**
46
- * Writes an unsigned integer value to a buffer.
47
- *
48
- * @param {Buffer} buf - Buffer to write to
49
- * @param {number} offset - Byte offset in buffer
50
- * @param {number} byteSize - Size in bytes (1, 2, 4, or 8)
51
- * @param {number|bigint} value - Value to write
52
- * @throws {Error} If byteSize is not supported
53
- * @private
54
- */
55
- export function _writeUintToBuffer(buf, offset, byteSize, value) {
56
- switch (byteSize) {
57
- case 1:
58
- buf.writeUInt8(value, offset);
59
- break;
60
- case 2:
61
- buf.writeUInt16LE(value, offset);
62
- break;
63
- case 4:
64
- buf.writeUInt32LE(value, offset);
65
- break;
66
- case 8:
67
- buf.writeBigUInt64LE(value, offset);
68
- break;
69
- default:
70
- throw new Error(`Unsupported byte size: ${byteSize}`);
71
- }
72
- }
13
+ const readers = {
14
+ 1: { le: (buf, off) => buf.readUInt8(off), be: (buf, off) => buf.readUInt8(off) },
15
+ 2: { le: (buf, off) => buf.readUInt16LE(off), be: (buf, off) => buf.readUInt16BE(off) },
16
+ 4: { le: (buf, off) => buf.readUInt32LE(off), be: (buf, off) => buf.readUInt32BE(off) },
17
+ 8: { le: (buf, off) => buf.readBigUInt64LE(off), be: (buf, off) => buf.readBigUInt64BE(off) },
18
+ };
73
19
 
74
- /**
75
- * Reads a bitfield value from a buffer.
76
- *
77
- * Extracts a specific range of bits from an integer value stored in memory.
78
- * Used by struct/union implementations to support packed bitfields.
79
- *
80
- * @param {Buffer} buf - Buffer to read from
81
- * @param {number} offset - Byte offset of the containing integer
82
- * @param {Function|Object} baseType - Base integer type (c_uint8, c_uint16, c_uint32, c_uint64)
83
- * @param {number} bitOffset - Starting bit position (0-based)
84
- * @param {number} bitSize - Number of bits to read
85
- * @param {Function} sizeof - sizeof function reference
86
- * @returns {number} Extracted bitfield value
87
- *
88
- * @example
89
- * ```javascript
90
- * // Read 3-bit field starting at bit 5
91
- * const value = _readBitField(buf, 0, c_uint32, 5, 3);
92
- * ```
93
- * @private
94
- */
95
- export function _readBitField(buf, offset, baseType, bitOffset, bitSize, sizeof) {
96
- const baseSize = sizeof(baseType);
97
- const value = _readUintFromBuffer(buf, offset, baseSize);
98
- // Parity Python ctypes: base type signed → sign-extend. `c_int8, 3`
99
- // con valore -1 (= 0b111 nei 3 bit) deve rileggere -1, non 7.
100
- const isSigned = baseType?._signed === true;
20
+ const writers = {
21
+ 1: { le: (buf, off, v) => buf.writeUInt8(v, off), be: (buf, off, v) => buf.writeUInt8(v, off) },
22
+ 2: { le: (buf, off, v) => buf.writeUInt16LE(v, off), be: (buf, off, v) => buf.writeUInt16BE(v, off) },
23
+ 4: { le: (buf, off, v) => buf.writeUInt32LE(v, off), be: (buf, off, v) => buf.writeUInt32BE(v, off) },
24
+ 8: { le: (buf, off, v) => buf.writeBigUInt64LE(v, off), be: (buf, off, v) => buf.writeBigUInt64BE(v, off) },
25
+ };
101
26
 
102
- if (baseSize === 8) {
103
- const mask = (1n << BigInt(bitSize)) - 1n;
104
- const raw = (value >> BigInt(bitOffset)) & mask;
105
- if (isSigned) {
106
- const signBit = 1n << BigInt(bitSize - 1);
107
- const extend = ~mask;
108
- const signed = (raw & signBit) ? (raw | extend) : raw;
109
- const asNum = Number(signed);
110
- return (asNum >= Number.MIN_SAFE_INTEGER && asNum <= Number.MAX_SAFE_INTEGER)
111
- ? asNum
112
- : signed;
113
- }
114
- return Number(raw);
115
- }
116
- const mask = (1 << bitSize) - 1;
117
- const raw = (value >> bitOffset) & mask;
118
- if (isSigned) {
119
- const signBit = 1 << (bitSize - 1);
120
- const extend = ~mask;
121
- return (raw & signBit) ? (raw | extend) : raw;
122
- }
123
- return raw;
124
- }
27
+ import { notIntegral } from "./common.js";
125
28
 
126
29
  /**
127
- * Writes a bitfield value to a buffer.
128
- *
129
- * Modifies a specific range of bits in an integer value stored in memory,
130
- * preserving other bits. Used by struct/union implementations to support
131
- * packed bitfields.
132
- *
133
- * @param {Buffer} buf - Buffer to write to
134
- * @param {number} offset - Byte offset of the containing integer
135
- * @param {Function|Object} baseType - Base integer type (c_uint8, c_uint16, c_uint32, c_uint64)
136
- * @param {number} bitOffset - Starting bit position (0-based)
137
- * @param {number} bitSize - Number of bits to write
138
- * @param {number} newValue - Value to write (will be masked to bitSize)
139
- * @param {Function} sizeof - sizeof function reference
30
+ * Reader and writer of one bitfield.
140
31
  *
141
- * @example
142
- * ```javascript
143
- * // Write 5 to a 3-bit field starting at bit 2
144
- * _writeBitField(buf, 0, c_uint32, 2, 3, 5);
145
- * ```
146
- * @private
32
+ * @param {Object} field
33
+ * @param {number} field.offset - Byte offset of the allocation unit
34
+ * @param {number} field.baseSize - Size of the base type (1, 2, 4 or 8)
35
+ * @param {number} field.bitOffset - First bit inside the unit
36
+ * @param {number} field.bitSize - Width in bits
37
+ * @param {boolean} [field.signed=false] - Signed base type
38
+ * @param {boolean} [field.bigEndian=false] - Unit stored big-endian
39
+ * @returns {{read: (buf: Buffer) => number|bigint, write: (buf: Buffer, value: number|bigint) => void}}
147
40
  */
148
- export function _writeBitField(buf, offset, baseType, bitOffset, bitSize, newValue, sizeof) {
149
- const baseSize = sizeof(baseType);
150
- let value = _readUintFromBuffer(buf, offset, baseSize);
41
+ export function bitFieldAccessors({ offset, baseSize, bitOffset, bitSize, signed = false, bigEndian = false }) {
42
+ const order = bigEndian ? "be" : "le";
43
+ const readUnit = readers[baseSize]?.[order];
44
+ const writeUnit = writers[baseSize]?.[order];
45
+ if (readUnit === undefined) throw new RangeError(`Unsupported bitfield base size: ${baseSize}`);
151
46
 
152
- // Modify the bits
153
47
  if (baseSize === 8) {
154
- const mask = (1n << BigInt(bitSize)) - 1n;
155
- const clearMask = ~(mask << BigInt(bitOffset));
156
- value = (value & clearMask) | ((BigInt(newValue) & mask) << BigInt(bitOffset));
157
- } else {
158
- const mask = (1 << bitSize) - 1;
159
- const clearMask = ~(mask << bitOffset);
160
- const bits = typeof newValue === "bigint" ? Number(BigInt.asUintN(32, newValue)) : newValue;
161
- value = (value & clearMask) | ((bits & mask) << bitOffset);
48
+ const shift = BigInt(bitOffset);
49
+ const width = BigInt(bitSize);
50
+ const mask = ((1n << width) - 1n) << shift;
51
+ const toValue = bitSize <= 53 ? Number : (v) => v;
52
+ return {
53
+ read: (buf) => {
54
+ const raw = (readUnit(buf, offset) & mask) >> shift;
55
+ return toValue(signed ? BigInt.asIntN(bitSize, raw) : raw);
56
+ },
57
+ write: (buf, value) => {
58
+ if (typeof value === "number" && !Number.isInteger(value)) notIntegral();
59
+ const bits = BigInt.asUintN(bitSize, BigInt(value)) << shift;
60
+ writeUnit(buf, offset, (readUnit(buf, offset) & ~mask) | bits);
61
+ },
62
+ };
162
63
  }
163
64
 
164
- _writeUintToBuffer(buf, offset, baseSize, value);
65
+ // Units up to 32 bits: >>> 0 keeps the results unsigned (also for 32-bit fields).
66
+ const fieldMask = bitSize === 32 ? 0xffffffff : 2 ** bitSize - 1;
67
+ const unitMask = (fieldMask * 2 ** bitOffset) >>> 0;
68
+ const unsignedValue = (value) => {
69
+ if (typeof value === "bigint") return Number(BigInt.asUintN(bitSize, value)) >>> 0;
70
+ if (typeof value === "number" && !Number.isInteger(value)) notIntegral();
71
+ return (Number(value) & fieldMask) >>> 0;
72
+ };
73
+ const signShift = 32 - bitSize;
74
+ return {
75
+ read: signed ? (buf) => (((readUnit(buf, offset) & unitMask) >>> bitOffset) << signShift) >> signShift : (buf) => (readUnit(buf, offset) & unitMask) >>> bitOffset,
76
+ write: (buf, value) => {
77
+ const bits = (unsignedValue(value) << bitOffset) >>> 0;
78
+ writeUnit(buf, offset, ((readUnit(buf, offset) & ~unitMask) | bits) >>> 0);
79
+ },
80
+ };
165
81
  }
@@ -137,6 +137,46 @@ export function _isBitField(type) {
137
137
  return typeof type === "object" && type !== null && type._isBitField === true;
138
138
  }
139
139
 
140
+ /**
141
+ * Writer of a SimpleCData field of a struct/union. An instance assigned to the
142
+ * field (or given as positional initializer) is copied when it has the same
143
+ * type, as Python (pointers keep the instance alive); another SimpleCData type
144
+ * is "incompatible types" (c_void_p fields accept the pointer types).
145
+ *
146
+ * @param {Function} fieldType - SimpleCData class of the field
147
+ * @param {Function} writer - `(buf, offset, value)` writer
148
+ * @param {number} offset - Field offset
149
+ * @returns {Function} `(buf, value)` writer
150
+ */
151
+ export function simpleFieldWriter(fieldType, writer, offset) {
152
+ const pointerValued = fieldType._isPointerValued === true;
153
+ return (buf, val) => {
154
+ if (typeof val === "object" && val !== null && val.constructor?._isSimpleCData === true) {
155
+ const T = val.constructor;
156
+ if (T._type === fieldType._type && T._size === fieldType._size) {
157
+ if (!pointerValued) return writer(buf, offset, val.value);
158
+ val._buffer.copy(buf, offset, 0, T._size);
159
+ keepAlive(buf, offset, val);
160
+ return;
161
+ }
162
+ if (!(fieldType._acceptsPointerValues === true && T._isPointerValued === true)) {
163
+ throw new TypeError(`incompatible types, ${T.name} instance instead of ${fieldType.name} instance`);
164
+ }
165
+ }
166
+ writer(buf, offset, val);
167
+ };
168
+ }
169
+
170
+ /**
171
+ * Python: a float is not an integer ("'float' object cannot be interpreted as
172
+ * an integer"); in JS, numbers that are not integral (or not finite).
173
+ *
174
+ * @throws {TypeError}
175
+ */
176
+ export function notIntegral() {
177
+ throw new TypeError("'float' object cannot be interpreted as an integer");
178
+ }
179
+
140
180
  /**
141
181
  * Address stored by a pointer field assignment: a pointer instance, a
142
182
  * CFUNCTYPE/callback object (`_as_parameter_`), a BigInt/number address,
@@ -179,23 +219,46 @@ export function funcPtrFieldType(prototype) {
179
219
  return fieldType;
180
220
  }
181
221
 
222
+ // Oggetti tenuti vivi dalla memoria che contiene i loro indirizzi, per
223
+ // ArrayBuffer e offset assoluto: tutte le view sulla stessa memoria (istanza,
224
+ // struct annidata, from_buffer) condividono la stessa tabella.
225
+ const keptObjects = new WeakMap();
226
+
182
227
  /**
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.
228
+ * Keep `value` alive as long as the memory of `targetBuf`, like Python ctypes
229
+ * `_objects`: an object whose address is stored in the buffer (string,
230
+ * pointer, callback) must not be garbage collected while native code can
231
+ * still read that address. The table belongs to the memory, not to the view,
232
+ * so assigning through a nested structure keeps the object alive with the
233
+ * outer one.
187
234
  *
188
- * @param {Buffer} targetBuf - Buffer holding the address
189
- * @param {number} offset - Offset of the slot
235
+ * @param {Uint8Array} targetBuf - Buffer holding the address
236
+ * @param {number} offset - Offset of the slot in `targetBuf`
190
237
  * @param {*} value - Referenced object (or null to clear the slot)
191
238
  */
192
239
  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 });
240
+ const position = targetBuf.byteOffset + offset;
241
+ let kept = keptObjects.get(targetBuf.buffer);
242
+ if (value === null || typeof value !== "object") {
243
+ kept?.delete(position);
244
+ return;
245
+ }
246
+ if (kept === undefined) {
247
+ kept = new Map();
248
+ keptObjects.set(targetBuf.buffer, kept);
197
249
  }
198
- keep[offset] = value !== null && typeof value === "object" ? value : undefined;
250
+ kept.set(position, value);
251
+ }
252
+
253
+ /**
254
+ * Object kept alive at `offset` of `buf` (see {@link keepAlive}).
255
+ *
256
+ * @param {Uint8Array} buf - Buffer
257
+ * @param {number} offset - Offset in `buf`
258
+ * @returns {*} The object, or undefined
259
+ */
260
+ export function keptObject(buf, offset) {
261
+ return keptObjects.get(buf.buffer)?.get(buf.byteOffset + offset);
199
262
  }
200
263
 
201
264
  /**
@@ -214,6 +277,35 @@ export function writePointerField(buf, offset, value, pointerSize) {
214
277
  keepAlive(buf, offset, value);
215
278
  }
216
279
 
280
+ /**
281
+ * Fields given to struct() / union(): `[name, type]` pairs in declaration
282
+ * order (Structure._fieldMap; an object would put integer-like names such as
283
+ * "1" first), a Map or a `{ name: type }` object.
284
+ *
285
+ * @param {Array|Map|Object} fields - Field declarations
286
+ * @returns {Array} `[name, type]` pairs
287
+ */
288
+ export function fieldEntries(fields) {
289
+ if (Array.isArray(fields)) return fields;
290
+ if (fields instanceof Map) return [...fields];
291
+ return Object.entries(fields);
292
+ }
293
+
294
+ /**
295
+ * Fields of a value used as "name → value" map: a struct/union instance (its
296
+ * fields are accessors of its class, not own properties) becomes the object
297
+ * of its fields, any other value is returned as is.
298
+ *
299
+ * @param {*} value - Plain object or instance
300
+ * @returns {*} Object whose own properties are the fields
301
+ */
302
+ export function fieldsOf(value) {
303
+ if (value !== null && typeof value === "object" && Buffer.isBuffer(value._buffer) && typeof value.toObject === "function") {
304
+ return value.toObject();
305
+ }
306
+ return value;
307
+ }
308
+
217
309
  /**
218
310
  * Copy a struct/union instance into a nested field: the bytes (as Python
219
311
  * does) plus the objects it keeps alive (strings, pointers, callbacks), so
@@ -227,10 +319,18 @@ export function writePointerField(buf, offset, value, pointerSize) {
227
319
  export function copyInstance(buf, offset, size, value) {
228
320
  const source = value._buffer;
229
321
  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]);
322
+ const target = buf.byteOffset + offset;
323
+ const targetKept = keptObjects.get(buf.buffer);
324
+ if (targetKept !== undefined) {
325
+ for (const position of targetKept.keys()) {
326
+ if (position >= target && position < target + size) targetKept.delete(position);
327
+ }
328
+ }
329
+ const sourceKept = keptObjects.get(source.buffer);
330
+ if (sourceKept !== undefined) {
331
+ for (const [position, object] of sourceKept) {
332
+ const relative = position - source.byteOffset;
333
+ if (relative >= 0 && relative < size) keepAlive(buf, offset + relative, object);
234
334
  }
235
335
  }
236
336
  }
@@ -0,0 +1,131 @@
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
+ /**
21
+ * Layout mode of a class or definition, as Python: `_layout_` if given,
22
+ * otherwise `"ms"` on Windows or with `_pack_`, `"gcc-sysv"` elsewhere.
23
+ *
24
+ * @param {string|undefined} layout - `_layout_`
25
+ * @param {number} pack - `_pack_` (0 when absent)
26
+ * @returns {boolean} true for the gcc-sysv layout
27
+ */
28
+ export function isGccLayout(layout, pack) {
29
+ if (layout === undefined || layout === null) {
30
+ return process.platform !== "win32" && !pack;
31
+ }
32
+ if (layout === "ms") return false;
33
+ if (layout === "gcc-sysv") {
34
+ if (pack) throw new Error("_pack_ is not compatible with gcc-sysv layout");
35
+ return true;
36
+ }
37
+ throw new Error(`unknown _layout_: ${String(layout)}`);
38
+ }
39
+
40
+ /**
41
+ * Compute the layout of a structure or union.
42
+ *
43
+ * @param {Array<{size: number, align: number, bitSize?: number}>} fields -
44
+ * Size and alignment of each field type; `bitSize` for bitfields.
45
+ * @param {Object} options
46
+ * @param {boolean} options.isStruct - false for unions
47
+ * @param {boolean} options.gccLayout - see {@link isGccLayout}
48
+ * @param {number} [options.pack=0] - `_pack_` (ms layout only)
49
+ * @param {number} [options.align=1] - `_align_` (minimum alignment)
50
+ * @param {{size: number, alignment: number}} [options.base] - Layout of the base class
51
+ * @param {boolean} [options.bigEndian=false] - Bitfields laid out from the big end
52
+ * @returns {{offsets: Array<{offset: number, bitOffset?: number}>, size: number, alignment: number}}
53
+ */
54
+ export function computeLayout(fields, { isStruct, gccLayout, pack = 0, align = 1, base = null, bigEndian = false }) {
55
+ if (!Number.isInteger(align) || align < 0) throw new RangeError("_align_ must be a non-negative integer");
56
+ let alignment = Math.max(align, 1);
57
+ if (base) alignment = Math.max(base.alignment, alignment);
58
+
59
+ let lastFieldBitSize = 0; // ms layout only
60
+ // `8 * nextByteOffset + nextBitOffset` points to where the next field would start.
61
+ let nextBitOffset = 0;
62
+ let nextByteOffset = 0;
63
+ let structSize = 0;
64
+ let unionSize = 0;
65
+
66
+ if (base) {
67
+ structSize = base.size;
68
+ if (gccLayout) nextBitOffset = structSize * 8;
69
+ else nextByteOffset = structSize;
70
+ unionSize = isStruct ? 0 : base.size;
71
+ }
72
+
73
+ const offsets = [];
74
+ for (const field of fields) {
75
+ if (!isStruct) {
76
+ // Unions start fresh each time
77
+ lastFieldBitSize = 0;
78
+ nextBitOffset = 0;
79
+ nextByteOffset = 0;
80
+ }
81
+
82
+ const isBitField = field.bitSize !== undefined && field.bitSize !== null;
83
+ const typeSize = field.size;
84
+ const typeBitSize = typeSize * 8;
85
+ const bitSize = isBitField ? field.bitSize : typeBitSize;
86
+ if (isBitField && (!Number.isInteger(bitSize) || bitSize <= 0 || bitSize > typeBitSize)) {
87
+ throw new RangeError(`number of bits invalid for bit field ${JSON.stringify(field.name)}`);
88
+ }
89
+ let typeAlign = field.align || 1;
90
+ let offset;
91
+ let bitOffset;
92
+
93
+ if (gccLayout) {
94
+ const typeBitAlign = typeAlign * 8;
95
+ // The "slot" sized and aligned for the type that contains the start of
96
+ // the field must also contain its last bit, otherwise pad to the next one.
97
+ const slotEndBit = roundDown(nextBitOffset, typeBitAlign) + typeBitSize;
98
+ if (nextBitOffset + bitSize > slotEndBit) {
99
+ nextBitOffset = roundUp(nextBitOffset, typeBitAlign);
100
+ }
101
+ offset = roundDown(nextBitOffset, typeBitAlign) / 8;
102
+ if (isBitField) bitOffset = nextBitOffset - 8 * offset;
103
+ nextBitOffset += bitSize;
104
+ structSize = roundUp(nextBitOffset, 8) / 8;
105
+ } else {
106
+ if (pack) typeAlign = Math.min(pack, typeAlign);
107
+ // Close the previous bitfield (if any) and start a new allocation unit.
108
+ if (0 < nextBitOffset + bitSize || typeBitSize !== lastFieldBitSize) {
109
+ nextByteOffset = roundUp(nextByteOffset, typeAlign) + typeSize;
110
+ lastFieldBitSize = typeBitSize;
111
+ nextBitOffset = -lastFieldBitSize;
112
+ }
113
+ offset = nextByteOffset - lastFieldBitSize / 8;
114
+ if (isBitField) bitOffset = lastFieldBitSize + nextBitOffset;
115
+ nextBitOffset += bitSize;
116
+ structSize = nextByteOffset;
117
+ }
118
+
119
+ if (isBitField && bigEndian) {
120
+ // Bitfields of big-endian structures start from the big end.
121
+ bitOffset = typeBitSize - bitSize - bitOffset;
122
+ }
123
+
124
+ offsets.push(isBitField ? { offset, bitOffset } : { offset });
125
+ alignment = Math.max(alignment, typeAlign);
126
+ if (!isStruct) unionSize = Math.max(unionSize, structSize);
127
+ }
128
+
129
+ const totalSize = isStruct ? structSize : unionSize;
130
+ return { offsets, size: roundUp(totalSize, alignment), alignment };
131
+ }