import "../index-DSGwv2Yx.js";
import { t as y } from "../tensor-D8e0Gd7c.js";
function l(t) {
  if (t === "float32") return "F32";
  if (t === "int32") return "I32";
  throw new Error(`Unsupported dtype: ${t}`);
}
function h(t) {
  if (t === "F32") return "float32";
  if (t === "I32") return "int32";
  throw new Error(`Unsupported dtype: ${t}`);
}
async function _(t) {
  const c = {};
  let a = 0;
  for (const [n, s] of Object.entries(t))
    c[n] = {
      dtype: l(s.dtype),
      shape: s.shape,
      data_offsets: [a, a + s.size * 4]
    }, a += s.size * 4;
  const p = JSON.stringify(c);
  let r = new TextEncoder().encode(p);
  if (r.length % 4 !== 0) {
    const n = 4 - r.length % 4, s = new Uint8Array(r.length + n);
    s.set(r);
    for (let w = r.length; w < s.length; w++)
      s[w] = 32;
    r = s;
  }
  const o = r.length, f = 8 + o + a, e = new ArrayBuffer(f);
  new DataView(e).setUint32(0, o, !0), new Uint8Array(e, 8, o).set(r);
  let d = 8 + o;
  for (const n of Object.values(t)) {
    if (n.size === 0) continue;
    const s = await n.data();
    if (n.dtype === "float32")
      new Float32Array(e, d, n.size).set(s), d += n.size * 4;
    else if (n.dtype === "int32")
      new Int32Array(e, d, n.size).set(s), d += n.size * 4;
    else
      throw new Error(`Unsupported dtype: ${n.dtype}`);
  }
  return e;
}
async function U(t) {
  const a = new DataView(t).getUint32(0, !0), p = new Uint8Array(t, 8, a), r = JSON.parse(new TextDecoder().decode(p)), o = {};
  for (const [f, e] of Object.entries(r)) {
    if (e.data_offsets[0] === e.data_offsets[1]) {
      o[f] = y([], e.shape, h(e.dtype));
      continue;
    }
    if (e.dtype === "F32") {
      const i = y(
        new Float32Array(
          t,
          e.data_offsets[0] + 8 + a,
          (e.data_offsets[1] - e.data_offsets[0]) / 4
        ),
        e.shape,
        h(e.dtype)
      );
      o[f] = i;
    } else if (e.dtype === "I32") {
      const i = y(
        new Int32Array(
          t,
          e.data_offsets[0] + 8 + a,
          (e.data_offsets[1] - e.data_offsets[0]) / 4
        ),
        e.shape,
        h(e.dtype)
      );
      o[f] = i;
    } else
      throw new Error(`Unsupported dtype: ${e.dtype}`);
  }
  return o;
}
export {
  U as load_safetensors,
  _ as save_safetensors
};
