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.
@@ -34,10 +34,11 @@
34
34
  * ```
35
35
  */
36
36
 
37
- import { _readBitField, _writeBitField } from "./bitfield.js";
37
+ import { bitFieldAccessors } from "./bitfield.js";
38
+ import { computeLayout, isGccLayout } from "./layout.js";
38
39
  import { buildWrapper } from "./wrap.js";
39
40
  import { syncDefinition } from "../../memory/mirror.js";
40
- import { copyInstance, funcPtrFieldType, writePointerField } from "./common.js";
41
+ import { copyInstance, fieldEntries, fieldsOf, funcPtrFieldType, simpleFieldWriter, writePointerField } from "./common.js";
41
42
 
42
43
  /**
43
44
  * Creates a union type definition where all fields share offset 0.
@@ -109,39 +110,64 @@ export function union(fields, options, sizeof, alloc, readValue, writeValue, _is
109
110
  }
110
111
  options = options || {};
111
112
  const swapped = options.swapped === true;
112
- let maxSize = 0;
113
- let maxAlignment = 1;
114
- const fieldDefs = [];
115
-
116
- for (const [name, type] of Object.entries(fields)) {
113
+ // Python _pack_: `pack` da solo, o `packed: true` (= pack 1).
114
+ const packValue = typeof options.pack === "number" ? options.pack : options.packed ? 1 : 0;
115
+ const gccLayout = isGccLayout(options.layout, packValue);
116
+ const base = options.base ?? null;
117
+ const fieldDefs = base ? base.fields.map((f) => ({ ...f })) : [];
118
+ const ownDefs = [];
119
+
120
+ const fieldNames = new Set(fieldDefs.map((f) => f.name));
121
+ for (const [name, type] of fieldEntries(fields)) {
122
+ if (fieldNames.has(name)) {
123
+ throw new TypeError(`Duplicate field name: ${name}`);
124
+ }
125
+ fieldNames.add(name);
117
126
  let size, alignment;
118
- let fieldDef = { name, type, offset: 0 };
119
-
127
+ let fieldDef = { name, type };
128
+
129
+ // Campo di _anonymous_: i suoi campi sono raggiungibili dalla union.
130
+ if (typeof type === "object" && type !== null && type.anonymous === true && type.type) {
131
+ let def = type.type;
132
+ fieldDef.cls = type.cls;
133
+ if (typeof def === "function" && typeof def._buildStruct === "function") {
134
+ fieldDef.cls = def;
135
+ def = def._structDef || def._buildStruct();
136
+ }
137
+ if (def === null || typeof def !== "object" || !Array.isArray(def.fields)) {
138
+ throw new TypeError(`anonymous field "${name}" must be a structure or union`);
139
+ }
140
+ fieldDef.type = def;
141
+ fieldDef.isNested = true;
142
+ fieldDef.isAnonymous = true;
143
+ size = def.size;
144
+ alignment = def.alignment;
145
+ }
120
146
  // Nested struct (object form or class form)
121
- if (_isStruct(type)) {
147
+ else if (_isStruct(type)) {
122
148
  // Normalize type: if it's a Structure/Union class, get its _structDef
123
149
  let nestedStruct = type;
124
150
  if (typeof type === "function" && typeof type._buildStruct === "function") {
125
151
  nestedStruct = type._structDef || type._buildStruct();
126
152
  fieldDef.type = nestedStruct;
153
+ // Python restituisce un'istanza della classe annidata.
154
+ fieldDef.cls = type;
127
155
  }
128
156
  size = nestedStruct.size;
129
157
  alignment = nestedStruct.alignment;
130
158
  fieldDef.isNested = true;
131
159
  }
132
- // Array type
160
+ // Array type: alignment == element alignment (C standard)
133
161
  else if (_isArrayType(type)) {
134
162
  size = type.getSize();
135
- const elemSize = sizeof(type.elementType);
136
- alignment = Math.min(elemSize, native.POINTER_SIZE);
163
+ alignment = typeof type.getAlignment === "function" ? type.getAlignment() : Math.min(sizeof(type.elementType), native.POINTER_SIZE);
137
164
  fieldDef.isArray = true;
138
165
  }
139
- // Bit field - in union ogni bitfield occupa l'intero baseType
166
+ // Bit field
140
167
  else if (_isBitField(type)) {
141
168
  size = type.baseSize;
142
169
  alignment = Math.min(size, native.POINTER_SIZE);
143
170
  fieldDef.isBitField = true;
144
- fieldDef.bitOffset = 0;
145
171
  fieldDef.bitSize = type.bits;
146
172
  fieldDef.baseSize = type.baseSize;
147
173
  fieldDef.type = type.baseType; // Usa il tipo base per lettura/scrittura
@@ -149,7 +175,7 @@ export function union(fields, options, sizeof, alloc, readValue, writeValue, _is
149
175
  // POINTER() type
150
176
  else if ((typeof type === "object" && type !== null && type._pointerTo !== undefined) || (typeof type === "function" && type._isFuncPtr === true)) {
151
177
  size = native.POINTER_SIZE;
152
- alignment = Math.min(size, native.POINTER_SIZE);
178
+ alignment = native.POINTER_SIZE;
153
179
  // CFUNCTYPE: campo puntatore letto come funzione chiamabile (Python parity)
154
180
  fieldDef.type = typeof type === "function" ? funcPtrFieldType(type) : type;
155
181
  fieldDef.isPointer = true;
@@ -167,20 +193,25 @@ export function union(fields, options, sizeof, alloc, readValue, writeValue, _is
167
193
 
168
194
  fieldDef.size = size;
169
195
  fieldDef.alignment = alignment;
170
- fieldDefs.push(fieldDef);
171
-
172
- if (size > maxSize) {
173
- maxSize = size;
174
- }
175
- if (alignment > maxAlignment) {
176
- maxAlignment = alignment;
177
- }
196
+ ownDefs.push(fieldDef);
178
197
  }
179
198
 
180
- // Padding finale per allineamento
181
- if (maxSize % maxAlignment !== 0) {
182
- maxSize += maxAlignment - (maxSize % maxAlignment);
183
- }
199
+ const layout = computeLayout(
200
+ 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 })),
201
+ { isStruct: false, gccLayout, pack: packValue, align: options.align ?? 1, base, bigEndian: swapped },
202
+ );
203
+ ownDefs.forEach((f, i) => {
204
+ f.offset = layout.offsets[i].offset;
205
+ if (f.isBitField) f.bitOffset = layout.offsets[i].bitOffset;
206
+ // Allineamento del tipo in C, prima di _pack_ (usato per le struct native
207
+ // passate per valore, lib/core/types.js).
208
+ f.naturalAlignment = f.alignment;
209
+ if (packValue) f.alignment = Math.min(f.alignment, packValue);
210
+ f.swapped = swapped;
211
+ fieldDefs.push(f);
212
+ });
213
+ const maxSize = layout.size;
214
+ const maxAlignment = layout.alignment;
184
215
 
185
216
  // Crea Map per lookup O(1)
186
217
  const fieldMap = new Map();
@@ -203,85 +234,18 @@ export function union(fields, options, sizeof, alloc, readValue, writeValue, _is
203
234
 
204
235
  // Bitfield precompilato (parity con struct.js).
205
236
  if (field.isBitField) {
206
- const baseSize = field.baseSize;
207
- const bitOffset = field.bitOffset;
208
- const bitSize = field.bitSize;
209
- const isSigned = field.type?._signed === true;
210
- // Union: offset è sempre 0, ma preserviamo la stessa variabile
211
- // name per leggibilità.
212
- const fieldOffset = offset;
213
- if (baseSize === 1) {
214
- const mask = (1 << bitSize) - 1;
215
- const clearMask = ~(mask << bitOffset);
216
- if (isSigned) {
217
- const signBit = 1 << (bitSize - 1);
218
- const extendMask = ~mask;
219
- fieldReaders[name] = (buf) => {
220
- const raw = (buf.readUInt8(fieldOffset) >> bitOffset) & mask;
221
- return (raw & signBit) ? (raw | extendMask) : raw;
222
- };
223
- } else {
224
- fieldReaders[name] = (buf) => (buf.readUInt8(fieldOffset) >> bitOffset) & mask;
225
- }
226
- fieldWriters[name] = (buf, val) => {
227
- const v = buf.readUInt8(fieldOffset);
228
- buf.writeUInt8(((v & clearMask) | ((val & mask) << bitOffset)) & 0xff, fieldOffset);
229
- };
230
- } else if (baseSize === 2) {
231
- const mask = (1 << bitSize) - 1;
232
- const clearMask = ~(mask << bitOffset);
233
- if (isSigned) {
234
- const signBit = 1 << (bitSize - 1);
235
- const extendMask = ~mask;
236
- fieldReaders[name] = (buf) => {
237
- const raw = (buf.readUInt16LE(fieldOffset) >> bitOffset) & mask;
238
- return (raw & signBit) ? (raw | extendMask) : raw;
239
- };
240
- } else {
241
- fieldReaders[name] = (buf) => (buf.readUInt16LE(fieldOffset) >> bitOffset) & mask;
242
- }
243
- fieldWriters[name] = (buf, val) => {
244
- const v = buf.readUInt16LE(fieldOffset);
245
- buf.writeUInt16LE(((v & clearMask) | ((val & mask) << bitOffset)) & 0xffff, fieldOffset);
246
- };
247
- } else if (baseSize === 4) {
248
- const mask = (1 << bitSize) - 1;
249
- const clearMask = ~(mask << bitOffset);
250
- if (isSigned) {
251
- const signBit = 1 << (bitSize - 1);
252
- const extendMask = ~mask;
253
- fieldReaders[name] = (buf) => {
254
- const raw = (buf.readUInt32LE(fieldOffset) >>> bitOffset) & mask;
255
- return (raw & signBit) ? (raw | extendMask) : raw;
256
- };
257
- } else {
258
- fieldReaders[name] = (buf) => (buf.readUInt32LE(fieldOffset) >>> bitOffset) & mask;
259
- }
260
- fieldWriters[name] = (buf, val) => {
261
- const v = buf.readUInt32LE(fieldOffset);
262
- buf.writeUInt32LE(((v & clearMask) | ((val & mask) << bitOffset)) >>> 0, fieldOffset);
263
- };
264
- } else if (baseSize === 8) {
265
- const bMask = (1n << BigInt(bitSize)) - 1n;
266
- const bBitOffset = BigInt(bitOffset);
267
- const bClearMask = ~(bMask << bBitOffset);
268
- if (isSigned) {
269
- const bSignBit = 1n << BigInt(bitSize - 1);
270
- const bExtend = ~bMask;
271
- fieldReaders[name] = (buf) => {
272
- const raw = (buf.readBigUInt64LE(fieldOffset) >> bBitOffset) & bMask;
273
- const signed = (raw & bSignBit) ? (raw | bExtend) : raw;
274
- const asNum = Number(signed);
275
- return (asNum >= Number.MIN_SAFE_INTEGER && asNum <= Number.MAX_SAFE_INTEGER) ? asNum : signed;
276
- };
277
- } else {
278
- fieldReaders[name] = (buf) => Number((buf.readBigUInt64LE(fieldOffset) >> bBitOffset) & bMask);
279
- }
280
- fieldWriters[name] = (buf, val) => {
281
- const v = buf.readBigUInt64LE(fieldOffset);
282
- buf.writeBigUInt64LE((v & bClearMask) | ((BigInt(val) & bMask) << bBitOffset), fieldOffset);
283
- };
284
- }
237
+ const { read, write } = bitFieldAccessors({
238
+ offset,
239
+ baseSize: field.baseSize,
240
+ bitOffset: field.bitOffset,
241
+ bitSize: field.bitSize,
242
+ signed: field.type?._signed === true,
243
+ bigEndian: field.swapped === true,
244
+ });
245
+ field.readBits = read;
246
+ field.writeBits = write;
247
+ fieldReaders[name] = read;
248
+ fieldWriters[name] = write;
285
249
  continue;
286
250
  }
287
251
  if (field.isPointer) {
@@ -302,15 +266,34 @@ export function union(fields, options, sizeof, alloc, readValue, writeValue, _is
302
266
 
303
267
  const fieldType = field.type;
304
268
  if (fieldType && fieldType._isSimpleCData) {
305
- const reader = swapped && fieldType._readerBE ? fieldType._readerBE : fieldType._reader;
306
- const writer = swapped && fieldType._writerBE ? fieldType._writerBE : fieldType._writer;
269
+ const reader = field.swapped && fieldType._readerBE ? fieldType._readerBE : fieldType._reader;
270
+ const writer = field.swapped && fieldType._writerBE ? fieldType._writerBE : fieldType._writer;
307
271
  if (reader && writer) {
308
272
  fieldReaders[name] = (buf) => reader(buf, offset);
309
- fieldWriters[name] = (buf, val) => writer(buf, offset, val);
273
+ fieldWriters[name] = simpleFieldWriter(fieldType, writer, offset);
310
274
  }
311
275
  }
312
276
  }
313
277
 
278
+ // Campi raggiungibili attraverso i campi di _anonymous_ (anche annidati).
279
+ const anonymousFieldNames = Object.create(null);
280
+ const anonymousOwner = new Map();
281
+ for (const field of fieldDefs) {
282
+ if (!field.isAnonymous) continue;
283
+ for (const sub of field.type.fields) {
284
+ anonymousFieldNames[sub.name] = true;
285
+ anonymousOwner.set(sub.name, field);
286
+ }
287
+ for (const name of Object.keys(field.type.anonymousFieldNames ?? {})) {
288
+ anonymousFieldNames[name] = true;
289
+ anonymousOwner.set(name, field);
290
+ }
291
+ }
292
+ const anonymousView = (buf, fieldName) => {
293
+ const owner = anonymousOwner.get(fieldName);
294
+ return owner === undefined ? undefined : { def: owner.type, buf: buf.subarray(owner.offset, owner.offset + owner.size) };
295
+ };
296
+
314
297
  const unionDef = {
315
298
  size: maxSize,
316
299
  alignment: maxAlignment,
@@ -318,7 +301,10 @@ export function union(fields, options, sizeof, alloc, readValue, writeValue, _is
318
301
  fieldMap,
319
302
  fieldReaders,
320
303
  fieldWriters,
304
+ anonymousFieldNames,
321
305
  isUnion: true,
306
+ swapped,
307
+ base, // definizione della union base (i suoi campi sono i primi di `fields`)
322
308
  _isStructType: true, // Per compatibilità con _isStruct()
323
309
 
324
310
  create(values = {}) {
@@ -332,12 +318,14 @@ export function union(fields, options, sizeof, alloc, readValue, writeValue, _is
332
318
  }
333
319
  }
334
320
 
335
- // Union: exposeAnonymous=false — i sotto-campi di _anonymous_ non
336
- // vengono elevati al livello dell'istanza.
337
- return new Proxy(buf, buildWrapper(unionDef, {
338
- instanceTag: "UnionInstance",
339
- exposeAnonymous: false,
340
- }));
321
+ // Come Python, i campi di _anonymous_ sono raggiungibili dall'istanza.
322
+ return new Proxy(
323
+ buf,
324
+ buildWrapper(unionDef, {
325
+ instanceTag: "UnionInstance",
326
+ exposeAnonymous: true,
327
+ }),
328
+ );
341
329
  },
342
330
 
343
331
  get(bufOrObj, fieldName) {
@@ -354,16 +342,22 @@ export function union(fields, options, sizeof, alloc, readValue, writeValue, _is
354
342
 
355
343
  // O(1) lookup con Map
356
344
  const field = fieldMap.get(fieldName);
357
- if (!field) throw new Error(`Unknown field: ${fieldName}`);
345
+ if (!field) {
346
+ const view = anonymousView(buf, fieldName);
347
+ if (view === undefined) throw new Error(`Unknown field: ${fieldName}`);
348
+ return view.def.get(view.buf, fieldName);
349
+ }
358
350
 
359
351
  // Bit field
360
352
  if (field.isBitField) {
361
- return _readBitField(buf, field.offset, field.type, field.bitOffset, field.bitSize, sizeof);
353
+ return field.readBits(buf);
362
354
  }
363
355
 
364
356
  // Nested struct
365
357
  if (field.isNested) {
366
358
  const nestedBuf = buf.subarray(field.offset, field.offset + field.size);
359
+ // Classe Structure/Union: un'istanza sulla stessa memoria (Python).
360
+ if (field.cls !== undefined) return new field.cls(nestedBuf);
367
361
  // Proxy-based nested instance
368
362
  return new Proxy(nestedBuf, {
369
363
  get(target, prop, receiver) {
@@ -437,11 +431,8 @@ export function union(fields, options, sizeof, alloc, readValue, writeValue, _is
437
431
  return pointerOrNull(field.type, addr);
438
432
  }
439
433
 
440
- // Tipo base — BigEndianUnion path when swapped + primitive
441
- if (swapped && field.type && typeof field.type === "function" && field.type._isSimpleCData && field.type._readerBE) {
442
- return field.type._readerBE(buf, field.offset);
443
- }
444
- return readValue(buf, field.type, field.offset);
434
+ // Tipo base: stesso accessor del fast path (rispetta l'endianness)
435
+ return fieldReaders[field.name](buf);
445
436
  },
446
437
 
447
438
  set(bufOrObj, fieldName, value) {
@@ -459,11 +450,16 @@ export function union(fields, options, sizeof, alloc, readValue, writeValue, _is
459
450
 
460
451
  // Lookup with Map
461
452
  const field = fieldMap.get(fieldName);
462
- if (!field) throw new Error(`Unknown field: ${fieldName}`);
453
+ if (!field) {
454
+ const view = anonymousView(buf, fieldName);
455
+ if (view === undefined) throw new Error(`Unknown field: ${fieldName}`);
456
+ view.def.set(view.buf, fieldName, value);
457
+ return;
458
+ }
463
459
 
464
460
  // Bit field
465
461
  if (field.isBitField) {
466
- _writeBitField(buf, field.offset, field.type, field.bitOffset, field.bitSize, value, sizeof);
462
+ field.writeBits(buf, value);
467
463
  return;
468
464
  }
469
465
 
@@ -485,7 +481,8 @@ export function union(fields, options, sizeof, alloc, readValue, writeValue, _is
485
481
 
486
482
  // Array
487
483
  if (field.isArray) {
488
- if (field.type._charKind !== undefined && typeof value === "string") {
484
+ // Python: bytes / str con il controllo di lunghezza ("bytes too long").
485
+ if (field.type._charKind !== undefined && (typeof value === "string" || (field.type._charKind === "char" && Buffer.isBuffer(value) && value._buffer === undefined))) {
489
486
  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})`);
490
487
  } else if (Buffer.isBuffer(value)) {
491
488
  value.copy(buf, field.offset, 0, field.size);
@@ -507,12 +504,8 @@ export function union(fields, options, sizeof, alloc, readValue, writeValue, _is
507
504
  return;
508
505
  }
509
506
 
510
- // Tipo base — BigEndianUnion path when swapped + primitive
511
- if (swapped && field.type && typeof field.type === "function" && field.type._isSimpleCData && field.type._writerBE) {
512
- field.type._writerBE(buf, field.offset, value);
513
- return;
514
- }
515
- writeValue(buf, field.type, value, field.offset);
507
+ // Tipo base: stesso accessor del fast path (rispetta l'endianness)
508
+ fieldWriters[field.name](buf, value);
516
509
  },
517
510
 
518
511
  toObject(bufOrObj) {
@@ -552,7 +545,7 @@ export function union(fields, options, sizeof, alloc, readValue, writeValue, _is
552
545
  Object.defineProperty(obj, field.name, {
553
546
  get() {
554
547
  if (field.isBitField) {
555
- return _readBitField(buf, 0, field.type, field.bitOffset, field.bitSize, sizeof);
548
+ return field.readBits(buf);
556
549
  } else if (field.isNested) {
557
550
  // Cache nested objects per evitare di ricrearli ogni volta
558
551
  if (!nestedCache.has(field.name)) {
@@ -568,21 +561,17 @@ export function union(fields, options, sizeof, alloc, readValue, writeValue, _is
568
561
  } else if (field.isPointer) {
569
562
  const addr = native.POINTER_SIZE === 8 ? buf.readBigUInt64LE(0) : BigInt(buf.readUInt32LE(0));
570
563
  return pointerOrNull(field.type, addr);
571
- } else if (swapped && typeof field.type === "function" && field.type._isSimpleCData && field.type._readerBE) {
572
- return field.type._readerBE(buf, 0);
573
564
  } else {
574
- return readValue(buf, field.type, 0);
565
+ return fieldReaders[field.name](buf);
575
566
  }
576
567
  },
577
568
  set(value) {
578
569
  if (field.isBitField) {
579
- _writeBitField(buf, 0, field.type, field.bitOffset, field.bitSize, value, sizeof);
570
+ field.writeBits(buf, value);
580
571
  } else if (field.isPointer) {
581
572
  writePointerField(buf, 0, value, native.POINTER_SIZE);
582
- } else if (swapped && typeof field.type === "function" && field.type._isSimpleCData && field.type._writerBE) {
583
- field.type._writerBE(buf, 0, value);
584
573
  } else {
585
- writeValue(buf, field.type, value, 0);
574
+ fieldWriters[field.name](buf, value);
586
575
  }
587
576
  },
588
577
  enumerable: true,
@@ -595,7 +584,7 @@ export function union(fields, options, sizeof, alloc, readValue, writeValue, _is
595
584
 
596
585
  // fromObject: write plain object values into buffer
597
586
  fromObject: function (buf, obj) {
598
- for (const [key, value] of Object.entries(obj)) {
587
+ for (const [key, value] of Object.entries(fieldsOf(obj))) {
599
588
  if (this.fields.some((f) => f.name === key)) {
600
589
  this.set(buf, key, value);
601
590
  }
@@ -22,13 +22,7 @@ import { mirroredAccessors } from "../../memory/mirror.js";
22
22
 
23
23
  // Proprietà meta del Buffer che NON vanno mai interpretate come field name.
24
24
  // Per i campi Proxy passano direttamente attraverso al target buffer.
25
- const BUFFER_META_PROPS = new Set([
26
- "length",
27
- "byteLength",
28
- "byteOffset",
29
- "buffer",
30
- "BYTES_PER_ELEMENT",
31
- ]);
25
+ const BUFFER_META_PROPS = new Set(["length", "byteLength", "byteOffset", "buffer", "BYTES_PER_ELEMENT"]);
32
26
 
33
27
  // L'handler dipende solo da def e opzioni (il Buffer è il target): uno per
34
28
  // combinazione, invece di ricrearlo a ogni accesso a un campo annidato.
@@ -104,10 +98,7 @@ function createWrapper(def, instanceTag, exposeAnonymous, mirrored) {
104
98
  if (r !== undefined) return r(target);
105
99
  }
106
100
  // FALLBACK: tipi complessi (nested/array) e anonymous subfields.
107
- if (
108
- fieldMap?.has(prop) ||
109
- (exposeAnonymous && anonymousFieldNames?.[prop] === true)
110
- ) {
101
+ if (fieldMap?.has(prop) || (exposeAnonymous && anonymousFieldNames?.[prop] === true)) {
111
102
  return def.get(target, prop);
112
103
  }
113
104
  }
@@ -126,10 +117,7 @@ function createWrapper(def, instanceTag, exposeAnonymous, mirrored) {
126
117
  return true;
127
118
  }
128
119
  }
129
- if (
130
- fieldMap?.has(prop) ||
131
- (exposeAnonymous && anonymousFieldNames?.[prop] === true)
132
- ) {
120
+ if (fieldMap?.has(prop) || (exposeAnonymous && anonymousFieldNames?.[prop] === true)) {
133
121
  def.set(target, prop, value);
134
122
  return true;
135
123
  }