MCPcopy Index your code
hub / github.com/Effect-TS/effect / decode

Function decode

packages/effect/src/internal/encoding/base64.ts:38–74  ·  view source on GitHub ↗
(str: string)

Source from the content-addressed store, hash-verified

36
37/** @internal */
38export 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 */
77export const stripCrlf = (str: string) => str.replace(/[\n\r]/g, "")

Callers

nothing calls this directly

Calls 3

stripCrlfFunction · 0.85
getBase64CodeFunction · 0.85
DecodeExceptionFunction · 0.70

Tested by

no test coverage detected