import * as tsplus_module_1 from "@effect/core/stm/TRef/operations/unsafeGet";
import * as tsplus_module_2 from "@tsplus/stdlib/collections/Chunk/builder";
import * as tsplus_module_3 from "@effect/core/stm/THub/definition";
import * as tsplus_module_4 from "@effect/core/stm/THub/operations/_internal/InternalNode";
import * as tsplus_module_5 from "@effect/core/stm/TRef/operations/unsafeSet";
import * as tsplus_module_6 from "@effect/core/stm/STM/operations/effect";
import { STMInterruptException } from "@effect/core/stm/STM";
import { concreteTDequeue } from "@effect/core/stm/THub/operations/_internal/InternalTDequeue";
/**
 * Takes up to the specified number of values from the queue.
 *
 * @tsplus fluent ets/THub/TDequeue takeUpTo
 */

export function takeUpTo_(self, max) {
  void 0;
  return tsplus_module_6.effect((journal, fiberId) => {
    let currentSubscriberHead = tsplus_module_1.unsafeGet_(self.subscriberHead, journal);

    if (currentSubscriberHead == null) {
      throw new STMInterruptException(fiberId);
    }

    const builder = tsplus_module_2.builder();
    let n = 0;

    while (n != max) {
      const node = tsplus_module_1.unsafeGet_(currentSubscriberHead, journal);

      if (node == null) {
        n = max;
      } else {
        const head = node.head;
        const tail = node.tail;

        if (head != null) {
          const subscribers = node.subscribers;

          if (subscribers == 1) {
            const size = tsplus_module_1.unsafeGet_(self.hubSize, journal);
            const updatedNode = tsplus_module_4.make(undefined, 0, node.tail);
            tsplus_module_5.unsafeSet_(currentSubscriberHead, updatedNode, journal);
            tsplus_module_5.unsafeSet_(self.publisherHead, tail, journal);
            tsplus_module_5.unsafeSet_(self.hubSize, size - 1, journal);
          } else {
            const updatedNode = tsplus_module_4.make(node.head, subscribers - 1, node.tail);
            tsplus_module_5.unsafeSet_(currentSubscriberHead, updatedNode, journal);
          }

          builder.append(head);
          n += 1;
        }

        currentSubscriberHead = tail;
      }
    }

    tsplus_module_5.unsafeSet_(self.subscriberHead, currentSubscriberHead, journal);
    return builder.build();
  });
}
/**
 * Takes up to the specified number of values from the queue.
 *
 * @tsplus static ets/THub/TDequeue/Aspects takeUpTo
 */

export const takeUpTo = max => self => takeUpTo_(self, max);
//# sourceMappingURL=takeUpTo.mjs.map