"use strict"; // TODO: Replace with native `bigint-buffer`, after figuring out a way to auto-determine the buffer size to pass to it const assert = require("assert"); function padHex(hex) { // NOTE: This is necessary because BigInt#toString will omit leading zeroes even if that leads to an uneven number of digits, and that will cause values to roundtrip incorrectly through Buffer (which seems to parse it as missing a *trailing* zero). return hex.padStart(2 * Math.ceil(hex.length / 2), "0"); } module.exports = { toBuffer: function bigintToBuffer(number) { assert(number >= 0n); let hex = padHex(number.toString(16)); return Buffer.from(hex, "hex"); }, toBigint: function bufferToBigint(buffer) { let hex = buffer.toString("hex"); return BigInt("0x" + hex); } };