@substrate-system/uint8-util
Version:
Fastest possible buffer-like utilities for uint8.
68 lines (67 loc) • 2.23 kB
JavaScript
var __defProp = Object.defineProperty;
var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
import { arr2hex, hex2arr, alphabet } from "./util.js";
import { decode, encode } from "base64-arraybuffer";
export * from "./types.js";
const decoder = new TextDecoder();
const arr2text = /* @__PURE__ */ __name((data, enc) => {
if (!enc) return decoder.decode(data);
const dec = new TextDecoder(enc);
return dec.decode(data);
}, "arr2text");
const encoder = new TextEncoder();
const text2arr = /* @__PURE__ */ __name((str) => encoder.encode(str), "text2arr");
const arr2base = /* @__PURE__ */ __name((data) => encode(data), "arr2base");
const base2arr = /* @__PURE__ */ __name((str) => new Uint8Array(decode(str)), "base2arr");
const bin2hex = /* @__PURE__ */ __name((str) => {
let res = "";
let c;
let i = 0;
const len = str.length;
while (i < len) {
c = str.charCodeAt(i++);
res += alphabet[c >> 4] + alphabet[c & 15];
}
return res;
}, "bin2hex");
const MAX_ARGUMENTS_LENGTH = 65536;
const hex2bin = /* @__PURE__ */ __name((hex) => {
const points = hex2arr(hex);
if (points.length <= MAX_ARGUMENTS_LENGTH) return String.fromCharCode(...points);
let res = "";
let i = 0;
while (i < points.length) {
res += String.fromCharCode(...points.subarray(i, i += MAX_ARGUMENTS_LENGTH));
}
return res;
}, "hex2bin");
const scope = typeof window !== "undefined" ? window : globalThis;
const crypto = scope.crypto || scope.msCrypto || {};
const subtle = crypto.subtle || crypto.webkitSubtle;
const formatMap = {
hex: arr2hex,
base64: arr2base
};
async function hash(data, format, algo = "sha-1") {
if (!subtle) throw new Error("no web crypto support");
if (typeof data === "string") data = text2arr(data);
const out = new Uint8Array(await subtle.digest(algo, data));
return format ? formatMap[format](out) : out;
}
__name(hash, "hash");
const randomBytes = /* @__PURE__ */ __name((size) => {
const view = new Uint8Array(size);
return crypto.getRandomValues(view);
}, "randomBytes");
export * from "./util.js";
export {
arr2base,
arr2text,
base2arr,
bin2hex,
hash,
hex2bin,
randomBytes,
text2arr
};
//# sourceMappingURL=browser.js.map