import * as tsplus_module_1 from "@effect/core/io/Cause/errors";
import * as tsplus_module_2 from "@effect/core/stream/Stream/operations/die";
import * as tsplus_module_3 from "@effect/core/stream/Channel/operations/unit";
import * as tsplus_module_4 from "@effect/core/stream/Channel/operations/pipeTo";
import * as tsplus_module_5 from "@effect/core/stream/Channel/operations/suspend";
import * as tsplus_module_6 from "@tsplus/stdlib/collections/Chunk/take";
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/stream/Channel/operations/fail";
import * as tsplus_module_10 from "@effect/core/stream/Channel/operations/succeed";
import * as tsplus_module_11 from "@effect/core/stream/Channel/operations/readWith";
import { concreteStream, StreamInternal } from "@effect/core/stream/Stream/operations/_internal/StreamInternal";
/**
 * Takes the specified number of elements from this stream.
 *
 * @tsplus fluent ets/Stream take
 */

export function take_(self, n, __tsplusTrace) {
  if (!Number.isInteger(n)) {
    return tsplus_module_2.die(() => new tsplus_module_1.IllegalArgumentException(`${n} must be an integer`), __tsplusTrace);
  }

  void 0;
  return new StreamInternal(n <= 0 ? tsplus_module_3.unit : tsplus_module_5.suspend(() => tsplus_module_4.pipeTo_(self.channel, () => loop(n, __tsplusTrace))));
}
/**
 * Takes the specified number of elements from this stream.
 *
 * @tsplus static ets/Stream/Aspects take
 */

export const take = (n, __tsplusTrace) => self => take_(self, n, __tsplusTrace);

function loop(n, __tsplusTrace) {
  return tsplus_module_11.readWith(chunk => {
    const taken = tsplus_module_6.take_(chunk, Math.min(n, Number.MAX_SAFE_INTEGER));
    const leftover = Math.max(0, n - taken.length);
    const more = leftover > 0;
    return more ? tsplus_module_8.zipRight_(tsplus_module_7.write(() => taken), () => loop(leftover, __tsplusTrace)) : tsplus_module_7.write(() => taken);
  }, err => tsplus_module_9.fail(() => err), done => tsplus_module_10.succeed(() => done));
}
//# sourceMappingURL=take.mjs.map