|
2 | 2 |
|
3 | 3 | const { |
4 | 4 | Array, |
| 5 | + ArrayBufferPrototypeGetByteLength, |
5 | 6 | ArrayPrototypeForEach, |
6 | 7 | ArrayPrototypePush, |
7 | 8 | ArrayPrototypeShift, |
8 | 9 | ArrayPrototypeSplice, |
9 | 10 | BigInt, |
| 11 | + BigIntPrototypeToString, |
| 12 | + DataView, |
| 13 | + DataViewPrototypeGetUint8, |
10 | 14 | FunctionPrototypeBind, |
11 | 15 | FunctionPrototypeCall, |
12 | 16 | MathMin, |
13 | 17 | NumberIsNaN, |
14 | 18 | NumberIsSafeInteger, |
15 | 19 | NumberPrototypeToString, |
| 20 | + StringFromCharCodeApply, |
16 | 21 | StringPrototypePadStart, |
17 | 22 | } = primordials; |
18 | 23 |
|
@@ -493,17 +498,39 @@ function generatePrimeSync(size, options = kEmptyObject) { |
493 | 498 | return job.result(prime); |
494 | 499 | } |
495 | 500 |
|
496 | | -function arrayBufferToUnsignedBigInt(arrayBuffer) { |
497 | | - return BigInt(`0x${Buffer.from(arrayBuffer).toString('hex')}`); |
| 501 | +/** |
| 502 | + * 48 is the ASCII code for '0', 97 is the ASCII code for 'a'. |
| 503 | + * @param {number} number An integer between 0 and 15. |
| 504 | + * @returns {number} corresponding to the ASCII code of the hex representation |
| 505 | + * of the parameter. |
| 506 | + */ |
| 507 | +const numberToHexCharCode = (number) => (number < 10 ? 48 : 87) + number; |
| 508 | + |
| 509 | +/** |
| 510 | + * @param {ArrayBuffer} buf An ArrayBuffer. |
| 511 | + * @return {bigint} |
| 512 | + */ |
| 513 | +function arrayBufferToUnsignedBigInt(buf) { |
| 514 | + const length = ArrayBufferPrototypeGetByteLength(buf); |
| 515 | + const chars = Array(length * 2); |
| 516 | + const view = new DataView(buf); |
| 517 | + |
| 518 | + for (let i = 0; i < length; i++) { |
| 519 | + const val = DataViewPrototypeGetUint8(view, i); |
| 520 | + chars[2 * i] = numberToHexCharCode(val >> 4); |
| 521 | + chars[2 * i + 1] = numberToHexCharCode(val & 0xf); |
| 522 | + } |
| 523 | + |
| 524 | + return BigInt(`0x${StringFromCharCodeApply(chars)}`); |
498 | 525 | } |
499 | 526 |
|
500 | 527 | function unsignedBigIntToBuffer(bigint, name) { |
501 | 528 | if (bigint < 0) { |
502 | 529 | throw new ERR_OUT_OF_RANGE(name, '>= 0', bigint); |
503 | 530 | } |
504 | 531 |
|
505 | | - const hex = bigint.toString(16); |
506 | | - const padded = hex.padStart(hex.length + (hex.length % 2), 0); |
| 532 | + const hex = BigIntPrototypeToString(bigint, 16); |
| 533 | + const padded = StringPrototypePadStart(hex, hex.length + (hex.length % 2), 0); |
507 | 534 | return Buffer.from(padded, 'hex'); |
508 | 535 | } |
509 | 536 |
|
|
0 commit comments