Repository Public
1export const utf8 = (s: string) => new TextEncoder().encode(s)2export const fromUtf8 = (b: Uint8Array) => new TextDecoder().decode(b)34export function b64(b: Uint8Array): string {5 let s = ""6 for (let i = 0; i < b.length; i += 0x8000) s += String.fromCharCode(...b.subarray(i, i + 0x8000))7 return btoa(s)8}9export function unb64(s: string): Uint8Array {10 const bin = atob(s)11 const out = new Uint8Array(bin.length)12 for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i)13 return out14}15export function concat(...parts: Uint8Array[]): Uint8Array {16 const out = new Uint8Array(parts.reduce((n, p) => n + p.length, 0))17 let o = 018 for (const p of parts) {19 out.set(p, o)20 o += p.length21 }22 return out23}24export function uuidBytes(u: string): Uint8Array {25 const h = u.replace(/-/g, "")26 const out = new Uint8Array(16)27 for (let i = 0; i < 16; i++) out[i] = parseInt(h.slice(i * 2, i * 2 + 2), 16)28 return out29}30export function bytesToUuid(b: Uint8Array): string {31 const h = [...b].map((x) => x.toString(16).padStart(2, "0")).join("")32 return `${h.slice(0, 8)}-${h.slice(8, 12)}-${h.slice(12, 16)}-${h.slice(16, 20)}-${h.slice(20)}`33}34export const hex = (b: Uint8Array) => [...b].map((x) => x.toString(16).padStart(2, "0")).join("")35export const randomBytes = (n: number) => crypto.getRandomValues(new Uint8Array(n))36export const uuid = () => crypto.randomUUID()37export function equalBytes(a: Uint8Array, b: Uint8Array) {38 if (a.length !== b.length) return false39 let d = 040 for (let i = 0; i < a.length; i++) d |= a[i] ^ b[i]41 return d === 042}43/** BufferSource view accepted by WebCrypto regardless of the backing buffer type. */44export const bs = (b: Uint8Array) => b as unknown as BufferSource45