Repository navigation
Expand file tree
/
Copy pathutils_native.js
More file actions
121 lines (114 loc) · 3.1 KB
/
Copy pathutils_native.js
File metadata and controls
121 lines (114 loc) · 3.1 KB
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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
/* global BigInt */
const assert = require("assert");
module.exports.stringifyBigInts = function stringifyBigInts(o) {
if ((typeof(o) == "bigint") || o.eq !== undefined) {
return o.toString(10);
} else if (Array.isArray(o)) {
return o.map(stringifyBigInts);
} else if (typeof o == "object") {
const res = {};
for (let k in o) {
res[k] = stringifyBigInts(o[k]);
}
return res;
} else {
return o;
}
};
module.exports.unstringifyBigInts = function unstringifyBigInts(o) {
if ((typeof(o) == "string") && (/^[0-9]+$/.test(o) )) {
return BigInt(o);
} else if (Array.isArray(o)) {
return o.map(unstringifyBigInts);
} else if (typeof o == "object") {
const res = {};
for (let k in o) {
res[k] = unstringifyBigInts(o[k]);
}
return res;
} else {
return o;
}
};
module.exports.beBuff2int = function beBuff2int(buff) {
let res = 0n;
let i = buff.length;
let offset = 0;
while (i>0) {
if (i >= 4) {
i -= 4;
res += BigInt(buff.readUInt32BE(i)) << BigInt(offset*8);
offset += 4;
} else if (i >= 2) {
i -= 2;
res += BigInt(buff.readUInt16BE(i)) << BigInt(offset*8);
offset += 2;
} else {
i -= 1;
res += BigInt(buff.readUInt8(i)) << BigInt(offset*8);
offset += 1;
}
}
return res;
};
module.exports.beInt2Buff = function beInt2Buff(n, len) {
let r = n;
const buff = Buffer.alloc(len);
let o = len;
while (o > 0) {
if (o-4 >= 0) {
o -= 4;
buff.writeUInt32BE(Number(r & 0xFFFFFFFFn), o);
r = r >> 32n;
} else if (o-2 >= 0) {
o -= 2;
buff.writeUInt16BE(Number(r & 0xFFFFn), o);
r = r >> 16n;
} else {
o -= 1;
buff.writeUInt8(Number(r & 0xFFn),o );
r = r >> 8n;
}
}
assert(r == 0n);
return buff;
};
module.exports.leBuff2int = function leBuff2int(buff) {
let res = 0n;
let i = 0;
while (i<buff.length) {
if (i + 4 <= buff.length) {
res += BigInt(buff.readUInt32LE(i)) << BigInt( i*8);
i += 4;
} else if (i + 4 <= buff.length) {
res += BigInt(buff.readUInt16LE(i)) << BigInt( i*8);
i += 2;
} else {
res += BigInt(buff.readUInt8(i)) << BigInt( i*8);
i += 1;
}
}
return res;
};
module.exports.leInt2Buff = function leInt2Buff(n, len) {
let r = n;
const buff = Buffer.alloc(len);
let o = 0;
while (o < len) {
if (o+4 <= len) {
buff.writeUInt32LE(Number(r & 0xFFFFFFFFn), o );
o += 4;
r = r >> 32n;
} else if (o+2 <= len) {
buff.writeUInt16LE(Number(r & 0xFFFFn), o );
o += 2;
r = r >> 16n;
} else {
buff.writeUInt8(Number(r & 0xFFn), o );
o += 1;
r = r >> 8n;
}
}
assert(r == 0n);
return buff;
};