Hyperlinkv0.8.0-beta.28

Encoding

Encoding.decodeHexconsteffect/Encoding.ts:447
(str: string): Result.Result<Uint8Array, EncodingError>

Decodes a hexadecimal string into bytes safely.

When to use

Use to decode hexadecimal text 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 has an odd length or contains invalid hex characters.

Example (Decoding hex bytes)

import { Encoding, Result } from "effect"

const result = Encoding.decodeHex("48656c6c6f")
if (Result.isSuccess(result)) {
  console.log(Array.from(result.success)) // [72, 101, 108, 108, 111]
}
decoding
Source effect/Encoding.ts:44734 lines
export const decodeHex = (str: string): Result.Result<Uint8Array, EncodingError> => {
  const bytes = new TextEncoder().encode(str)
  if (bytes.length % 2 !== 0) {
    return Result.fail(
      new EncodingError({
        module: "Hex",
        kind: "Decode",
        input: str,
        message: `Length must be a multiple of 2, but is ${bytes.length}`
      })
    )
  }

  try {
    const length = bytes.length / 2
    const result = new Uint8Array(length)
    for (let i = 0; i < length; i++) {
      const a = fromHexChar(bytes[i * 2])
      const b = fromHexChar(bytes[i * 2 + 1])
      result[i] = (a << 4) | b
    }

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