Skip to main content

numcodecs_wasm/
lib.rs

1#![allow(clippy::multiple_crate_versions)]
2#![expect(missing_docs)] // FIXME
3
4use numcodecs_python::{PyCodec, PyCodecAdapter, PyCodecClass};
5use numcodecs_wasm_host_reproducible::{ReproducibleWasmCodec, ReproducibleWasmCodecType};
6use pyo3::{exceptions::PyTypeError, prelude::*};
7
8// FIXME: https://github.com/bytecodealliance/rustix/issues/1620
9use ::memfd as _;
10
11mod engine;
12
13use engine::{Engine, default_engine};
14
15#[pymodule]
16#[pyo3(name = "_wasm")]
17fn wasm<'py>(py: Python<'py>, module: &Bound<'py, PyModule>) -> Result<(), PyErr> {
18    let logger = pyo3_log::Logger::new(py, pyo3_log::Caching::Nothing)?;
19    logger
20        .install()
21        .map_err(|err| pyo3_error::PyErrChain::new(py, err))?;
22
23    module.add_function(wrap_pyfunction!(create_codec_class, module)?)?;
24    module.add_function(wrap_pyfunction!(read_codec_instruction_counter, module)?)?;
25
26    Ok(())
27}
28
29#[pyfunction]
30#[pyo3(name = "_create_codec_class")]
31fn create_codec_class<'py>(
32    py: Python<'py>,
33    module: &Bound<'py, PyModule>,
34    wasm: Vec<u8>,
35) -> Result<Bound<'py, PyCodecClass>, PyErr> {
36    let engine = default_engine(py)?;
37
38    // TODO: we should allow restricting the codecs that the reproducible codec can 'see'
39    let codec_ty = ReproducibleWasmCodecType::new_with_registry(
40        engine,
41        wasm,
42        numcodecs_python::PyCodecRegistryHandle,
43    )
44    .map_err(|err| pyo3_error::PyErrChain::new(py, err))?;
45
46    let codec_class = numcodecs_python::export_codec_class(py, codec_ty, module.as_borrowed())?;
47
48    Ok(codec_class)
49}
50
51#[pyfunction]
52#[pyo3(name = "_read_codec_instruction_counter")]
53fn read_codec_instruction_counter<'py>(
54    py: Python<'py>,
55    codec: &Bound<'py, PyCodec>,
56) -> Result<u64, PyErr> {
57    let Some(instruction_counter) =
58        PyCodecAdapter::with_downcast(py, codec, |codec: &ReproducibleWasmCodec<Engine>| {
59            codec.instruction_counter()
60        })
61        .transpose()
62        .map_err(|err| pyo3_error::PyErrChain::new(py, err))?
63    else {
64        return Err(PyTypeError::new_err(
65            "`codec` is not a wasm codec, only wasm codecs have instruction counts",
66        ));
67    };
68
69    Ok(instruction_counter.0)
70}