UNPKG

@substrate-system/uint8-util

Version:

Fastest possible buffer-like utilities for uint8.

41 lines (40 loc) 1.55 kB
"use strict"; var __defProp = Object.defineProperty; var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); import { createHash, randomBytes as rand } from "node:crypto"; export * from "../util.js"; export * from "../types.js"; const decoder = new TextDecoder(); export const arr2text = /* @__PURE__ */ __name((data, enc) => { if (data.byteLength > 1024) { if (!enc) return decoder.decode(data); const dec = new TextDecoder(enc); return dec.decode(data); } return Buffer.from(data).toString(enc || "utf8"); }, "arr2text"); export const text2arr = /* @__PURE__ */ __name((str) => new Uint8Array(Buffer.from(str, "utf8")), "text2arr"); export const arr2base = /* @__PURE__ */ __name((data) => { return Buffer.from(data).toString("base64"); }, "arr2base"); export const base2arr = /* @__PURE__ */ __name((str) => { return new Uint8Array(Buffer.from(str, "base64")); }, "base2arr"); export const hex2bin = /* @__PURE__ */ __name((hex) => { return Buffer.from(hex, "hex").toString("binary"); }, "hex2bin"); export const bin2hex = /* @__PURE__ */ __name((bin) => { return Buffer.from(bin, "binary").toString("hex"); }, "bin2hex"); export async function hash(data, format, algo = "sha1") { algo = algo.replace("sha-", "sha"); const out = createHash(algo).update(data); return format ? out.digest(format) : new Uint8Array(out.digest().buffer); } __name(hash, "hash"); export const randomBytes = /* @__PURE__ */ __name((size) => { return new Uint8Array(rand(size)); }, "randomBytes");