node-ctypes 2.1.1 → 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.
Files changed (36) hide show
  1. package/README.md +98 -13
  2. package/build/Release/ctypes-darwin-arm64.node +0 -0
  3. package/build/Release/ctypes-darwin-x64.node +0 -0
  4. package/build/Release/ctypes-linux-arm64-musl.node +0 -0
  5. package/build/Release/ctypes-linux-arm64.node +0 -0
  6. package/build/Release/ctypes-linux-x64-musl.node +0 -0
  7. package/build/Release/ctypes-linux-x64.node +0 -0
  8. package/build/Release/ctypes-win32-arm64.node +0 -0
  9. package/build/Release/ctypes-win32-x64.node +0 -0
  10. package/lib/core/Library.js +86 -76
  11. package/lib/core/callback.js +10 -17
  12. package/lib/core/conversions.js +193 -3
  13. package/lib/core/funcptr.js +67 -52
  14. package/lib/core/lazy-loader.js +10 -4
  15. package/lib/core/types.js +196 -98
  16. package/lib/index.d.ts +193 -47
  17. package/lib/index.js +51 -28
  18. package/lib/memory/buffer.js +66 -19
  19. package/lib/memory/mirror.js +283 -0
  20. package/lib/memory/operations.js +59 -42
  21. package/lib/memory/pointer.js +180 -61
  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/structures/Structure.js +260 -172
  26. package/lib/structures/Union.js +10 -21
  27. package/lib/structures/helpers/array.js +235 -92
  28. package/lib/structures/helpers/bitfield.js +66 -150
  29. package/lib/structures/helpers/common.js +115 -15
  30. package/lib/structures/helpers/layout.js +131 -0
  31. package/lib/structures/helpers/struct.js +144 -400
  32. package/lib/structures/helpers/union.js +132 -142
  33. package/lib/structures/helpers/wrap.js +29 -17
  34. package/lib/types/SimpleCData.js +14 -7
  35. package/lib/types/primitives.js +130 -101
  36. package/package.json +2 -1
@@ -106,6 +106,8 @@
106
106
  */
107
107
  import { encodeWide, decodeWide } from "../../memory/buffer.js";
108
108
  import { funcPtrFieldType, writePointerField } from "./common.js";
109
+ import { buildWrapper } from "./wrap.js";
110
+ import { flush, isMirror, mirrorsActive, refresh } from "../../memory/mirror.js";
109
111
 
110
112
  // Python: gli array di c_char / c_wchar (anche come campi struct) hanno un
111
113
  // `.value` stringa fino al primo NUL; quelli di c_char anche `.raw` (bytes).
@@ -129,17 +131,67 @@ function setCharArrayValue(buf, charKind, wcharSize, value, message) {
129
131
  }
130
132
  }
131
133
 
132
- export function array(elementType, count, sizeof, alloc, readValue, writeValue, Structure, Union, ArrayType, voidPointerType) {
134
+ // Metodi di Array che sul proxy operano sugli elementi (Python: arr[1:3],
135
+ // x in arr, list(arr)), non sui byte del Buffer: le versioni generiche di
136
+ // Array.prototype usano `length` e gli indici del proxy. I metodi propri di
137
+ // Buffer/TypedArray (readInt32LE, subarray, copy, ...) restano sui byte.
138
+ const elementMethods = new Map(
139
+ [
140
+ "at",
141
+ "copyWithin",
142
+ "entries",
143
+ "every",
144
+ "fill",
145
+ "filter",
146
+ "find",
147
+ "findIndex",
148
+ "findLast",
149
+ "findLastIndex",
150
+ "forEach",
151
+ "includes",
152
+ "indexOf",
153
+ "join",
154
+ "keys",
155
+ "lastIndexOf",
156
+ "map",
157
+ "reduce",
158
+ "reduceRight",
159
+ "reverse",
160
+ "slice",
161
+ "some",
162
+ "sort",
163
+ "toLocaleString",
164
+ "toReversed",
165
+ "toSorted",
166
+ "values",
167
+ "with",
168
+ ]
169
+ .filter((name) => typeof Array.prototype[name] === "function")
170
+ .map((name) => [name, Array.prototype[name]]),
171
+ );
172
+
173
+ function elementsToJSON() {
174
+ return Array.from(this);
175
+ }
176
+
177
+ // Python: lo slice di c_char * n / c_wchar * n è bytes / str.
178
+ function charSlice(...args) {
179
+ return Array.prototype.slice.apply(this, args).join("");
180
+ }
181
+
182
+ export function array(elementType, count, sizeof, alloc, readValue, writeValue, Structure, Union, ArrayType, voidPointerType, ptrToBuffer) {
133
183
  // Validate elementType: accept SimpleCData classes, Structure/Union classes,
134
184
  // or native CType-like objects.
135
185
  const isSimple = typeof elementType === "function" && elementType._isSimpleCData;
136
186
  const isStruct = typeof elementType === "function" && (elementType.prototype instanceof Structure || elementType.prototype instanceof Union);
137
187
  // Array di puntatori (Python: POINTER(T) * n, CFUNCTYPE * n).
138
188
  const isPointerElem = (typeof elementType === "object" && elementType !== null && elementType._pointerTo !== undefined) || (typeof elementType === "function" && elementType._isFuncPtr === true);
139
- const isNativeTypeObj = !isPointerElem && typeof elementType === "object" && elementType !== null && (typeof elementType.getSize === "function" || elementType.size !== undefined);
189
+ // Definizione di struct()/union(): come una classe Structure/Union.
190
+ const isStructDef = !isPointerElem && typeof elementType === "object" && elementType !== null && elementType._isStructType === true;
191
+ const isNativeTypeObj = !isPointerElem && !isStructDef && typeof elementType === "object" && elementType !== null && (typeof elementType.getSize === "function" || elementType.size !== undefined);
140
192
  // Array di array (Python: (c_int * 2) * 3).
141
193
  const isArrayElem = typeof elementType === "function" && elementType._isArrayType === true;
142
- if (!isSimple && !isStruct && !isNativeTypeObj && !isArrayElem && !isPointerElem) {
194
+ if (!isSimple && !isStruct && !isStructDef && !isNativeTypeObj && !isArrayElem && !isPointerElem) {
143
195
  throw new TypeError("array elementType must be a SimpleCData class or a Structure/Union class");
144
196
  }
145
197
 
@@ -147,7 +199,7 @@ export function array(elementType, count, sizeof, alloc, readValue, writeValue,
147
199
  // Array alignment == element alignment (C standard), NOT element size.
148
200
  // For Structure/Union: ask the class. For SimpleCData: alignment == size
149
201
  // (each primitive is self-aligned on all platforms we target).
150
- const elementAlignment = isStruct ? (elementType.alignment ?? elementSize) : isArrayElem ? elementType.getAlignment() : elementSize;
202
+ const elementAlignment = isStruct ? (elementType.alignment ?? elementSize) : isStructDef ? elementType.alignment : isArrayElem ? elementType.getAlignment() : elementSize;
151
203
  let nativeArray;
152
204
  if (isPointerElem && ArrayType && voidPointerType) {
153
205
  nativeArray = new ArrayType(voidPointerType._type, count);
@@ -194,6 +246,7 @@ export function array(elementType, count, sizeof, alloc, readValue, writeValue,
194
246
  if (bytes.length > buf.length) throw new RangeError("byte string too long");
195
247
  bytes.copy(buf);
196
248
  };
249
+ const getRaw = (buf) => Buffer.from(buf);
197
250
 
198
251
  // Elementi puntatore: NULL → null, altrimenti oggetto puntatore / funzione.
199
252
  const pointerElemType = !isPointerElem ? null : typeof elementType === "function" ? funcPtrFieldType(elementType) : elementType;
@@ -212,6 +265,10 @@ export function array(elementType, count, sizeof, alloc, readValue, writeValue,
212
265
  if (isStructElem) {
213
266
  return new elementType(target.subarray(off, off + elementSize));
214
267
  }
268
+ if (isStructDef) {
269
+ const view = target.subarray(off, off + elementSize);
270
+ return new Proxy(view, buildWrapper(elementType, { instanceTag: "NestedStructInstance", exposeAnonymous: true, mirrored: isMirror(view) }));
271
+ }
215
272
  if (isArrayElem) {
216
273
  return elementType.wrap(target.subarray(off, off + elementSize));
217
274
  }
@@ -249,6 +306,43 @@ export function array(elementType, count, sizeof, alloc, readValue, writeValue,
249
306
  return false;
250
307
  };
251
308
 
309
+ // Array su una copia della memoria nativa (memory/mirror.js): un elemento
310
+ // scalare o puntatore si rilegge prima di leggerlo e si ricopia dopo averlo
311
+ // scritto (viene sovrascritto per intero). Gli elementi struct e array sono
312
+ // istanze che si sincronizzano da sole.
313
+ const scalarElem = !isStructElem && !isStructDef && !isArrayElem;
314
+ const mirroredReadAt = (target, index) => {
315
+ if (scalarElem && index >= 0 && index < count) refresh(target, index * elementSize, elementSize);
316
+ return readAt(target, index);
317
+ };
318
+ const mirroredWriteAt = (target, index, value) => {
319
+ const result = writeAt(target, index, value);
320
+ if (result && (scalarElem || (isArrayElem && (Buffer.isBuffer(value) || Buffer.isBuffer(value?._buffer))))) {
321
+ flush(target, index * elementSize, elementSize);
322
+ }
323
+ return result;
324
+ };
325
+ const synced =
326
+ (fn) =>
327
+ (buf, ...args) => {
328
+ refresh(buf);
329
+ const result = fn(buf, ...args);
330
+ flush(buf);
331
+ return result;
332
+ };
333
+ const mirroredGetValue =
334
+ getValue &&
335
+ ((buf) => {
336
+ refresh(buf);
337
+ return getValue(buf);
338
+ });
339
+ const mirroredSetValue = setValue && synced(setValue);
340
+ const mirroredSetRaw = synced(setRaw);
341
+ const mirroredGetRaw = (buf) => {
342
+ refresh(buf);
343
+ return Buffer.from(buf);
344
+ };
345
+
252
346
  // Indice da una chiave che inizia con una cifra (il caso comune arr[i]);
253
347
  // NaN per tutto il resto, che segue il percorso generico.
254
348
  const fastIndex = (prop) => {
@@ -262,109 +356,120 @@ export function array(elementType, count, sizeof, alloc, readValue, writeValue,
262
356
  return NaN;
263
357
  };
264
358
 
265
- // Wrap function that returns a Proxy for array-like indexing
266
- const wrap = function (buffer) {
267
- return new Proxy(buffer, {
268
- get(target, prop, receiver) {
269
- const fast = fastIndex(prop);
270
- if (fast === fast) {
271
- return readAt(target, fast);
272
- }
273
-
274
- if (charKind !== undefined) {
275
- if (prop === "value") return getValue(target);
276
- if (prop === "raw" && charKind === "char") return Buffer.from(target);
277
- }
278
-
279
- // Special case for _buffer to return the underlying buffer
280
- if (prop === "_buffer") {
281
- return target;
282
- }
359
+ // Proxy handler for array-like indexing: one per array type (and one for
360
+ // copies of native memory), the buffer is the target.
361
+ const makeHandler = (readAt, writeAt, getValue, setValue, setRaw, getRaw) => ({
362
+ get(target, prop, receiver) {
363
+ const fast = fastIndex(prop);
364
+ if (fast === fast) {
365
+ return readAt(target, fast);
366
+ }
283
367
 
284
- // Python ctypes parity: `len(arr)` ritorna il numero di elementi,
285
- // non la dimensione in byte del buffer. Senza questo trap,
286
- // `arr.length` casca sul buffer sottostante e ritorna byte count,
287
- // rompendo il pattern idiomatico `for (let i = 0; i < arr.length; i++)`.
288
- if (prop === "length") return count;
289
- if (prop === "byteLength") return target.length;
290
-
291
- // Special case for toString to show array contents
292
- if (prop === "toString") {
293
- return function () {
294
- try {
295
- const arr = Array.from(this);
296
- return `[${arr.join(", ")}]`;
297
- } catch (e) {
298
- return "[error]";
299
- }
300
- }.bind(receiver);
301
- }
368
+ if (charKind !== undefined) {
369
+ if (prop === "value") return getValue(target);
370
+ if (prop === "raw" && charKind === "char") return getRaw(target);
371
+ }
302
372
 
303
- // Intercept Symbol.iterator to iterate over elements, not bytes
304
- if (prop === Symbol.iterator) {
305
- return function* () {
306
- for (let i = 0; i < count; i++) {
307
- yield readAt(target, i);
308
- }
309
- };
310
- }
373
+ // Special case for _buffer to return the underlying buffer
374
+ if (prop === "_buffer") {
375
+ return target;
376
+ }
377
+ // Tipo dell'array (controllo degli argomenti: Python accetta solo
378
+ // istanze dello stesso tipo array).
379
+ if (prop === "_arrayType") {
380
+ return ArrayCType;
381
+ }
311
382
 
312
- // Ignore other Symbols
313
- if (typeof prop === "symbol") {
314
- const value = Reflect.get(target, prop, target);
315
- if (typeof value === "function") {
316
- return value.bind(target);
383
+ // Python ctypes parity: `len(arr)` ritorna il numero di elementi,
384
+ // non la dimensione in byte del buffer. Senza questo trap,
385
+ // `arr.length` casca sul buffer sottostante e ritorna byte count,
386
+ // rompendo il pattern idiomatico `for (let i = 0; i < arr.length; i++)`.
387
+ if (prop === "length") return count;
388
+ if (prop === "byteLength") return target.length;
389
+
390
+ // Special case for toString to show array contents
391
+ if (prop === "toString") {
392
+ return function () {
393
+ try {
394
+ const arr = Array.from(this);
395
+ return `[${arr.join(", ")}]`;
396
+ } catch (e) {
397
+ return "[error]";
317
398
  }
318
- return value;
319
- }
399
+ }.bind(receiver);
400
+ }
320
401
 
321
- // If it's a number (index) - intercept BEFORE checking target
322
- const index = Number(prop);
323
- if (Number.isInteger(index) && !isNaN(index)) {
324
- return readAt(target, index);
325
- }
402
+ // Intercept Symbol.iterator to iterate over elements, not bytes
403
+ if (prop === Symbol.iterator) {
404
+ return function* () {
405
+ for (let i = 0; i < count; i++) {
406
+ yield readAt(target, i);
407
+ }
408
+ };
409
+ }
326
410
 
327
- // For everything else, use the normal buffer
411
+ // Ignore other Symbols
412
+ if (typeof prop === "symbol") {
328
413
  const value = Reflect.get(target, prop, target);
329
- // If it's a function, bind it to the target
330
414
  if (typeof value === "function") {
331
415
  return value.bind(target);
332
416
  }
333
417
  return value;
334
- },
335
- set(target, prop, value) {
336
- const fast = fastIndex(prop);
337
- if (fast === fast) {
338
- return writeAt(target, fast, value);
339
- }
418
+ }
340
419
 
341
- if (charKind !== undefined) {
342
- if (prop === "value") {
343
- setValue(target, value);
344
- return true;
345
- }
346
- if (prop === "raw" && charKind === "char") {
347
- setRaw(target, value);
348
- return true;
349
- }
350
- }
420
+ // If it's a number (index) - intercept BEFORE checking target
421
+ const index = Number(prop);
422
+ if (Number.isInteger(index) && !isNaN(index)) {
423
+ return readAt(target, index);
424
+ }
351
425
 
352
- // Ignore Symbols
353
- if (typeof prop === "symbol") {
354
- return Reflect.set(target, prop, value, target);
355
- }
426
+ const method = elementMethods.get(prop);
427
+ if (method !== undefined) return charKind !== undefined && prop === "slice" ? charSlice : method;
428
+ if (prop === "toJSON") return elementsToJSON;
356
429
 
357
- // `length`/`byteLength` sono read-only (parity Python Array).
358
- if (prop === "length" || prop === "byteLength") return false;
430
+ // For everything else, use the normal buffer
431
+ const value = Reflect.get(target, prop, target);
432
+ // If it's a function, bind it to the target
433
+ if (typeof value === "function") {
434
+ return value.bind(target);
435
+ }
436
+ return value;
437
+ },
438
+ set(target, prop, value) {
439
+ const fast = fastIndex(prop);
440
+ if (fast === fast) {
441
+ return writeAt(target, fast, value);
442
+ }
359
443
 
360
- const index = Number(prop);
361
- if (Number.isInteger(index) && !isNaN(index)) {
362
- return writeAt(target, index, value);
444
+ if (charKind !== undefined) {
445
+ if (prop === "value") {
446
+ setValue(target, value);
447
+ return true;
448
+ }
449
+ if (prop === "raw" && charKind === "char") {
450
+ setRaw(target, value);
451
+ return true;
363
452
  }
453
+ }
454
+
455
+ // Ignore Symbols
456
+ if (typeof prop === "symbol") {
364
457
  return Reflect.set(target, prop, value, target);
365
- },
366
- });
367
- };
458
+ }
459
+
460
+ // `length`/`byteLength` sono read-only (parity Python Array).
461
+ if (prop === "length" || prop === "byteLength") return false;
462
+
463
+ const index = Number(prop);
464
+ if (Number.isInteger(index) && !isNaN(index)) {
465
+ return writeAt(target, index, value);
466
+ }
467
+ return Reflect.set(target, prop, value, target);
468
+ },
469
+ });
470
+ const handler = makeHandler(readAt, writeAt, getValue, setValue, setRaw, getRaw);
471
+ const mirroredHandler = mirrorsActive ? makeHandler(mirroredReadAt, mirroredWriteAt, mirroredGetValue, mirroredSetValue, mirroredSetRaw, mirroredGetRaw) : null;
472
+ const wrap = (buffer) => new Proxy(buffer, mirroredHandler !== null && isMirror(buffer) ? mirroredHandler : handler);
368
473
 
369
474
  // create automatically returns the proxy
370
475
  const create = (values) => {
@@ -373,6 +478,9 @@ export function array(elementType, count, sizeof, alloc, readValue, writeValue,
373
478
  for (let i = 0; i < Math.min(values.length, count); i++) {
374
479
  writeAt(buffer, i, values[i]);
375
480
  }
481
+ } else if (typeof values === "string" && setValue !== undefined) {
482
+ // c_char * n / c_wchar * n: stessa codifica di `.value` (UTF-8 / wchar_t).
483
+ setValue(buffer, values);
376
484
  } else if (typeof values === "string") {
377
485
  for (let i = 0; i < Math.min(values.length, count); i++) {
378
486
  writeAt(buffer, i, values.charCodeAt(i));
@@ -381,6 +489,36 @@ export function array(elementType, count, sizeof, alloc, readValue, writeValue,
381
489
  return wrap(buffer);
382
490
  };
383
491
 
492
+ // Python: (c_int * 3).from_buffer / from_buffer_copy / from_address.
493
+ const byteSize = count * elementSize;
494
+ const bytesOf = (source, name) => {
495
+ const bytes = source !== null && typeof source === "object" && Buffer.isBuffer(source._buffer) ? source._buffer : source;
496
+ if (!(bytes instanceof Uint8Array)) throw new TypeError(`${name}: source must be a Buffer or a ctypes instance`);
497
+ return bytes;
498
+ };
499
+ const checkRange = (bytes, offset, name) => {
500
+ if (!Number.isInteger(offset) || offset < 0) throw new RangeError(`${name}: offset must be a non-negative integer`);
501
+ if (bytes.byteLength - offset < byteSize) throw new RangeError(`${name}: source too small (${bytes.byteLength - offset} < ${byteSize})`);
502
+ };
503
+ const from_buffer = (source, offset = 0) => {
504
+ const bytes = bytesOf(source, "from_buffer");
505
+ checkRange(bytes, offset, "from_buffer");
506
+ const view = Buffer.from(bytes.buffer, bytes.byteOffset + offset, byteSize);
507
+ return wrap(view);
508
+ };
509
+ const from_buffer_copy = (source, offset = 0) => {
510
+ const bytes = bytesOf(source, "from_buffer_copy");
511
+ checkRange(bytes, offset, "from_buffer_copy");
512
+ const copy = alloc(byteSize);
513
+ copy.set(bytes.subarray(offset, offset + byteSize));
514
+ return wrap(copy);
515
+ };
516
+ const from_address = (address) => {
517
+ if (!address) throw new TypeError("from_address: NULL address");
518
+ if (byteSize === 0) return wrap(alloc(0));
519
+ return wrap(ptrToBuffer(typeof address === "bigint" ? address : BigInt(address), byteSize));
520
+ };
521
+
384
522
  // Python: il tipo array si chiama con gli elementi, (c_int * 3)(1, 2, 3)
385
523
  // → array(c_int, 3)(1, 2, 3) (anche con `new`). `.create([...])` resta.
386
524
  const ArrayCType = function (...values) {
@@ -404,10 +542,15 @@ export function array(elementType, count, sizeof, alloc, readValue, writeValue,
404
542
  // Explicit wrap method
405
543
  wrap: { value: wrap, enumerable: true },
406
544
 
545
+ // Python ctypes: instances on existing memory
546
+ from_buffer: { value: from_buffer, enumerable: true },
547
+ from_buffer_copy: { value: from_buffer_copy, enumerable: true },
548
+ from_address: { value: from_address, enumerable: true },
549
+
407
550
  // Array di caratteri: tipo e conversione da/verso stringa (campi struct).
408
551
  _charKind: { value: charKind },
409
- getValue: { value: getValue },
410
- setValue: { value: setValue },
552
+ getValue: { value: mirrorsActive && getValue ? (buf) => (isMirror(buf) ? mirroredGetValue : getValue)(buf) : getValue },
553
+ setValue: { value: mirrorsActive && setValue ? (buf, ...args) => (isMirror(buf) ? mirroredSetValue : setValue)(buf, ...args) : setValue },
411
554
 
412
555
  // For compatibility, expose the native array (needed for StructType.addField)
413
556
  _native: { value: nativeArray },
@@ -1,165 +1,81 @@
1
1
  /**
2
- * @file bitfield-helpers.js
3
- * @module structures/bitfield-helpers
4
- * @description Helper functions for reading and writing bitfield values in structs.
2
+ * @file bitfield.js
3
+ * @module structures/helpers/bitfield
4
+ * @description Readers and writers of bitfields in structs and unions.
5
5
  *
6
- * This module provides low-level bitfield manipulation functions used by struct
7
- * and union implementations to pack multiple small integer values into single bytes.
8
- *
9
- * @example
10
- * ```javascript
11
- * import { _readBitField, _writeBitField } from './structures/bitfield-helpers.js';
12
- *
13
- * const buf = Buffer.alloc(4);
14
- * _writeBitField(buf, 0, c_uint32, 0, 3, 5); // Write 5 to bits 0-2
15
- * const value = _readBitField(buf, 0, c_uint32, 0, 3); // Read bits 0-2
16
- * ```
17
- */
18
-
19
- /**
20
- * Reads an unsigned integer value from a buffer.
21
- *
22
- * @param {Buffer} buf - Buffer to read from
23
- * @param {number} offset - Byte offset in buffer
24
- * @param {number} byteSize - Size in bytes (1, 2, 4, or 8)
25
- * @param {Function} sizeof - sizeof function reference
26
- * @returns {number|bigint} Value read from buffer
27
- * @throws {Error} If byteSize is not supported
28
- * @private
6
+ * A bitfield is `bitSize` bits at `bitOffset` inside an allocation unit of
7
+ * its base type (`baseSize` bytes at `offset`), as computed by layout.js.
8
+ * Values are truncated to the field width on write; signed base types are
9
+ * sign-extended on read, as in Python ctypes. Fields up to 53 bits read as
10
+ * numbers, wider ones (only possible with 64-bit base types) as BigInt.
29
11
  */
30
- export function _readUintFromBuffer(buf, offset, byteSize) {
31
- switch (byteSize) {
32
- case 1:
33
- return buf.readUInt8(offset);
34
- case 2:
35
- return buf.readUInt16LE(offset);
36
- case 4:
37
- return buf.readUInt32LE(offset);
38
- case 8:
39
- return buf.readBigUInt64LE(offset);
40
- default:
41
- throw new Error(`Unsupported byte size: ${byteSize}`);
42
- }
43
- }
44
12
 
45
- /**
46
- * Writes an unsigned integer value to a buffer.
47
- *
48
- * @param {Buffer} buf - Buffer to write to
49
- * @param {number} offset - Byte offset in buffer
50
- * @param {number} byteSize - Size in bytes (1, 2, 4, or 8)
51
- * @param {number|bigint} value - Value to write
52
- * @throws {Error} If byteSize is not supported
53
- * @private
54
- */
55
- export function _writeUintToBuffer(buf, offset, byteSize, value) {
56
- switch (byteSize) {
57
- case 1:
58
- buf.writeUInt8(value, offset);
59
- break;
60
- case 2:
61
- buf.writeUInt16LE(value, offset);
62
- break;
63
- case 4:
64
- buf.writeUInt32LE(value, offset);
65
- break;
66
- case 8:
67
- buf.writeBigUInt64LE(value, offset);
68
- break;
69
- default:
70
- throw new Error(`Unsupported byte size: ${byteSize}`);
71
- }
72
- }
13
+ const readers = {
14
+ 1: { le: (buf, off) => buf.readUInt8(off), be: (buf, off) => buf.readUInt8(off) },
15
+ 2: { le: (buf, off) => buf.readUInt16LE(off), be: (buf, off) => buf.readUInt16BE(off) },
16
+ 4: { le: (buf, off) => buf.readUInt32LE(off), be: (buf, off) => buf.readUInt32BE(off) },
17
+ 8: { le: (buf, off) => buf.readBigUInt64LE(off), be: (buf, off) => buf.readBigUInt64BE(off) },
18
+ };
73
19
 
74
- /**
75
- * Reads a bitfield value from a buffer.
76
- *
77
- * Extracts a specific range of bits from an integer value stored in memory.
78
- * Used by struct/union implementations to support packed bitfields.
79
- *
80
- * @param {Buffer} buf - Buffer to read from
81
- * @param {number} offset - Byte offset of the containing integer
82
- * @param {Function|Object} baseType - Base integer type (c_uint8, c_uint16, c_uint32, c_uint64)
83
- * @param {number} bitOffset - Starting bit position (0-based)
84
- * @param {number} bitSize - Number of bits to read
85
- * @param {Function} sizeof - sizeof function reference
86
- * @returns {number} Extracted bitfield value
87
- *
88
- * @example
89
- * ```javascript
90
- * // Read 3-bit field starting at bit 5
91
- * const value = _readBitField(buf, 0, c_uint32, 5, 3);
92
- * ```
93
- * @private
94
- */
95
- export function _readBitField(buf, offset, baseType, bitOffset, bitSize, sizeof) {
96
- const baseSize = sizeof(baseType);
97
- const value = _readUintFromBuffer(buf, offset, baseSize);
98
- // Parity Python ctypes: base type signed → sign-extend. `c_int8, 3`
99
- // con valore -1 (= 0b111 nei 3 bit) deve rileggere -1, non 7.
100
- const isSigned = baseType?._signed === true;
20
+ const writers = {
21
+ 1: { le: (buf, off, v) => buf.writeUInt8(v, off), be: (buf, off, v) => buf.writeUInt8(v, off) },
22
+ 2: { le: (buf, off, v) => buf.writeUInt16LE(v, off), be: (buf, off, v) => buf.writeUInt16BE(v, off) },
23
+ 4: { le: (buf, off, v) => buf.writeUInt32LE(v, off), be: (buf, off, v) => buf.writeUInt32BE(v, off) },
24
+ 8: { le: (buf, off, v) => buf.writeBigUInt64LE(v, off), be: (buf, off, v) => buf.writeBigUInt64BE(v, off) },
25
+ };
101
26
 
102
- if (baseSize === 8) {
103
- const mask = (1n << BigInt(bitSize)) - 1n;
104
- const raw = (value >> BigInt(bitOffset)) & mask;
105
- if (isSigned) {
106
- const signBit = 1n << BigInt(bitSize - 1);
107
- const extend = ~mask;
108
- const signed = (raw & signBit) ? (raw | extend) : raw;
109
- const asNum = Number(signed);
110
- return (asNum >= Number.MIN_SAFE_INTEGER && asNum <= Number.MAX_SAFE_INTEGER)
111
- ? asNum
112
- : signed;
113
- }
114
- return Number(raw);
115
- }
116
- const mask = (1 << bitSize) - 1;
117
- const raw = (value >> bitOffset) & mask;
118
- if (isSigned) {
119
- const signBit = 1 << (bitSize - 1);
120
- const extend = ~mask;
121
- return (raw & signBit) ? (raw | extend) : raw;
122
- }
123
- return raw;
124
- }
27
+ import { notIntegral } from "./common.js";
125
28
 
126
29
  /**
127
- * Writes a bitfield value to a buffer.
128
- *
129
- * Modifies a specific range of bits in an integer value stored in memory,
130
- * preserving other bits. Used by struct/union implementations to support
131
- * packed bitfields.
132
- *
133
- * @param {Buffer} buf - Buffer to write to
134
- * @param {number} offset - Byte offset of the containing integer
135
- * @param {Function|Object} baseType - Base integer type (c_uint8, c_uint16, c_uint32, c_uint64)
136
- * @param {number} bitOffset - Starting bit position (0-based)
137
- * @param {number} bitSize - Number of bits to write
138
- * @param {number} newValue - Value to write (will be masked to bitSize)
139
- * @param {Function} sizeof - sizeof function reference
30
+ * Reader and writer of one bitfield.
140
31
  *
141
- * @example
142
- * ```javascript
143
- * // Write 5 to a 3-bit field starting at bit 2
144
- * _writeBitField(buf, 0, c_uint32, 2, 3, 5);
145
- * ```
146
- * @private
32
+ * @param {Object} field
33
+ * @param {number} field.offset - Byte offset of the allocation unit
34
+ * @param {number} field.baseSize - Size of the base type (1, 2, 4 or 8)
35
+ * @param {number} field.bitOffset - First bit inside the unit
36
+ * @param {number} field.bitSize - Width in bits
37
+ * @param {boolean} [field.signed=false] - Signed base type
38
+ * @param {boolean} [field.bigEndian=false] - Unit stored big-endian
39
+ * @returns {{read: (buf: Buffer) => number|bigint, write: (buf: Buffer, value: number|bigint) => void}}
147
40
  */
148
- export function _writeBitField(buf, offset, baseType, bitOffset, bitSize, newValue, sizeof) {
149
- const baseSize = sizeof(baseType);
150
- let value = _readUintFromBuffer(buf, offset, baseSize);
41
+ export function bitFieldAccessors({ offset, baseSize, bitOffset, bitSize, signed = false, bigEndian = false }) {
42
+ const order = bigEndian ? "be" : "le";
43
+ const readUnit = readers[baseSize]?.[order];
44
+ const writeUnit = writers[baseSize]?.[order];
45
+ if (readUnit === undefined) throw new RangeError(`Unsupported bitfield base size: ${baseSize}`);
151
46
 
152
- // Modify the bits
153
47
  if (baseSize === 8) {
154
- const mask = (1n << BigInt(bitSize)) - 1n;
155
- const clearMask = ~(mask << BigInt(bitOffset));
156
- value = (value & clearMask) | ((BigInt(newValue) & mask) << BigInt(bitOffset));
157
- } else {
158
- const mask = (1 << bitSize) - 1;
159
- const clearMask = ~(mask << bitOffset);
160
- const bits = typeof newValue === "bigint" ? Number(BigInt.asUintN(32, newValue)) : newValue;
161
- value = (value & clearMask) | ((bits & mask) << bitOffset);
48
+ const shift = BigInt(bitOffset);
49
+ const width = BigInt(bitSize);
50
+ const mask = ((1n << width) - 1n) << shift;
51
+ const toValue = bitSize <= 53 ? Number : (v) => v;
52
+ return {
53
+ read: (buf) => {
54
+ const raw = (readUnit(buf, offset) & mask) >> shift;
55
+ return toValue(signed ? BigInt.asIntN(bitSize, raw) : raw);
56
+ },
57
+ write: (buf, value) => {
58
+ if (typeof value === "number" && !Number.isInteger(value)) notIntegral();
59
+ const bits = BigInt.asUintN(bitSize, BigInt(value)) << shift;
60
+ writeUnit(buf, offset, (readUnit(buf, offset) & ~mask) | bits);
61
+ },
62
+ };
162
63
  }
163
64
 
164
- _writeUintToBuffer(buf, offset, baseSize, value);
65
+ // Units up to 32 bits: >>> 0 keeps the results unsigned (also for 32-bit fields).
66
+ const fieldMask = bitSize === 32 ? 0xffffffff : 2 ** bitSize - 1;
67
+ const unitMask = (fieldMask * 2 ** bitOffset) >>> 0;
68
+ const unsignedValue = (value) => {
69
+ if (typeof value === "bigint") return Number(BigInt.asUintN(bitSize, value)) >>> 0;
70
+ if (typeof value === "number" && !Number.isInteger(value)) notIntegral();
71
+ return (Number(value) & fieldMask) >>> 0;
72
+ };
73
+ const signShift = 32 - bitSize;
74
+ return {
75
+ read: signed ? (buf) => (((readUnit(buf, offset) & unitMask) >>> bitOffset) << signShift) >> signShift : (buf) => (readUnit(buf, offset) & unitMask) >>> bitOffset,
76
+ write: (buf, value) => {
77
+ const bits = (unsignedValue(value) << bitOffset) >>> 0;
78
+ writeUnit(buf, offset, ((readUnit(buf, offset) & ~unitMask) | bits) >>> 0);
79
+ },
80
+ };
165
81
  }