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.
@@ -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 } 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, 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
@@ -90,33 +92,28 @@ const pointerOrNull = (ptrType, address) => (address === 0n ? null : ptrType.fro
90
92
 
91
93
  export function struct(fields, options = {}, sizeof, alloc, readValue, writeValue, _isStruct, _isArrayType, _isBitField, Structure, Union, native) {
92
94
  // Validate inputs
93
- if (!fields || typeof fields !== "object" || Array.isArray(fields)) {
95
+ // Un oggetto { name: type }, o le coppie [name, type] in ordine (Structure).
96
+ if (!fields || typeof fields !== "object") {
94
97
  throw new TypeError("fields must be a non-null object");
95
98
  }
96
99
 
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").
100
+ // Python _pack_: `pack` (massimo allineamento), o `packed: true` (= pack 1).
101
+ const packValue = typeof options.pack === "number" ? options.pack : options.packed ? 1 : 0;
102
+ // `swapped` selects _readerBE/_writerBE on primitive SimpleCData fields and
103
+ // lays out bitfields from the big end. Used by BigEndianStructure /
104
+ // LittleEndianStructure (on LE host, swapped=true means "use BE").
106
105
  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)) {
106
+ const gccLayout = isGccLayout(options.layout, packValue);
107
+ // Python: una sottoclasse con _fields_ estende il layout della base, i cui
108
+ // campi restano agli stessi offset.
109
+ const base = options.base ?? null;
110
+ const fieldDefs = base ? base.fields.map((f) => ({ ...f })) : [];
111
+ const fieldNames = new Set(fieldDefs.map((f) => f.name));
112
+
113
+ // Tipo, dimensione e allineamento naturale di ogni campo; gli offset sono
114
+ // calcolati dopo, tutti insieme, da computeLayout (come Python).
115
+ const ownDefs = [];
116
+ for (const [name, type] of fieldEntries(fields)) {
120
117
  // Validate field name
121
118
  if (!name || typeof name !== "string" || name.trim().length === 0) {
122
119
  throw new TypeError("Field name must be a non-empty string");
@@ -125,279 +122,78 @@ export function struct(fields, options = {}, sizeof, alloc, readValue, writeValu
125
122
  throw new TypeError(`Duplicate field name: ${name}`);
126
123
  }
127
124
  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;
125
+ ownDefs.push(describeField(name, type));
126
+ }
156
127
 
157
- if (alignment > maxAlignment) {
158
- maxAlignment = alignment;
159
- }
128
+ // Campo di _anonymous_: una struct/union (classe o definizione), i cui
129
+ // campi sono raggiungibili dalla struct esterna.
130
+ function anonymousField(name, { type, cls }) {
131
+ let def = type;
132
+ if (typeof type === "function" && typeof type._buildStruct === "function") {
133
+ cls = type;
134
+ def = type._structDef || type._buildStruct();
160
135
  }
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
- }
136
+ if (def === null || typeof def !== "object" || !Array.isArray(def.fields)) {
137
+ throw new TypeError(`anonymous field "${name}" must be a structure or union`);
199
138
  }
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;
139
+ return { name, type: def, cls, size: def.size, alignment: def.alignment, isNested: true, isAnonymous: true };
140
+ }
225
141
 
226
- if (alignment > maxAlignment) {
227
- maxAlignment = alignment;
228
- }
142
+ function describeField(name, type) {
143
+ // Anonymous field - { type: SomeStruct, anonymous: true }
144
+ if (typeof type === "object" && type !== null && type.anonymous === true && type.type) {
145
+ return anonymousField(name, type);
229
146
  }
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
- }
147
+ // Bit field
148
+ if (_isBitField(type)) {
149
+ const { baseType, bits, baseSize } = type;
150
+ return { name, type: baseType, size: 0, alignment: Math.min(baseSize, native.POINTER_SIZE), isBitField: true, bitSize: bits, baseSize };
259
151
  }
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
- }
152
+ // Structure / Union class (Union estende Structure)
153
+ if (typeof type === "function" && type.prototype instanceof Structure) {
154
+ const nested = type._structDef || type._buildStruct();
155
+ // `cls`: Python restituisce un'istanza della classe annidata, sulla
156
+ // stessa memoria.
157
+ return { name, type: nested, cls: type, size: nested.size, alignment: nested.alignment, isNested: true };
294
158
  }
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).
159
+ // struct() / union() definition
160
+ if (_isStruct(type)) {
161
+ return { name, type, size: type.size, alignment: type.alignment, isNested: true };
162
+ }
163
+ // Array type: alignment == element alignment (C standard).
164
+ if (_isArrayType(type)) {
306
165
  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
- }
166
+ const alignment = typeof type.getAlignment === "function" ? type.getAlignment() : Math.min(elemSize, native.POINTER_SIZE);
167
+ return { name, type, size: type.getSize(), alignment, isArray: true };
329
168
  }
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
- }
169
+ // POINTER() / CFUNCTYPE — pointer-sized field with typed access
170
+ if ((typeof type === "object" && type !== null && type._pointerTo !== undefined) || (typeof type === "function" && type._isFuncPtr === true)) {
171
+ // CFUNCTYPE: campo puntatore letto come funzione chiamabile (Python parity)
172
+ return { name, type: typeof type === "function" ? funcPtrFieldType(type) : type, size: native.POINTER_SIZE, alignment: native.POINTER_SIZE, isPointer: true };
358
173
  }
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
- }
174
+ // Tipo base (SimpleCData)
175
+ if (!(typeof type === "function" && type._isSimpleCData)) {
176
+ throw new TypeError(`struct field "${name}": type must be a SimpleCData class, struct, union, or array`);
392
177
  }
393
-
394
- fieldDefs.push(fieldDef);
178
+ return { name, type, size: type._size, alignment: Math.min(type._size, native.POINTER_SIZE) };
395
179
  }
396
180
 
397
- // Padding finale per allineamento della struct
398
- if (totalSize % maxAlignment !== 0) {
399
- totalSize += maxAlignment - (totalSize % maxAlignment);
400
- }
181
+ const layout = computeLayout(
182
+ 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 })),
183
+ { isStruct: true, gccLayout, pack: packValue, align: options.align ?? 1, base, bigEndian: swapped },
184
+ );
185
+ ownDefs.forEach((f, i) => {
186
+ f.offset = layout.offsets[i].offset;
187
+ if (f.isBitField) f.bitOffset = layout.offsets[i].bitOffset;
188
+ // Allineamento del tipo in C, prima di _pack_ (usato per le struct native
189
+ // passate per valore, lib/core/types.js).
190
+ f.naturalAlignment = f.alignment;
191
+ if (packValue) f.alignment = Math.min(f.alignment, packValue);
192
+ f.swapped = swapped;
193
+ fieldDefs.push(f);
194
+ });
195
+ const totalSize = layout.size;
196
+ const maxAlignment = layout.alignment;
401
197
 
402
198
  // Crea Map per lookup O(1) invece di find() O(n)
403
199
  const fieldMap = new Map();
@@ -409,14 +205,20 @@ export function struct(fields, options = {}, sizeof, alloc, readValue, writeValu
409
205
  // inclusi i sotto-campi dei campi _anonymous_. Il Proxy get/set/has
410
206
  // altrimenti scansionerebbe linearmente tutti i campi anonymous e i loro
411
207
  // subfields su ogni accesso. Usa un null-proto object per IC monomorfo.
412
- const anonymousFieldNames = Object.create(null); // subField.name -> true
208
+ // Come Python, la promozione è ricorsiva: un campo anonimo dentro un campo
209
+ // anonimo è raggiungibile dalla struct esterna.
210
+ const anonymousFieldNames = Object.create(null); // subField.name -> true
413
211
  for (const field of fieldDefs) {
414
212
  if (field.isAnonymous && field.type && field.type.fields) {
415
213
  for (const subField of field.type.fields) {
416
214
  anonymousFieldNames[subField.name] = true;
417
215
  }
216
+ for (const name of Object.keys(field.type.anonymousFieldNames ?? {})) {
217
+ anonymousFieldNames[name] = true;
218
+ }
418
219
  }
419
220
  }
221
+ const promotes = (f, name) => f.type.fields.some((subField) => subField.name === name) || f.type.anonymousFieldNames?.[name] === true;
420
222
 
421
223
  // Pre-compile reader/writer functions for each field.
422
224
  // We use null-prototype plain objects rather than `Map` because V8 builds
@@ -434,92 +236,21 @@ export function struct(fields, options = {}, sizeof, alloc, readValue, writeValu
434
236
  const offset = field.offset;
435
237
  const name = field.name;
436
238
 
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).
239
+ // Bitfield: accessor precompilati (sign-extension per base type signed,
240
+ // come Python: `c_int8, 3` con valore -1 rilegge -1, non 7).
441
241
  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
- }
242
+ const { read, write } = bitFieldAccessors({
243
+ offset,
244
+ baseSize: field.baseSize,
245
+ bitOffset: field.bitOffset,
246
+ bitSize: field.bitSize,
247
+ signed: field.type?._signed === true,
248
+ bigEndian: field.swapped === true,
249
+ });
250
+ field.readBits = read;
251
+ field.writeBits = write;
252
+ fieldReaders[name] = read;
253
+ fieldWriters[name] = write;
523
254
  continue;
524
255
  }
525
256
 
@@ -551,10 +282,10 @@ export function struct(fields, options = {}, sizeof, alloc, readValue, writeValu
551
282
  const fieldType = field.type;
552
283
  if (fieldType && fieldType._isSimpleCData) {
553
284
  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;
285
+ const reader = field.swapped && fieldType._readerBE ? fieldType._readerBE : fieldType._reader;
286
+ const writer = field.swapped && fieldType._writerBE ? fieldType._writerBE : fieldType._writer;
556
287
  fieldReaders[name] = (buf) => reader(buf, fieldOffset);
557
- fieldWriters[name] = (buf, val) => writer(buf, fieldOffset, val);
288
+ fieldWriters[name] = simpleFieldWriter(fieldType, writer, fieldOffset);
558
289
  }
559
290
  }
560
291
 
@@ -565,8 +296,10 @@ export function struct(fields, options = {}, sizeof, alloc, readValue, writeValu
565
296
  fieldMap,
566
297
  fieldReaders,
567
298
  fieldWriters,
568
- anonymousFieldNames, // usato dai nested proxy per evitare ricostruzioni
569
- packed: packed,
299
+ anonymousFieldNames, // usato dai nested proxy per evitare ricostruzioni
300
+ packed: packValue !== 0,
301
+ swapped,
302
+ base, // definizione della classe base (i suoi campi sono i primi di `fields`)
570
303
  _isStructType: true,
571
304
 
572
305
  /**
@@ -596,10 +329,13 @@ export function struct(fields, options = {}, sizeof, alloc, readValue, writeValu
596
329
  }
597
330
  }
598
331
 
599
- return new Proxy(buf, buildWrapper(structDef, {
600
- instanceTag: "StructInstance",
601
- exposeAnonymous: true,
602
- }));
332
+ return new Proxy(
333
+ buf,
334
+ buildWrapper(structDef, {
335
+ instanceTag: "StructInstance",
336
+ exposeAnonymous: true,
337
+ }),
338
+ );
603
339
  },
604
340
 
605
341
  /**
@@ -650,18 +386,23 @@ export function struct(fields, options = {}, sizeof, alloc, readValue, writeValu
650
386
  if (field) {
651
387
  // Bit field
652
388
  if (field.isBitField) {
653
- return _readBitField(buf, field.offset, field.type, field.bitOffset, field.bitSize, sizeof);
389
+ return field.readBits(buf);
654
390
  }
655
391
 
656
392
  // Nested struct (senza dot = ritorna intero oggetto)
657
393
  if (field.isNested) {
658
394
  const nestedBuf = buf.subarray(field.offset, field.offset + field.size);
395
+ // Classe Structure/Union: un'istanza sulla stessa memoria (Python).
396
+ if (field.cls !== undefined) return new field.cls(nestedBuf);
659
397
  return field.type.create
660
- ? new Proxy(nestedBuf, buildWrapper(field.type, {
661
- instanceTag: "NestedStructInstance",
662
- exposeAnonymous: true,
663
- mirrored: isMirror(nestedBuf),
664
- }))
398
+ ? new Proxy(
399
+ nestedBuf,
400
+ buildWrapper(field.type, {
401
+ instanceTag: "NestedStructInstance",
402
+ exposeAnonymous: true,
403
+ mirrored: isMirror(nestedBuf),
404
+ }),
405
+ )
665
406
  : field.type.toObject(nestedBuf);
666
407
  }
667
408
 
@@ -678,8 +419,8 @@ export function struct(fields, options = {}, sizeof, alloc, readValue, writeValu
678
419
  return field.type.wrap(arrayBuf);
679
420
  }
680
421
 
681
- // Tipo base - fast path!
682
- return readValue(buf, field.type, field.offset);
422
+ // Tipo base: stesso accessor del fast path (rispetta l'endianness)
423
+ return fieldReaders[field.name](buf);
683
424
  }
684
425
 
685
426
  // supporto per accesso nested 'outer.inner' o anonymous fields
@@ -692,7 +433,7 @@ export function struct(fields, options = {}, sizeof, alloc, readValue, writeValu
692
433
  if (!field) {
693
434
  for (const f of fieldDefs) {
694
435
  if (f.isAnonymous && f.type && f.type.fields) {
695
- const hasField = f.type.fields.some((subField) => subField.name === firstPart);
436
+ const hasField = promotes(f, firstPart);
696
437
  if (hasField) {
697
438
  const nestedBuf = buf.subarray(f.offset, f.offset + f.size);
698
439
  return f.type.get(nestedBuf, fieldName);
@@ -741,7 +482,7 @@ export function struct(fields, options = {}, sizeof, alloc, readValue, writeValu
741
482
  if (field) {
742
483
  // Bit field
743
484
  if (field.isBitField) {
744
- _writeBitField(buf, field.offset, field.type, field.bitOffset, field.bitSize, value, sizeof);
485
+ field.writeBits(buf, value);
745
486
  return;
746
487
  }
747
488
 
@@ -769,7 +510,8 @@ export function struct(fields, options = {}, sizeof, alloc, readValue, writeValu
769
510
 
770
511
  // Array field
771
512
  if (field.isArray) {
772
- if (field.type._charKind !== undefined && typeof value === "string") {
513
+ // Python: bytes / str con il controllo di lunghezza ("bytes too long").
514
+ if (field.type._charKind !== undefined && (typeof value === "string" || (field.type._charKind === "char" && Buffer.isBuffer(value) && value._buffer === undefined))) {
773
515
  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
516
  } else if (Buffer.isBuffer(value)) {
775
517
  value.copy(buf, field.offset, 0, field.size);
@@ -783,8 +525,8 @@ export function struct(fields, options = {}, sizeof, alloc, readValue, writeValu
783
525
  return;
784
526
  }
785
527
 
786
- // Tipo base - fast path!
787
- writeValue(buf, field.type, value, field.offset);
528
+ // Tipo base: stesso accessor del fast path (rispetta l'endianness)
529
+ fieldWriters[field.name](buf, value);
788
530
  return;
789
531
  }
790
532
 
@@ -799,7 +541,7 @@ export function struct(fields, options = {}, sizeof, alloc, readValue, writeValu
799
541
  for (const f of fieldDefs) {
800
542
  if (f.isAnonymous && f.type && f.type.fields) {
801
543
  // Verifica se il campo esiste nel tipo anonimo
802
- const hasField = f.type.fields.some((subField) => subField.name === firstPart);
544
+ const hasField = promotes(f, firstPart);
803
545
  if (hasField) {
804
546
  // Scrive nel campo dell'anonymous field
805
547
  const nestedBuf = buf.subarray(f.offset, f.offset + f.size);
@@ -813,7 +555,7 @@ export function struct(fields, options = {}, sizeof, alloc, readValue, writeValu
813
555
 
814
556
  // Bit field
815
557
  if (field.isBitField) {
816
- _writeBitField(buf, field.offset, field.type, field.bitOffset, field.bitSize, value, sizeof);
558
+ field.writeBits(buf, value);
817
559
  return;
818
560
  }
819
561
 
@@ -858,7 +600,7 @@ export function struct(fields, options = {}, sizeof, alloc, readValue, writeValu
858
600
  }
859
601
 
860
602
  // Tipo base
861
- writeValue(buf, field.type, value, field.offset);
603
+ fieldWriters[field.name](buf, value);
862
604
  },
863
605
 
864
606
  /**
@@ -891,7 +633,7 @@ export function struct(fields, options = {}, sizeof, alloc, readValue, writeValu
891
633
  // Leggi tutti i campi in una volta (eager approach)
892
634
  for (const field of fieldDefs) {
893
635
  if (field.isBitField) {
894
- result[field.name] = _readBitField(buf, field.offset, field.type, field.bitOffset, field.bitSize, sizeof);
636
+ result[field.name] = field.readBits(buf);
895
637
  } else if (field.isNested) {
896
638
  const nestedBuf = buf.subarray(field.offset, field.offset + field.size);
897
639
  const nestedObj = field.type.toObject(nestedBuf);
@@ -909,7 +651,7 @@ export function struct(fields, options = {}, sizeof, alloc, readValue, writeValu
909
651
  result[field.name] = field.type._charKind !== undefined ? field.type.getValue(arrayBuf) : field.type.wrap(arrayBuf);
910
652
  } else {
911
653
  // Tipo base - lettura diretta
912
- result[field.name] = readValue(buf, field.type, field.offset);
654
+ result[field.name] = fieldReaders[field.name](buf);
913
655
  }
914
656
  }
915
657
 
@@ -933,7 +675,7 @@ export function struct(fields, options = {}, sizeof, alloc, readValue, writeValu
933
675
 
934
676
  // fromObject: write plain object values into buffer
935
677
  structDef.fromObject = function (buf, obj) {
936
- for (const [key, value] of Object.entries(obj)) {
678
+ for (const [key, value] of Object.entries(fieldsOf(obj))) {
937
679
  if (this.fields.some((f) => f.name === key)) {
938
680
  this.set(buf, key, value);
939
681
  }