def level_to_jl(level: Level, pin_fill: bool = False):
"""Convert a level to its Julia counterpart, optionally pinning its fill."""
match level:
case ElementLevel():
fill = level.fill_value
if pin_fill:
fill = jl_dtypes._zero_value(ftype(fill))
return jl.ElementLevel(
_as_julia_scalar(fill),
_buffer_to_jl(level.val),
)
case DenseLevel(lvl=lvl, dimension=dimension):
return jl.DenseLevel(level_to_jl(lvl, pin_fill), int(dimension))
case SparseListLevel(lvl=lvl, dimension=dimension, ptr=ptr, idx=idx):
if ptr is None or idx is None:
raise ValueError("SparseListLevel must have ptr and idx buffers")
constructor = jl.SparseListLevel[jl_dtypes.to_jl_type(ftype(dimension))]
return constructor(
level_to_jl(lvl, pin_fill),
int(dimension),
_buffer_to_jl(cast(Buffer, ptr), offset=1),
_buffer_to_jl(cast(Buffer, idx), offset=1),
)
case SparseByteMapLevel(
lvl=lvl, dimension=dimension, ptr=ptr, tbl=tbl, srt=srt
):
if ptr is None or tbl is None or srt is None:
raise ValueError(
"SparseByteMapLevel must have ptr, tbl, and srt buffers"
)
constructor = jl.SparseByteMapLevel[jl_dtypes.to_jl_type(ftype(dimension))]
return constructor(
level_to_jl(lvl, pin_fill),
int(dimension),
_buffer_to_jl(cast(Buffer, ptr), offset=1),
_buffer_to_jl(cast(Buffer, tbl)),
_buffer_to_jl(cast(Buffer, srt), offset=1),
)
case SparseCOOLevel(lvl=lvl, coo_shape=coo_shape, ptr=ptr, tbl=tbl):
assert isinstance(tbl, tuple)
# Julia's COO lists its dims fastest first, Python's slowest first
return jl.SparseCOOLevel(
level_to_jl(lvl, pin_fill),
tuple(int(dim) for dim in reversed(coo_shape)),
_buffer_to_jl(ptr, offset=1),
tuple(_buffer_to_jl(idx, offset=1) for idx in reversed(tbl)),
)
case SparseHashLevel(
lvl=lvl,
dimension=dimension,
ptr=ptr,
tbl_ctrl=tbl_ctrl,
tbl=tbl,
key=key,
perm=perm,
tbl_count=tbl_count,
subtables=subtables,
pos_multiplier=pos_multiplier,
):
if (
ptr is None
or tbl_ctrl is None
or tbl is None
or key is None
or perm is None
or tbl_count is None
):
raise ValueError(
"SparseHashLevel must have ptr, tbl_ctrl, tbl, key, perm, "
"and tbl_count buffers"
)
constructor = jl.SparseHashLevel[jl_dtypes.to_jl_type(ftype(dimension))]
return constructor(
level_to_jl(lvl, pin_fill),
int(dimension),
int(subtables),
pos_multiplier,
_buffer_to_jl(cast(Buffer, ptr), offset=1),
_buffer_to_jl(cast(Buffer, tbl_ctrl)),
_buffer_to_jl(cast(Buffer, tbl), offset=1),
_buffer_to_jl(cast(Buffer, key), offset=1, index_fields=(0, 1)),
_buffer_to_jl(cast(Buffer, perm), offset=1),
_buffer_to_jl(cast(Buffer, tbl_count)),
)
case _:
raise ValueError(f"Unsupported Finch level type: {type(level)}")