MCPcopy Create free account
hub / github.com/Effect-TS/effect / decodeHex

Function decodeHex

packages/effect/src/Encoding.ts:432–465  ·  view source on GitHub ↗
(str: string)

Source from the content-addressed store, hash-verified

430 * @since 2.0.0
431 */
432export const decodeHex = (str: string): Result.Result<Uint8Array, EncodingError> => {
433 const bytes = new TextEncoder().encode(str)
434 if (bytes.length % 2 !== 0) {
435 return Result.fail(
436 new EncodingError({
437 module: "Hex",
438 kind: "Decode",
439 input: str,
440 message: `Length must be a multiple of 2, but is ${bytes.length}`
441 })
442 )
443 }
444
445 try {
446 const length = bytes.length / 2
447 const result = new Uint8Array(length)
448 for (let i = 0; i < length; i++) {
449 const a = fromHexChar(bytes[i * 2])
450 const b = fromHexChar(bytes[i * 2 + 1])
451 result[i] = (a << 4) | b
452 }
453
454 return Result.succeed(result)
455 } catch (e) {
456 return Result.fail(
457 new EncodingError({
458 module: "Hex",
459 kind: "Decode",
460 input: str,
461 message: e instanceof Error ? e.message : "Invalid input"
462 })
463 )
464 }
465}
466
467/**
468 * Decodes a hexadecimal string into a UTF-8 string safely.

Callers 1

decodeHexStringFunction · 0.70

Calls 3

fromHexCharFunction · 0.85
failMethod · 0.45
succeedMethod · 0.45

Tested by

no test coverage detected