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/Channel/operations/write";
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 "@tsplus/stdlib/collections/Chunk/isEmpty";
import * as tsplus_module_8 from "@effect/core/stream/Channel/operations/unit";
import * as tsplus_module_9 from "@effect/core/stream/Channel/operations/readWith";
import * as tsplus_module_10 from "@tsplus/stdlib/collections/Chunk/concat";
import * as tsplus_module_11 from "@tsplus/stdlib/data/Tuple/make";
import * as tsplus_module_12 from "@tsplus/stdlib/collections/Chunk/splitAt";
import * as tsplus_module_13 from "@tsplus/stdlib/collections/Chunk/materialize";
import { concreteStream, StreamInternal } from "@effect/core/stream/Stream/operations/_internal/StreamInternal";
import { stringChunkFrom } from "@effect/core/stream/Stream/operations/_internal/stringChunkFrom";
const emptyByteChunk = /*#__PURE__*/tsplus_module_1.empty();
const emptyStringChunk = /*#__PURE__*/tsplus_module_1.empty();
export function utfDecodeFixedLength(charset, fixedLength, __tsplusTrace) {
  return stream => {
    void 0;
    return new StreamInternal(tsplus_module_3.suspend(() => tsplus_module_2.pipeTo_(stream.channel, () => readThenTransduce(emptyByteChunk, charset, fixedLength, __tsplusTrace))));
  };
}

function readThenTransduce(buffer, charset, fixedLength, __tsplusTrace) {
  return tsplus_module_9.readWith(received => {
    const {
      tuple: [string, buffered]
    } = process(buffer, received, charset, fixedLength);
    return tsplus_module_5.zipRight_(tsplus_module_4.write(() => string), () => readThenTransduce(buffered, charset, fixedLength, __tsplusTrace));
  }, err => tsplus_module_6.fail(() => err), () => tsplus_module_7.isEmpty(buffer) ? tsplus_module_8.unit : tsplus_module_4.write(() => stringChunkFrom(buffer, charset)));
}

function process(buffered, received, charset, fixedLength) {
  const bytes = tsplus_module_10.concat_(buffered, received);
  const remainder = bytes.length % fixedLength;

  if (remainder === 0) {
    return tsplus_module_11.make(stringChunkFrom(bytes, charset), emptyByteChunk);
  }

  if (bytes.length > fixedLength) {
    const {
      tuple: [fullChunk, rest]
    } = tsplus_module_12.splitAt_(bytes, bytes.length - remainder);
    return tsplus_module_11.make(stringChunkFrom(fullChunk, charset), rest);
  }

  return tsplus_module_11.make(emptyStringChunk, tsplus_module_13.materialize(bytes));
}
//# sourceMappingURL=utfDecodeFixedLength.mjs.map