// Copyright 2018-2024 the Deno authors. All rights reserved. MIT license.
// This module is browser compatible.

import { concat } from "jsr:@std/bytes@^1.0.2/concat";
import { DEFAULT_CHUNK_SIZE } from "./_constants.ts";
import type { Reader, ReaderSync } from "./types.ts";

/**
 * Read {@linkcode Reader} `r` until EOF (`null`) and resolve to the content as
 * {@linkcode Uint8Array}.
 *
 * @example Usage
 * ```ts no-eval
 * import { readAll } from "@std/io/read-all";
 *
 * // Example from stdin
 * const stdinContent = await readAll(Deno.stdin);
 *
 * // Example from file
 * using file = await Deno.open("my_file.txt", {read: true});
 * const myFileContent = await readAll(file);
 * ```
 *
 * @param reader The reader to read from
 * @returns The content as Uint8Array
 */
export async function readAll(reader: Reader): Promise<Uint8Array> {
  const chunks: Uint8Array[] = [];
  while (true) {
    let chunk = new Uint8Array(DEFAULT_CHUNK_SIZE);
    const n = await reader.read(chunk);
    if (n === null) {
      break;
    }
    if (n < DEFAULT_CHUNK_SIZE) {
      chunk = chunk.subarray(0, n);
    }
    chunks.push(chunk);
  }
  return concat(chunks);
}

/**
 * Synchronously reads {@linkcode ReaderSync} `r` until EOF (`null`) and returns
 * the content as {@linkcode Uint8Array}.
 *
 * @example Usage
 * ```ts no-eval
 * import { readAllSync } from "@std/io/read-all";
 *
 * // Example from stdin
 * const stdinContent = readAllSync(Deno.stdin);
 *
 * // Example from file
 * using file = Deno.openSync("my_file.txt", {read: true});
 * const myFileContent = readAllSync(file);
 * ```
 *
 * @param reader The reader to read from
 * @returns The content as Uint8Array
 */
export function readAllSync(reader: ReaderSync): Uint8Array {
  const chunks: Uint8Array[] = [];
  while (true) {
    const chunk = new Uint8Array(DEFAULT_CHUNK_SIZE);
    const n = reader.readSync(chunk);
    if (n === null) {
      break;
    }
    if (n < DEFAULT_CHUNK_SIZE) {
      chunks.push(chunk.subarray(0, n));
      break;
    }
    chunks.push(chunk);
  }
  return concat(chunks);
}

// denoCacheMetadata={"headers":{"vary":"Origin","content-length":"2080","report-to":"{\"group\":\"cf-nel\",\"max_age\":604800,\"endpoints\":[{\"url\":\"https://a.nel.cloudflare.com/report/v4?s=62YdMghB4lfhq9d9Qx3P6xzn7AhgAQKqFlRww6oABDGOz%2BwQQn1ABfnFfrOsYQobfYfmA86sybGRaKqTNezoCwgehmGhAXoQc2Nj%2Fn4%2BGrKDngnHjEGPy2Y%3D\"}]}","x-content-type-options":"nosniff","server":"cloudflare","alt-svc":"h3=\":443\"; ma=86400","date":"Tue, 28 Jul 2026 12:31:15 GMT","cf-ray":"a223e656f86a7db6-LAX","access-control-expose-headers":"*","etag":"\"2f4f0976d6d54906fc23bc1a450c6820\"","cross-origin-resource-policy":"cross-origin","x-jsr-backend":"modules","set-cookie":"__cf_bm=uNFtimX.lKrzB9Muta_lWk_7l0bPUXN0XVS9e.ew8yk-1785241875.0336013-1.0.1.1-GeXC4FaAcYO8DRkcuSj69C.7o957cgNwDVYezNZDmiHCSAIHjHBXoS43xqYaj14MJVNnkOaroKtWA1I7Jx2flli6fiI.3MkcDfTUHQlbEutuxTH8_GXHLwxdT1LDcaMQ; HttpOnly; SameSite=None; Secure; Path=/; Domain=jsr.io; Expires=Tue, 28 Jul 2026 13:01:15 GMT","content-type":"text/typescript","access-control-allow-origin":"*","nel":"{\"report_to\":\"cf-nel\",\"success_fraction\":0.0,\"max_age\":604800}","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';","x-robots-tag":"noindex","cache-control":"public, max-age=31536000, immutable"},"url":"https://jsr.io/@std/io/0.224.8/read_all.ts","time":1785241875}