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
@@ -33,10 +33,11 @@
33
33
  * ```
34
34
  */
35
35
 
36
- import { _readBitField, _writeBitField } from "./bitfield.js";
36
+ import { bitFieldAccessors } from "./bitfield.js";
37
+ import { computeLayout, isGccLayout, normalizePack } from "./layout.js";
37
38
  import { buildWrapper } from "./wrap.js";
38
39
  import { isMirror, syncDefinition } from "../../memory/mirror.js";
39
- import { copyInstance, funcPtrFieldType, writePointerField } from "./common.js";
40
+ import { copyInstance, fieldEntries, fieldsOf, funcPtrFieldType, pointerOwner, scalarReader, simpleFieldWriter, writePointerField } from "./common.js";
40
41
 
41
42
  /**
42
43
  * Creates a struct type definition with proper alignment and padding.
@@ -50,7 +51,8 @@ import { copyInstance, funcPtrFieldType, writePointerField } from "./common.js";
50
51
  *
51
52
  * @param {Object} fields - Field definitions { name: type, ... }
52
53
  * @param {Object} [options] - Options { packed: false }
53
- * @param {boolean} [options.packed=false] - If true, disable padding/alignment
54
+ * @param {boolean} [options.packed=false] - If true, disable padding/alignment (pack 1)
55
+ * @param {number} [options.pack] - Maximum field alignment (Python `_pack_`)
54
56
  * @param {Function} sizeof - sizeof function reference
55
57
  * @param {Function} alloc - alloc function reference
56
58
  * @param {Function} readValue - readValue function reference
@@ -86,37 +88,35 @@ import { copyInstance, funcPtrFieldType, writePointerField } from "./common.js";
86
88
  * ```
87
89
  */
88
90
  // Python: un campo POINTER(T) NULL è un puntatore falsy; in JS `null`.
89
- 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
+ };
90
95
 
91
96
  export function struct(fields, options = {}, sizeof, alloc, readValue, writeValue, _isStruct, _isArrayType, _isBitField, Structure, Union, native) {
92
97
  // Validate inputs
93
- if (!fields || typeof fields !== "object" || Array.isArray(fields)) {
98
+ // Un oggetto { name: type }, o le coppie [name, type] in ordine (Structure).
99
+ if (!fields || typeof fields !== "object") {
94
100
  throw new TypeError("fields must be a non-null object");
95
101
  }
96
102
 
97
- const packed = options.packed || false;
98
- // Python-ctypes `_pack_` semantics: numeric max alignment. Boolean `packed`
99
- // (no numeric pack value) means fully packed => pack = 1.
100
- const packValue = packed ? (typeof options.pack === "number" ? options.pack : 1) : 0;
101
- const packAlign = (natural) => (packValue ? Math.min(natural, packValue) : natural);
102
- // `swapped` selects _readerBE/_writerBE on primitive SimpleCData fields.
103
- // Used by BigEndianStructure / LittleEndianStructure (on LE host, swapped=true
104
- // means "use BE"; on theoretical BE host, same flag would mean LE — but we
105
- // only officially support LE hosts, so "swapped" == "big-endian").
103
+ // Python _pack_: `pack` (massimo allineamento), o `packed: true` (= pack 1).
104
+ const packValue = normalizePack(options.pack ?? (options.packed ? 1 : 0));
105
+ // `swapped` selects _readerBE/_writerBE on primitive SimpleCData fields and
106
+ // lays out bitfields from the big end. Used by BigEndianStructure /
107
+ // LittleEndianStructure (on LE host, swapped=true means "use BE").
106
108
  const swapped = options.swapped === true;
107
- let totalSize = 0;
108
- const fieldDefs = [];
109
- let maxAlignment = 1;
110
-
111
- // Track field names to detect duplicates
112
- const fieldNames = new Set();
113
-
114
- // Stato per bit fields consecutivi
115
- let currentBitFieldBase = null;
116
- let currentBitFieldOffset = 0;
117
- let currentBitOffset = 0;
118
-
119
- for (const [name, type] of Object.entries(fields)) {
109
+ const gccLayout = isGccLayout(options.layout, packValue, options.pack != null || options.packed === true);
110
+ // Python: una sottoclasse con _fields_ estende il layout della base, i cui
111
+ // campi restano agli stessi offset.
112
+ const base = options.base ?? null;
113
+ const fieldDefs = base ? base.fields.map((f) => ({ ...f })) : [];
114
+ const fieldNames = new Set(fieldDefs.map((f) => f.name));
115
+
116
+ // Tipo, dimensione e allineamento naturale di ogni campo; gli offset sono
117
+ // calcolati dopo, tutti insieme, da computeLayout (come Python).
118
+ const ownDefs = [];
119
+ for (const [name, type] of fieldEntries(fields)) {
120
120
  // Validate field name
121
121
  if (!name || typeof name !== "string" || name.trim().length === 0) {
122
122
  throw new TypeError("Field name must be a non-empty string");
@@ -125,279 +125,79 @@ export function struct(fields, options = {}, sizeof, alloc, readValue, writeValu
125
125
  throw new TypeError(`Duplicate field name: ${name}`);
126
126
  }
127
127
  fieldNames.add(name);
128
- let fieldDef;
129
-
130
- // Caso 0: Anonymous field - { type: SomeStruct, anonymous: true }
131
- if (typeof type === "object" && type !== null && type.anonymous === true && type.type) {
132
- // Reset bit field state
133
- currentBitFieldBase = null;
134
- currentBitOffset = 0;
135
-
136
- const actualType = type.type;
137
- const size = actualType.size;
138
- const alignment = packAlign(actualType.alignment);
139
-
140
- // Applica padding per allineamento
141
- if (totalSize % alignment !== 0) {
142
- totalSize += alignment - (totalSize % alignment);
143
- }
144
-
145
- fieldDef = {
146
- name,
147
- type: actualType,
148
- offset: totalSize,
149
- size,
150
- alignment,
151
- isNested: true,
152
- isAnonymous: true,
153
- };
154
-
155
- totalSize += size;
128
+ ownDefs.push(describeField(name, type));
129
+ }
156
130
 
157
- if (alignment > maxAlignment) {
158
- maxAlignment = alignment;
159
- }
131
+ // Campo di _anonymous_: una struct/union (classe o definizione), i cui
132
+ // campi sono raggiungibili dalla struct esterna.
133
+ function anonymousField(name, { type, cls }) {
134
+ let def = type;
135
+ if (typeof type === "function" && typeof type._buildStruct === "function") {
136
+ cls = type;
137
+ def = type._structDef || type._buildStruct();
160
138
  }
161
- // Caso 1: Bit field
162
- else if (_isBitField(type)) {
163
- const { baseType, bits, baseSize } = type;
164
- const alignment = packAlign(Math.min(baseSize, native.POINTER_SIZE));
165
-
166
- // Verifica se possiamo continuare nel bit field corrente
167
- const canContinue = currentBitFieldBase === baseType && currentBitOffset + bits <= baseSize * 8;
168
-
169
- if (!canContinue) {
170
- // Inizia un nuovo bit field
171
- // Applica padding per allineamento
172
- if (totalSize % alignment !== 0) {
173
- totalSize += alignment - (totalSize % alignment);
174
- }
175
-
176
- currentBitFieldBase = baseType;
177
- currentBitFieldOffset = totalSize;
178
- currentBitOffset = 0;
179
- totalSize += baseSize;
180
- }
181
-
182
- fieldDef = {
183
- name,
184
- type: baseType,
185
- offset: currentBitFieldOffset,
186
- size: 0, // Bit fields non aggiungono size extra
187
- alignment,
188
- isBitField: true,
189
- bitOffset: currentBitOffset,
190
- bitSize: bits,
191
- baseSize,
192
- };
193
-
194
- currentBitOffset += bits;
195
-
196
- if (alignment > maxAlignment) {
197
- maxAlignment = alignment;
198
- }
139
+ if (def === null || typeof def !== "object" || !Array.isArray(def.fields)) {
140
+ throw new TypeError(`anonymous field "${name}" must be a structure or union`);
199
141
  }
200
- // Caso 2a: Struct class (declarata come `class X extends Structure`)
201
- else if (typeof type === "function" && type.prototype instanceof Structure) {
202
- // Reset bit field state
203
- currentBitFieldBase = null;
204
- currentBitOffset = 0;
205
-
206
- const nestedStruct = type._structDef || type._buildStruct();
207
- const size = nestedStruct.size;
208
- const alignment = packAlign(nestedStruct.alignment);
209
-
210
- // Applica padding per allineamento
211
- if (totalSize % alignment !== 0) {
212
- totalSize += alignment - (totalSize % alignment);
213
- }
214
-
215
- fieldDef = {
216
- name,
217
- type: nestedStruct,
218
- offset: totalSize,
219
- size,
220
- alignment,
221
- isNested: true,
222
- };
223
-
224
- totalSize += size;
142
+ return { name, type: def, cls, size: def.size, alignment: def.alignment, isNested: true, isAnonymous: true };
143
+ }
225
144
 
226
- if (alignment > maxAlignment) {
227
- maxAlignment = alignment;
228
- }
145
+ function describeField(name, type) {
146
+ // Anonymous field - { type: SomeStruct, anonymous: true }
147
+ if (typeof type === "object" && type !== null && type.anonymous === true && type.type) {
148
+ return anonymousField(name, type);
229
149
  }
230
- // Caso 2b: Union class (declarata come `class X extends Union`)
231
- else if (typeof type === "function" && type.prototype instanceof Union) {
232
- // Reset bit field state
233
- currentBitFieldBase = null;
234
- currentBitOffset = 0;
235
-
236
- const nestedUnion = type._unionDef || type._buildUnion();
237
- const size = nestedUnion.size;
238
- const alignment = packAlign(nestedUnion.alignment);
239
-
240
- // Applica padding per allineamento
241
- if (totalSize % alignment !== 0) {
242
- totalSize += alignment - (totalSize % alignment);
243
- }
244
-
245
- fieldDef = {
246
- name,
247
- type: nestedUnion,
248
- offset: totalSize,
249
- size,
250
- alignment,
251
- isNested: true,
252
- };
253
-
254
- totalSize += size;
255
-
256
- if (alignment > maxAlignment) {
257
- maxAlignment = alignment;
258
- }
150
+ // Bit field
151
+ if (_isBitField(type)) {
152
+ const { baseType, bits, baseSize } = type;
153
+ return { name, type: baseType, size: 0, alignment: Math.min(baseSize, native.POINTER_SIZE), isBitField: true, bitSize: bits, baseSize };
259
154
  }
260
- // Caso 2: Nested struct
261
- else if (_isStruct(type)) {
262
- // Reset bit field state
263
- currentBitFieldBase = null;
264
- currentBitOffset = 0;
265
-
266
- // Normalize type: if it's a Structure/Union class, get its _structDef
267
- let nestedStruct = type;
268
- if (typeof type === "function" && typeof type._buildStruct === "function") {
269
- nestedStruct = type._structDef || type._buildStruct();
270
- }
271
-
272
- const size = nestedStruct.size;
273
- const alignment = packAlign(nestedStruct.alignment);
274
-
275
- // Applica padding per allineamento
276
- if (totalSize % alignment !== 0) {
277
- totalSize += alignment - (totalSize % alignment);
278
- }
279
-
280
- fieldDef = {
281
- name,
282
- type: nestedStruct,
283
- offset: totalSize,
284
- size,
285
- alignment,
286
- isNested: true,
287
- };
288
-
289
- totalSize += size;
290
-
291
- if (alignment > maxAlignment) {
292
- maxAlignment = alignment;
293
- }
155
+ // Structure / Union class (Union estende Structure)
156
+ if (typeof type === "function" && type.prototype instanceof Structure) {
157
+ const nested = type._structDef || type._buildStruct();
158
+ // `cls`: Python restituisce un'istanza della classe annidata, sulla
159
+ // stessa memoria.
160
+ return { name, type: nested, cls: type, size: nested.size, alignment: nested.alignment, isNested: true };
294
161
  }
295
- // Caso 3: Array type
296
- else if (_isArrayType(type)) {
297
- // Reset bit field state
298
- currentBitFieldBase = null;
299
- currentBitOffset = 0;
300
-
301
- const size = type.getSize();
302
- // Array alignment == element alignment (C standard). For primitives we
303
- // clamp to POINTER_SIZE (same as natural alignment for all types ≤ 8
304
- // bytes on x64). For Structure/Union elements we must use their
305
- // declared alignment (smaller than size when the struct has padding).
162
+ // struct() / union() definition
163
+ if (_isStruct(type)) {
164
+ return { name, type, size: type.size, alignment: type.alignment, isNested: true };
165
+ }
166
+ // Array type: alignment == element alignment (C standard).
167
+ if (_isArrayType(type)) {
168
+ if (swapped) type = type._swappedType ?? type;
306
169
  const elemSize = sizeof(type.elementType);
307
- const elemAlignment = typeof type.getAlignment === "function" ? type.getAlignment() : Math.min(elemSize, native.POINTER_SIZE);
308
- const alignment = packAlign(elemAlignment);
309
-
310
- // Applica padding per allineamento
311
- if (totalSize % alignment !== 0) {
312
- totalSize += alignment - (totalSize % alignment);
313
- }
314
-
315
- fieldDef = {
316
- name,
317
- type,
318
- offset: totalSize,
319
- size,
320
- alignment,
321
- isArray: true,
322
- };
323
-
324
- totalSize += size;
325
-
326
- if (alignment > maxAlignment) {
327
- maxAlignment = alignment;
328
- }
170
+ const alignment = typeof type.getAlignment === "function" ? type.getAlignment() : Math.min(elemSize, native.POINTER_SIZE);
171
+ return { name, type, size: type.getSize(), alignment, isArray: true };
329
172
  }
330
- // Caso 4b: POINTER() type — stored as pointer-sized field with typed access
331
- else if ((typeof type === "object" && type !== null && type._pointerTo !== undefined) || (typeof type === "function" && type._isFuncPtr === true)) {
332
- // Reset bit field state
333
- currentBitFieldBase = null;
334
- currentBitOffset = 0;
335
-
336
- const size = native.POINTER_SIZE;
337
- const alignment = packAlign(Math.min(size, native.POINTER_SIZE));
338
-
339
- if (totalSize % alignment !== 0) {
340
- totalSize += alignment - (totalSize % alignment);
341
- }
342
-
343
- fieldDef = {
344
- name,
345
- // CFUNCTYPE: campo puntatore letto come funzione chiamabile (Python parity)
346
- type: typeof type === "function" ? funcPtrFieldType(type) : type,
347
- offset: totalSize,
348
- size,
349
- alignment,
350
- isPointer: true,
351
- };
352
-
353
- totalSize += size;
354
-
355
- if (alignment > maxAlignment) {
356
- maxAlignment = alignment;
357
- }
173
+ // POINTER() / CFUNCTYPE — pointer-sized field with typed access
174
+ if ((typeof type === "object" && type !== null && type._pointerTo !== undefined) || (typeof type === "function" && type._isFuncPtr === true)) {
175
+ // CFUNCTYPE: campo puntatore letto come funzione chiamabile (Python parity)
176
+ return { name, type: typeof type === "function" ? funcPtrFieldType(type) : type, size: native.POINTER_SIZE, alignment: native.POINTER_SIZE, isPointer: true };
358
177
  }
359
- // Caso 4: Tipo base (SimpleCData)
360
- else {
361
- // Reset bit field state
362
- currentBitFieldBase = null;
363
- currentBitOffset = 0;
364
-
365
- // Validate type is a SimpleCData class
366
- if (!(typeof type === "function" && type._isSimpleCData)) {
367
- throw new TypeError(`struct field "${name}": type must be a SimpleCData class, struct, union, or array`);
368
- }
369
-
370
- const size = type._size;
371
- const naturalAlign = Math.min(size, native.POINTER_SIZE);
372
- const alignment = packAlign(naturalAlign);
373
-
374
- // Applica padding per allineamento
375
- if (totalSize % alignment !== 0) {
376
- totalSize += alignment - (totalSize % alignment);
377
- }
378
-
379
- fieldDef = {
380
- name,
381
- type,
382
- offset: totalSize,
383
- size,
384
- alignment,
385
- };
386
-
387
- totalSize += size;
388
-
389
- if (alignment > maxAlignment) {
390
- maxAlignment = alignment;
391
- }
178
+ // Tipo base (SimpleCData)
179
+ if (!(typeof type === "function" && type._isSimpleCData)) {
180
+ throw new TypeError(`struct field "${name}": type must be a SimpleCData class, struct, union, or array`);
392
181
  }
393
-
394
- fieldDefs.push(fieldDef);
182
+ return { name, type, size: type._size, alignment: Math.min(type._size, native.POINTER_SIZE) };
395
183
  }
396
184
 
397
- // Padding finale per allineamento della struct
398
- if (totalSize % maxAlignment !== 0) {
399
- totalSize += maxAlignment - (totalSize % maxAlignment);
400
- }
185
+ const layout = computeLayout(
186
+ ownDefs.map((f) => (f.isBitField ? { name: f.name, size: f.baseSize, align: f.alignment, bitSize: f.bitSize } : { name: f.name, size: f.size, align: f.alignment })),
187
+ { isStruct: true, gccLayout, pack: packValue, align: options.align ?? 1, base, bigEndian: swapped },
188
+ );
189
+ ownDefs.forEach((f, i) => {
190
+ f.offset = layout.offsets[i].offset;
191
+ if (f.isBitField) f.bitOffset = layout.offsets[i].bitOffset;
192
+ // Allineamento del tipo in C, prima di _pack_ (usato per le struct native
193
+ // passate per valore, lib/core/types.js).
194
+ f.naturalAlignment = f.alignment;
195
+ if (packValue) f.alignment = Math.min(f.alignment, packValue);
196
+ f.swapped = swapped;
197
+ fieldDefs.push(f);
198
+ });
199
+ const totalSize = layout.size;
200
+ const maxAlignment = layout.alignment;
401
201
 
402
202
  // Crea Map per lookup O(1) invece di find() O(n)
403
203
  const fieldMap = new Map();
@@ -409,14 +209,20 @@ export function struct(fields, options = {}, sizeof, alloc, readValue, writeValu
409
209
  // inclusi i sotto-campi dei campi _anonymous_. Il Proxy get/set/has
410
210
  // altrimenti scansionerebbe linearmente tutti i campi anonymous e i loro
411
211
  // subfields su ogni accesso. Usa un null-proto object per IC monomorfo.
412
- const anonymousFieldNames = Object.create(null); // subField.name -> true
212
+ // Come Python, la promozione è ricorsiva: un campo anonimo dentro un campo
213
+ // anonimo è raggiungibile dalla struct esterna.
214
+ const anonymousFieldNames = Object.create(null); // subField.name -> true
413
215
  for (const field of fieldDefs) {
414
216
  if (field.isAnonymous && field.type && field.type.fields) {
415
217
  for (const subField of field.type.fields) {
416
218
  anonymousFieldNames[subField.name] = true;
417
219
  }
220
+ for (const name of Object.keys(field.type.anonymousFieldNames ?? {})) {
221
+ anonymousFieldNames[name] = true;
222
+ }
418
223
  }
419
224
  }
225
+ const promotes = (f, name) => f.type.fields.some((subField) => subField.name === name) || f.type.anonymousFieldNames?.[name] === true;
420
226
 
421
227
  // Pre-compile reader/writer functions for each field.
422
228
  // We use null-prototype plain objects rather than `Map` because V8 builds
@@ -434,92 +240,22 @@ export function struct(fields, options = {}, sizeof, alloc, readValue, writeValu
434
240
  const offset = field.offset;
435
241
  const name = field.name;
436
242
 
437
- // Bitfield: pre-calcola mask/shift così read/write salta il dispatch
438
- // generico. Sign-extension applicata quando il base type è signed
439
- // (parity Python ctypes — `c_int8, 3` con valore -1 deve rileggere -1,
440
- // non 7).
243
+ // Bitfield: accessor precompilati (sign-extension per base type signed,
244
+ // come Python: `c_int8, 3` con valore -1 rilegge -1, non 7).
441
245
  if (field.isBitField) {
442
- const fieldOffset = offset;
443
- const baseSize = field.baseSize;
444
- const bitOffset = field.bitOffset;
445
- const bitSize = field.bitSize;
446
- const isSigned = field.type?._signed === true;
447
-
448
- if (baseSize === 1) {
449
- const mask = (1 << bitSize) - 1;
450
- const clearMask = ~(mask << bitOffset);
451
- if (isSigned) {
452
- const signBit = 1 << (bitSize - 1);
453
- const extendMask = ~mask;
454
- fieldReaders[name] = (buf) => {
455
- const raw = (buf.readUInt8(fieldOffset) >> bitOffset) & mask;
456
- return (raw & signBit) ? (raw | extendMask) : raw;
457
- };
458
- } else {
459
- fieldReaders[name] = (buf) => (buf.readUInt8(fieldOffset) >> bitOffset) & mask;
460
- }
461
- fieldWriters[name] = (buf, val) => {
462
- const v = buf.readUInt8(fieldOffset);
463
- buf.writeUInt8(((v & clearMask) | ((val & mask) << bitOffset)) & 0xff, fieldOffset);
464
- };
465
- } else if (baseSize === 2) {
466
- const mask = (1 << bitSize) - 1;
467
- const clearMask = ~(mask << bitOffset);
468
- if (isSigned) {
469
- const signBit = 1 << (bitSize - 1);
470
- const extendMask = ~mask;
471
- fieldReaders[name] = (buf) => {
472
- const raw = (buf.readUInt16LE(fieldOffset) >> bitOffset) & mask;
473
- return (raw & signBit) ? (raw | extendMask) : raw;
474
- };
475
- } else {
476
- fieldReaders[name] = (buf) => (buf.readUInt16LE(fieldOffset) >> bitOffset) & mask;
477
- }
478
- fieldWriters[name] = (buf, val) => {
479
- const v = buf.readUInt16LE(fieldOffset);
480
- buf.writeUInt16LE(((v & clearMask) | ((val & mask) << bitOffset)) & 0xffff, fieldOffset);
481
- };
482
- } else if (baseSize === 4) {
483
- const mask = (1 << bitSize) - 1;
484
- const clearMask = ~(mask << bitOffset);
485
- if (isSigned) {
486
- const signBit = 1 << (bitSize - 1);
487
- const extendMask = ~mask;
488
- fieldReaders[name] = (buf) => {
489
- const raw = (buf.readUInt32LE(fieldOffset) >>> bitOffset) & mask;
490
- return (raw & signBit) ? (raw | extendMask) : raw;
491
- };
492
- } else {
493
- fieldReaders[name] = (buf) => (buf.readUInt32LE(fieldOffset) >>> bitOffset) & mask;
494
- }
495
- fieldWriters[name] = (buf, val) => {
496
- const v = buf.readUInt32LE(fieldOffset);
497
- buf.writeUInt32LE(((v & clearMask) | ((val & mask) << bitOffset)) >>> 0, fieldOffset);
498
- };
499
- } else if (baseSize === 8) {
500
- const bMask = (1n << BigInt(bitSize)) - 1n;
501
- const bBitOffset = BigInt(bitOffset);
502
- const bClearMask = ~(bMask << bBitOffset);
503
- if (isSigned) {
504
- const bSignBit = 1n << BigInt(bitSize - 1);
505
- const bExtend = ~bMask;
506
- fieldReaders[name] = (buf) => {
507
- const raw = (buf.readBigUInt64LE(fieldOffset) >> bBitOffset) & bMask;
508
- const signed = (raw & bSignBit) ? (raw | bExtend) : raw;
509
- // Ritorna Number se sta nel safe range, altrimenti BigInt
510
- const asNum = Number(signed);
511
- return (asNum >= Number.MIN_SAFE_INTEGER && asNum <= Number.MAX_SAFE_INTEGER)
512
- ? asNum
513
- : signed;
514
- };
515
- } else {
516
- fieldReaders[name] = (buf) => Number((buf.readBigUInt64LE(fieldOffset) >> bBitOffset) & bMask);
517
- }
518
- fieldWriters[name] = (buf, val) => {
519
- const v = buf.readBigUInt64LE(fieldOffset);
520
- buf.writeBigUInt64LE((v & bClearMask) | ((BigInt(val) & bMask) << bBitOffset), fieldOffset);
521
- };
522
- }
246
+ const { read, write } = bitFieldAccessors({
247
+ offset,
248
+ baseSize: field.baseSize,
249
+ bitOffset: field.bitOffset,
250
+ bitSize: field.bitSize,
251
+ signed: field.type?._signed === true,
252
+ bigEndian: field.swapped === true,
253
+ boolean: field.type?._isBoolean === true,
254
+ });
255
+ field.readBits = read;
256
+ field.writeBits = simpleFieldWriter(field.type, (buf, offset, value) => write(buf, value), 0);
257
+ fieldReaders[name] = read;
258
+ fieldWriters[name] = field.writeBits;
523
259
  continue;
524
260
  }
525
261
 
@@ -533,12 +269,12 @@ export function struct(fields, options = {}, sizeof, alloc, readValue, writeValu
533
269
  const fieldOffset = offset;
534
270
  const ptrType = field.type;
535
271
  if (is64) {
536
- fieldReaders[name] = (buf) => pointerOrNull(ptrType, buf.readBigUInt64LE(fieldOffset));
272
+ fieldReaders[name] = (buf) => pointerOrNull(ptrType, buf.readBigUInt64LE(fieldOffset), buf, fieldOffset);
537
273
  fieldWriters[name] = (buf, val) => {
538
274
  writePointerField(buf, fieldOffset, val, 8);
539
275
  };
540
276
  } else {
541
- fieldReaders[name] = (buf) => pointerOrNull(ptrType, BigInt(buf.readUInt32LE(fieldOffset)));
277
+ fieldReaders[name] = (buf) => pointerOrNull(ptrType, BigInt(buf.readUInt32LE(fieldOffset)), buf, fieldOffset);
542
278
  fieldWriters[name] = (buf, val) => {
543
279
  writePointerField(buf, fieldOffset, val, 4);
544
280
  };
@@ -551,10 +287,10 @@ export function struct(fields, options = {}, sizeof, alloc, readValue, writeValu
551
287
  const fieldType = field.type;
552
288
  if (fieldType && fieldType._isSimpleCData) {
553
289
  const fieldOffset = offset; // Capture offset for closure
554
- const reader = swapped && fieldType._readerBE ? fieldType._readerBE : fieldType._reader;
555
- const writer = swapped && fieldType._writerBE ? fieldType._writerBE : fieldType._writer;
290
+ const reader = scalarReader(fieldType, field.swapped && fieldType._readerBE ? fieldType._readerBE : fieldType._reader, field.swapped);
291
+ const writer = field.swapped && fieldType._writerBE ? fieldType._writerBE : fieldType._writer;
556
292
  fieldReaders[name] = (buf) => reader(buf, fieldOffset);
557
- fieldWriters[name] = (buf, val) => writer(buf, fieldOffset, val);
293
+ fieldWriters[name] = simpleFieldWriter(fieldType, writer, fieldOffset);
558
294
  }
559
295
  }
560
296
 
@@ -565,8 +301,10 @@ export function struct(fields, options = {}, sizeof, alloc, readValue, writeValu
565
301
  fieldMap,
566
302
  fieldReaders,
567
303
  fieldWriters,
568
- anonymousFieldNames, // usato dai nested proxy per evitare ricostruzioni
569
- packed: packed,
304
+ anonymousFieldNames, // usato dai nested proxy per evitare ricostruzioni
305
+ packed: packValue !== 0,
306
+ swapped,
307
+ base, // definizione della classe base (i suoi campi sono i primi di `fields`)
570
308
  _isStructType: true,
571
309
 
572
310
  /**
@@ -596,10 +334,13 @@ export function struct(fields, options = {}, sizeof, alloc, readValue, writeValu
596
334
  }
597
335
  }
598
336
 
599
- return new Proxy(buf, buildWrapper(structDef, {
600
- instanceTag: "StructInstance",
601
- exposeAnonymous: true,
602
- }));
337
+ return new Proxy(
338
+ buf,
339
+ buildWrapper(structDef, {
340
+ instanceTag: "StructInstance",
341
+ exposeAnonymous: true,
342
+ }),
343
+ );
603
344
  },
604
345
 
605
346
  /**
@@ -650,25 +391,30 @@ export function struct(fields, options = {}, sizeof, alloc, readValue, writeValu
650
391
  if (field) {
651
392
  // Bit field
652
393
  if (field.isBitField) {
653
- return _readBitField(buf, field.offset, field.type, field.bitOffset, field.bitSize, sizeof);
394
+ return field.readBits(buf);
654
395
  }
655
396
 
656
397
  // Nested struct (senza dot = ritorna intero oggetto)
657
398
  if (field.isNested) {
658
399
  const nestedBuf = buf.subarray(field.offset, field.offset + field.size);
400
+ // Classe Structure/Union: un'istanza sulla stessa memoria (Python).
401
+ if (field.cls !== undefined) return new field.cls(nestedBuf);
659
402
  return field.type.create
660
- ? new Proxy(nestedBuf, buildWrapper(field.type, {
661
- instanceTag: "NestedStructInstance",
662
- exposeAnonymous: true,
663
- mirrored: isMirror(nestedBuf),
664
- }))
403
+ ? new Proxy(
404
+ nestedBuf,
405
+ buildWrapper(field.type, {
406
+ instanceTag: "NestedStructInstance",
407
+ exposeAnonymous: true,
408
+ mirrored: isMirror(nestedBuf),
409
+ }),
410
+ )
665
411
  : field.type.toObject(nestedBuf);
666
412
  }
667
413
 
668
414
  // POINTER() field — return PointerInstance
669
415
  if (field.isPointer) {
670
416
  const addr = native.POINTER_SIZE === 8 ? buf.readBigUInt64LE(field.offset) : BigInt(buf.readUInt32LE(field.offset));
671
- return pointerOrNull(field.type, addr);
417
+ return pointerOrNull(field.type, addr, buf, field.offset);
672
418
  }
673
419
 
674
420
  // Array field (Python: c_char * n / c_wchar * n si leggono come stringa)
@@ -678,8 +424,8 @@ export function struct(fields, options = {}, sizeof, alloc, readValue, writeValu
678
424
  return field.type.wrap(arrayBuf);
679
425
  }
680
426
 
681
- // Tipo base - fast path!
682
- return readValue(buf, field.type, field.offset);
427
+ // Tipo base: stesso accessor del fast path (rispetta l'endianness)
428
+ return fieldReaders[field.name](buf);
683
429
  }
684
430
 
685
431
  // supporto per accesso nested 'outer.inner' o anonymous fields
@@ -692,7 +438,7 @@ export function struct(fields, options = {}, sizeof, alloc, readValue, writeValu
692
438
  if (!field) {
693
439
  for (const f of fieldDefs) {
694
440
  if (f.isAnonymous && f.type && f.type.fields) {
695
- const hasField = f.type.fields.some((subField) => subField.name === firstPart);
441
+ const hasField = promotes(f, firstPart);
696
442
  if (hasField) {
697
443
  const nestedBuf = buf.subarray(f.offset, f.offset + f.size);
698
444
  return f.type.get(nestedBuf, fieldName);
@@ -741,17 +487,15 @@ export function struct(fields, options = {}, sizeof, alloc, readValue, writeValu
741
487
  if (field) {
742
488
  // Bit field
743
489
  if (field.isBitField) {
744
- _writeBitField(buf, field.offset, field.type, field.bitOffset, field.bitSize, value, sizeof);
490
+ field.writeBits(buf, value);
745
491
  return;
746
492
  }
747
493
 
748
494
  // Nested struct (senza dot = imposta da oggetto)
749
495
  if (field.isNested) {
750
- if (Buffer.isBuffer(value)) {
751
- value.copy(buf, field.offset, 0, field.size);
752
- } else if (value !== null && typeof value === "object" && Buffer.isBuffer(value._buffer)) {
496
+ if (Buffer.isBuffer(value) || (value !== null && typeof value === "object" && Buffer.isBuffer(value._buffer))) {
753
497
  // Istanza struct/union: copia dei byte (Python), non campo per campo
754
- copyInstance(buf, field.offset, field.size, value);
498
+ copyInstance(buf, field.offset, field.size, value, 0, field.type);
755
499
  } else if (typeof value === "object") {
756
500
  const nestedBuf = buf.subarray(field.offset, field.offset + field.size);
757
501
  for (const [k, v] of Object.entries(value)) {
@@ -769,10 +513,11 @@ export function struct(fields, options = {}, sizeof, alloc, readValue, writeValu
769
513
 
770
514
  // Array field
771
515
  if (field.isArray) {
772
- if (field.type._charKind !== undefined && typeof value === "string") {
516
+ // Python: bytes / str con il controllo di lunghezza ("bytes too long").
517
+ if (field.type._charKind !== undefined && (typeof value === "string" || (field.type._charKind === "char" && Buffer.isBuffer(value) && value._buffer === undefined))) {
773
518
  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})`);
774
- } else if (Buffer.isBuffer(value)) {
775
- value.copy(buf, field.offset, 0, field.size);
519
+ } else if (Buffer.isBuffer(value) || Buffer.isBuffer(value?._buffer)) {
520
+ copyInstance(buf, field.offset, field.size, value, 0, field.type);
776
521
  } else if (Array.isArray(value)) {
777
522
  const arrayBuf = buf.subarray(field.offset, field.offset + field.size);
778
523
  const wrapped = field.type.wrap(arrayBuf);
@@ -783,8 +528,8 @@ export function struct(fields, options = {}, sizeof, alloc, readValue, writeValu
783
528
  return;
784
529
  }
785
530
 
786
- // Tipo base - fast path!
787
- writeValue(buf, field.type, value, field.offset);
531
+ // Tipo base: stesso accessor del fast path (rispetta l'endianness)
532
+ fieldWriters[field.name](buf, value);
788
533
  return;
789
534
  }
790
535
 
@@ -799,7 +544,7 @@ export function struct(fields, options = {}, sizeof, alloc, readValue, writeValu
799
544
  for (const f of fieldDefs) {
800
545
  if (f.isAnonymous && f.type && f.type.fields) {
801
546
  // Verifica se il campo esiste nel tipo anonimo
802
- const hasField = f.type.fields.some((subField) => subField.name === firstPart);
547
+ const hasField = promotes(f, firstPart);
803
548
  if (hasField) {
804
549
  // Scrive nel campo dell'anonymous field
805
550
  const nestedBuf = buf.subarray(f.offset, f.offset + f.size);
@@ -813,7 +558,7 @@ export function struct(fields, options = {}, sizeof, alloc, readValue, writeValu
813
558
 
814
559
  // Bit field
815
560
  if (field.isBitField) {
816
- _writeBitField(buf, field.offset, field.type, field.bitOffset, field.bitSize, value, sizeof);
561
+ field.writeBits(buf, value);
817
562
  return;
818
563
  }
819
564
 
@@ -823,12 +568,9 @@ export function struct(fields, options = {}, sizeof, alloc, readValue, writeValu
823
568
  // Accesso a campo annidato singolo
824
569
  const nestedBuf = buf.subarray(field.offset, field.offset + field.size);
825
570
  field.type.set(nestedBuf, parts.slice(1).join("."), value);
826
- } else if (Buffer.isBuffer(value)) {
827
- // Copia buffer
828
- value.copy(buf, field.offset, 0, field.size);
829
- } else if (value !== null && typeof value === "object" && Buffer.isBuffer(value._buffer)) {
571
+ } else if (Buffer.isBuffer(value) || (value !== null && typeof value === "object" && Buffer.isBuffer(value._buffer))) {
830
572
  // Istanza struct/union: copia dei byte (Python), non campo per campo
831
- copyInstance(buf, field.offset, field.size, value);
573
+ copyInstance(buf, field.offset, field.size, value, 0, field.type);
832
574
  } else if (typeof value === "object") {
833
575
  // Imposta campi da oggetto
834
576
  const nestedBuf = buf.subarray(field.offset, field.offset + field.size);
@@ -843,9 +585,8 @@ export function struct(fields, options = {}, sizeof, alloc, readValue, writeValu
843
585
  if (field.isArray) {
844
586
  if (field.type._charKind !== undefined && typeof value === "string") {
845
587
  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})`);
846
- } else if (Buffer.isBuffer(value)) {
847
- // Copia buffer array
848
- value.copy(buf, field.offset, 0, field.size);
588
+ } else if (Buffer.isBuffer(value) || Buffer.isBuffer(value?._buffer)) {
589
+ copyInstance(buf, field.offset, field.size, value, 0, field.type);
849
590
  } else if (Array.isArray(value)) {
850
591
  // Inizializza da array JavaScript
851
592
  const arrayBuf = buf.subarray(field.offset, field.offset + field.size);
@@ -858,7 +599,7 @@ export function struct(fields, options = {}, sizeof, alloc, readValue, writeValu
858
599
  }
859
600
 
860
601
  // Tipo base
861
- writeValue(buf, field.type, value, field.offset);
602
+ fieldWriters[field.name](buf, value);
862
603
  },
863
604
 
864
605
  /**
@@ -891,7 +632,7 @@ export function struct(fields, options = {}, sizeof, alloc, readValue, writeValu
891
632
  // Leggi tutti i campi in una volta (eager approach)
892
633
  for (const field of fieldDefs) {
893
634
  if (field.isBitField) {
894
- result[field.name] = _readBitField(buf, field.offset, field.type, field.bitOffset, field.bitSize, sizeof);
635
+ result[field.name] = field.readBits(buf);
895
636
  } else if (field.isNested) {
896
637
  const nestedBuf = buf.subarray(field.offset, field.offset + field.size);
897
638
  const nestedObj = field.type.toObject(nestedBuf);
@@ -903,13 +644,13 @@ export function struct(fields, options = {}, sizeof, alloc, readValue, writeValu
903
644
  }
904
645
  } else if (field.isPointer) {
905
646
  const addr = native.POINTER_SIZE === 8 ? buf.readBigUInt64LE(field.offset) : BigInt(buf.readUInt32LE(field.offset));
906
- result[field.name] = pointerOrNull(field.type, addr);
647
+ result[field.name] = pointerOrNull(field.type, addr, buf, field.offset);
907
648
  } else if (field.isArray) {
908
649
  const arrayBuf = buf.subarray(field.offset, field.offset + field.size);
909
650
  result[field.name] = field.type._charKind !== undefined ? field.type.getValue(arrayBuf) : field.type.wrap(arrayBuf);
910
651
  } else {
911
652
  // Tipo base - lettura diretta
912
- result[field.name] = readValue(buf, field.type, field.offset);
653
+ result[field.name] = fieldReaders[field.name](buf);
913
654
  }
914
655
  }
915
656
 
@@ -933,7 +674,7 @@ export function struct(fields, options = {}, sizeof, alloc, readValue, writeValu
933
674
 
934
675
  // fromObject: write plain object values into buffer
935
676
  structDef.fromObject = function (buf, obj) {
936
- for (const [key, value] of Object.entries(obj)) {
677
+ for (const [key, value] of Object.entries(fieldsOf(obj))) {
937
678
  if (this.fields.some((f) => f.name === key)) {
938
679
  this.set(buf, key, value);
939
680
  }