import * as tsplus_module_1 from "@effect/core/stream/Stream/operations/toQueueOfElements";
import * as tsplus_module_2 from "@effect/core/stream/Channel/operations/unit";
import * as tsplus_module_3 from "@effect/core/stream/Channel/operations/failCause";
import * as tsplus_module_4 from "@effect/core/io/Cause/operations/flipCauseMaybe";
import * as tsplus_module_5 from "@tsplus/stdlib/data/Maybe/fold";
import * as tsplus_module_6 from "@tsplus/stdlib/collections/Chunk/single";
import * as tsplus_module_7 from "@effect/core/stream/Channel/operations/write";
import * as tsplus_module_8 from "@effect/core/stream/Channel/operations/zipRight";
import * as tsplus_module_9 from "@effect/core/io/Exit/operations/fold";
import * as tsplus_module_10 from "@effect/core/stream/Channel/operations/fromEffect";
import * as tsplus_module_11 from "@effect/core/stream/Channel/operations/flatMap";
import * as tsplus_module_12 from "@effect/core/io/Effect/operations/map";
import * as tsplus_module_13 from "@effect/core/stream/Channel/operations/unwrapScoped";
import { StreamInternal } from "@effect/core/stream/Stream/operations/_internal/StreamInternal";
/**
 * Allows a faster producer to progress independently of a slower consumer by
 * buffering up to `capacity` elements in a queue.
 *
 * This combinator destroys the chunking structure. It's recommended to use
 * rechunk afterwards.
 *
 * Note: prefer capacities that are powers of 2 for better performance.
 *
 * @tsplus fluent ets/Stream buffer
 */

export function buffer_(self, capacity, __tsplusTrace) {
  const queue = tsplus_module_1.toQueueOfElements_(self, capacity, __tsplusTrace);
  return new StreamInternal(tsplus_module_13.unwrapScoped(tsplus_module_12.map_(queue, queue => {
    const process = tsplus_module_11.flatMap_(tsplus_module_10.fromEffect(() => queue.take), exit => tsplus_module_9.fold_(exit, cause => tsplus_module_5.fold_(tsplus_module_4.flipCauseMaybe(cause), () => tsplus_module_2.unit, cause => tsplus_module_3.failCause(() => cause)), a => tsplus_module_8.zipRight_(tsplus_module_7.write(() => tsplus_module_6.single(a)), () => process)));
    return process;
  }, __tsplusTrace)));
}
/**
 * Allows a faster producer to progress independently of a slower consumer by
 * buffering up to `capacity` elements in a queue.
 *
 * This combinator destroys the chunking structure. It's recommended to use
 * rechunk afterwards.
 *
 * Note: prefer capacities that are powers of 2 for better performance.
 *
 * @tsplus static ets/Stream/Aspects buffer
 */

export const buffer = (capacity, __tsplusTrace) => self => buffer_(self, capacity, __tsplusTrace);
//# sourceMappingURL=buffer.mjs.map