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

import { concat } from "jsr:/@std/bytes@^1.0.0-rc.3/concat";

/**
 * Converts a {@linkcode ReadableStream} of {@linkcode Uint8Array}s to an
 * {@linkcode ArrayBuffer}. Works the same as {@linkcode Response.arrayBuffer}.
 *
 * @param readableStream A `ReadableStream` of `Uint8Array`s to convert into an `ArrayBuffer`.
 * @returns A promise that resolves with the `ArrayBuffer` containing all the data from the stream.
 *
 * @example Basic usage
 * ```ts
 * import { toArrayBuffer } from "@std/streams/to-array-buffer";
 * import { assertEquals } from "@std/assert/assert-equals";
 *
 * const stream = ReadableStream.from([
 *   new Uint8Array([1, 2]),
 *   new Uint8Array([3, 4, 5]),
 * ]);
 * const buf = await toArrayBuffer(stream);
 * assertEquals(buf.byteLength, 5);
 * ```
 */
export async function toArrayBuffer(
  readableStream: ReadableStream<Uint8Array>,
): Promise<ArrayBuffer> {
  const reader = readableStream.getReader();
  const chunks: Uint8Array[] = [];

  while (true) {
    const { done, value } = await reader.read();

    if (done) {
      break;
    }

    chunks.push(value);
  }

  return concat(chunks).buffer;
}

// denoCacheMetadata={"headers":{"report-to":"{\"group\":\"cf-nel\",\"max_age\":604800,\"endpoints\":[{\"url\":\"https://a.nel.cloudflare.com/report/v4?s=8Akg0lQ%2BTM%2BXjiA6E4AdXEhCQq7bDNe88fUbJX4clneZ67GvDDkJuGNWmxmgtma4SfkiewUEr47rBoD7UQCIv6LoT%2Fy5fh1%2BkF3irNKB1t4txWdriNQo3bY%3D\"}]}","x-content-type-options":"nosniff","server":"cloudflare","cache-control":"public, max-age=31536000, immutable","content-length":"1252","x-robots-tag":"noindex","nel":"{\"report_to\":\"cf-nel\",\"success_fraction\":0.0,\"max_age\":604800}","etag":"\"bfd4fd09269d7e7c414fd94ca135ba6c\"","date":"Tue, 28 Jul 2026 12:31:15 GMT","content-type":"text/typescript","access-control-allow-origin":"*","access-control-expose-headers":"*","cross-origin-resource-policy":"cross-origin","x-jsr-backend":"modules","set-cookie":"__cf_bm=lJCMvBw0Oe_tYmMegyLDtdUi.1LrFcb.gJeEbg5KpTk-1785241875.1826127-1.0.1.1-YqI2a.DuLZxtNqphOqthefX9ramgq98hkRw4d4h8IPSM60Ma_GZNb4jyQL__MLMtAFNyYrUSvB7yqbI0wLc7_zbkno6VvtYxW1cFD2OWCGqmpiaYw2BmxSDv4vi11ihb; HttpOnly; SameSite=None; Secure; Path=/; Domain=jsr.io; Expires=Tue, 28 Jul 2026 13:01:15 GMT","cf-ray":"a223e657daca7db6-LAX","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';","alt-svc":"h3=\":443\"; ma=86400","vary":"Origin"},"url":"https://jsr.io/@std/streams/0.224.5/to_array_buffer.ts","time":1785241875}