/**
 * @bytelyst/client-encrypt — Hex encoding utilities
 *
 * Converts between Uint8Array and hex strings.
 * Compatible with the hex encoding used by @bytelyst/field-encrypt (Node.js)
 * and BLFieldEncrypt (Swift/Kotlin).
 */

/** Encode a Uint8Array to a lowercase hex string. */
export function toHex(bytes: Uint8Array): string {
  const parts: string[] = new Array(bytes.length);
  for (let i = 0; i < bytes.length; i++) {
    parts[i] = bytes[i].toString(16).padStart(2, '0');
  }
  return parts.join('');
}

/** Decode a hex string to a Uint8Array. */
export function fromHex(hex: string): Uint8Array {
  if (hex.length % 2 !== 0) {
    throw new Error(`Hex string must have even length, got ${hex.length}`);
  }
  const bytes = new Uint8Array(hex.length / 2);
  for (let i = 0; i < bytes.length; i++) {
    bytes[i] = parseInt(hex.substring(i * 2, i * 2 + 2), 16);
  }
  return bytes;
}
