import * as tsplus_module_1 from "@tsplus/stdlib/collections/Chunk/empty";
import * as tsplus_module_2 from "@effect/core/stream/Channel/operations/pipeTo";
import * as tsplus_module_3 from "@effect/core/stream/Channel/operations/suspend";
import * as tsplus_module_4 from "@effect/core/stream/Stream/operations/fromChunk";
import * as tsplus_module_5 from "@effect/core/stream/Channel/operations/zipRight";
import * as tsplus_module_6 from "@effect/core/stream/Channel/operations/fail";
import * as tsplus_module_7 from "@effect/core/stream/Channel/operations/unit";
import * as tsplus_module_8 from "@effect/core/stream/Channel/operations/readWith";
import * as tsplus_module_9 from "@tsplus/stdlib/collections/Chunk/concat";
import * as tsplus_module_10 from "@tsplus/stdlib/collections/Chunk/splitAt";
import * as tsplus_module_11 from "@tsplus/stdlib/collections/Chunk/isEmpty";
import { concreteStream, StreamInternal } from "@effect/core/stream/Stream/operations/_internal/StreamInternal";
export function utfDecodeDetectingBom(bomSize, processBom, __tsplusTrace) {
  return stream => {
    void 0;
    return new StreamInternal(tsplus_module_3.suspend(() => tsplus_module_2.pipeTo_(stream.channel, () => lookingForBom(tsplus_module_1.empty(), bomSize, processBom, __tsplusTrace))));
  };
}

function passThrough(decodingPipeline, __tsplusTrace) {
  return tsplus_module_8.readWith(received => {
    const stream = decodingPipeline(tsplus_module_4.fromChunk(() => received, __tsplusTrace));
    void 0;
    return tsplus_module_5.zipRight_(stream.channel, () => passThrough(decodingPipeline, __tsplusTrace));
  }, err => tsplus_module_6.fail(() => err), () => tsplus_module_7.unit);
}

function lookingForBom(buffer, bomSize, processBom, __tsplusTrace) {
  return tsplus_module_8.readWith(received => {
    const data = tsplus_module_9.concat_(buffer, received);

    if (data.length >= bomSize) {
      const {
        tuple: [bom, rest]
      } = tsplus_module_10.splitAt_(data, bomSize);
      const {
        tuple: [dataWithoutBom, decodingPipeline]
      } = processBom(bom);
      const stream = decodingPipeline(tsplus_module_4.fromChunk(() => tsplus_module_9.concat_(dataWithoutBom, rest), __tsplusTrace));
      void 0;
      return tsplus_module_5.zipRight_(stream.channel, () => passThrough(decodingPipeline, __tsplusTrace));
    }

    return lookingForBom(data, bomSize, processBom, __tsplusTrace);
  }, err => tsplus_module_6.fail(() => err), () => {
    if (tsplus_module_11.isEmpty(buffer)) {
      return tsplus_module_7.unit;
    }

    const {
      tuple: [dataWithoutBom, decodingPipeline]
    } = processBom(buffer);
    const stream = decodingPipeline(tsplus_module_4.fromChunk(() => dataWithoutBom, __tsplusTrace));
    void 0;
    return tsplus_module_5.zipRight_(stream.channel, () => passThrough(decodingPipeline, __tsplusTrace));
  });
}
//# sourceMappingURL=utfDecodeDetectingBom.mjs.map