(str: string)
| 36 | |
| 37 | /** @internal */ |
| 38 | export const decode = (str: string): Either.Either<Uint8Array, Encoding.DecodeException> => { |
| 39 | const stripped = stripCrlf(str) |
| 40 | const length = stripped.length |
| 41 | if (length % 4 !== 0) { |
| 42 | return Either.left( |
| 43 | DecodeException(stripped, `Length must be a multiple of 4, but is ${length}`) |
| 44 | ) |
| 45 | } |
| 46 | |
| 47 | const index = stripped.indexOf("=") |
| 48 | if (index !== -1 && ((index < length - 2) || (index === length - 2 && stripped[length - 1] !== "="))) { |
| 49 | return Either.left( |
| 50 | DecodeException(stripped, "Found a '=' character, but it is not at the end") |
| 51 | ) |
| 52 | } |
| 53 | |
| 54 | try { |
| 55 | const missingOctets = stripped.endsWith("==") ? 2 : stripped.endsWith("=") ? 1 : 0 |
| 56 | const result = new Uint8Array(3 * (length / 4) - missingOctets) |
| 57 | for (let i = 0, j = 0; i < length; i += 4, j += 3) { |
| 58 | const buffer = getBase64Code(stripped.charCodeAt(i)) << 18 | |
| 59 | getBase64Code(stripped.charCodeAt(i + 1)) << 12 | |
| 60 | getBase64Code(stripped.charCodeAt(i + 2)) << 6 | |
| 61 | getBase64Code(stripped.charCodeAt(i + 3)) |
| 62 | |
| 63 | result[j] = buffer >> 16 |
| 64 | result[j + 1] = (buffer >> 8) & 0xff |
| 65 | result[j + 2] = buffer & 0xff |
| 66 | } |
| 67 | |
| 68 | return Either.right(result) |
| 69 | } catch (e) { |
| 70 | return Either.left( |
| 71 | DecodeException(stripped, e instanceof Error ? e.message : "Invalid input") |
| 72 | ) |
| 73 | } |
| 74 | } |
| 75 | |
| 76 | /** @internal */ |
| 77 | export const stripCrlf = (str: string) => str.replace(/[\n\r]/g, "") |
nothing calls this directly
no test coverage detected