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

import type { Reader, Writer } from "./types.ts";

const DEFAULT_BUFFER_SIZE = 32 * 1024;

/**
 * Copy N size at the most. If read size is lesser than N, then returns nread
 *
 * @example Usage
 * ```ts
 * import { copyN } from "@std/io/copy-n";
 * import { assertEquals } from "@std/assert/equals";
 *
 * const source = await Deno.open("README.md");
 *
 * const res = await copyN(source, Deno.stdout, 10);
 * assertEquals(res, 10);
 * ```
 *
 * @param r Reader
 * @param dest Writer
 * @param size Read size
 * @returns Number of bytes copied
 *
 * @deprecated This will be removed in 1.0.0. Use the {@link https://developer.mozilla.org/en-US/docs/Web/API/Streams_API | Web Streams API} instead.
 */
export async function copyN(
  r: Reader,
  dest: Writer,
  size: number,
): Promise<number> {
  let bytesRead = 0;
  let buf = new Uint8Array(DEFAULT_BUFFER_SIZE);
  while (bytesRead < size) {
    if (size - bytesRead < DEFAULT_BUFFER_SIZE) {
      buf = new Uint8Array(size - bytesRead);
    }
    const result = await r.read(buf);
    const nread = result ?? 0;
    bytesRead += nread;
    if (nread > 0) {
      let n = 0;
      while (n < nread) {
        n += await dest.write(buf.slice(n, nread));
      }
      if (n !== nread) {
        throw new Error("Could not write");
      }
    }
    if (result === null) {
      break;
    }
  }
  return bytesRead;
}

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