Hyperlinkv0.8.0-beta.28

Encoding

Encoding.decodeBase64consteffect/Encoding.ts:177
(str: string): Result.Result<Uint8Array, EncodingError>

Decodes a base64 (RFC4648) string into bytes safely.

When to use

Use to decode a standard padded Base64 string into bytes without throwing on invalid input.

Details

Returns Result.succeed with a Uint8Array when decoding succeeds, or Result.fail with an EncodingError when the input is not valid base64.

Example (Decoding Base64 bytes)

import { Encoding, Result } from "effect"

const result = Encoding.decodeBase64("SGVsbG8=")
if (Result.isSuccess(result)) {
  console.log(Array.from(result.success)) // [72, 101, 108, 108, 111]
}
decoding
Source effect/Encoding.ts:17752 lines
export const decodeBase64 = (str: string): Result.Result<Uint8Array, EncodingError> => {
  const stripped = stripCrlf(str)
  const length = stripped.length
  if (length % 4 !== 0) {
    return Result.fail(
      new EncodingError({
        kind: "Decode",
        module: "Base64",
        input: stripped,
        message: `Length must be a multiple of 4, but is ${length}`
      })
    )
  }

  const index = stripped.indexOf("=")
  if (index !== -1 && ((index < length - 2) || (index === length - 2 && stripped[length - 1] !== "="))) {
    return Result.fail(
      new EncodingError({
        kind: "Decode",
        module: "Base64",
        input: stripped,
        message: `Found a '=' character, but it is not at the end`
      })
    )
  }

  try {
    const missingOctets = stripped.endsWith("==") ? 2 : stripped.endsWith("=") ? 1 : 0
    const result = new Uint8Array(3 * (length / 4) - missingOctets)
    for (let i = 0, j = 0; i < length; i += 4, j += 3) {
      const buffer = getBase64Code(stripped.charCodeAt(i)) << 18 |
        getBase64Code(stripped.charCodeAt(i + 1)) << 12 |
        getBase64Code(stripped.charCodeAt(i + 2)) << 6 |
        getBase64Code(stripped.charCodeAt(i + 3))

      result[j] = buffer >> 16
      result[j + 1] = (buffer >> 8) & 0xff
      result[j + 2] = buffer & 0xff
    }

    return Result.succeed(result)
  } catch (e) {
    return Result.fail(
      new EncodingError({
        kind: "Decode",
        module: "Base64",
        input: stripped,
        message: e instanceof Error ? e.message : "Invalid input"
      })
    )
  }
}
Referenced by 4 symbols