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

import { DEFAULT_BUFFER_SIZE } from "./_constants.ts";
import { writeAll } from "./write_all.ts";
import type { Reader, Writer } from "./types.ts";

/**
 * Copies from `src` to `dst` until either EOF (`null`) is read from `src` or
 * an error occurs. It resolves to the number of bytes copied or rejects with
 * the first error encountered while copying.
 *
 * @example Usage
 * ```ts no-eval
 * import { copy } from "@std/io/copy";
 *
 * const source = await Deno.open("my_file.txt");
 * const bytesCopied1 = await copy(source, Deno.stdout);
 * const destination = await Deno.create("my_file_2.txt");
 * const bytesCopied2 = await copy(source, destination);
 * ```
 *
 * @param src The source to copy from
 * @param dst The destination to copy to
 * @param options Can be used to tune size of the buffer. Default size is 32kB
 * @returns Number of bytes copied
 */
export async function copy(
  src: Reader,
  dst: Writer,
  options?: {
    bufSize?: number;
  },
): Promise<number> {
  let n = 0;
  const b = new Uint8Array(options?.bufSize ?? DEFAULT_BUFFER_SIZE);
  while (true) {
    const result = await src.read(b);
    if (result === null) break;
    await writeAll(dst, b.subarray(0, result));
    n += result;
  }
  return n;
}

// denoCacheMetadata={"headers":{"date":"Tue, 28 Jul 2026 12:31:15 GMT","x-content-type-options":"nosniff","content-type":"text/typescript","vary":"Origin","set-cookie":"__cf_bm=Ki01EbNudjWniB.gfDtNpKulQA_B_nPZ5_xDSKrtemc-1785241875.0321658-1.0.1.1-_FOgPqbeF1sB6iVN08USAKgODZbyYTY.9mzYxIPHdzyJlSkjLNmzjp7zgcHvXZHn9OrXmzKYYM5qsT.B2n8ji0e.fJVdhyDqlJZbDr.W5.vTTlmxkK7VE9plz8M6d6YC; HttpOnly; SameSite=None; Secure; Path=/; Domain=jsr.io; Expires=Tue, 28 Jul 2026 13:01:15 GMT","alt-svc":"h3=\":443\"; ma=86400","x-robots-tag":"noindex","cache-control":"public, max-age=31536000, immutable","etag":"\"c719c7b76493f37ce48bdd04f6f4e157\"","content-length":"1352","nel":"{\"report_to\":\"cf-nel\",\"success_fraction\":0.0,\"max_age\":604800}","x-jsr-backend":"modules","server":"cloudflare","cf-ray":"a223e656f8627db6-LAX","report-to":"{\"group\":\"cf-nel\",\"max_age\":604800,\"endpoints\":[{\"url\":\"https://a.nel.cloudflare.com/report/v4?s=EmUVLA%2B2jHpGRCdz0LATLCt2YuuLP4Jn%2B5NUfluYu%2FS%2Fsr9jy%2FFG7OCMrUF7xXsxzG%2BnslYKlqpsIQ64Eg%2BzDRWSoYqfqzcjCU4WtUQ8uGAHMS5AQIQdRZ4%3D\"}]}","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';","access-control-expose-headers":"*","access-control-allow-origin":"*","cross-origin-resource-policy":"cross-origin"},"url":"https://jsr.io/@std/io/0.224.8/copy.ts","time":1785241875}