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

import { Buffer } from "./buffer.ts";
import { writeAll } from "./write_all.ts";
import type { Reader } from "./types.ts";

/**
 * Create a {@linkcode Reader} from a {@linkcode ReadableStreamDefaultReader}.
 *
 * @example Usage
 * ```ts no-assert
 * import { copy } from "@std/io/copy";
 * import { readerFromStreamReader } from "@std/io/reader-from-stream-reader";
 *
 * const res = await fetch("https://deno.land");
 *
 * const reader = readerFromStreamReader(res.body!.getReader());
 * await copy(reader, Deno.stdout);
 * ```
 *
 * @param streamReader The stream reader to read from
 * @returns The reader
 */
export function readerFromStreamReader(
  streamReader: ReadableStreamDefaultReader<Uint8Array>,
): Reader {
  const buffer = new Buffer();

  return {
    async read(p: Uint8Array): Promise<number | null> {
      if (buffer.empty()) {
        const res = await streamReader.read();
        if (res.done) {
          return null; // EOF
        }

        await writeAll(buffer, res.value);
      }

      return buffer.read(p);
    },
  };
}

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