Debian Codegraph @

.cargo/vendor/wasm-bindgen/guide/src/reference/arbitrary-data-with-serde.md

raw
1 # Serializing and Deserializing Arbitrary Data Into and From `JsValue` with Serde
2
3 It's possible to pass arbitrary data from Rust to JavaScript by serializing it
4 with [Serde](https://github.com/serde-rs/serde). This can be done through the
5 [`serde-wasm-bindgen`](https://docs.rs/serde-wasm-bindgen) crate.
6
7 ## Add dependencies
8
9 To use `serde-wasm-bindgen`, you first have to add it as a dependency in your
10 `Cargo.toml`. You also need the `serde` crate, with the `derive` feature
11 enabled, to allow your types to be serialized and deserialized with Serde.
12
13 ```toml
14 [dependencies]
15 serde = { version = "1.0", features = ["derive"] }
16 serde-wasm-bindgen = "0.4"
17 ```
18
19 ## Derive the `Serialize` and `Deserialize` Traits
20
21 Add `#[derive(Serialize, Deserialize)]` to your type. All of your type's
22 members must also be supported by Serde, i.e. their types must also implement
23 the `Serialize` and `Deserialize` traits.
24
25 For example, let's say we'd like to pass this `struct` to JavaScript; doing so
26 is not possible in `wasm-bindgen` normally due to the use of `HashMap`s, arrays,
27 and nested `Vec`s. None of those types are supported for sending across the wasm
28 ABI naively, but all of them implement Serde's `Serialize` and `Deserialize`.
29
30 Note that we do not need to use the `#[wasm_bindgen]` macro.
31
32 ```rust
33 use serde::{Serialize, Deserialize};
34
35 #[derive(Serialize, Deserialize)]
36 pub struct Example {
37 pub field1: HashMap<u32, String>,
38 pub field2: Vec<Vec<f32>>,
39 pub field3: [f32; 4],
40 }
41 ```
42
43 ## Send it to JavaScript with `serde_wasm_bindgen::to_value`
44
45 Here's a function that will pass an `Example` to JavaScript by serializing it to
46 `JsValue`:
47
48 ```rust
49 #[wasm_bindgen]
50 pub fn send_example_to_js() -> JsValue {
51 let mut field1 = HashMap::new();
52 field1.insert(0, String::from("ex"));
53 let example = Example {
54 field1,
55 field2: vec![vec![1., 2.], vec![3., 4.]],
56 field3: [1., 2., 3., 4.]
57 };
58
59 serde_wasm_bindgen::to_value(&example).unwrap()
60 }
61 ```
62
63 ## Receive it from JavaScript with `serde_wasm_bindgen::from_value`
64
65 Here's a function that will receive a `JsValue` parameter from JavaScript and
66 then deserialize an `Example` from it:
67
68 ```rust
69 #[wasm_bindgen]
70 pub fn receive_example_from_js(val: JsValue) {
71 let example: Example = serde_wasm_bindgen::from_value(val).unwrap();
72 ...
73 }
74 ```
75
76 ## JavaScript Usage
77
78 In the `JsValue` that JavaScript gets, `field1` will be a `Map`, `field2` will
79 be a JavaScript `Array` whose members are `Array`s of numbers, and `field3`
80 will be an `Array` of numbers.
81
82 ```js
83 import { send_example_to_js, receive_example_from_js } from "example";
84
85 // Get the example object from wasm.
86 let example = send_example_to_js();
87
88 // Add another "Vec" element to the end of the "Vec<Vec<f32>>"
89 example.field2.push([5, 6]);
90
91 // Send the example object back to wasm.
92 receive_example_from_js(example);
93 ```
94
95 ## An alternative approach - using JSON
96
97 `serde-wasm-bindgen` works by directly manipulating JavaScript values. This
98 requires a lot of calls back and forth between Rust and JavaScript, which can
99 sometimes be slow. An alternative way of doing this is to serialize values to
100 JSON, and then parse them on the other end. Browsers' JSON implementations are
101 usually quite fast, and so this approach can outstrip `serde-wasm-bindgen`'s
102 performance in some cases. But this approach supports only types that can be
103 serialized as JSON, leaving out some important types that `serde-wasm-bindgen`
104 supports such as `Map`, `Set`, and array buffers.
105
106 That's not to say that using JSON is always faster, though - the JSON approach
107 can be anywhere from 2x to 0.2x the speed of `serde-wasm-bindgen`, depending on
108 the JS runtime and the values being passed. It also leads to larger code size
109 than `serde-wasm-bindgen`. So, make sure to profile each for your own use
110 cases.
111
112 This approach is implemented in [`gloo_utils::format::JsValueSerdeExt`]:
113
114 ```toml
115 # Cargo.toml
116 [dependencies]
117 gloo-utils = { version = "0.1", features = ["serde"] }
118 ```
119
120 ```rust
121 use gloo_utils::format::JsValueSerdeExt;
122
123 #[wasm_bindgen]
124 pub fn send_example_to_js() -> JsValue {
125 let mut field1 = HashMap::new();
126 field1.insert(0, String::from("ex"));
127 let example = Example {
128 field1,
129 field2: vec![vec![1., 2.], vec![3., 4.]],
130 field3: [1., 2., 3., 4.]
131 };
132
133 JsValue::from_serde(&example).unwrap()
134 }
135
136 #[wasm_bindgen]
137 pub fn receive_example_from_js(val: JsValue) {
138 let example: Example = val.into_serde().unwrap();
139 ...
140 }
141 ```
142
143 [`gloo_utils::format::JsValueSerdeExt`]: https://docs.rs/gloo-utils/latest/gloo_utils/format/trait.JsValueSerdeExt.html
144
145 ## History
146
147 In previous versions of `wasm-bindgen`, `gloo-utils`'s JSON-based Serde support
148 (`JsValue::from_serde` and `JsValue::into_serde`) was built into `wasm-bindgen`
149 itself. However, this required a dependency on `serde_json`, which had a
150 problem: with certain features of `serde_json` and other crates enabled,
151 `serde_json` would end up with a circular dependency on `wasm-bindgen`, which
152 is illegal in Rust and caused people's code to fail to compile. So, these
153 methods were extracted out into `gloo-utils` with an extension trait and the
154 originals were deprecated.