This is unreleased documentation for Yew Next version.
For up-to-date documentation, see the latest version on docs.rs.

yew_agent/
codec.rs

1//! Submodule providing the `Codec` trait and its default implementation using `bincode`.
2
3use js_sys::Uint8Array;
4use serde::{Deserialize, Serialize};
5use wasm_bindgen::JsValue;
6
7/// Message Encoding and Decoding Format
8pub trait Codec {
9    /// Encode an input to JsValue
10    fn encode<I>(input: I) -> JsValue
11    where
12        I: Serialize;
13
14    /// Decode a message to a type
15    fn decode<O>(input: JsValue) -> O
16    where
17        O: for<'de> Deserialize<'de>;
18}
19
20/// Default message encoding with [bincode].
21#[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::serialize(&input).expect("can't serialize an worker message");
30        Uint8Array::from(buf.as_slice()).into()
31    }
32
33    fn decode<O>(input: JsValue) -> O
34    where
35        O: for<'de> Deserialize<'de>,
36    {
37        let data = Uint8Array::from(input).to_vec();
38        bincode::deserialize(&data).expect("can't deserialize an worker message")
39    }
40}