Skip to main content

numcodecs_wasm_guest/
lib.rs

1//! [![CI Status]][workflow] [![MSRV]][repo] [![Latest Version]][crates.io] [![Rust Doc Crate]][docs.rs] [![Rust Doc Main]][docs]
2//!
3//! [CI Status]: https://img.shields.io/github/actions/workflow/status/juntyr/numcodecs-rs/ci.yml?branch=main
4//! [workflow]: https://github.com/juntyr/numcodecs-rs/actions/workflows/ci.yml?query=branch%3Amain
5//!
6//! [MSRV]: https://img.shields.io/badge/MSRV-1.88.0-blue
7//! [repo]: https://github.com/juntyr/numcodecs-rs
8//!
9//! [Latest Version]: https://img.shields.io/crates/v/numcodecs-wasm-guest
10//! [crates.io]: https://crates.io/crates/numcodecs-wasm-guest
11//!
12//! [Rust Doc Crate]: https://img.shields.io/docsrs/numcodecs-wasm-guest
13//! [docs.rs]: https://docs.rs/numcodecs-wasm-guest/
14//!
15//! [Rust Doc Main]: https://img.shields.io/badge/docs-main-blue
16//! [docs]: https://juntyr.github.io/numcodecs-rs/numcodecs_wasm_guest
17//!
18//! wasm32 guest-side bindings for the [`numcodecs`] API, which allows you to
19//! export one [`StaticCodec`] from a WASM component.
20
21#![allow(clippy::multiple_crate_versions)]
22
23// Required in docs and the [`export_codec`] macro
24#[doc(hidden)]
25pub use numcodecs;
26
27#[cfg(doc)]
28use numcodecs::StaticCodec;
29
30#[cfg(target_arch = "wasm32")]
31use ::{
32    numcodecs::{Codec, DynCodecType, StaticCodec, StaticCodecType},
33    serde::Deserialize,
34};
35
36#[cfg(target_arch = "wasm32")]
37mod convert;
38
39#[cfg(all(feature = "registry", target_arch = "wasm32"))]
40mod external;
41
42#[cfg(target_arch = "wasm32")]
43use crate::convert::{
44    from_wit_any_array, into_wit_any_array, into_wit_error, zeros_from_wit_any_array_prototype,
45};
46
47#[doc(hidden)]
48#[expect(clippy::same_length_and_capacity)]
49pub mod bindings {
50    #[cfg(not(feature = "registry"))]
51    wit_bindgen::generate!({
52        world: "numcodecs:abc/exports@0.1.1",
53        with: {
54            "numcodecs:abc/codec@0.1.1": generate,
55        },
56        pub_export_macro: true,
57    });
58    #[cfg(feature = "registry")]
59    wit_bindgen::generate!({
60        world: "numcodecs:abc/exports@0.1.1",
61        with: {
62            "numcodecs:abc/codec@0.1.1": generate,
63            // TODO: generate the separate types interface
64            "numcodecs:abc/types@0.1.1": crate::bindings::exports::numcodecs::abc::codec,
65        },
66        pub_export_macro: true,
67        features: ["registry"],
68    });
69}
70
71#[cfg(target_arch = "wasm32")]
72mod wit {
73    pub mod codec {
74        pub use crate::bindings::exports::numcodecs::abc::codec::{Codec, Guest, GuestCodec};
75    }
76
77    #[cfg(feature = "registry")]
78    pub mod registry {
79        pub use crate::bindings::numcodecs::abc::registry::{
80            ExternalCodec, ExternalCodecType, get_external_codec,
81        };
82    }
83
84    pub mod types {
85        // TODO: use crate::bindings::numcodecs::abc::types
86        pub use crate::bindings::exports::numcodecs::abc::codec::{
87            AnyArray, AnyArrayData, AnyArrayDtype, AnyArrayPrototype, Error, Json, JsonSchema,
88            Usize,
89        };
90    }
91}
92
93#[macro_export]
94/// Export a [`StaticCodec`] type using the WASM component model.
95///
96/// ```rust,ignore
97/// # use numcodecs_wasm_guest::export_codec;
98///
99/// struct MyCodec {
100///     // ...
101/// }
102///
103/// impl numcodecs::Codec for MyCodec {
104///     // ...
105/// }
106///
107/// impl numcodecs::StaticCodec for MyCodec {
108///     // ...
109/// }
110///
111/// export_codec!(MyCodec);
112/// ```
113macro_rules! export_codec {
114    ($codec:ty) => {
115        #[cfg(target_arch = "wasm32")]
116        const _: () = {
117            type Codec = $codec;
118
119            $crate::bindings::export!(
120                Codec with_types_in $crate::bindings
121            );
122        };
123
124        const _: () = {
125            const fn can_only_export_static_codec<T: $crate::numcodecs::StaticCodec>() {}
126
127            can_only_export_static_codec::<$codec>()
128        };
129    };
130}
131
132#[cfg(target_arch = "wasm32")]
133#[doc(hidden)]
134impl<T: StaticCodec> wit::codec::Guest for T {
135    type Codec = Self;
136
137    fn codec_id() -> String {
138        String::from(<Self as StaticCodec>::CODEC_ID)
139    }
140
141    fn codec_config_schema() -> wit::types::JsonSchema {
142        StaticCodecType::<Self>::of()
143            .codec_config_schema()
144            .to_value()
145            .to_string()
146    }
147}
148
149#[cfg(target_arch = "wasm32")]
150impl<T: StaticCodec> wit::codec::GuestCodec for T {
151    fn from_config(config: String) -> Result<wit::codec::Codec, wit::types::Error> {
152        let err = match <Self as StaticCodec>::Config::deserialize(
153            &mut serde_json::Deserializer::from_str(&config),
154        ) {
155            Ok(config) => {
156                return Ok(wit::codec::Codec::new(<Self as StaticCodec>::from_config(
157                    config,
158                )));
159            }
160            Err(err) => err,
161        };
162
163        let err = format_serde_error::SerdeError::new(config, err);
164        Err(into_wit_error(err))
165    }
166
167    fn encode(
168        &self,
169        data: wit::types::AnyArray,
170    ) -> Result<wit::types::AnyArray, wit::types::Error> {
171        let data = match from_wit_any_array(data) {
172            Ok(data) => data,
173            Err(err) => return Err(into_wit_error(err)),
174        };
175
176        match <Self as Codec>::encode(self, data.into_cow()) {
177            Ok(encoded) => match into_wit_any_array(encoded) {
178                Ok(encoded) => Ok(encoded),
179                Err(err) => Err(into_wit_error(err)),
180            },
181            Err(err) => Err(into_wit_error(err)),
182        }
183    }
184
185    fn decode(
186        &self,
187        encoded: wit::types::AnyArray,
188    ) -> Result<wit::types::AnyArray, wit::types::Error> {
189        let encoded = match from_wit_any_array(encoded) {
190            Ok(encoded) => encoded,
191            Err(err) => return Err(into_wit_error(err)),
192        };
193
194        match <Self as Codec>::decode(self, encoded.into_cow()) {
195            Ok(decoded) => match into_wit_any_array(decoded) {
196                Ok(decoded) => Ok(decoded),
197                Err(err) => Err(into_wit_error(err)),
198            },
199            Err(err) => Err(into_wit_error(err)),
200        }
201    }
202
203    fn decode_into(
204        &self,
205        encoded: wit::types::AnyArray,
206        decoded: wit::types::AnyArrayPrototype,
207    ) -> Result<wit::types::AnyArray, wit::types::Error> {
208        let encoded = match from_wit_any_array(encoded) {
209            Ok(encoded) => encoded,
210            Err(err) => return Err(into_wit_error(err)),
211        };
212
213        let mut decoded = zeros_from_wit_any_array_prototype(decoded);
214
215        match <Self as Codec>::decode_into(self, encoded.view(), decoded.view_mut()) {
216            Ok(()) => match into_wit_any_array(decoded) {
217                Ok(decoded) => Ok(decoded),
218                Err(err) => Err(into_wit_error(err)),
219            },
220            Err(err) => Err(into_wit_error(err)),
221        }
222    }
223
224    fn get_config(&self) -> Result<wit::types::Json, wit::types::Error> {
225        match serde_json::to_string(&<Self as StaticCodec>::get_config(self)) {
226            Ok(config) => Ok(config),
227            Err(err) => Err(into_wit_error(err)),
228        }
229    }
230}