// Copyright 2018-2024 the Deno authors. All rights reserved. MIT license.
// Copyright (c) 2014 Jameson Little. MIT License.
// This module is browser compatible.

/**
 * Utilities for
 * {@link https://datatracker.ietf.org/doc/html/rfc4648#section-6 | base32}
 * encoding and decoding.
 *
 * Modified from {@link https://github.com/beatgammit/base64-js}.
 *
 * This module is browser compatible.
 *
 * ```ts
 * import { encodeBase32, decodeBase32 } from "https://deno.land/std@$STD_VERSION/encoding/base32.ts";
 *
 * const encoded = encodeBase32("foobar"); // "MZXW6YTBOI======"
 *
 * decodeBase32(encoded); // Uint8Array(6) [ 102, 111, 111, 98, 97, 114 ]
 * ```
 *
 * @module
 */

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

const lookup: string[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567".split("");
const revLookup: number[] = [];
lookup.forEach((c, i) => revLookup[c.charCodeAt(0)] = i);

const placeHolderPadLookup = [0, 1, , 2, 3, , 4];
function _getPadLen(placeHoldersLen: number): number {
  const maybeLen = placeHolderPadLookup[placeHoldersLen];
  if (typeof maybeLen !== "number") {
    throw new Error("Invalid pad length");
  }
  return maybeLen;
}

function getLens(b32: string): [number, number] {
  const len = b32.length;

  if (len % 8 > 0) {
    throw new Error("Invalid string. Length must be a multiple of 8");
  }

  let validLen = b32.indexOf("=");
  if (validLen === -1) validLen = len;

  const placeHoldersLen = validLen === len ? 0 : 8 - (validLen % 8);

  return [validLen, placeHoldersLen];
}

function _byteLength(validLen: number, placeHoldersLen: number): number {
  return ((validLen + placeHoldersLen) * 5) / 8 - _getPadLen(placeHoldersLen);
}

/**
 * Decodes a base32-encoded string.
 *
 * @see {@link https://datatracker.ietf.org/doc/html/rfc4648#section-6}
 *
 * @param b32 The base32-encoded string to decode.
 * @returns The decoded data.
 *
 * @example
 * ```ts
 * import { decodeBase32 } from "https://deno.land/std@$STD_VERSION/encoding/base32.ts";
 *
 * decodeBase32("NRQMA===");
 * // Uint8Array(3) [ 108, 96, 192 ]
 * ```
 */
export function decodeBase32(b32: string): Uint8Array {
  let tmp: number;
  const [validLen, placeHoldersLen] = getLens(b32);

  const arr = new Uint8Array(_byteLength(validLen, placeHoldersLen));

  let curByte = 0;

  // if there are placeholders, only get up to the last complete 8 chars
  const len = placeHoldersLen > 0 ? validLen - 8 : validLen;

  let i: number;
  for (i = 0; i < len; i += 8) {
    tmp = (revLookup[b32.charCodeAt(i)]! << 20) |
      (revLookup[b32.charCodeAt(i + 1)]! << 15) |
      (revLookup[b32.charCodeAt(i + 2)]! << 10) |
      (revLookup[b32.charCodeAt(i + 3)]! << 5) |
      revLookup[b32.charCodeAt(i + 4)]!;
    arr[curByte++] = (tmp >> 17) & 0xff;
    arr[curByte++] = (tmp >> 9) & 0xff;
    arr[curByte++] = (tmp >> 1) & 0xff;

    tmp = ((tmp & 1) << 15) |
      (revLookup[b32.charCodeAt(i + 5)]! << 10) |
      (revLookup[b32.charCodeAt(i + 6)]! << 5) |
      revLookup[b32.charCodeAt(i + 7)]!;
    arr[curByte++] = (tmp >> 8) & 0xff;
    arr[curByte++] = tmp & 0xff;
  }

  if (placeHoldersLen === 1) {
    tmp = (revLookup[b32.charCodeAt(i)]! << 20) |
      (revLookup[b32.charCodeAt(i + 1)]! << 15) |
      (revLookup[b32.charCodeAt(i + 2)]! << 10) |
      (revLookup[b32.charCodeAt(i + 3)]! << 5) |
      revLookup[b32.charCodeAt(i + 4)]!;
    arr[curByte++] = (tmp >> 17) & 0xff;
    arr[curByte++] = (tmp >> 9) & 0xff;
    arr[curByte++] = (tmp >> 1) & 0xff;
    tmp = ((tmp & 1) << 7) |
      (revLookup[b32.charCodeAt(i + 5)]! << 2) |
      (revLookup[b32.charCodeAt(i + 6)]! >> 3);
    arr[curByte++] = tmp & 0xff;
  } else if (placeHoldersLen === 3) {
    tmp = (revLookup[b32.charCodeAt(i)]! << 19) |
      (revLookup[b32.charCodeAt(i + 1)]! << 14) |
      (revLookup[b32.charCodeAt(i + 2)]! << 9) |
      (revLookup[b32.charCodeAt(i + 3)]! << 4) |
      (revLookup[b32.charCodeAt(i + 4)]! >> 1);
    arr[curByte++] = (tmp >> 16) & 0xff;
    arr[curByte++] = (tmp >> 8) & 0xff;
    arr[curByte++] = tmp & 0xff;
  } else if (placeHoldersLen === 4) {
    tmp = (revLookup[b32.charCodeAt(i)]! << 11) |
      (revLookup[b32.charCodeAt(i + 1)]! << 6) |
      (revLookup[b32.charCodeAt(i + 2)]! << 1) |
      (revLookup[b32.charCodeAt(i + 3)]! >> 4);
    arr[curByte++] = (tmp >> 8) & 0xff;
    arr[curByte++] = tmp & 0xff;
  } else if (placeHoldersLen === 6) {
    tmp = (revLookup[b32.charCodeAt(i)]! << 3) |
      (revLookup[b32.charCodeAt(i + 1)]! >> 2);
    arr[curByte++] = tmp & 0xff;
  }

  return arr;
}

function encodeChunk(uint8: Uint8Array, start: number, end: number): string {
  let tmp: number;
  const output = [];
  for (let i = start; i < end; i += 5) {
    tmp = ((uint8[i]! << 16) & 0xff0000) |
      ((uint8[i + 1]! << 8) & 0xff00) |
      (uint8[i + 2]! & 0xff);
    output.push(lookup[(tmp >> 19) & 0x1f]);
    output.push(lookup[(tmp >> 14) & 0x1f]);
    output.push(lookup[(tmp >> 9) & 0x1f]);
    output.push(lookup[(tmp >> 4) & 0x1f]);
    tmp = ((tmp & 0xf) << 16) |
      ((uint8[i + 3]! << 8) & 0xff00) |
      (uint8[i + 4]! & 0xff);
    output.push(lookup[(tmp >> 15) & 0x1f]);
    output.push(lookup[(tmp >> 10) & 0x1f]);
    output.push(lookup[(tmp >> 5) & 0x1f]);
    output.push(lookup[tmp & 0x1f]);
  }
  return output.join("");
}

/**
 * Converts data into a base32-encoded string.
 *
 * @see {@link https://datatracker.ietf.org/doc/html/rfc4648#section-6}
 *
 * @param data The data to encode.
 * @returns The base32-encoded string.
 *
 * @example
 * ```ts
 * import { encodeBase32 } from "https://deno.land/std@$STD_VERSION/encoding/base32.ts";
 *
 * encodeBase32("6c60c0"); // "NRQMA==="
 * ```
 */
export function encodeBase32(data: ArrayBuffer | Uint8Array | string): string {
  const uint8 = validateBinaryLike(data);

  let tmp: number;
  const len = uint8.length;
  const extraBytes = len % 5;
  const parts = [];
  const maxChunkLength = 16385; // must be multiple of 5
  const len2 = len - extraBytes;

  // go through the array every 5 bytes, we'll deal with trailing stuff later
  for (let i = 0; i < len2; i += maxChunkLength) {
    parts.push(
      encodeChunk(
        uint8,
        i,
        i + maxChunkLength > len2 ? len2 : i + maxChunkLength,
      ),
    );
  }

  // pad the end with zeros, but make sure to not forget the extra bytes
  if (extraBytes === 4) {
    tmp = ((uint8[len2]! & 0xff) << 16) |
      ((uint8[len2 + 1]! & 0xff) << 8) |
      (uint8[len2 + 2]! & 0xff);
    parts.push(lookup[(tmp >> 19) & 0x1f]);
    parts.push(lookup[(tmp >> 14) & 0x1f]);
    parts.push(lookup[(tmp >> 9) & 0x1f]);
    parts.push(lookup[(tmp >> 4) & 0x1f]);
    tmp = ((tmp & 0xf) << 11) | (uint8[len2 + 3]! << 3);
    parts.push(lookup[(tmp >> 10) & 0x1f]);
    parts.push(lookup[(tmp >> 5) & 0x1f]);
    parts.push(lookup[tmp & 0x1f]);
    parts.push("=");
  } else if (extraBytes === 3) {
    tmp = ((uint8[len2]! & 0xff) << 17) |
      ((uint8[len2 + 1]! & 0xff) << 9) |
      ((uint8[len2 + 2]! & 0xff) << 1);
    parts.push(lookup[(tmp >> 20) & 0x1f]);
    parts.push(lookup[(tmp >> 15) & 0x1f]);
    parts.push(lookup[(tmp >> 10) & 0x1f]);
    parts.push(lookup[(tmp >> 5) & 0x1f]);
    parts.push(lookup[tmp & 0x1f]);
    parts.push("===");
  } else if (extraBytes === 2) {
    tmp = ((uint8[len2]! & 0xff) << 12) |
      ((uint8[len2 + 1]! & 0xff) << 4);
    parts.push(lookup[(tmp >> 15) & 0x1f]);
    parts.push(lookup[(tmp >> 10) & 0x1f]);
    parts.push(lookup[(tmp >> 5) & 0x1f]);
    parts.push(lookup[tmp & 0x1f]);
    parts.push("====");
  } else if (extraBytes === 1) {
    tmp = (uint8[len2]! & 0xff) << 2;
    parts.push(lookup[(tmp >> 5) & 0x1f]);
    parts.push(lookup[tmp & 0x1f]);
    parts.push("======");
  }

  return parts.join("");
}

// denoCacheMetadata={"headers":{"via":"1.1 8267ddda05eecda7c23d647573952fee.cloudfront.net (CloudFront),HTTP/2 ord.vultr.prod.deno-cluster.net","cross-origin-resource-policy":"same-origin","server-timing":"fetchSource;dur=9","date":"Tue, 14 Jul 2026 15:18:30 GMT","access-control-allow-origin":"*","alt-svc":"h3=\":443\"; ma=86400","strict-transport-security":"max-age=63072000; includeSubDomains; preload","referrer-policy":"strict-origin-when-cross-origin","x-frame-options":"DENY","content-security-policy":"default-src 'none'; style-src 'unsafe-inline'; sandbox","access-control-max-age":"0","content-length":"7740","etag":"\"d4af86a998208e3168ae0b658078dc7c\"","x-deno-trace-id":"37cff4f1c8752542e4ffb09f8dc619ae","cache-status":"deno; hit","x-amz-version-id":"cVblyZ1xxnxtCMmQwt4LPBCHQCn4SO._","x-amz-cf-id":"toeebhhdKk05swWIGVn-Uay41ktm05T89odftwbP1ZMjwbO99x9XzQ==","cache-control":"public, max-age=31536000, immutable","x-amz-replication-status":"COMPLETED","x-cache":"Hit from cloudfront","x-amz-cf-pop":"ORD56-P16","last-modified":"Thu, 25 Apr 2024 03:01:09 GMT","cross-origin-embedder-policy":"same-origin","server":"AmazonS3,deployd","x-content-type-options":"nosniff","age":"1199563","accept-ranges":"bytes","access-control-allow-methods":"GET, HEAD","x-amz-server-side-encryption":"AES256","content-type":"application/typescript; charset=utf-8","cross-origin-opener-policy":"same-origin"},"url":"https://deno.land/std@0.224.0/encoding/base32.ts","time":1785241873}