// Copyright 2009 The Go Authors. All rights reserved.
// https://github.com/golang/go/blob/master/LICENSE
// Copyright 2018-2024 the Deno authors. All rights reserved. MIT license.
// This module is browser compatible.

/**
 * Port of the Go
 * {@link https://github.com/golang/go/blob/go1.12.5/src/encoding/hex/hex.go | encoding/hex}
 * library.
 *
 * ```ts
 * import {
 *   decodeHex,
 *   encodeHex,
 * } from "@std/encoding/hex";
 * import { assertEquals } from "@std/assert/assert-equals";
 *
 * assertEquals(encodeHex("abc"), "616263");
 *
 * assertEquals(
 *   decodeHex("616263"),
 *   new TextEncoder().encode("abc"),
 * );
 * ```
 *
 * @module
 */

import { validateBinaryLike } from "./_validate_binary_like.ts";

const hexTable = new TextEncoder().encode("0123456789abcdef");
const textEncoder = new TextEncoder();
const textDecoder = new TextDecoder();

function errInvalidByte(byte: number) {
  return new TypeError(`Invalid byte '${String.fromCharCode(byte)}'`);
}

function errLength() {
  return new RangeError("Odd length hex string");
}

/** Converts a hex character into its value. */
function fromHexChar(byte: number): number {
  // '0' <= byte && byte <= '9'
  if (48 <= byte && byte <= 57) return byte - 48;
  // 'a' <= byte && byte <= 'f'
  if (97 <= byte && byte <= 102) return byte - 97 + 10;
  // 'A' <= byte && byte <= 'F'
  if (65 <= byte && byte <= 70) return byte - 65 + 10;

  throw errInvalidByte(byte);
}

/**
 * Converts data into a hex-encoded string.
 *
 * @param src The data to encode.
 *
 * @returns The hex-encoded string.
 *
 * @example Usage
 * ```ts
 * import { encodeHex } from "@std/encoding/hex";
 * import { assertEquals } from "@std/assert/assert-equals";
 *
 * assertEquals(encodeHex("abc"), "616263");
 * ```
 */
export function encodeHex(src: string | Uint8Array | ArrayBuffer): string {
  const u8 = validateBinaryLike(src);

  const dst = new Uint8Array(u8.length * 2);
  for (let i = 0; i < dst.length; i++) {
    const v = u8[i]!;
    dst[i * 2] = hexTable[v >> 4]!;
    dst[i * 2 + 1] = hexTable[v & 0x0f]!;
  }
  return textDecoder.decode(dst);
}

/**
 * Decodes the given hex-encoded string. If the input is malformed, an error is
 * thrown.
 *
 * @param src The hex-encoded string to decode.
 *
 * @returns The decoded data.
 *
 * @example Usage
 * ```ts
 * import { decodeHex } from "@std/encoding/hex";
 * import { assertEquals } from "@std/assert/assert-equals";
 *
 * assertEquals(
 *   decodeHex("616263"),
 *   new TextEncoder().encode("abc"),
 * );
 * ```
 */
export function decodeHex(src: string): Uint8Array {
  const u8 = textEncoder.encode(src);
  const dst = new Uint8Array(u8.length / 2);
  for (let i = 0; i < dst.length; i++) {
    const a = fromHexChar(u8[i * 2]!);
    const b = fromHexChar(u8[i * 2 + 1]!);
    dst[i] = (a << 4) | b;
  }

  if (u8.length % 2 === 1) {
    // Check for invalid char before reporting bad length,
    // since the invalid char (if present) is an earlier problem.
    fromHexChar(u8[dst.length * 2]!);
    throw errLength();
  }

  return dst;
}

// denoCacheMetadata={"headers":{"report-to":"{\"group\":\"cf-nel\",\"max_age\":604800,\"endpoints\":[{\"url\":\"https://a.nel.cloudflare.com/report/v4?s=Y1GhOqoZzLOvb82WIbFtR0XftSrSsH0aCYR90l7e2U0nc4b3V48uGPxodjz79dLLWeqDEzCL%2BZ1QgKU9RwsWVCLjeFwnrEOR51aNUIvOc7PEkc1wLSQaQ6Y%3D\"}]}","cross-origin-resource-policy":"cross-origin","x-jsr-backend":"modules","content-length":"3056","content-security-policy":"default-src 'none'; script-src 'none'; style-src 'none'; img-src 'none'; font-src 'none'; connect-src 'none'; frame-src 'none'; object-src 'none'; frame-ancestors 'none'; sandbox; form-action 'none';","content-type":"text/typescript","access-control-expose-headers":"*","cache-control":"public, max-age=31536000, immutable","alt-svc":"h3=\":443\"; ma=86400","access-control-allow-origin":"*","vary":"Origin","date":"Tue, 28 Jul 2026 12:31:15 GMT","set-cookie":"__cf_bm=cqDtSqPU45O1WLusifbrXTg_gBQzDN6evebwbRX.l7A-1785241875.3128684-1.0.1.1-.dxO0tA2J4SdqnNo2F9xBzhyy5R3Y4QmicKAQGZ.ufgMK3MvfQp8FbBiIlWy7X1mXF.mp2VZdUzBU5_m1r.m_oGU4ANAGT6lhEsbG5fP.2wo2Dvjs.7UTIbAMAK.OvYk; HttpOnly; SameSite=None; Secure; Path=/; Domain=jsr.io; Expires=Tue, 28 Jul 2026 13:01:15 GMT","nel":"{\"report_to\":\"cf-nel\",\"success_fraction\":0.0,\"max_age\":604800}","x-robots-tag":"noindex","cf-ray":"a223e658bd397db6-LAX","x-content-type-options":"nosniff","etag":"\"bef48b0e2e46b3a8893ca7d438d0545c\"","server":"cloudflare"},"url":"https://jsr.io/@std/encoding/1.0.0-rc.2/hex.ts","time":1785241875}