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.
- package/CHANGELOG.md +932 -0
- package/README.md +504 -99
- package/build/Release/ctypes-darwin-arm64.node +0 -0
- package/build/Release/ctypes-darwin-x64.node +0 -0
- package/build/Release/ctypes-linux-arm64-musl.node +0 -0
- package/build/Release/ctypes-linux-arm64.node +0 -0
- package/build/Release/ctypes-linux-x64-musl.node +0 -0
- package/build/Release/ctypes-linux-x64.node +0 -0
- package/build/Release/ctypes-win32-arm64.node +0 -0
- package/build/Release/ctypes-win32-x64.node +0 -0
- package/lib/core/Library.js +136 -109
- package/lib/core/callback.js +17 -20
- package/lib/core/conversions.js +376 -16
- package/lib/core/funcptr.js +148 -73
- package/lib/core/lazy-loader.js +10 -4
- package/lib/core/types.js +201 -98
- package/lib/index.d.ts +276 -83
- package/lib/index.js +44 -32
- package/lib/memory/buffer.js +82 -22
- package/lib/memory/operations.js +55 -45
- package/lib/memory/pointer.js +233 -57
- package/lib/platform/constants.js +0 -1
- package/lib/platform/errors.js +48 -4
- package/lib/platform/find_library.js +78 -19
- package/lib/platform/win_types.js +8 -3
- package/lib/structures/Structure.js +252 -203
- package/lib/structures/Union.js +10 -21
- package/lib/structures/helpers/array.js +102 -16
- package/lib/structures/helpers/bitfield.js +75 -150
- package/lib/structures/helpers/common.js +310 -21
- package/lib/structures/helpers/layout.js +145 -0
- package/lib/structures/helpers/struct.js +160 -419
- package/lib/structures/helpers/union.js +154 -155
- package/lib/structures/helpers/wrap.js +3 -15
- package/lib/types/SimpleCData.js +11 -32
- package/lib/types/primitives.js +160 -113
- package/lib/utils/cache.js +34 -2
- package/package.json +4 -1
|
@@ -105,24 +105,30 @@
|
|
|
105
105
|
* ```
|
|
106
106
|
*/
|
|
107
107
|
import { encodeWide, decodeWide } from "../../memory/buffer.js";
|
|
108
|
-
import { funcPtrFieldType, writePointerField } from "./common.js";
|
|
108
|
+
import { copyInstance, funcPtrFieldType, pointerOwner, scalarReader, simpleFieldWriter, writePointerField } from "./common.js";
|
|
109
|
+
import { buildWrapper } from "./wrap.js";
|
|
109
110
|
import { flush, isMirror, mirrorsActive, refresh } from "../../memory/mirror.js";
|
|
110
111
|
|
|
111
112
|
// Python: gli array di c_char / c_wchar (anche come campi struct) hanno un
|
|
112
113
|
// `.value` stringa fino al primo NUL; quelli di c_char anche `.raw` (bytes).
|
|
113
|
-
function charArrayValue(buf, charKind, wcharSize) {
|
|
114
|
+
function charArrayValue(buf, charKind, wcharSize, swapped) {
|
|
114
115
|
if (charKind === "char") {
|
|
115
116
|
const end = buf.indexOf(0);
|
|
116
117
|
return buf.toString("utf8", 0, end === -1 ? buf.length : end);
|
|
117
118
|
}
|
|
119
|
+
if (swapped) {
|
|
120
|
+
buf = Buffer.from(buf);
|
|
121
|
+
wcharSize === 2 ? buf.swap16() : buf.swap32();
|
|
122
|
+
}
|
|
118
123
|
return decodeWide(buf, wcharSize);
|
|
119
124
|
}
|
|
120
125
|
|
|
121
|
-
function setCharArrayValue(buf, charKind, wcharSize, value, message) {
|
|
126
|
+
function setCharArrayValue(buf, charKind, wcharSize, value, message, swapped) {
|
|
122
127
|
const units = charKind === "char" ? (Buffer.isBuffer(value) ? value : Buffer.from(String(value), "utf8")) : encodeWide(String(value), wcharSize);
|
|
123
128
|
if (units.length > buf.length) {
|
|
124
129
|
throw new RangeError(message(units.length / (charKind === "char" ? 1 : wcharSize), buf.length / (charKind === "char" ? 1 : wcharSize)));
|
|
125
130
|
}
|
|
131
|
+
if (swapped && charKind === "wchar") wcharSize === 2 ? units.swap16() : units.swap32();
|
|
126
132
|
units.copy(buf);
|
|
127
133
|
const unit = charKind === "char" ? 1 : wcharSize;
|
|
128
134
|
if (units.length + unit <= buf.length) {
|
|
@@ -130,25 +136,76 @@ function setCharArrayValue(buf, charKind, wcharSize, value, message) {
|
|
|
130
136
|
}
|
|
131
137
|
}
|
|
132
138
|
|
|
133
|
-
|
|
139
|
+
// Metodi di Array che sul proxy operano sugli elementi (Python: arr[1:3],
|
|
140
|
+
// x in arr, list(arr)), non sui byte del Buffer: le versioni generiche di
|
|
141
|
+
// Array.prototype usano `length` e gli indici del proxy. I metodi propri di
|
|
142
|
+
// Buffer/TypedArray (readInt32LE, subarray, copy, ...) restano sui byte.
|
|
143
|
+
const elementMethods = new Map(
|
|
144
|
+
[
|
|
145
|
+
"at",
|
|
146
|
+
"copyWithin",
|
|
147
|
+
"entries",
|
|
148
|
+
"every",
|
|
149
|
+
"fill",
|
|
150
|
+
"filter",
|
|
151
|
+
"find",
|
|
152
|
+
"findIndex",
|
|
153
|
+
"findLast",
|
|
154
|
+
"findLastIndex",
|
|
155
|
+
"forEach",
|
|
156
|
+
"includes",
|
|
157
|
+
"indexOf",
|
|
158
|
+
"join",
|
|
159
|
+
"keys",
|
|
160
|
+
"lastIndexOf",
|
|
161
|
+
"map",
|
|
162
|
+
"reduce",
|
|
163
|
+
"reduceRight",
|
|
164
|
+
"reverse",
|
|
165
|
+
"slice",
|
|
166
|
+
"some",
|
|
167
|
+
"sort",
|
|
168
|
+
"toLocaleString",
|
|
169
|
+
"toReversed",
|
|
170
|
+
"toSorted",
|
|
171
|
+
"values",
|
|
172
|
+
"with",
|
|
173
|
+
]
|
|
174
|
+
.filter((name) => typeof Array.prototype[name] === "function")
|
|
175
|
+
.map((name) => [name, Array.prototype[name]]),
|
|
176
|
+
);
|
|
177
|
+
|
|
178
|
+
function elementsToJSON() {
|
|
179
|
+
return Array.from(this);
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
// Python: lo slice di c_char * n / c_wchar * n è bytes / str.
|
|
183
|
+
function charSlice(...args) {
|
|
184
|
+
return Array.prototype.slice.apply(this, args).join("");
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
export function array(elementType, count, sizeof, alloc, readValue, writeValue, Structure, Union, ArrayType, voidPointerType, ptrToBuffer, swapped = false) {
|
|
134
188
|
// Validate elementType: accept SimpleCData classes, Structure/Union classes,
|
|
135
189
|
// or native CType-like objects.
|
|
136
190
|
const isSimple = typeof elementType === "function" && elementType._isSimpleCData;
|
|
137
191
|
const isStruct = typeof elementType === "function" && (elementType.prototype instanceof Structure || elementType.prototype instanceof Union);
|
|
138
192
|
// Array di puntatori (Python: POINTER(T) * n, CFUNCTYPE * n).
|
|
139
193
|
const isPointerElem = (typeof elementType === "object" && elementType !== null && elementType._pointerTo !== undefined) || (typeof elementType === "function" && elementType._isFuncPtr === true);
|
|
140
|
-
|
|
194
|
+
// Definizione di struct()/union(): come una classe Structure/Union.
|
|
195
|
+
const isStructDef = !isPointerElem && typeof elementType === "object" && elementType !== null && elementType._isStructType === true;
|
|
196
|
+
const isNativeTypeObj = !isPointerElem && !isStructDef && typeof elementType === "object" && elementType !== null && (typeof elementType.getSize === "function" || elementType.size !== undefined);
|
|
141
197
|
// Array di array (Python: (c_int * 2) * 3).
|
|
142
198
|
const isArrayElem = typeof elementType === "function" && elementType._isArrayType === true;
|
|
143
|
-
if (!isSimple && !isStruct && !isNativeTypeObj && !isArrayElem && !isPointerElem) {
|
|
199
|
+
if (!isSimple && !isStruct && !isStructDef && !isNativeTypeObj && !isArrayElem && !isPointerElem) {
|
|
144
200
|
throw new TypeError("array elementType must be a SimpleCData class or a Structure/Union class");
|
|
145
201
|
}
|
|
202
|
+
if (swapped && isArrayElem) elementType = elementType._swappedType ?? elementType;
|
|
146
203
|
|
|
147
204
|
const elementSize = sizeof(elementType);
|
|
148
205
|
// Array alignment == element alignment (C standard), NOT element size.
|
|
149
206
|
// For Structure/Union: ask the class. For SimpleCData: alignment == size
|
|
150
207
|
// (each primitive is self-aligned on all platforms we target).
|
|
151
|
-
const elementAlignment = isStruct ? (elementType.alignment ?? elementSize) : isArrayElem ? elementType.getAlignment() : elementSize;
|
|
208
|
+
const elementAlignment = isStruct ? (elementType.alignment ?? elementSize) : isStructDef ? elementType.alignment : isArrayElem ? elementType.getAlignment() : elementSize;
|
|
152
209
|
let nativeArray;
|
|
153
210
|
if (isPointerElem && ArrayType && voidPointerType) {
|
|
154
211
|
nativeArray = new ArrayType(voidPointerType._type, count);
|
|
@@ -182,14 +239,14 @@ export function array(elementType, count, sizeof, alloc, readValue, writeValue,
|
|
|
182
239
|
// Precalcolati una volta per tipo: l'handler del Proxy li ripeteva ad ogni
|
|
183
240
|
// accesso indicizzato (instanceof Structure/Union + dispatch di readValue).
|
|
184
241
|
const isStructElem = typeof elementType === "function" && (elementType.prototype instanceof Structure || elementType.prototype instanceof Union);
|
|
185
|
-
const elemReader = isSimple ? elementType._reader : null;
|
|
186
|
-
const elemWriter = isSimple ? elementType._writer : null;
|
|
242
|
+
const elemReader = isSimple ? scalarReader(elementType, swapped && elementType._readerBE ? elementType._readerBE : elementType._reader, swapped) : null;
|
|
243
|
+
const elemWriter = isSimple ? simpleFieldWriter(elementType, swapped && elementType._writerBE ? elementType._writerBE : elementType._writer, 0) : null;
|
|
187
244
|
|
|
188
245
|
// Array di caratteri (Python: c_char * n / c_wchar * n): `.value` e `.raw`.
|
|
189
246
|
const charKind = isSimple ? elementType._charKind : undefined;
|
|
190
247
|
const tooLong = charKind === "char" ? () => "byte string too long" : () => "string too long";
|
|
191
|
-
const getValue = charKind === undefined ? undefined : (buf) => charArrayValue(buf, charKind, elementSize);
|
|
192
|
-
const setValue = charKind === undefined ? undefined : (buf, value, message = tooLong) => setCharArrayValue(buf, charKind, elementSize, value, message);
|
|
248
|
+
const getValue = charKind === undefined ? undefined : (buf) => charArrayValue(buf, charKind, elementSize, swapped);
|
|
249
|
+
const setValue = charKind === undefined ? undefined : (buf, value, message = tooLong) => setCharArrayValue(buf, charKind, elementSize, value, message, swapped);
|
|
193
250
|
const setRaw = (buf, value) => {
|
|
194
251
|
const bytes = Buffer.isBuffer(value) ? value : Buffer.from(String(value), "utf8");
|
|
195
252
|
if (bytes.length > buf.length) throw new RangeError("byte string too long");
|
|
@@ -201,7 +258,8 @@ export function array(elementType, count, sizeof, alloc, readValue, writeValue,
|
|
|
201
258
|
const pointerElemType = !isPointerElem ? null : typeof elementType === "function" ? funcPtrFieldType(elementType) : elementType;
|
|
202
259
|
const readPointer = (target, off) => {
|
|
203
260
|
const address = elementSize === 8 ? target.readBigUInt64LE(off) : BigInt(target.readUInt32LE(off));
|
|
204
|
-
|
|
261
|
+
const owner = pointerOwner(target, off, address);
|
|
262
|
+
return address === 0n ? null : pointerElemType.fromAddress(address, owner);
|
|
205
263
|
};
|
|
206
264
|
const writePointer = (target, off, value) => writePointerField(target, off, value, elementSize);
|
|
207
265
|
|
|
@@ -214,6 +272,10 @@ export function array(elementType, count, sizeof, alloc, readValue, writeValue,
|
|
|
214
272
|
if (isStructElem) {
|
|
215
273
|
return new elementType(target.subarray(off, off + elementSize));
|
|
216
274
|
}
|
|
275
|
+
if (isStructDef) {
|
|
276
|
+
const view = target.subarray(off, off + elementSize);
|
|
277
|
+
return new Proxy(view, buildWrapper(elementType, { instanceTag: "NestedStructInstance", exposeAnonymous: true, mirrored: isMirror(view) }));
|
|
278
|
+
}
|
|
217
279
|
if (isArrayElem) {
|
|
218
280
|
return elementType.wrap(target.subarray(off, off + elementSize));
|
|
219
281
|
}
|
|
@@ -235,13 +297,13 @@ export function array(elementType, count, sizeof, alloc, readValue, writeValue,
|
|
|
235
297
|
const inner = target.subarray(off, off + elementSize);
|
|
236
298
|
const source = value !== null && typeof value === "object" && Buffer.isBuffer(value._buffer) ? value._buffer : value;
|
|
237
299
|
if (Buffer.isBuffer(source)) {
|
|
238
|
-
|
|
300
|
+
copyInstance(inner, 0, elementSize, value, 0, elementType);
|
|
239
301
|
} else if (source !== null && typeof source === "object" && typeof source.length === "number") {
|
|
240
302
|
const view = elementType.wrap(inner);
|
|
241
303
|
for (let i = 0; i < Math.min(source.length, elementType.length); i++) view[i] = source[i];
|
|
242
304
|
}
|
|
243
305
|
} else if (elemWriter !== null && off + elementSize <= target.length) {
|
|
244
|
-
elemWriter(target,
|
|
306
|
+
elemWriter(target, value, off);
|
|
245
307
|
} else {
|
|
246
308
|
writeValue(target, elementType, value, off);
|
|
247
309
|
}
|
|
@@ -255,7 +317,7 @@ export function array(elementType, count, sizeof, alloc, readValue, writeValue,
|
|
|
255
317
|
// scalare o puntatore si rilegge prima di leggerlo e si ricopia dopo averlo
|
|
256
318
|
// scritto (viene sovrascritto per intero). Gli elementi struct e array sono
|
|
257
319
|
// istanze che si sincronizzano da sole.
|
|
258
|
-
const scalarElem = !isStructElem && !isArrayElem;
|
|
320
|
+
const scalarElem = !isStructElem && !isStructDef && !isArrayElem;
|
|
259
321
|
const mirroredReadAt = (target, index) => {
|
|
260
322
|
if (scalarElem && index >= 0 && index < count) refresh(target, index * elementSize, elementSize);
|
|
261
323
|
return readAt(target, index);
|
|
@@ -319,6 +381,11 @@ export function array(elementType, count, sizeof, alloc, readValue, writeValue,
|
|
|
319
381
|
if (prop === "_buffer") {
|
|
320
382
|
return target;
|
|
321
383
|
}
|
|
384
|
+
// Tipo dell'array (controllo degli argomenti: Python accetta solo
|
|
385
|
+
// istanze dello stesso tipo array).
|
|
386
|
+
if (prop === "_arrayType") {
|
|
387
|
+
return ArrayCType;
|
|
388
|
+
}
|
|
322
389
|
|
|
323
390
|
// Python ctypes parity: `len(arr)` ritorna il numero di elementi,
|
|
324
391
|
// non la dimensione in byte del buffer. Senza questo trap,
|
|
@@ -363,6 +430,10 @@ export function array(elementType, count, sizeof, alloc, readValue, writeValue,
|
|
|
363
430
|
return readAt(target, index);
|
|
364
431
|
}
|
|
365
432
|
|
|
433
|
+
const method = elementMethods.get(prop);
|
|
434
|
+
if (method !== undefined) return charKind !== undefined && prop === "slice" ? charSlice : method;
|
|
435
|
+
if (prop === "toJSON") return elementsToJSON;
|
|
436
|
+
|
|
366
437
|
// For everything else, use the normal buffer
|
|
367
438
|
const value = Reflect.get(target, prop, target);
|
|
368
439
|
// If it's a function, bind it to the target
|
|
@@ -414,6 +485,9 @@ export function array(elementType, count, sizeof, alloc, readValue, writeValue,
|
|
|
414
485
|
for (let i = 0; i < Math.min(values.length, count); i++) {
|
|
415
486
|
writeAt(buffer, i, values[i]);
|
|
416
487
|
}
|
|
488
|
+
} else if (typeof values === "string" && setValue !== undefined) {
|
|
489
|
+
// c_char * n / c_wchar * n: stessa codifica di `.value` (UTF-8 / wchar_t).
|
|
490
|
+
setValue(buffer, values);
|
|
417
491
|
} else if (typeof values === "string") {
|
|
418
492
|
for (let i = 0; i < Math.min(values.length, count); i++) {
|
|
419
493
|
writeAt(buffer, i, values.charCodeAt(i));
|
|
@@ -443,7 +517,7 @@ export function array(elementType, count, sizeof, alloc, readValue, writeValue,
|
|
|
443
517
|
const bytes = bytesOf(source, "from_buffer_copy");
|
|
444
518
|
checkRange(bytes, offset, "from_buffer_copy");
|
|
445
519
|
const copy = alloc(byteSize);
|
|
446
|
-
copy
|
|
520
|
+
copyInstance(copy, 0, byteSize, bytes, offset, ArrayCType);
|
|
447
521
|
return wrap(copy);
|
|
448
522
|
};
|
|
449
523
|
const from_address = (address) => {
|
|
@@ -457,6 +531,7 @@ export function array(elementType, count, sizeof, alloc, readValue, writeValue,
|
|
|
457
531
|
const ArrayCType = function (...values) {
|
|
458
532
|
return create(values);
|
|
459
533
|
};
|
|
534
|
+
let swappedType;
|
|
460
535
|
|
|
461
536
|
// `length` (numero di elementi) è una proprietà propria non scrivibile delle
|
|
462
537
|
// funzioni: va ridefinita con defineProperties.
|
|
@@ -490,6 +565,17 @@ export function array(elementType, count, sizeof, alloc, readValue, writeValue,
|
|
|
490
565
|
|
|
491
566
|
// Helper to check if this is an ArrayType wrapper
|
|
492
567
|
_isArrayType: { value: true },
|
|
568
|
+
_swapped_: { value: swapped },
|
|
569
|
+
_swappedType: {
|
|
570
|
+
get() {
|
|
571
|
+
if (swapped) return ArrayCType;
|
|
572
|
+
if (swappedType === undefined) {
|
|
573
|
+
swappedType = array(elementType, count, sizeof, alloc, readValue, writeValue, Structure, Union, ArrayType, voidPointerType, ptrToBuffer, true);
|
|
574
|
+
Object.defineProperty(swappedType, "_baseArrayType", { value: ArrayCType });
|
|
575
|
+
}
|
|
576
|
+
return swappedType;
|
|
577
|
+
},
|
|
578
|
+
},
|
|
493
579
|
});
|
|
494
580
|
|
|
495
581
|
return ArrayCType;
|
|
@@ -1,165 +1,90 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @file bitfield
|
|
3
|
-
* @module structures/bitfield
|
|
4
|
-
* @description
|
|
2
|
+
* @file bitfield.js
|
|
3
|
+
* @module structures/helpers/bitfield
|
|
4
|
+
* @description Readers and writers of bitfields in structs and unions.
|
|
5
5
|
*
|
|
6
|
-
*
|
|
7
|
-
*
|
|
8
|
-
*
|
|
9
|
-
*
|
|
10
|
-
*
|
|
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
|
-
* ```
|
|
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.
|
|
17
11
|
*/
|
|
18
12
|
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
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
|
|
29
|
-
*/
|
|
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
|
-
|
|
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
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
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
|
-
|
|
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 { booleanValue, notIntegral } from "./common.js";
|
|
125
28
|
|
|
126
29
|
/**
|
|
127
|
-
*
|
|
30
|
+
* Reader and writer of one bitfield.
|
|
128
31
|
*
|
|
129
|
-
*
|
|
130
|
-
*
|
|
131
|
-
*
|
|
132
|
-
*
|
|
133
|
-
* @param {
|
|
134
|
-
* @param {
|
|
135
|
-
* @param {
|
|
136
|
-
* @param {
|
|
137
|
-
* @
|
|
138
|
-
* @param {number} newValue - Value to write (will be masked to bitSize)
|
|
139
|
-
* @param {Function} sizeof - sizeof function reference
|
|
140
|
-
*
|
|
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
|
+
* @param {boolean} [field.boolean=false] - Normalize and return boolean values
|
|
40
|
+
* @returns {{read: (buf: Buffer) => number|bigint|boolean, write: (buf: Buffer, value: number|bigint|boolean) => void}}
|
|
147
41
|
*/
|
|
148
|
-
export function
|
|
149
|
-
const
|
|
150
|
-
|
|
42
|
+
export function bitFieldAccessors({ offset, baseSize, bitOffset, bitSize, signed = false, bigEndian = false, boolean = false }) {
|
|
43
|
+
const order = bigEndian ? "be" : "le";
|
|
44
|
+
const readUnit = readers[baseSize]?.[order];
|
|
45
|
+
const writeUnit = writers[baseSize]?.[order];
|
|
46
|
+
if (readUnit === undefined) throw new RangeError(`Unsupported bitfield base size: ${baseSize}`);
|
|
47
|
+
const integerValue = (value) => {
|
|
48
|
+
if (boolean) return booleanValue(value) ? 1 : 0;
|
|
49
|
+
if (typeof value === "number") {
|
|
50
|
+
if (!Number.isInteger(value)) notIntegral();
|
|
51
|
+
return value;
|
|
52
|
+
}
|
|
53
|
+
if (typeof value === "bigint" || typeof value === "boolean") return value;
|
|
54
|
+
throw new TypeError(`'${value === null ? "null" : typeof value}' object cannot be interpreted as an integer`);
|
|
55
|
+
};
|
|
151
56
|
|
|
152
|
-
// Modify the bits
|
|
153
57
|
if (baseSize === 8) {
|
|
154
|
-
const
|
|
155
|
-
const
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
58
|
+
const shift = BigInt(bitOffset);
|
|
59
|
+
const width = BigInt(bitSize);
|
|
60
|
+
const mask = ((1n << width) - 1n) << shift;
|
|
61
|
+
const toValue = boolean ? Boolean : bitSize <= 53 ? Number : (v) => v;
|
|
62
|
+
return {
|
|
63
|
+
read: (buf) => {
|
|
64
|
+
const raw = (readUnit(buf, offset) & mask) >> shift;
|
|
65
|
+
return toValue(signed ? BigInt.asIntN(bitSize, raw) : raw);
|
|
66
|
+
},
|
|
67
|
+
write: (buf, value) => {
|
|
68
|
+
const bits = BigInt.asUintN(bitSize, BigInt(integerValue(value))) << shift;
|
|
69
|
+
writeUnit(buf, offset, (readUnit(buf, offset) & ~mask) | bits);
|
|
70
|
+
},
|
|
71
|
+
};
|
|
162
72
|
}
|
|
163
73
|
|
|
164
|
-
|
|
74
|
+
// Units up to 32 bits: >>> 0 keeps the results unsigned (also for 32-bit fields).
|
|
75
|
+
const fieldMask = bitSize === 32 ? 0xffffffff : 2 ** bitSize - 1;
|
|
76
|
+
const unitMask = (fieldMask * 2 ** bitOffset) >>> 0;
|
|
77
|
+
const unsignedValue = (value) => {
|
|
78
|
+
value = integerValue(value);
|
|
79
|
+
if (typeof value === "bigint") return Number(BigInt.asUintN(bitSize, value)) >>> 0;
|
|
80
|
+
return (Number(value) & fieldMask) >>> 0;
|
|
81
|
+
};
|
|
82
|
+
const signShift = 32 - bitSize;
|
|
83
|
+
return {
|
|
84
|
+
read: boolean ? (buf) => (readUnit(buf, offset) & unitMask) !== 0 : signed ? (buf) => (((readUnit(buf, offset) & unitMask) >>> bitOffset) << signShift) >> signShift : (buf) => (readUnit(buf, offset) & unitMask) >>> bitOffset,
|
|
85
|
+
write: (buf, value) => {
|
|
86
|
+
const bits = (unsignedValue(value) << bitOffset) >>> 0;
|
|
87
|
+
writeUnit(buf, offset, ((readUnit(buf, offset) & ~unitMask) | bits) >>> 0);
|
|
88
|
+
},
|
|
89
|
+
};
|
|
165
90
|
}
|