| 25 | } |
| 26 | |
| 27 | export function crockfordDecode(input: string): Uint8Array { |
| 28 | const sanitizedInput = input.toUpperCase().split("").reverse().join(""); |
| 29 | const output: number[] = []; |
| 30 | let bitsRead = 0; |
| 31 | let buffer = 0; |
| 32 | for (const character of sanitizedInput) { |
| 33 | const byte = B32_CHARACTERS.indexOf(character); |
| 34 | if (byte === -1) { |
| 35 | throw new Error(`Invalid base 32 character found in string: ${character}`); |
| 36 | } |
| 37 | buffer |= byte << bitsRead; |
| 38 | bitsRead += 5; |
| 39 | while (bitsRead >= 8) { |
| 40 | output.unshift(buffer & 0xff); |
| 41 | buffer >>>= 8; |
| 42 | bitsRead -= 8; |
| 43 | } |
| 44 | } |
| 45 | if (bitsRead >= 5 || buffer > 0) { |
| 46 | output.unshift(buffer & 0xff); |
| 47 | } |
| 48 | return new Uint8Array(output); |
| 49 | } |
| 50 | |
| 51 | /** |
| 52 | * Fix a ULID's Base32 encoding - |