UNPKG

@lodestar/utils

Version:

Utilities required across multiple lodestar packages

61 lines 1.85 kB
import { toBigIntBE, toBigIntLE, toBufferBE, toBufferLE } from "bigint-buffer"; const hexByByte = []; /** * @deprecated Use toHex() instead. */ export function toHexString(bytes) { let hex = "0x"; for (const byte of bytes) { if (!hexByByte[byte]) { hexByByte[byte] = byte < 16 ? "0" + byte.toString(16) : byte.toString(16); } hex += hexByByte[byte]; } return hex; } /** * Return a byte array from a number or BigInt */ export function intToBytes(value, length, endianness = "le") { return bigIntToBytes(BigInt(value), length, endianness); } /** * Convert byte array in LE to integer. */ export function bytesToInt(value, endianness = "le") { return Number(bytesToBigInt(value, endianness)); } export function bigIntToBytes(value, length, endianness = "le") { if (endianness === "le") { return toBufferLE(value, length); } if (endianness === "be") { return toBufferBE(value, length); } throw new Error("endianness must be either 'le' or 'be'"); } export function bytesToBigInt(value, endianness = "le") { if (endianness === "le") { return toBigIntLE(value); } if (endianness === "be") { return toBigIntBE(value); } throw new Error("endianness must be either 'le' or 'be'"); } export function formatBytes(bytes) { if (bytes < 0) { throw new Error("bytes must be a positive number, got " + bytes); } if (bytes === 0) { return "0 Bytes"; } // size of a kb const k = 1024; // only support up to GB const units = ["Bytes", "KB", "MB", "GB"]; const i = Math.min(Math.floor(Math.log(bytes) / Math.log(k)), units.length - 1); const formattedSize = (bytes / Math.pow(k, i)).toFixed(2); return `${formattedSize} ${units[i]}`; } //# sourceMappingURL=bytes.js.map