import * as tsplus_module_1 from "@tsplus/stdlib/collections/List/definition";
import * as tsplus_module_2 from "@tsplus/stdlib/collections/List/forEach";
import * as tsplus_module_3 from "@tsplus/stdlib/data/Tuple/fromNative";
import * as tsplus_module_4 from "@effect/core/stm/TMap/operations/indexOf";
import * as tsplus_module_5 from "@tsplus/stdlib/collections/List/prepend";
import * as tsplus_module_6 from "@effect/core/stm/TRef/operations/make";
import * as tsplus_module_7 from "@effect/core/stm/STM/operations/map";
import * as tsplus_module_8 from "@effect/core/stm/STM/operations/flatMap";
import * as tsplus_module_9 from "@effect/core/stm/TArray/operations/from";
import * as tsplus_module_10 from "@tsplus/stdlib/collections/List/from";
import * as tsplus_module_11 from "@effect/core/stm/STM/operations/suspend";
import { InternalTMap } from "@effect/core/stm/TMap/operations/_internal/InternalTMap";
const INITIAL_CAPACITY = 16;

function nextPowerOfTwo(size) {
  const n = -1 >>> Math.clz32(size - 1);
  return n < 0 ? 1 : n + 1;
}

function allocate(capacity, data) {
  const buckets = Array.from({
    length: capacity
  }, () => tsplus_module_1.nil());
  const distinct = new Map();
  tsplus_module_2.forEach_(data, kv => distinct.set(kv.get(0), kv.get(1)));
  let size = 0;

  for (const kv0 of distinct) {
    const kv = tsplus_module_3.fromNative(kv0);
    const idx = tsplus_module_4.indexOf(kv.get(0), capacity);
    buckets[idx] = tsplus_module_5.prepend_(buckets[idx], kv);
    size += 1;
  }

  return tsplus_module_8.flatMap_(tsplus_module_9.from(() => buckets), tArray => tsplus_module_8.flatMap_(tsplus_module_6.make(() => tArray), tBuckets => tsplus_module_7.map_(tsplus_module_6.make(() => size), tSize => new InternalTMap(tBuckets, tSize))));
}
/**
 * Retrieves value associated with given key.
 *
 * @tsplus static ets/TMap/Ops fromIterable
 */


export function fromIterable(data0) {
  return tsplus_module_11.suspend(() => {
    const data = tsplus_module_10.from(data0);
    const size = tsplus_module_1.length(data);
    const capacity = size < INITIAL_CAPACITY ? INITIAL_CAPACITY : nextPowerOfTwo(size);
    return allocate(capacity, data);
  });
}
//# sourceMappingURL=fromIterable.mjs.map