// Shorten a long Trystero/Nostr peer id for display. export const shortId = (id: string): string => id.slice(0, 8) // Human-readable byte sizes. export const formatBytes = (n: number): string => { if (n < 1024) return `${n} B` const units = ['KB', 'MB', 'GB'] let v = n / 1024 let i = 0 while (v >= 1024 && i < units.length - 1) { v /= 1024 i++ } return `${v.toFixed(v < 10 ? 2 : 1)} ${units[i]}` } // A short random id for transfers / log keys. export const uid = (): string => Math.random().toString(36).slice(2, 10) // SHA-256 of a buffer, hex-encoded. Used to prove that what arrived on the // other side is byte-for-byte identical to what was sent. export const sha256Hex = async ( data: Uint8Array | ArrayBuffer ): Promise => { const digest = await crypto.subtle.digest('SHA-256', data) return [...new Uint8Array(digest)] .map(b => b.toString(16).padStart(2, '0')) .join('') } // Generate `size` bytes of random data, to demo sending large binary payloads // without needing a file. crypto.getRandomValues caps at 65536 bytes per call, // so we fill in chunks. export const randomBytes = (size: number): Uint8Array => { const out = new Uint8Array(size) const chunk = 65536 for (let offset = 0; offset < size; offset += chunk) { crypto.getRandomValues(out.subarray(offset, Math.min(offset + chunk, size))) } return out }