1use js_sys::Uint8Array;
4use serde::{Deserialize, Serialize};
5use wasm_bindgen::JsValue;
6
7pub trait Codec {
9 fn encode<I>(input: I) -> JsValue
11 where
12 I: Serialize;
13
14 fn decode<O>(input: JsValue) -> O
16 where
17 O: for<'de> Deserialize<'de>;
18}
19
20#[derive(Debug)]
22pub struct Bincode;
23
24impl Codec for Bincode {
25 fn encode<I>(input: I) -> JsValue
26 where
27 I: Serialize,
28 {
29 let buf = bincode::serde::encode_to_vec(&input, bincode::config::standard())
30 .expect("can't serialize an worker message");
31 Uint8Array::from(buf.as_slice()).into()
32 }
33
34 fn decode<O>(input: JsValue) -> O
35 where
36 O: for<'de> Deserialize<'de>,
37 {
38 let data = Uint8Array::from(input).to_vec();
39 let (result, _) = bincode::serde::decode_from_slice(&data, bincode::config::standard())
40 .expect("can't deserialize an worker message");
41 result
42 }
43}