| 4 | import { replaceCharAt } from "./utils.js"; |
| 5 | |
| 6 | export function crockfordEncode(input: Uint8Array): string { |
| 7 | const output: number[] = []; |
| 8 | let bitsRead = 0; |
| 9 | let buffer = 0; |
| 10 | const reversedInput = new Uint8Array(input.slice().reverse()); |
| 11 | for (const byte of reversedInput) { |
| 12 | buffer |= byte << bitsRead; |
| 13 | bitsRead += 8; |
| 14 | |
| 15 | while (bitsRead >= 5) { |
| 16 | output.unshift(buffer & 0x1f); |
| 17 | buffer >>>= 5; |
| 18 | bitsRead -= 5; |
| 19 | } |
| 20 | } |
| 21 | if (bitsRead > 0) { |
| 22 | output.unshift(buffer & 0x1f); |
| 23 | } |
| 24 | return output.map(byte => B32_CHARACTERS.charAt(byte)).join(""); |
| 25 | } |
| 26 | |
| 27 | export function crockfordDecode(input: string): Uint8Array { |
| 28 | const sanitizedInput = input.toUpperCase().split("").reverse().join(""); |