node-ctypes 2.3.0 → 2.5.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 +1003 -0
- package/README.md +483 -103
- 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 +79 -106
- package/lib/core/callback.js +7 -3
- package/lib/core/conversions.js +374 -48
- package/lib/core/funcptr.js +186 -64
- package/lib/core/types.js +7 -2
- package/lib/index.d.ts +139 -61
- package/lib/index.js +10 -8
- package/lib/memory/buffer.js +62 -13
- package/lib/memory/operations.js +4 -6
- package/lib/memory/pointer.js +147 -74
- package/lib/platform/win_types.js +8 -3
- package/lib/structures/Structure.js +60 -45
- package/lib/structures/helpers/array.js +31 -12
- package/lib/structures/helpers/bitfield.js +17 -8
- package/lib/structures/helpers/common.js +223 -29
- package/lib/structures/helpers/layout.js +17 -3
- package/lib/structures/helpers/struct.js +66 -51
- package/lib/structures/helpers/union.js +36 -26
- package/lib/types/SimpleCData.js +11 -32
- package/lib/types/primitives.js +35 -16
- package/lib/utils/cache.js +34 -2
- package/package.json +3 -1
|
@@ -65,7 +65,8 @@
|
|
|
65
65
|
*/
|
|
66
66
|
|
|
67
67
|
import { kMirrorBase, mirrorBase, mirroredAccessors, mirrorsActive } from "../memory/mirror.js";
|
|
68
|
-
import { fieldsOf } from "./helpers/common.js";
|
|
68
|
+
import { copyInstance, fieldsOf, inDllBuffer, sourceBytes } from "./helpers/common.js";
|
|
69
|
+
import { normalizePack } from "./helpers/layout.js";
|
|
69
70
|
|
|
70
71
|
/**
|
|
71
72
|
* Creates the Structure base class with required dependencies injected.
|
|
@@ -81,18 +82,6 @@ function isPlainObject(value) {
|
|
|
81
82
|
return proto === Object.prototype || proto === null;
|
|
82
83
|
}
|
|
83
84
|
|
|
84
|
-
// Sorgente di from_buffer / from_buffer_copy (Python: ValueError per offset
|
|
85
|
-
// negativi e sorgenti troppo piccole): Buffer, TypedArray/DataView o istanza
|
|
86
|
-
// ctypes, come per gli array.
|
|
87
|
-
function sourceBytes(source, offset, size, name) {
|
|
88
|
-
const bytes = source !== null && typeof source === "object" && !ArrayBuffer.isView(source) && Buffer.isBuffer(source._buffer) ? source._buffer : source;
|
|
89
|
-
if (!ArrayBuffer.isView(bytes)) throw new TypeError(`${name}: source must be a Buffer, a typed array or a ctypes instance`);
|
|
90
|
-
if (!Number.isInteger(offset)) throw new TypeError(`${name}: offset must be an integer`);
|
|
91
|
-
if (offset < 0) throw new RangeError(`${name}: offset cannot be negative`);
|
|
92
|
-
if (bytes.byteLength - offset < size) throw new RangeError(`${name}: Buffer size too small (${bytes.byteLength} instead of at least ${size + offset} bytes)`);
|
|
93
|
-
return bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes.buffer, bytes.byteOffset, bytes.byteLength);
|
|
94
|
-
}
|
|
95
|
-
|
|
96
85
|
export function createStructureClass(alloc, struct, bitfield, ptrToBuffer) {
|
|
97
86
|
// Buffer dell'istanza, letto dall'handler condiviso. Chiave privata e non
|
|
98
87
|
// `__buffer`, così riassegnare `__buffer` non cambia i campi (come prima).
|
|
@@ -102,13 +91,42 @@ export function createStructureClass(alloc, struct, bitfield, ptrToBuffer) {
|
|
|
102
91
|
|
|
103
92
|
// Definizione con cui è stata creata l'istanza (layout dei suoi byte).
|
|
104
93
|
const kDef = Symbol("def");
|
|
94
|
+
// A field may shadow the public constructor property.
|
|
95
|
+
const kCtor = Symbol("constructor");
|
|
105
96
|
// Istanze dei campi struct/union annidati, create al primo accesso: sono
|
|
106
97
|
// viste sulla memoria dell'istanza, quindi restano valide.
|
|
107
98
|
const kViews = Symbol("views");
|
|
108
99
|
// Nomi dei campi con un accessor installato da noi, per prototipo.
|
|
109
100
|
const installedNames = new WeakMap();
|
|
110
101
|
// Nomi che restano proprietà della libreria anche se usati come campi.
|
|
111
|
-
const reservedNames = new Set(["
|
|
102
|
+
const reservedNames = new Set(["_buffer", "__buffer", "_structDef", "__structDef"]);
|
|
103
|
+
const finalizedClasses = new WeakSet();
|
|
104
|
+
|
|
105
|
+
function assignClassFields(Ctor, fields) {
|
|
106
|
+
if (finalizedClasses.has(Ctor)) throw new TypeError("_fields_ is final");
|
|
107
|
+
Object.defineProperty(Ctor, "_fields_", { value: fields, writable: true, enumerable: true, configurable: true });
|
|
108
|
+
Ctor._structDef = null;
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
function finalizeFields(Ctor) {
|
|
112
|
+
if (finalizedClasses.has(Ctor)) return;
|
|
113
|
+
if (Object.hasOwn(Ctor, "_fields_")) {
|
|
114
|
+
const fields = Ctor._fields_;
|
|
115
|
+
Object.defineProperty(Ctor, "_fields_", {
|
|
116
|
+
get() {
|
|
117
|
+
return fields;
|
|
118
|
+
},
|
|
119
|
+
set(value) {
|
|
120
|
+
assignClassFields(this, value);
|
|
121
|
+
},
|
|
122
|
+
enumerable: true,
|
|
123
|
+
configurable: false,
|
|
124
|
+
});
|
|
125
|
+
}
|
|
126
|
+
finalizedClasses.add(Ctor);
|
|
127
|
+
const own = Ctor[kStructDef];
|
|
128
|
+
if (own?.owner === Ctor) own.finalized = true;
|
|
129
|
+
}
|
|
112
130
|
|
|
113
131
|
// Percorso generale di un campo: istanza con un'altra definizione (creata
|
|
114
132
|
// prima di un'invalidazione del layout), copia di memoria nativa (Electron,
|
|
@@ -135,6 +153,7 @@ export function createStructureClass(alloc, struct, bitfield, ptrToBuffer) {
|
|
|
135
153
|
// veloce usa il lettore/scrittore precompilato della definizione della classe.
|
|
136
154
|
function installFieldAccessors(Ctor, def) {
|
|
137
155
|
const proto = Ctor.prototype;
|
|
156
|
+
Object.defineProperty(proto, kCtor, { value: Ctor, configurable: true });
|
|
138
157
|
for (const name of installedNames.get(proto) ?? []) {
|
|
139
158
|
delete proto[name];
|
|
140
159
|
}
|
|
@@ -292,11 +311,12 @@ export function createStructureClass(alloc, struct, bitfield, ptrToBuffer) {
|
|
|
292
311
|
*/
|
|
293
312
|
class Structure {
|
|
294
313
|
constructor(...args) {
|
|
295
|
-
const Ctor =
|
|
314
|
+
const Ctor = new.target;
|
|
296
315
|
// Definizione propria della classe (percorso caldo di `new`: una lettura
|
|
297
316
|
// di proprietà invece di Object.hasOwn).
|
|
298
317
|
const own = Ctor[kStructDef];
|
|
299
318
|
const def = own !== undefined && own.owner === Ctor ? own.def : Ctor._buildStruct();
|
|
319
|
+
if (own?.owner !== Ctor || !own.finalized) finalizeFields(Ctor);
|
|
300
320
|
let buf;
|
|
301
321
|
|
|
302
322
|
// Support positional args: new Point(10,20)
|
|
@@ -362,7 +382,7 @@ export function createStructureClass(alloc, struct, bitfield, ptrToBuffer) {
|
|
|
362
382
|
}
|
|
363
383
|
|
|
364
384
|
get [Symbol.toStringTag]() {
|
|
365
|
-
return this
|
|
385
|
+
return this[kCtor]?.name || "Structure";
|
|
366
386
|
}
|
|
367
387
|
|
|
368
388
|
// I campi non sono proprietà proprie (come in Python): JSON.stringify e
|
|
@@ -372,7 +392,21 @@ export function createStructureClass(alloc, struct, bitfield, ptrToBuffer) {
|
|
|
372
392
|
}
|
|
373
393
|
|
|
374
394
|
[Symbol.for("nodejs.util.inspect.custom")](depth, options, inspect) {
|
|
375
|
-
return `${this
|
|
395
|
+
return `${this[kCtor]?.name || "Structure"} ${inspect(this.toObject(), options)}`;
|
|
396
|
+
}
|
|
397
|
+
|
|
398
|
+
static get _fields_() {
|
|
399
|
+
return undefined;
|
|
400
|
+
}
|
|
401
|
+
|
|
402
|
+
static set _fields_(fields) {
|
|
403
|
+
assignClassFields(this, fields);
|
|
404
|
+
}
|
|
405
|
+
|
|
406
|
+
static _finalizeFields() {
|
|
407
|
+
const def = this._structDef || this._buildStruct();
|
|
408
|
+
finalizeFields(this);
|
|
409
|
+
return def;
|
|
376
410
|
}
|
|
377
411
|
|
|
378
412
|
// Static getters for size, alignment, and fields (enables use as nested type)
|
|
@@ -427,7 +461,7 @@ export function createStructureClass(alloc, struct, bitfield, ptrToBuffer) {
|
|
|
427
461
|
const def = this._structDef || this._buildStruct();
|
|
428
462
|
const bytes = sourceBytes(source, offset, def.size, "from_buffer_copy");
|
|
429
463
|
const copy = Buffer.alloc(def.size);
|
|
430
|
-
copy.
|
|
464
|
+
copyInstance(copy, 0, def.size, bytes, offset, def);
|
|
431
465
|
return new this(copy);
|
|
432
466
|
}
|
|
433
467
|
|
|
@@ -456,15 +490,8 @@ export function createStructureClass(alloc, struct, bitfield, ptrToBuffer) {
|
|
|
456
490
|
* Python ctypes parity: `S.in_dll(library, name)`.
|
|
457
491
|
*/
|
|
458
492
|
static in_dll(library, name) {
|
|
459
|
-
const
|
|
460
|
-
|
|
461
|
-
throw new TypeError("in_dll: first arg must be a Library (CDLL/WinDLL)");
|
|
462
|
-
}
|
|
463
|
-
const addr = nativeLib.symbol(name);
|
|
464
|
-
if (!addr) {
|
|
465
|
-
throw new Error(`in_dll: symbol '${name}' not found`);
|
|
466
|
-
}
|
|
467
|
-
return this.from_address(addr);
|
|
493
|
+
const def = this._structDef || this._buildStruct();
|
|
494
|
+
return new this(inDllBuffer(library, name, def.size, ptrToBuffer));
|
|
468
495
|
}
|
|
469
496
|
|
|
470
497
|
// Build the underlying struct definition and cache it on the constructor
|
|
@@ -482,8 +509,9 @@ export function createStructureClass(alloc, struct, bitfield, ptrToBuffer) {
|
|
|
482
509
|
return;
|
|
483
510
|
}
|
|
484
511
|
// { owner, def }: una sottoclasse eredita la proprietà ma non è `owner`.
|
|
485
|
-
Object.defineProperty(this, kStructDef, { value: { owner: this, def }, configurable: true, writable: true });
|
|
512
|
+
Object.defineProperty(this, kStructDef, { value: { owner: this, def, finalized: finalizedClasses.has(this) }, configurable: true, writable: true });
|
|
486
513
|
installFieldAccessors(this, def);
|
|
514
|
+
if (Object.hasOwn(this, "_fields_")) finalizeFields(this);
|
|
487
515
|
}
|
|
488
516
|
|
|
489
517
|
// Classe base con un layout (Python: la sottoclasse ne estende i campi),
|
|
@@ -523,7 +551,7 @@ export function createStructureClass(alloc, struct, bitfield, ptrToBuffer) {
|
|
|
523
551
|
if (!anonymous.has(name)) return [name, type];
|
|
524
552
|
// Classe Structure/Union: la sua definizione, e la classe per le istanze.
|
|
525
553
|
if (typeof type === "function" && typeof type._buildStruct === "function") {
|
|
526
|
-
return [name, { anonymous: true, type: type.
|
|
554
|
+
return [name, { anonymous: true, type: type._finalizeFields(), cls: type }];
|
|
527
555
|
}
|
|
528
556
|
return [name, { anonymous: true, type }];
|
|
529
557
|
});
|
|
@@ -535,22 +563,9 @@ export function createStructureClass(alloc, struct, bitfield, ptrToBuffer) {
|
|
|
535
563
|
// `_pack_`, `_layout_`, `_align_` e byte order.
|
|
536
564
|
static _layoutOptions() {
|
|
537
565
|
const options = {};
|
|
538
|
-
if (this._pack_ !== undefined) {
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
// `true` is tolerated as an alias for `_pack_ = 1`. Anything else is
|
|
542
|
-
// rejected so we don't silently produce a mislaid struct.
|
|
543
|
-
const p = this._pack_;
|
|
544
|
-
if (p === true) {
|
|
545
|
-
options.pack = 1;
|
|
546
|
-
} else if (p === false) {
|
|
547
|
-
// explicit false = no packing, same as absent
|
|
548
|
-
} else if (typeof p === "number" && Number.isInteger(p) && p >= 1 && (p & (p - 1)) === 0) {
|
|
549
|
-
options.pack = p;
|
|
550
|
-
} else {
|
|
551
|
-
throw new TypeError(`_pack_ must be a positive power-of-two integer, got ${p}`);
|
|
552
|
-
}
|
|
553
|
-
if (options.pack !== undefined) options.packed = true;
|
|
566
|
+
if (this._pack_ !== undefined && this._pack_ !== null) {
|
|
567
|
+
options.pack = normalizePack(this._pack_);
|
|
568
|
+
options.packed = options.pack !== 0;
|
|
554
569
|
}
|
|
555
570
|
// Python ctypes: "ms" (Windows, or with _pack_) or "gcc-sysv" bitfield layout.
|
|
556
571
|
if (this._layout_ !== undefined) options.layout = this._layout_;
|
|
@@ -105,25 +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
109
|
import { buildWrapper } from "./wrap.js";
|
|
110
110
|
import { flush, isMirror, mirrorsActive, refresh } from "../../memory/mirror.js";
|
|
111
111
|
|
|
112
112
|
// Python: gli array di c_char / c_wchar (anche come campi struct) hanno un
|
|
113
113
|
// `.value` stringa fino al primo NUL; quelli di c_char anche `.raw` (bytes).
|
|
114
|
-
function charArrayValue(buf, charKind, wcharSize) {
|
|
114
|
+
function charArrayValue(buf, charKind, wcharSize, swapped) {
|
|
115
115
|
if (charKind === "char") {
|
|
116
116
|
const end = buf.indexOf(0);
|
|
117
117
|
return buf.toString("utf8", 0, end === -1 ? buf.length : end);
|
|
118
118
|
}
|
|
119
|
+
if (swapped) {
|
|
120
|
+
buf = Buffer.from(buf);
|
|
121
|
+
wcharSize === 2 ? buf.swap16() : buf.swap32();
|
|
122
|
+
}
|
|
119
123
|
return decodeWide(buf, wcharSize);
|
|
120
124
|
}
|
|
121
125
|
|
|
122
|
-
function setCharArrayValue(buf, charKind, wcharSize, value, message) {
|
|
126
|
+
function setCharArrayValue(buf, charKind, wcharSize, value, message, swapped) {
|
|
123
127
|
const units = charKind === "char" ? (Buffer.isBuffer(value) ? value : Buffer.from(String(value), "utf8")) : encodeWide(String(value), wcharSize);
|
|
124
128
|
if (units.length > buf.length) {
|
|
125
129
|
throw new RangeError(message(units.length / (charKind === "char" ? 1 : wcharSize), buf.length / (charKind === "char" ? 1 : wcharSize)));
|
|
126
130
|
}
|
|
131
|
+
if (swapped && charKind === "wchar") wcharSize === 2 ? units.swap16() : units.swap32();
|
|
127
132
|
units.copy(buf);
|
|
128
133
|
const unit = charKind === "char" ? 1 : wcharSize;
|
|
129
134
|
if (units.length + unit <= buf.length) {
|
|
@@ -179,7 +184,7 @@ function charSlice(...args) {
|
|
|
179
184
|
return Array.prototype.slice.apply(this, args).join("");
|
|
180
185
|
}
|
|
181
186
|
|
|
182
|
-
export function array(elementType, count, sizeof, alloc, readValue, writeValue, Structure, Union, ArrayType, voidPointerType, ptrToBuffer) {
|
|
187
|
+
export function array(elementType, count, sizeof, alloc, readValue, writeValue, Structure, Union, ArrayType, voidPointerType, ptrToBuffer, swapped = false) {
|
|
183
188
|
// Validate elementType: accept SimpleCData classes, Structure/Union classes,
|
|
184
189
|
// or native CType-like objects.
|
|
185
190
|
const isSimple = typeof elementType === "function" && elementType._isSimpleCData;
|
|
@@ -194,6 +199,7 @@ export function array(elementType, count, sizeof, alloc, readValue, writeValue,
|
|
|
194
199
|
if (!isSimple && !isStruct && !isStructDef && !isNativeTypeObj && !isArrayElem && !isPointerElem) {
|
|
195
200
|
throw new TypeError("array elementType must be a SimpleCData class or a Structure/Union class");
|
|
196
201
|
}
|
|
202
|
+
if (swapped && isArrayElem) elementType = elementType._swappedType ?? elementType;
|
|
197
203
|
|
|
198
204
|
const elementSize = sizeof(elementType);
|
|
199
205
|
// Array alignment == element alignment (C standard), NOT element size.
|
|
@@ -233,14 +239,14 @@ export function array(elementType, count, sizeof, alloc, readValue, writeValue,
|
|
|
233
239
|
// Precalcolati una volta per tipo: l'handler del Proxy li ripeteva ad ogni
|
|
234
240
|
// accesso indicizzato (instanceof Structure/Union + dispatch di readValue).
|
|
235
241
|
const isStructElem = typeof elementType === "function" && (elementType.prototype instanceof Structure || elementType.prototype instanceof Union);
|
|
236
|
-
const elemReader = isSimple ? elementType._reader : null;
|
|
237
|
-
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;
|
|
238
244
|
|
|
239
245
|
// Array di caratteri (Python: c_char * n / c_wchar * n): `.value` e `.raw`.
|
|
240
246
|
const charKind = isSimple ? elementType._charKind : undefined;
|
|
241
247
|
const tooLong = charKind === "char" ? () => "byte string too long" : () => "string too long";
|
|
242
|
-
const getValue = charKind === undefined ? undefined : (buf) => charArrayValue(buf, charKind, elementSize);
|
|
243
|
-
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);
|
|
244
250
|
const setRaw = (buf, value) => {
|
|
245
251
|
const bytes = Buffer.isBuffer(value) ? value : Buffer.from(String(value), "utf8");
|
|
246
252
|
if (bytes.length > buf.length) throw new RangeError("byte string too long");
|
|
@@ -252,7 +258,8 @@ export function array(elementType, count, sizeof, alloc, readValue, writeValue,
|
|
|
252
258
|
const pointerElemType = !isPointerElem ? null : typeof elementType === "function" ? funcPtrFieldType(elementType) : elementType;
|
|
253
259
|
const readPointer = (target, off) => {
|
|
254
260
|
const address = elementSize === 8 ? target.readBigUInt64LE(off) : BigInt(target.readUInt32LE(off));
|
|
255
|
-
|
|
261
|
+
const owner = pointerOwner(target, off, address);
|
|
262
|
+
return address === 0n ? null : pointerElemType.fromAddress(address, owner);
|
|
256
263
|
};
|
|
257
264
|
const writePointer = (target, off, value) => writePointerField(target, off, value, elementSize);
|
|
258
265
|
|
|
@@ -290,13 +297,13 @@ export function array(elementType, count, sizeof, alloc, readValue, writeValue,
|
|
|
290
297
|
const inner = target.subarray(off, off + elementSize);
|
|
291
298
|
const source = value !== null && typeof value === "object" && Buffer.isBuffer(value._buffer) ? value._buffer : value;
|
|
292
299
|
if (Buffer.isBuffer(source)) {
|
|
293
|
-
|
|
300
|
+
copyInstance(inner, 0, elementSize, value, 0, elementType);
|
|
294
301
|
} else if (source !== null && typeof source === "object" && typeof source.length === "number") {
|
|
295
302
|
const view = elementType.wrap(inner);
|
|
296
303
|
for (let i = 0; i < Math.min(source.length, elementType.length); i++) view[i] = source[i];
|
|
297
304
|
}
|
|
298
305
|
} else if (elemWriter !== null && off + elementSize <= target.length) {
|
|
299
|
-
elemWriter(target,
|
|
306
|
+
elemWriter(target, value, off);
|
|
300
307
|
} else {
|
|
301
308
|
writeValue(target, elementType, value, off);
|
|
302
309
|
}
|
|
@@ -510,7 +517,7 @@ export function array(elementType, count, sizeof, alloc, readValue, writeValue,
|
|
|
510
517
|
const bytes = bytesOf(source, "from_buffer_copy");
|
|
511
518
|
checkRange(bytes, offset, "from_buffer_copy");
|
|
512
519
|
const copy = alloc(byteSize);
|
|
513
|
-
copy
|
|
520
|
+
copyInstance(copy, 0, byteSize, bytes, offset, ArrayCType);
|
|
514
521
|
return wrap(copy);
|
|
515
522
|
};
|
|
516
523
|
const from_address = (address) => {
|
|
@@ -524,6 +531,7 @@ export function array(elementType, count, sizeof, alloc, readValue, writeValue,
|
|
|
524
531
|
const ArrayCType = function (...values) {
|
|
525
532
|
return create(values);
|
|
526
533
|
};
|
|
534
|
+
let swappedType;
|
|
527
535
|
|
|
528
536
|
// `length` (numero di elementi) è una proprietà propria non scrivibile delle
|
|
529
537
|
// funzioni: va ridefinita con defineProperties.
|
|
@@ -557,6 +565,17 @@ export function array(elementType, count, sizeof, alloc, readValue, writeValue,
|
|
|
557
565
|
|
|
558
566
|
// Helper to check if this is an ArrayType wrapper
|
|
559
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
|
+
},
|
|
560
579
|
});
|
|
561
580
|
|
|
562
581
|
return ArrayCType;
|
|
@@ -24,7 +24,7 @@ const writers = {
|
|
|
24
24
|
8: { le: (buf, off, v) => buf.writeBigUInt64LE(v, off), be: (buf, off, v) => buf.writeBigUInt64BE(v, off) },
|
|
25
25
|
};
|
|
26
26
|
|
|
27
|
-
import { notIntegral } from "./common.js";
|
|
27
|
+
import { booleanValue, notIntegral } from "./common.js";
|
|
28
28
|
|
|
29
29
|
/**
|
|
30
30
|
* Reader and writer of one bitfield.
|
|
@@ -36,27 +36,36 @@ import { notIntegral } from "./common.js";
|
|
|
36
36
|
* @param {number} field.bitSize - Width in bits
|
|
37
37
|
* @param {boolean} [field.signed=false] - Signed base type
|
|
38
38
|
* @param {boolean} [field.bigEndian=false] - Unit stored big-endian
|
|
39
|
-
* @
|
|
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}}
|
|
40
41
|
*/
|
|
41
|
-
export function bitFieldAccessors({ offset, baseSize, bitOffset, bitSize, signed = false, bigEndian = false }) {
|
|
42
|
+
export function bitFieldAccessors({ offset, baseSize, bitOffset, bitSize, signed = false, bigEndian = false, boolean = false }) {
|
|
42
43
|
const order = bigEndian ? "be" : "le";
|
|
43
44
|
const readUnit = readers[baseSize]?.[order];
|
|
44
45
|
const writeUnit = writers[baseSize]?.[order];
|
|
45
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
|
+
};
|
|
46
56
|
|
|
47
57
|
if (baseSize === 8) {
|
|
48
58
|
const shift = BigInt(bitOffset);
|
|
49
59
|
const width = BigInt(bitSize);
|
|
50
60
|
const mask = ((1n << width) - 1n) << shift;
|
|
51
|
-
const toValue = bitSize <= 53 ? Number : (v) => v;
|
|
61
|
+
const toValue = boolean ? Boolean : bitSize <= 53 ? Number : (v) => v;
|
|
52
62
|
return {
|
|
53
63
|
read: (buf) => {
|
|
54
64
|
const raw = (readUnit(buf, offset) & mask) >> shift;
|
|
55
65
|
return toValue(signed ? BigInt.asIntN(bitSize, raw) : raw);
|
|
56
66
|
},
|
|
57
67
|
write: (buf, value) => {
|
|
58
|
-
|
|
59
|
-
const bits = BigInt.asUintN(bitSize, BigInt(value)) << shift;
|
|
68
|
+
const bits = BigInt.asUintN(bitSize, BigInt(integerValue(value))) << shift;
|
|
60
69
|
writeUnit(buf, offset, (readUnit(buf, offset) & ~mask) | bits);
|
|
61
70
|
},
|
|
62
71
|
};
|
|
@@ -66,13 +75,13 @@ export function bitFieldAccessors({ offset, baseSize, bitOffset, bitSize, signed
|
|
|
66
75
|
const fieldMask = bitSize === 32 ? 0xffffffff : 2 ** bitSize - 1;
|
|
67
76
|
const unitMask = (fieldMask * 2 ** bitOffset) >>> 0;
|
|
68
77
|
const unsignedValue = (value) => {
|
|
78
|
+
value = integerValue(value);
|
|
69
79
|
if (typeof value === "bigint") return Number(BigInt.asUintN(bitSize, value)) >>> 0;
|
|
70
|
-
if (typeof value === "number" && !Number.isInteger(value)) notIntegral();
|
|
71
80
|
return (Number(value) & fieldMask) >>> 0;
|
|
72
81
|
};
|
|
73
82
|
const signShift = 32 - bitSize;
|
|
74
83
|
return {
|
|
75
|
-
read: signed ? (buf) => (((readUnit(buf, offset) & unitMask) >>> bitOffset) << signShift) >> signShift : (buf) => (readUnit(buf, offset) & unitMask) >>> bitOffset,
|
|
84
|
+
read: boolean ? (buf) => (readUnit(buf, offset) & unitMask) !== 0 : signed ? (buf) => (((readUnit(buf, offset) & unitMask) >>> bitOffset) << signShift) >> signShift : (buf) => (readUnit(buf, offset) & unitMask) >>> bitOffset,
|
|
76
85
|
write: (buf, value) => {
|
|
77
86
|
const bits = (unsignedValue(value) << bitOffset) >>> 0;
|
|
78
87
|
writeUnit(buf, offset, ((readUnit(buf, offset) & ~unitMask) | bits) >>> 0);
|