-
-
Notifications
You must be signed in to change notification settings - Fork 31.4k
/
Copy pathtest.js
83 lines (76 loc) Β· 2.17 KB
/
test.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
'use strict';
const common = require('../../common');
const assert = require('assert');
const path = require('path');
const os = require('os');
const ffi = require('node:ffi');
const ext = common.isOSX ? 'dylib' : common.isWindows ? 'dll' : 'so';
const shared = path.join(__dirname, `./build/${common.buildType}/types.${ext}`);
const basicTypes = [
'char',
'signed char',
'unsigned char',
'short',
'short int',
'signed short',
'signed short int',
'unsigned short',
'unsigned short int',
'int',
'signed',
'signed int',
'unsigned',
'unsigned int',
'long',
'long int',
'signed long',
'signed long int',
'unsigned long',
'unsigned long int',
'long long',
'long long int',
'signed long long',
'signed long long int',
'unsigned long long',
'unsigned long long int',
'float',
'double',
'uint8_t',
'int8_t',
'uint16_t',
'int16_t',
'uint32_t',
'int32_t',
'uint64_t',
'int64_t',
];
function getRWName(type, size) {
const end = size > 1 ? os.endianness() : '';
if (type === 'float') return `Float${end}`;
if (type === 'double') return `Double${end}`;
const big = size >= 8 ? 'Big' : '';
const u = type.startsWith('u') && size < 8 ? 'U' : '';
return `${u}${big}Int${size * 8}${end}`;
}
function isBigInt(type) {
return type !== 'double' && ffi.sizeof(type) === 8;
}
for (const type of basicTypes) {
const fnName = `test_add_${type.replace(/ /g, '_')}`;
const fn = ffi.getNativeFunction(shared, fnName, type, [type, type]);
const three = isBigInt(type) ? 3n : 3;
const four = isBigInt(type) ? 4n : 4;
const seven = isBigInt(type) ? 7n : 7;
assert.strictEqual(fn(three, four), seven);
const ptrFnName = `test_add_ptr_${type.replace(/ /g, '_')}`;
const ptrType = type + '*';
const ptrFn = ffi.getNativeFunction(shared, ptrFnName, 'void', [ptrType, ptrType, ptrType]);
const size = ffi.sizeof(type);
const buf = Buffer.alloc(size * 3);
const retPtr = ffi.getBufferPointer(buf);
const rwName = getRWName(type, size);
buf[`write${rwName}`](three, size);
buf[`write${rwName}`](four, 2 * size);
ptrFn(retPtr, retPtr + BigInt(size), retPtr + BigInt(2 * size));
assert.strictEqual(buf[`read${rwName}`](0), seven);
}