node-ctypes 2.3.0 → 2.5.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.
@@ -1,3 +1,77 @@
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 activeArgumentOwners = new Set();
6
+ export const byrefOwners = new WeakMap();
7
+ export const structArgumentFactories = new WeakMap();
8
+
9
+ export function resolveParameter(value, owners) {
10
+ if (value === null || (typeof value !== "object" && typeof value !== "function")) return value;
11
+ if (owners !== undefined) owners.push(value);
12
+ if (ArrayBuffer.isView(value) && !("_as_parameter_" in value)) return value;
13
+ if (value._isSimpleCDataInstance === true || value._pointerType !== undefined || value._arrayType !== undefined || value._structDef !== undefined || byrefOwners.has(value)) return value;
14
+ const parameter = value._as_parameter_;
15
+ if (parameter === undefined) return value;
16
+ if (parameter === null || (typeof parameter !== "object" && typeof parameter !== "function")) return parameter;
17
+ if (owners !== undefined) return resolveParameter(parameter, owners);
18
+
19
+ // Resolver-only memory operations also retain parents while nested getters can collect.
20
+ const retained = [value];
21
+ activeArgumentOwners.add(retained);
22
+ try {
23
+ return resolveParameter(parameter, retained);
24
+ } finally {
25
+ activeArgumentOwners.delete(retained);
26
+ }
27
+ }
28
+
29
+ export function sourceBytes(source, offset, size, name) {
30
+ const bytes = source !== null && typeof source === "object" && !ArrayBuffer.isView(source) && Buffer.isBuffer(source._buffer) ? source._buffer : source;
31
+ if (!ArrayBuffer.isView(bytes)) throw new TypeError(`${name}: source must be a Buffer, a typed array or a ctypes instance`);
32
+ if (!Number.isSafeInteger(offset)) throw new TypeError(`${name}: offset must be a safe integer`);
33
+ if (offset < 0) throw new RangeError(`${name}: offset cannot be negative`);
34
+ if (bytes.byteLength - offset < size) throw new RangeError(`${name}: Buffer size too small (${bytes.byteLength} instead of at least ${size + offset} bytes)`);
35
+ return bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes.buffer, bytes.byteOffset, bytes.byteLength);
36
+ }
37
+
38
+ export function registerSimpleType(type) {
39
+ simpleTypes.add(type);
40
+ }
41
+
42
+ export function isScalarSubclass(type) {
43
+ return typeof type === "function" && type._isSimpleCData === true && !simpleTypes.has(type);
44
+ }
45
+
46
+ export function scalarView(type, buffer, swapped = false) {
47
+ // C-owned representations must bypass application constructors and writers.
48
+ const base = mirrorsActive ? mirrorBase(buffer) : undefined;
49
+ const value = Object.create(base === undefined ? type.prototype : mirroredPrototype(type));
50
+ value._buffer = buffer;
51
+ if (base !== undefined) value[kMirrorBase] = base;
52
+ if (swapped && type._readerBE && type._writerBE) {
53
+ Object.defineProperty(value, "value", {
54
+ get() {
55
+ if (base !== undefined) refresh(buffer);
56
+ return type._readerBE(buffer, 0);
57
+ },
58
+ set(v) {
59
+ type._writerBE(buffer, 0, v);
60
+ if (base !== undefined) flush(buffer);
61
+ },
62
+ });
63
+ }
64
+ return value;
65
+ }
66
+
67
+ export function scalarReader(type, reader, swapped = false) {
68
+ return isScalarSubclass(type) ? (buffer, offset) => scalarView(type, buffer.subarray(offset, offset + type._size), swapped) : reader;
69
+ }
70
+
71
+ export function scalarOutparam() {
72
+ return isScalarSubclass(this.constructor) ? this : this.value;
73
+ }
74
+
1
75
  /**
2
76
  * @file helpers.js
3
77
  * @module structures/helpers
@@ -146,24 +220,24 @@ export function _isBitField(type) {
146
220
  * @param {Function} fieldType - SimpleCData class of the field
147
221
  * @param {Function} writer - `(buf, offset, value)` writer
148
222
  * @param {number} offset - Field offset
149
- * @returns {Function} `(buf, value)` writer
223
+ * @returns {Function} `(buf, value, relativeOffset = 0)` writer
150
224
  */
151
225
  export function simpleFieldWriter(fieldType, writer, offset) {
152
226
  const pointerValued = fieldType._isPointerValued === true;
153
- return (buf, val) => {
227
+ return (buf, val, relativeOffset = 0) => {
228
+ const fieldOffset = offset + relativeOffset;
154
229
  if (typeof val === "object" && val !== null && val.constructor?._isSimpleCData === true) {
155
230
  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);
231
+ if (T._type === fieldType._type && T._size === fieldType._size && T._isBoolean === fieldType._isBoolean) {
232
+ if (!pointerValued) return writer(buf, fieldOffset, val.value);
233
+ copyInstance(buf, fieldOffset, T._size, val, 0, fieldType);
160
234
  return;
161
235
  }
162
236
  if (!(fieldType._acceptsPointerValues === true && T._isPointerValued === true)) {
163
237
  throw new TypeError(`incompatible types, ${T.name} instance instead of ${fieldType.name} instance`);
164
238
  }
165
239
  }
166
- writer(buf, offset, val);
240
+ writer(buf, fieldOffset, val);
167
241
  };
168
242
  }
169
243
 
@@ -177,6 +251,10 @@ export function notIntegral() {
177
251
  throw new TypeError("'float' object cannot be interpreted as an integer");
178
252
  }
179
253
 
254
+ export function booleanValue(value) {
255
+ return !!(value !== null && typeof value === "object" && value._isSimpleCDataInstance === true ? value.value : value);
256
+ }
257
+
180
258
  /**
181
259
  * Address stored by a pointer field assignment: a pointer instance, a
182
260
  * CFUNCTYPE/callback object (`_as_parameter_`), a BigInt/number address,
@@ -188,10 +266,11 @@ export function notIntegral() {
188
266
  * @returns {bigint} Address to store
189
267
  */
190
268
  export function pointerFieldAddress(value, pointerSize) {
269
+ value = resolveParameter(value);
191
270
  if (typeof value === "bigint") return value;
192
271
  if (typeof value === "number") return BigInt(value);
193
272
  if (value === null || value === undefined) return 0n;
194
- if (typeof value === "object") {
273
+ if (typeof value === "object" || typeof value === "function") {
195
274
  if (typeof value.address === "bigint") return value.address;
196
275
  const param = value._as_parameter_;
197
276
  if (typeof param === "bigint") return param;
@@ -213,16 +292,100 @@ const funcPtrFieldTypes = new WeakMap();
213
292
  export function funcPtrFieldType(prototype) {
214
293
  let fieldType = funcPtrFieldTypes.get(prototype);
215
294
  if (fieldType === undefined) {
216
- fieldType = { _pointerTo: prototype, _isFuncPtrField: true, fromAddress: (address) => prototype(address) };
295
+ fieldType = {
296
+ _pointerTo: prototype,
297
+ _isFuncPtrField: true,
298
+ fromAddress: (address, owner) => keepFunctionOwner(prototype(address), owner),
299
+ };
217
300
  funcPtrFieldTypes.set(prototype, fieldType);
218
301
  }
219
302
  return fieldType;
220
303
  }
221
304
 
305
+ export function keepFunctionOwner(fn, owner) {
306
+ if (owner !== undefined) {
307
+ Object.defineProperty(fn, "_objects", { value: owner });
308
+ // AsyncWorker pins the native handle, not its public JS function.
309
+ Object.defineProperty(fn._ffi, "_objects", { value: owner });
310
+ }
311
+ return fn;
312
+ }
313
+
222
314
  // Oggetti tenuti vivi dalla memoria che contiene i loro indirizzi, per
223
315
  // ArrayBuffer e offset assoluto: tutte le view sulla stessa memoria (istanza,
224
316
  // struct annidata, from_buffer) condividono la stessa tabella.
225
317
  const keptObjects = new WeakMap();
318
+ const memoryOwners = new WeakMap();
319
+ // Address-backed aliases share the reference table of their known owner.
320
+ const memoryDomains = new WeakMap();
321
+ export const kPointerMemory = Symbol("pointerMemory");
322
+
323
+ export function memoryDomain(buf) {
324
+ return memoryDomains.get(buf.buffer) ?? { root: buf.buffer, offset: 0n };
325
+ }
326
+
327
+ function memoryPosition(buf, offset) {
328
+ return BigInt(buf.byteOffset + offset) + (memoryDomains.get(buf.buffer)?.offset ?? 0n);
329
+ }
330
+
331
+ export function shareMemory(buf, memory, position) {
332
+ memoryDomains.set(buf.buffer, { root: memory.root, offset: position - BigInt(buf.byteOffset) });
333
+ return keepMemoryOwner(buf, memory);
334
+ }
335
+
336
+ // Attach to the backing store, so subarrays and typed arrays keep the lease too.
337
+ export function keepMemoryOwner(buf, owner) {
338
+ if (owner === undefined || owner === null) return buf;
339
+ let owners = memoryOwners.get(buf.buffer);
340
+ if (owners === undefined) memoryOwners.set(buf.buffer, (owners = new Set()));
341
+ owners.add(owner);
342
+ return buf;
343
+ }
344
+
345
+ function storedAddress(buf, offset) {
346
+ return POINTER_SIZE === 8 ? buf.readBigUInt64LE(offset) : BigInt(buf.readUInt32LE(offset));
347
+ }
348
+
349
+ export function pointerOwner(buf, offset, address) {
350
+ const root = memoryDomains.get(buf.buffer)?.root ?? buf.buffer;
351
+ const kept = keptObjects.get(root);
352
+ if (kept === undefined) return buf;
353
+ const position = memoryPosition(buf, offset);
354
+ const reference = kept.get(position);
355
+ if (reference !== undefined && reference.address !== (address ?? storedAddress(buf, offset))) {
356
+ kept.delete(position);
357
+ return buf;
358
+ }
359
+ return reference?.owner ?? buf;
360
+ }
361
+
362
+ export function inDllBuffer(library, name, size, ptrToBuffer) {
363
+ const lib = library?._lib ?? library;
364
+ if (typeof lib?._symbolView !== "function") throw new TypeError("in_dll: first arg must be a Library (CDLL/WinDLL)");
365
+ const { address, owner } = lib._symbolView(name);
366
+ return keepMemoryOwner(ptrToBuffer(address, size), owner);
367
+ }
368
+
369
+ function pointerSlots(type, offset = 0, size) {
370
+ if (type?._isPointerValued || type?._isFuncPtr || type?._pointerTo !== undefined) return [[offset, type._size ?? type.size ?? size]];
371
+ if (type?._isArrayType) {
372
+ const slots = [];
373
+ const elementSize = type.length === 0 ? 0 : type.getSize() / type.length;
374
+ const elements = pointerSlots(type.elementType, 0, elementSize);
375
+ if (elements.length === 0) return slots;
376
+ for (let i = 0; i < type.length; i++) {
377
+ for (const [position, width] of elements) slots.push([offset + i * elementSize + position, width]);
378
+ }
379
+ return slots;
380
+ }
381
+ const def = typeof type?._buildStruct === "function" ? (type._structDef ?? type._buildStruct()) : type;
382
+ const slots = [];
383
+ for (const field of def?.fields ?? []) {
384
+ if (field.isPointer) slots.push([offset + field.offset, field.size]);
385
+ else slots.push(...pointerSlots(field.type, offset + field.offset, field.size));
386
+ }
387
+ return slots;
388
+ }
226
389
 
227
390
  /**
228
391
  * Keep `value` alive as long as the memory of `targetBuf`, like Python ctypes
@@ -237,17 +400,21 @@ const keptObjects = new WeakMap();
237
400
  * @param {*} value - Referenced object (or null to clear the slot)
238
401
  */
239
402
  export function keepAlive(targetBuf, offset, value) {
240
- const position = targetBuf.byteOffset + offset;
241
- let kept = keptObjects.get(targetBuf.buffer);
242
- if (value === null || typeof value !== "object") {
403
+ const position = memoryPosition(targetBuf, offset);
404
+ const root = memoryDomains.get(targetBuf.buffer)?.root ?? targetBuf.buffer;
405
+ let kept = keptObjects.get(root);
406
+ if (value === null || (typeof value !== "object" && typeof value !== "function")) {
243
407
  kept?.delete(position);
244
408
  return;
245
409
  }
246
410
  if (kept === undefined) {
247
411
  kept = new Map();
248
- keptObjects.set(targetBuf.buffer, kept);
412
+ keptObjects.set(root, kept);
249
413
  }
250
- kept.set(position, value);
414
+ // A pointer wrapper can later be repointed; retain its current memory.
415
+ if (value._pointerType !== undefined) value = value._buffer ?? value._objects ?? value;
416
+ else if (value._isSimpleCDataInstance && value.constructor._isPointerValued) value = pointerOwner(value._buffer, 0);
417
+ kept.set(position, { owner: value, address: storedAddress(targetBuf, offset) });
251
418
  }
252
419
 
253
420
  /**
@@ -258,7 +425,19 @@ export function keepAlive(targetBuf, offset, value) {
258
425
  * @returns {*} The object, or undefined
259
426
  */
260
427
  export function keptObject(buf, offset) {
261
- return keptObjects.get(buf.buffer)?.get(buf.byteOffset + offset);
428
+ const root = memoryDomains.get(buf.buffer)?.root ?? buf.buffer;
429
+ return keptObjects.get(root)?.get(memoryPosition(buf, offset))?.owner;
430
+ }
431
+
432
+ export function clearKeepAlives(buf, offset, size) {
433
+ const root = memoryDomains.get(buf.buffer)?.root ?? buf.buffer;
434
+ const kept = keptObjects.get(root);
435
+ if (kept === undefined) return;
436
+ const start = BigInt(memoryPosition(buf, offset));
437
+ const end = start + BigInt(size);
438
+ for (const position of kept.keys()) {
439
+ if (position >= start && position < end) kept.delete(position);
440
+ }
262
441
  }
263
442
 
264
443
  /**
@@ -314,23 +493,38 @@ export function fieldsOf(value) {
314
493
  * @param {Buffer} buf - Target buffer
315
494
  * @param {number} offset - Field offset
316
495
  * @param {number} size - Field size
317
- * @param {Object} value - Instance with a `_buffer`
496
+ * @param {Object|Buffer} value - Instance with a `_buffer`, or source bytes
497
+ * @param {number} [sourceOffset=0] - Byte offset in the source
498
+ * @param {Function|Object} [type] - Layout used to retain references into leased memory
318
499
  */
319
- export function copyInstance(buf, offset, size, value) {
320
- const source = value._buffer;
321
- source.copy(buf, offset, 0, size);
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);
500
+ export function copyInstance(buf, offset, size, value, sourceOffset = 0, type) {
501
+ const bytes = value._buffer ?? value;
502
+ const source = Buffer.isBuffer(bytes) ? bytes : Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength);
503
+ if (mirrorsActive) refresh(source, sourceOffset, size);
504
+ const start = memoryPosition(source, sourceOffset);
505
+ const sourceRoot = memoryDomains.get(source.buffer)?.root ?? source.buffer;
506
+ const sourceKept = keptObjects.get(sourceRoot);
507
+ const snapshot = new Map();
508
+ if (sourceKept !== undefined) {
509
+ for (const [position, reference] of sourceKept) {
510
+ if (position < start || position + BigInt(POINTER_SIZE) > start + BigInt(size)) continue;
511
+ const relative = Number(position - start);
512
+ if (reference.address === storedAddress(source, sourceOffset + relative)) snapshot.set(relative, reference.owner);
327
513
  }
328
514
  }
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);
515
+ if (type !== undefined && memoryOwners.has(source.buffer)) {
516
+ for (const [position, width] of pointerSlots(type)) {
517
+ if (snapshot.has(position) || position + width > size) continue;
518
+ for (let i = 0; i < width; i++) {
519
+ if (source[sourceOffset + position + i] !== 0) {
520
+ snapshot.set(position, source);
521
+ break;
522
+ }
523
+ }
334
524
  }
335
525
  }
526
+ source.copy(buf, offset, sourceOffset, sourceOffset + size);
527
+ clearKeepAlives(buf, offset, size);
528
+ for (const [relative, object] of snapshot) keepAlive(buf, offset + relative, object);
529
+ if (mirrorsActive) flush(buf, offset, size);
336
530
  }
@@ -17,6 +17,20 @@
17
17
  const roundDown = (n, multiple) => Math.floor(n / multiple) * multiple;
18
18
  const roundUp = (n, multiple) => Math.ceil(n / multiple) * multiple;
19
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
+
20
34
  /**
21
35
  * Layout mode of a class or definition, as Python: `_layout_` if given,
22
36
  * otherwise `"ms"` on Windows or with `_pack_`, `"gcc-sysv"` elsewhere.
@@ -25,13 +39,13 @@ const roundUp = (n, multiple) => Math.ceil(n / multiple) * multiple;
25
39
  * @param {number} pack - `_pack_` (0 when absent)
26
40
  * @returns {boolean} true for the gcc-sysv layout
27
41
  */
28
- export function isGccLayout(layout, pack) {
42
+ export function isGccLayout(layout, pack, specified = pack !== 0) {
29
43
  if (layout === undefined || layout === null) {
30
- return process.platform !== "win32" && !pack;
44
+ return process.platform !== "win32" && !specified;
31
45
  }
32
46
  if (layout === "ms") return false;
33
47
  if (layout === "gcc-sysv") {
34
- if (pack) throw new Error("_pack_ is not compatible with gcc-sysv layout");
48
+ if (specified) throw new Error("_pack_ is not compatible with gcc-sysv layout");
35
49
  return true;
36
50
  }
37
51
  throw new Error(`unknown _layout_: ${String(layout)}`);
@@ -34,10 +34,10 @@
34
34
  */
35
35
 
36
36
  import { bitFieldAccessors } from "./bitfield.js";
37
- import { computeLayout, isGccLayout } from "./layout.js";
37
+ import { computeLayout, isGccLayout, normalizePack } from "./layout.js";
38
38
  import { buildWrapper } from "./wrap.js";
39
39
  import { isMirror, syncDefinition } from "../../memory/mirror.js";
40
- import { copyInstance, fieldEntries, fieldsOf, funcPtrFieldType, simpleFieldWriter, writePointerField } from "./common.js";
40
+ import { copyInstance, fieldEntries, fieldsOf, funcPtrFieldType, isScalarSubclass, pointerOwner, scalarReader, simpleFieldWriter, structArgumentFactories, writePointerField } from "./common.js";
41
41
 
42
42
  /**
43
43
  * Creates a struct type definition with proper alignment and padding.
@@ -88,7 +88,10 @@ import { copyInstance, fieldEntries, fieldsOf, funcPtrFieldType, simpleFieldWrit
88
88
  * ```
89
89
  */
90
90
  // Python: un campo POINTER(T) NULL è un puntatore falsy; in JS `null`.
91
- const pointerOrNull = (ptrType, address) => (address === 0n ? null : ptrType.fromAddress(address));
91
+ const pointerOrNull = (ptrType, address, buf, offset) => {
92
+ const owner = pointerOwner(buf, offset, address);
93
+ return address === 0n ? null : ptrType.fromAddress(address, owner);
94
+ };
92
95
 
93
96
  export function struct(fields, options = {}, sizeof, alloc, readValue, writeValue, _isStruct, _isArrayType, _isBitField, Structure, Union, native) {
94
97
  // Validate inputs
@@ -98,12 +101,12 @@ export function struct(fields, options = {}, sizeof, alloc, readValue, writeValu
98
101
  }
99
102
 
100
103
  // Python _pack_: `pack` (massimo allineamento), o `packed: true` (= pack 1).
101
- const packValue = typeof options.pack === "number" ? options.pack : options.packed ? 1 : 0;
104
+ const packValue = normalizePack(options.pack ?? (options.packed ? 1 : 0));
102
105
  // `swapped` selects _readerBE/_writerBE on primitive SimpleCData fields and
103
106
  // lays out bitfields from the big end. Used by BigEndianStructure /
104
107
  // LittleEndianStructure (on LE host, swapped=true means "use BE").
105
108
  const swapped = options.swapped === true;
106
- const gccLayout = isGccLayout(options.layout, packValue);
109
+ const gccLayout = isGccLayout(options.layout, packValue, options.pack != null || options.packed === true);
107
110
  // Python: una sottoclasse con _fields_ estende il layout della base, i cui
108
111
  // campi restano agli stessi offset.
109
112
  const base = options.base ?? null;
@@ -115,7 +118,7 @@ export function struct(fields, options = {}, sizeof, alloc, readValue, writeValu
115
118
  const ownDefs = [];
116
119
  for (const [name, type] of fieldEntries(fields)) {
117
120
  // Validate field name
118
- if (!name || typeof name !== "string" || name.trim().length === 0) {
121
+ if (typeof name !== "string" || (!Array.isArray(fields) && !(fields instanceof Map) && name.trim().length === 0)) {
119
122
  throw new TypeError("Field name must be a non-empty string");
120
123
  }
121
124
  if (fieldNames.has(name)) {
@@ -131,7 +134,7 @@ export function struct(fields, options = {}, sizeof, alloc, readValue, writeValu
131
134
  let def = type;
132
135
  if (typeof type === "function" && typeof type._buildStruct === "function") {
133
136
  cls = type;
134
- def = type._structDef || type._buildStruct();
137
+ def = type._finalizeFields();
135
138
  }
136
139
  if (def === null || typeof def !== "object" || !Array.isArray(def.fields)) {
137
140
  throw new TypeError(`anonymous field "${name}" must be a structure or union`);
@@ -151,7 +154,7 @@ export function struct(fields, options = {}, sizeof, alloc, readValue, writeValu
151
154
  }
152
155
  // Structure / Union class (Union estende Structure)
153
156
  if (typeof type === "function" && type.prototype instanceof Structure) {
154
- const nested = type._structDef || type._buildStruct();
157
+ const nested = type._finalizeFields();
155
158
  // `cls`: Python restituisce un'istanza della classe annidata, sulla
156
159
  // stessa memoria.
157
160
  return { name, type: nested, cls: type, size: nested.size, alignment: nested.alignment, isNested: true };
@@ -162,6 +165,7 @@ export function struct(fields, options = {}, sizeof, alloc, readValue, writeValu
162
165
  }
163
166
  // Array type: alignment == element alignment (C standard).
164
167
  if (_isArrayType(type)) {
168
+ if (swapped) type = type._swappedType ?? type;
165
169
  const elemSize = sizeof(type.elementType);
166
170
  const alignment = typeof type.getAlignment === "function" ? type.getAlignment() : Math.min(elemSize, native.POINTER_SIZE);
167
171
  return { name, type, size: type.getSize(), alignment, isArray: true };
@@ -246,11 +250,12 @@ export function struct(fields, options = {}, sizeof, alloc, readValue, writeValu
246
250
  bitSize: field.bitSize,
247
251
  signed: field.type?._signed === true,
248
252
  bigEndian: field.swapped === true,
253
+ boolean: field.type?._isBoolean === true,
249
254
  });
250
255
  field.readBits = read;
251
- field.writeBits = write;
256
+ field.writeBits = simpleFieldWriter(field.type, (buf, offset, value) => write(buf, value), 0);
252
257
  fieldReaders[name] = read;
253
- fieldWriters[name] = write;
258
+ fieldWriters[name] = field.writeBits;
254
259
  continue;
255
260
  }
256
261
 
@@ -264,12 +269,12 @@ export function struct(fields, options = {}, sizeof, alloc, readValue, writeValu
264
269
  const fieldOffset = offset;
265
270
  const ptrType = field.type;
266
271
  if (is64) {
267
- fieldReaders[name] = (buf) => pointerOrNull(ptrType, buf.readBigUInt64LE(fieldOffset));
272
+ fieldReaders[name] = (buf) => pointerOrNull(ptrType, buf.readBigUInt64LE(fieldOffset), buf, fieldOffset);
268
273
  fieldWriters[name] = (buf, val) => {
269
274
  writePointerField(buf, fieldOffset, val, 8);
270
275
  };
271
276
  } else {
272
- fieldReaders[name] = (buf) => pointerOrNull(ptrType, BigInt(buf.readUInt32LE(fieldOffset)));
277
+ fieldReaders[name] = (buf) => pointerOrNull(ptrType, BigInt(buf.readUInt32LE(fieldOffset)), buf, fieldOffset);
273
278
  fieldWriters[name] = (buf, val) => {
274
279
  writePointerField(buf, fieldOffset, val, 4);
275
280
  };
@@ -282,13 +287,35 @@ export function struct(fields, options = {}, sizeof, alloc, readValue, writeValu
282
287
  const fieldType = field.type;
283
288
  if (fieldType && fieldType._isSimpleCData) {
284
289
  const fieldOffset = offset; // Capture offset for closure
285
- const reader = field.swapped && fieldType._readerBE ? fieldType._readerBE : fieldType._reader;
290
+ const reader = scalarReader(fieldType, field.swapped && fieldType._readerBE ? fieldType._readerBE : fieldType._reader, field.swapped);
286
291
  const writer = field.swapped && fieldType._writerBE ? fieldType._writerBE : fieldType._writer;
287
292
  fieldReaders[name] = (buf) => reader(buf, fieldOffset);
288
293
  fieldWriters[name] = simpleFieldWriter(fieldType, writer, fieldOffset);
289
294
  }
290
295
  }
291
296
 
297
+ function createBuffer(values) {
298
+ const buf = alloc(totalSize);
299
+ buf.fill(0);
300
+
301
+ for (const field of fieldDefs) {
302
+ if (Object.hasOwn(values, field.name) && values[field.name] !== undefined) {
303
+ structDef.set(buf, field.name, values[field.name]);
304
+ }
305
+ }
306
+
307
+ for (const field of fieldDefs) {
308
+ if (field.isAnonymous && field.type && field.type.fields) {
309
+ for (const subField of field.type.fields) {
310
+ if (Object.hasOwn(values, subField.name) && values[subField.name] !== undefined) {
311
+ structDef.set(buf, subField.name, values[subField.name]);
312
+ }
313
+ }
314
+ }
315
+ }
316
+ return buf;
317
+ }
318
+
292
319
  const structDef = {
293
320
  size: totalSize,
294
321
  alignment: maxAlignment,
@@ -308,29 +335,8 @@ export function struct(fields, options = {}, sizeof, alloc, readValue, writeValu
308
335
  * @returns {Proxy} Proxy-based struct instance
309
336
  */
310
337
  create(values = {}) {
311
- const buf = alloc(totalSize);
312
- buf.fill(0); // Inizializza a zero
313
-
314
- // Prima imposta i campi diretti
315
- for (const field of fieldDefs) {
316
- if (values[field.name] !== undefined) {
317
- structDef.set(buf, field.name, values[field.name]);
318
- }
319
- }
320
-
321
- // Poi gestisci i campi anonymous - i loro campi possono essere passati direttamente nell'oggetto values
322
- for (const field of fieldDefs) {
323
- if (field.isAnonymous && field.type && field.type.fields) {
324
- for (const subField of field.type.fields) {
325
- if (values[subField.name] !== undefined) {
326
- structDef.set(buf, subField.name, values[subField.name]);
327
- }
328
- }
329
- }
330
- }
331
-
332
338
  return new Proxy(
333
- buf,
339
+ createBuffer(values),
334
340
  buildWrapper(structDef, {
335
341
  instanceTag: "StructInstance",
336
342
  exposeAnonymous: true,
@@ -409,7 +415,7 @@ export function struct(fields, options = {}, sizeof, alloc, readValue, writeValu
409
415
  // POINTER() field — return PointerInstance
410
416
  if (field.isPointer) {
411
417
  const addr = native.POINTER_SIZE === 8 ? buf.readBigUInt64LE(field.offset) : BigInt(buf.readUInt32LE(field.offset));
412
- return pointerOrNull(field.type, addr);
418
+ return pointerOrNull(field.type, addr, buf, field.offset);
413
419
  }
414
420
 
415
421
  // Array field (Python: c_char * n / c_wchar * n si leggono come stringa)
@@ -488,11 +494,9 @@ export function struct(fields, options = {}, sizeof, alloc, readValue, writeValu
488
494
 
489
495
  // Nested struct (senza dot = imposta da oggetto)
490
496
  if (field.isNested) {
491
- if (Buffer.isBuffer(value)) {
492
- value.copy(buf, field.offset, 0, field.size);
493
- } else if (value !== null && typeof value === "object" && Buffer.isBuffer(value._buffer)) {
497
+ if (Buffer.isBuffer(value) || (value !== null && typeof value === "object" && Buffer.isBuffer(value._buffer))) {
494
498
  // Istanza struct/union: copia dei byte (Python), non campo per campo
495
- copyInstance(buf, field.offset, field.size, value);
499
+ copyInstance(buf, field.offset, field.size, value, 0, field.type);
496
500
  } else if (typeof value === "object") {
497
501
  const nestedBuf = buf.subarray(field.offset, field.offset + field.size);
498
502
  for (const [k, v] of Object.entries(value)) {
@@ -513,8 +517,8 @@ export function struct(fields, options = {}, sizeof, alloc, readValue, writeValu
513
517
  // Python: bytes / str con il controllo di lunghezza ("bytes too long").
514
518
  if (field.type._charKind !== undefined && (typeof value === "string" || (field.type._charKind === "char" && Buffer.isBuffer(value) && value._buffer === undefined))) {
515
519
  field.type.setValue(buf.subarray(field.offset, field.offset + field.size), value, (len, max) => `${field.type._charKind === "char" ? "bytes" : "string"} too long (${len}, maximum length ${max})`);
516
- } else if (Buffer.isBuffer(value)) {
517
- value.copy(buf, field.offset, 0, field.size);
520
+ } else if (Buffer.isBuffer(value) || Buffer.isBuffer(value?._buffer)) {
521
+ copyInstance(buf, field.offset, field.size, value, 0, field.type);
518
522
  } else if (Array.isArray(value)) {
519
523
  const arrayBuf = buf.subarray(field.offset, field.offset + field.size);
520
524
  const wrapped = field.type.wrap(arrayBuf);
@@ -565,12 +569,9 @@ export function struct(fields, options = {}, sizeof, alloc, readValue, writeValu
565
569
  // Accesso a campo annidato singolo
566
570
  const nestedBuf = buf.subarray(field.offset, field.offset + field.size);
567
571
  field.type.set(nestedBuf, parts.slice(1).join("."), value);
568
- } else if (Buffer.isBuffer(value)) {
569
- // Copia buffer
570
- value.copy(buf, field.offset, 0, field.size);
571
- } else if (value !== null && typeof value === "object" && Buffer.isBuffer(value._buffer)) {
572
+ } else if (Buffer.isBuffer(value) || (value !== null && typeof value === "object" && Buffer.isBuffer(value._buffer))) {
572
573
  // Istanza struct/union: copia dei byte (Python), non campo per campo
573
- copyInstance(buf, field.offset, field.size, value);
574
+ copyInstance(buf, field.offset, field.size, value, 0, field.type);
574
575
  } else if (typeof value === "object") {
575
576
  // Imposta campi da oggetto
576
577
  const nestedBuf = buf.subarray(field.offset, field.offset + field.size);
@@ -585,9 +586,8 @@ export function struct(fields, options = {}, sizeof, alloc, readValue, writeValu
585
586
  if (field.isArray) {
586
587
  if (field.type._charKind !== undefined && typeof value === "string") {
587
588
  field.type.setValue(buf.subarray(field.offset, field.offset + field.size), value, (len, max) => `${field.type._charKind === "char" ? "bytes" : "string"} too long (${len}, maximum length ${max})`);
588
- } else if (Buffer.isBuffer(value)) {
589
- // Copia buffer array
590
- value.copy(buf, field.offset, 0, field.size);
589
+ } else if (Buffer.isBuffer(value) || Buffer.isBuffer(value?._buffer)) {
590
+ copyInstance(buf, field.offset, field.size, value, 0, field.type);
591
591
  } else if (Array.isArray(value)) {
592
592
  // Inizializza da array JavaScript
593
593
  const arrayBuf = buf.subarray(field.offset, field.offset + field.size);
@@ -632,6 +632,9 @@ export function struct(fields, options = {}, sizeof, alloc, readValue, writeValu
632
632
 
633
633
  // Leggi tutti i campi in una volta (eager approach)
634
634
  for (const field of fieldDefs) {
635
+ if (field.name === "__proto__" && !field.isAnonymous) {
636
+ Object.defineProperty(result, field.name, { value: undefined, writable: true, enumerable: true, configurable: true });
637
+ }
635
638
  if (field.isBitField) {
636
639
  result[field.name] = field.readBits(buf);
637
640
  } else if (field.isNested) {
@@ -639,13 +642,16 @@ export function struct(fields, options = {}, sizeof, alloc, readValue, writeValu
639
642
  const nestedObj = field.type.toObject(nestedBuf);
640
643
  if (field.isAnonymous) {
641
644
  // Anonymous fields: promote their fields to parent level
645
+ if (Object.hasOwn(nestedObj, "__proto__")) {
646
+ Object.defineProperty(result, "__proto__", { value: undefined, writable: true, enumerable: true, configurable: true });
647
+ }
642
648
  Object.assign(result, nestedObj);
643
649
  } else {
644
650
  result[field.name] = nestedObj;
645
651
  }
646
652
  } else if (field.isPointer) {
647
653
  const addr = native.POINTER_SIZE === 8 ? buf.readBigUInt64LE(field.offset) : BigInt(buf.readUInt32LE(field.offset));
648
- result[field.name] = pointerOrNull(field.type, addr);
654
+ result[field.name] = pointerOrNull(field.type, addr, buf, field.offset);
649
655
  } else if (field.isArray) {
650
656
  const arrayBuf = buf.subarray(field.offset, field.offset + field.size);
651
657
  result[field.name] = field.type._charKind !== undefined ? field.type.getValue(arrayBuf) : field.type.wrap(arrayBuf);
@@ -687,5 +693,14 @@ export function struct(fields, options = {}, sizeof, alloc, readValue, writeValu
687
693
  return this.toObject(this.create(values)._buffer);
688
694
  };
689
695
 
696
+ if (fieldDefs.every((field) => !field.isBitField && !field.isNested && !field.isArray && !field.isPointer && !field.type._isPointerValued && !isScalarSubclass(field.type))) {
697
+ const create = structDef.create;
698
+ structArgumentFactories.set(structDef, (values) => {
699
+ // A later create override must still run, with the definition as receiver.
700
+ const current = structDef.create;
701
+ return current === create ? createBuffer(values) : current.call(structDef, values);
702
+ });
703
+ }
704
+
690
705
  return syncDefinition(structDef);
691
706
  }