### JavaScript Usage Example Source: https://docs.rs/serde-wasm-bindgen/latest/serde_wasm_bindgen/index.html Demonstrates how to import and use the `send_example_to_js` and `receive_example_from_js` functions in JavaScript. It shows receiving an object, modifying it, and sending it back. ```javascript import { send_example_to_js, receive_example_from_js } from "example"; // Get the example object from wasm. let example = send_example_to_js(); // Add another "Vec" element to the end of the "Vec>" example.field2.push([5, 6]); // Send the example object back to wasm. receive_example_from_js(example); ``` -------------------------------- ### JSON Compatible Serialization Source: https://docs.rs/serde-wasm-bindgen/latest/serde_wasm_bindgen Use `Serializer::json_compatible()` if strict JSON compatibility is required, for example, to serialize `HashMap` as plain objects instead of JavaScript `Map` instances. ```rust let mut serializer = serde_wasm_bindgen::Serializer::json_compatible(); ``` -------------------------------- ### Deserialize Struct with Serde Wasm Bindgen Source: https://docs.rs/serde-wasm-bindgen/latest/src/serde_wasm_bindgen/de.rs.html Implement the `Deserialize` trait for custom structs to enable deserialization from JavaScript. This example shows how to deserialize a struct with specific fields. ```rust impl<'de> de::Deserialize<'de> for MyStruct { fn deserialize(deserializer: D) -> Result where D: de::Deserializer<'de>, { #[derive(Deserialize)] #[serde(field_identifier)] enum Field { Field1, Field2, } struct Visitor; impl<'de> de::Visitor<'de> for Visitor { type Value = MyStruct; fn expecting(&self, formatter: &mut fmt::Formatter) { formatter.write_str("struct MyStruct") } fn visit_map(self, mut map: A) -> Result where A: de::MapAccess<'de>, { let mut field1 = None; let mut field2 = None; while let Some(field) = map.next_key()? { match field { Field::Field1 => { if field1.is_some() { return Err(de::Error::duplicate_field("field1")); } field1 = Some(map.next_value()?); } Field::Field2 => { if field2.is_some() { return Err(de::Error::duplicate_field("field2")); } field2 = Some(map.next_value()?); } } } let field1 = field1.ok_or_else(|| de::Error::missing_field("field1"))?; let field2 = field2.ok_or_else(|| de::Error::missing_field("field2"))?; Ok(MyStruct { field1, field2 }) } } deserializer.deserialize_struct("MyStruct", &["field1", "field2"], Visitor) } } ``` -------------------------------- ### Preserve JavaScript Objects During Serialization Source: https://docs.rs/serde-wasm-bindgen/latest/src/serde_wasm_bindgen/lib.rs.html Example of using `serde(with)` to preserve JavaScript objects like `Int8Array` when serializing Rust structs. ```rust struct MyStruct { int_field: i32, #[serde(with = "serde_wasm_bindgen::preserve")] js_field: js_sys::Int8Array, } let s = MyStruct { int_field: 5, js_field: js_sys::Int8Array::new_with_length(1000), }; // serde_wasm_bindgen::to_value(&s) will return a JsValue representing an object with two fields // (`int_field` and `js_field`), where `js_field` will be an `Int8Array` pointing to the same // underlying JavaScript object as `s.js_field` does. ``` -------------------------------- ### Get Safe Integer from JsValue Source: https://docs.rs/serde-wasm-bindgen/latest/src/serde_wasm_bindgen/de.rs.html Safely retrieves an integer value from a `JsValue` if it represents a safe integer. Returns `None` otherwise. ```rust fn as_safe_integer(&self) -> Option { if Number::is_safe_integer(&self.value) { return Some(self.value.unchecked_into_f64() as i64); } None } ``` -------------------------------- ### Experimental Provide Method Source: https://docs.rs/serde-wasm-bindgen/latest/serde_wasm_bindgen/struct.Error.html This is a nightly-only experimental API (`error_generic_member_access`) that provides type-based access to context for error reports. ```rust fn provide<'a>(&'a self, request: &mut Request<'a>) ``` -------------------------------- ### Serializer::new Source: https://docs.rs/serde-wasm-bindgen/latest/serde_wasm_bindgen/struct.Serializer.html Creates a new default Serializer instance. ```APIDOC ## Serializer::new ### Description Creates a new default `Serializer`. ### Method `const fn new() -> Self` ``` -------------------------------- ### Get Source Error Source: https://docs.rs/serde-wasm-bindgen/latest/serde_wasm_bindgen/struct.Error.html The `source` method returns the lower-level underlying error, if any. This is part of the standard `std::error::Error` trait implementation. ```rust fn source(&self) -> Option<&(dyn Error + 'static)> ``` -------------------------------- ### Create a new default Serializer Source: https://docs.rs/serde-wasm-bindgen/latest/serde_wasm_bindgen/struct.Serializer.html Instantiates a new `Serializer` with default settings. Use this when standard serialization behavior is desired. ```rust pub const fn new() -> Self ``` -------------------------------- ### Deprecated Description Method Source: https://docs.rs/serde-wasm-bindgen/latest/serde_wasm_bindgen/struct.Error.html The `description` method is deprecated and users should instead use the `Display` implementation or `to_string()` for obtaining an error description. ```rust fn description(&self) -> &str ``` -------------------------------- ### Get JS Object Entries as Array Source: https://docs.rs/serde-wasm-bindgen/latest/src/serde_wasm_bindgen/de.rs.html Retrieves the entries of a JavaScript object as a `wasm_bindgen::JsValue` representing an array of `[key, value]` pairs. Returns `None` if the `JsValue` is not an object. ```rust fn as_object_entries(&self) -> Option { if self.value.is_object() { Some(Object::entries(self.value.unchecked_ref())) } else { None } } ``` -------------------------------- ### Create a JSON compatible Serializer Source: https://docs.rs/serde-wasm-bindgen/latest/serde_wasm_bindgen/struct.Serializer.html Creates a `Serializer` configured for JSON compatibility. This ensures that `null` is used instead of `undefined` and plain objects are used instead of ES Maps, allowing for lossless stringification to JSON. ```rust pub const fn json_compatible() -> Self ``` -------------------------------- ### Serializer Configuration Options Source: https://docs.rs/serde-wasm-bindgen/latest/src/serde_wasm_bindgen/ser.rs.html Provides methods to configure the `Serializer`'s behavior, such as serializing missing values as null, maps as objects, large number types as BigInts, and bytes as arrays. ```rust impl Serializer { /// Creates a new default [`Serializer`]. pub const fn new() -> Self { Self { serialize_missing_as_null: false, serialize_maps_as_objects: false, serialize_large_number_types_as_bigints: false, serialize_bytes_as_arrays: false, } } /// Creates a JSON compatible serializer. This uses null instead of undefined, and /// uses plain objects instead of ES maps. So you will get the same result of /// `JsValue::from_serde`, and you can stringify results to JSON and store /// it without data loss. pub const fn json_compatible() -> Self { Self { serialize_missing_as_null: true, serialize_maps_as_objects: true, serialize_large_number_types_as_bigints: false, serialize_bytes_as_arrays: true, } } /// Set to `true` to serialize `()`, unit structs and `Option::None` to `null` /// instead of `undefined` in JS. `false` by default. pub const fn serialize_missing_as_null(mut self, value: bool) -> Self { self.serialize_missing_as_null = value; self } /// Set to `true` to serialize maps into plain JavaScript objects instead of /// ES2015 `Map`s. `false` by default. pub const fn serialize_maps_as_objects(mut self, value: bool) -> Self { self.serialize_maps_as_objects = value; self } /// Set to `true` to serialize 64-bit numbers to JavaScript `BigInt` instead of /// plain numbers. `false` by default. pub const fn serialize_large_number_types_as_bigints(mut self, value: bool) -> Self { self.serialize_large_number_types_as_bigints = value; self } /// Set to `true` to serialize bytes into plain JavaScript arrays instead of /// ES2015 `Uint8Array`s. `false` by default. pub const fn serialize_bytes_as_arrays(mut self, value: bool) -> Self { self.serialize_bytes_as_arrays = value; self } } ``` -------------------------------- ### Serializer::json_compatible Source: https://docs.rs/serde-wasm-bindgen/latest/serde_wasm_bindgen/struct.Serializer.html Creates a JSON compatible serializer, using null for undefined values and plain objects for maps. ```APIDOC ## Serializer::json_compatible ### Description Creates a JSON compatible serializer. This uses null instead of undefined, and uses plain objects instead of ES maps. So you will get the same result of `JsValue::from_serde`, and you can stringify results to JSON and store it without data loss. ### Method `const fn json_compatible() -> Self` ``` -------------------------------- ### Add serde-wasm-bindgen and Serde Dependencies Source: https://docs.rs/serde-wasm-bindgen/latest/serde_wasm_bindgen/index.html Add `serde-wasm-bindgen` and `serde` with the `derive` feature to your `Cargo.toml` to enable serialization and deserialization. ```toml [dependencies] serde = { version = "1.0", features = ["derive"] } serde-wasm-bindgen = "0.4" ``` -------------------------------- ### impl Default for Serializer Source: https://docs.rs/serde-wasm-bindgen/latest/serde_wasm_bindgen/struct.Serializer.html Provides a default implementation for the Serializer. ```APIDOC ## impl Default for Serializer ### Description Returns the default value for a `Serializer`. ### Method `fn default() -> Serializer` ``` -------------------------------- ### Deserialize F32 from F64 Source: https://docs.rs/serde-wasm-bindgen/latest/src/serde_wasm_bindgen/de.rs.html Forwards deserialization of `f32` to `f64` deserialization, as Serde handles the conversion with checks. ```rust fn deserialize_f32>(self, visitor: V) -> Result { self.deserialize_f64(visitor) } ``` -------------------------------- ### Send Rust data to JavaScript with `serde_wasm_bindgen::to_value` Source: https://docs.rs/serde-wasm-bindgen/latest/index.html Demonstrates how to serialize a Rust struct into a `JsValue` that can be consumed by JavaScript. ```APIDOC ## Function: send_example_to_js ### Description Serializes a Rust struct `Example` into a `JsValue` for use in JavaScript. ### Signature ```rust pub fn send_example_to_js() -> Result ``` ### Example Usage ```rust use std::collections::HashMap; use serde::{Serialize, Deserialize}; use wasm_bindgen::JsValue; #[derive(Serialize, Deserialize)] pub struct Example { pub field1: HashMap, pub field2: Vec>, pub field3: [f32; 4], } #[wasm_bindgen] pub fn send_example_to_js() -> Result { let mut field1 = HashMap::new(); field1.insert(0, String::from("ex")); let example = Example { field1, field2: vec![vec![1., 2.], vec![3., 4.]], field3: [1., 2., 3., 4.], }; Ok(serde_wasm_bindgen::to_value(&example)?) } ``` ``` -------------------------------- ### Configure Serializer to serialize bytes as arrays Source: https://docs.rs/serde-wasm-bindgen/latest/serde_wasm_bindgen/struct.Serializer.html Sets whether to serialize byte slices (`&[u8]`) into plain JavaScript arrays instead of ES2015 `Uint8Array`s. Defaults to `false`. ```rust pub const fn serialize_bytes_as_arrays(self, value: bool) -> Self ``` -------------------------------- ### deserialize_any Source: https://docs.rs/serde-wasm-bindgen/latest/serde_wasm_bindgen/struct.Deserializer.html Drives the visitor based on the input data type, allowing the `Deserializer` to infer the correct deserialization strategy. ```APIDOC ### fn deserialize_any>(self, visitor: V) -> Result Require the `Deserializer` to figure out how to drive the visitor based on what data type is in the input. Read more ``` -------------------------------- ### Serialize tuple Source: https://docs.rs/serde-wasm-bindgen/latest/serde_wasm_bindgen/struct.Serializer.html Begins serialization of a tuple, which will be represented as a JavaScript Array. ```rust fn serialize_tuple(self, len: usize) -> Result ``` -------------------------------- ### try_from Method Source: https://docs.rs/serde-wasm-bindgen/latest/serde_wasm_bindgen/struct.Error.html This associated function attempts to perform a conversion from type `U` to type `T`. It returns a `Result` which is `Ok(T)` on success or `Err(>::Error)` on failure. ```APIDOC #### fn try_from(value: U) -> Result>::Error> Performs the conversion. ``` -------------------------------- ### Serializer Configuration Source: https://docs.rs/serde-wasm-bindgen/latest/serde_wasm_bindgen/struct.Serializer.html Method to determine if the serializer should output human-readable data. ```APIDOC ## is_human_readable ### Description Determine whether `Serialize` implementations should serialize in human-readable form. ### Signature `fn is_human_readable(&self) -> bool` ``` -------------------------------- ### Serialize sequence Source: https://docs.rs/serde-wasm-bindgen/latest/serde_wasm_bindgen/struct.Serializer.html Begins serialization of a sequence, which will be represented as a JavaScript Array. ```rust fn serialize_seq(self, _len: Option) -> Result ``` -------------------------------- ### Configure Serializer to serialize maps as objects Source: https://docs.rs/serde-wasm-bindgen/latest/serde_wasm_bindgen/struct.Serializer.html Sets whether to serialize JavaScript `Map`s as plain JavaScript objects. Defaults to `false`, meaning `Map`s are serialized as ES2015 `Map`s. ```rust pub const fn serialize_maps_as_objects(self, value: bool) -> Self ``` -------------------------------- ### IntoDeserializer<'de, Error> for Deserializer Source: https://docs.rs/serde-wasm-bindgen/latest/serde_wasm_bindgen/struct.Deserializer.html Implementation of the `IntoDeserializer` trait for the `Deserializer` struct, allowing it to be converted into a `serde` deserializer. ```APIDOC ## type Deserializer = Deserializer The type of the deserializer being converted into. ``` ```APIDOC ## fn into_deserializer(self) -> Self::Deserializer Convert this value into a deserializer. ``` -------------------------------- ### Serializer Configuration Source: https://docs.rs/serde-wasm-bindgen/latest/src/serde_wasm_bindgen/ser.rs.html The `Serializer` struct allows customization of how Rust data is converted to JavaScript values. Options include handling missing values, serializing maps as objects, and serializing large number types as BigInts. ```APIDOC /// A [`serde::Serializer`] that converts supported Rust values into a [`JsValue`]. #[derive(Default)] pub struct Serializer { serialize_missing_as_null: bool, serialize_maps_as_objects: bool, serialize_large_number_types_as_bigints: bool, serialize_bytes_as_arrays: bool, } impl Serializer { /// Creates a new default [`Serializer`]. pub const fn new() -> Self { Self { serialize_missing_as_null: false, serialize_maps_as_objects: false, serialize_large_number_types_as_bigints: false, serialize_bytes_as_arrays: false, } } /// Creates a JSON compatible serializer. This uses null instead of undefined, and /// uses plain objects instead of ES maps. So you will get the same result of /// `JsValue::from_serde`, and you can stringify results to JSON and store /// it without data loss. pub const fn json_compatible() -> Self { Self { serialize_missing_as_null: true, serialize_maps_as_objects: true, serialize_large_number_types_as_bigints: false, serialize_bytes_as_arrays: true, } } /// Set to `true` to serialize `()`, unit structs and `Option::None` to `null` /// instead of `undefined` in JS. `false` by default. pub const fn serialize_missing_as_null(mut self, value: bool) -> Self { self.serialize_missing_as_null = value; self } /// Set to `true` to serialize maps into plain JavaScript objects instead of /// ES2015 `Map`s. `false` by default. pub const fn serialize_maps_as_objects(mut self, value: bool) -> Self { self.serialize_maps_as_objects = value; self } /// Set to `true` to serialize 64-bit numbers to JavaScript `BigInt` instead of /// plain numbers. `false` by default. pub const fn serialize_large_number_types_as_bigints(mut self, value: bool) -> Self { self.serialize_large_number_types_as_bigints = value; self } /// Set to `true` to serialize bytes into plain JavaScript arrays instead of /// ES2015 `Uint8Array`s. `false` by default. pub const fn serialize_bytes_as_arrays(mut self, value: bool) -> Self { self.serialize_bytes_as_arrays = value; self } } ``` -------------------------------- ### try_into Method Source: https://docs.rs/serde-wasm-bindgen/latest/serde_wasm_bindgen/struct.Error.html This method attempts to perform a conversion from type `T` to type `U`. It returns a `Result` which is `Ok(U)` on success or `Err(Error)` on failure. ```APIDOC #### fn try_into(self) -> Result>::Error> Performs the conversion. ``` -------------------------------- ### Deserialize Any JsValue Source: https://docs.rs/serde-wasm-bindgen/latest/src/serde_wasm_bindgen/de.rs.html The main entry point for deserializing any `JsValue`. It handles nullish values, booleans, BigInts, and floating-point numbers, dispatching to appropriate visitor methods. ```rust fn deserialize_any>(self, visitor: V) -> Result { if self.is_nullish() { // Ideally we would only treat `undefined` as `()` / `None` which would be semantically closer // to JS definitions, but, unfortunately, WebIDL generates missing values as `null` // and we probably want to support these as well. visitor.visit_unit() } else if let Some(v) = self.value.as_bool() { visitor.visit_bool(v) } else if self.value.is_bigint() { match i64::try_from(self.value) { Ok(v) => visitor.visit_i64(v), Err(value) => match u64::try_from(value) { Ok(v) => visitor.visit_u64(v), Err(_) => Err(de::Error::custom("Couldn't deserialize i64 or u64 from a BigInt outside i64::MIN..u64::MAX bounds")) } } } else if let Some(v) = self.value.as_f64() { ``` -------------------------------- ### Configure Serializer for BigInt serialization Source: https://docs.rs/serde-wasm-bindgen/latest/serde_wasm_bindgen/struct.Serializer.html Sets whether to serialize 64-bit integer types (`i64`, `u64`) to JavaScript `BigInt` instead of plain numbers. Defaults to `false`. When `false`, only numbers within the safe integer range are supported. ```rust pub const fn serialize_large_number_types_as_bigints(self, value: bool) -> Self ``` -------------------------------- ### Receive Rust data from JavaScript with `serde_wasm_bindgen::from_value` Source: https://docs.rs/serde-wasm-bindgen/latest/index.html Demonstrates how to deserialize a `JsValue` received from JavaScript into a Rust data type. ```APIDOC ## Function: receive_example_from_js ### Description Deserializes a `JsValue` received from JavaScript into a Rust struct `Example`. ### Signature ```rust pub fn receive_example_from_js(val: JsValue) -> Result<(), JsValue> ``` ### Parameters #### Request Body - **val** (JsValue) - Required - The JavaScript value to deserialize. ### Example Usage ```rust use serde::{Serialize, Deserialize}; use wasm_bindgen::JsValue; #[derive(Serialize, Deserialize)] pub struct Example { pub field1: HashMap, pub field2: Vec>, pub field3: [f32; 4], } #[wasm_bindgen] pub fn receive_example_from_js(val: JsValue) -> Result<(), JsValue> { let example: Example = serde_wasm_bindgen::from_value(val)?; /* ...do something with `example`... */ Ok(()) } ``` ``` -------------------------------- ### Cache Static String to JsString Source: https://docs.rs/serde-wasm-bindgen/latest/src/serde_wasm_bindgen/lib.rs.html Optimizes conversion of static string literals to JsString by caching based on pointer address. ```rust fn static_str_to_js(s: &'static str) -> JsString { use std::cell::RefCell; use std::collections::HashMap; #[derive(Default)] struct PtrHasher { addr: usize, } impl std::hash::Hasher for PtrHasher { fn write(&mut self, _bytes: &[u8]) { unreachable!(); } fn write_usize(&mut self, addr_or_len: usize) { if self.addr == 0 { self.addr = addr_or_len; } } fn finish(&self) -> u64 { self.addr as _ } } type PtrBuildHasher = std::hash::BuildHasherDefault; thread_local! { // Since we're mainly optimising for converting the exact same string literal over and over again, // which will always have the same pointer, we can speed things up by indexing by the string's pointer // instead of its value. static CACHE: RefCell> = Default::default(); } CACHE.with(|cache| { cache .borrow_mut() .entry(s) .or_insert_with(|| s.into()) .clone() }) } ``` -------------------------------- ### Configure Serializer to use null for missing values Source: https://docs.rs/serde-wasm-bindgen/latest/serde_wasm_bindgen/struct.Serializer.html Sets whether to serialize `()`, unit structs, and `Option::None` to JavaScript `null` instead of `undefined`. Defaults to `false`. ```rust pub const fn serialize_missing_as_null(self, value: bool) -> Self ``` -------------------------------- ### impl<'s> Serializer for &'s Serializer - serialize_unit_variant Source: https://docs.rs/serde-wasm-bindgen/latest/serde_wasm_bindgen/struct.Serializer.html Serializes unit variants as strings for compatibility with `serde-json`. ```APIDOC ## Serializer::serialize_unit_variant ### Description For compatibility with serde-json, serializes unit variants as “Variant” strings. ### Method `fn serialize_unit_variant( self, _name: &'static str, _variant_index: u32, variant: &'static str, ) -> Result` ``` -------------------------------- ### Serialize tuple struct Source: https://docs.rs/serde-wasm-bindgen/latest/serde_wasm_bindgen/struct.Serializer.html Begins serialization of a tuple struct, which will be represented as a JavaScript Array. ```rust fn serialize_tuple_struct( self, _name: &'static str, len: usize, ) -> Result ``` -------------------------------- ### impl<'s> Serializer for &'s Serializer - serialize_none Source: https://docs.rs/serde-wasm-bindgen/latest/serde_wasm_bindgen/struct.Serializer.html Serializes `None` into JavaScript `undefined` or `null`, based on the `serialize_missing_as_null` configuration. ```APIDOC ## Serializer::serialize_none ### Description Serializes `None` into `undefined` or `null`. If `serialize_missing_as_null` is set to `true`, `None` is serialized as `null`. ### Method `fn serialize_none(self) -> Result` ``` -------------------------------- ### impl<'s> Serializer for &'s Serializer - serialize_unit_struct Source: https://docs.rs/serde-wasm-bindgen/latest/serde_wasm_bindgen/struct.Serializer.html Serializes unit structs into JavaScript `undefined` or `null`. ```APIDOC ## Serializer::serialize_unit_struct ### Description Serializes unit structs into `undefined` or `null`. ### Method `fn serialize_unit_struct(self, _name: &'static str) -> Result` ``` -------------------------------- ### ObjectSerializer Source: https://docs.rs/serde-wasm-bindgen/latest/src/serde_wasm_bindgen/ser.rs.html Handles the serialization of Rust structs into plain JavaScript objects. ```APIDOC /// Serializes Rust structs into plain JS objects. pub struct ObjectSerializer<'s> { serializer: &'s Serializer, target: ObjectExt, } impl<'s> ObjectSerializer<'s> { pub fn new(serializer: &'s Serializer) -> Self { Self { serializer, target: Object::new().unchecked_into::(), } } } impl ser::SerializeStruct for ObjectSerializer<'_> { type Ok = JsValue; type Error = Error; fn serialize_field( &mut self, key: &'static str, value: &T, ) -> Result<()> { let value = value.serialize(self.serializer)?; self.target.set(static_str_to_js(key), value); Ok(()) } fn end(self) -> Result { Ok(self.target.into()) } } ``` -------------------------------- ### Collection and Struct Serialization Source: https://docs.rs/serde-wasm-bindgen/latest/serde_wasm_bindgen/struct.Serializer.html Methods for serializing complex Rust data structures like sequences, maps, structs, and variants into JavaScript representations. ```APIDOC ## serialize_seq ### Description Serializes Rust sequences into JS arrays. ### Signature `fn serialize_seq(self, _len: Option) -> Result` ## serialize_tuple ### Description Serializes Rust tuples into JS arrays. ### Signature `fn serialize_tuple(self, _len: usize) -> Result` ## serialize_tuple_struct ### Description Serializes Rust tuple structs into JS arrays. ### Signature `fn serialize_tuple_struct(self, _name: &'static str, _len: usize) -> Result` ## serialize_tuple_variant ### Description Serializes Rust tuple variants into JS objects with a single key representing the variant name. ### Signature `fn serialize_tuple_variant(self, _name: &'static str, _variant_index: u32, variant: &'static str, len: usize) -> Result` ## serialize_map ### Description Serializes Rust maps into JS `Map` or plain JS objects. See [`MapSerializer`] for more details. ### Signature `fn serialize_map(self, _len: Option) -> Result` ## serialize_struct ### Description Serializes Rust typed structs into plain JS objects. ### Signature `fn serialize_struct(self, _name: &'static str, _len: usize) -> Result` ## serialize_struct_variant ### Description Serializes Rust struct-like variants into `{"Variant": { ...fields... }}`. ### Signature `fn serialize_struct_variant(self, _name: &'static str, _variant_index: u32, variant: &'static str, len: usize) -> Result` ``` -------------------------------- ### Custom Object Access for Plain Objects Source: https://docs.rs/serde-wasm-bindgen/latest/src/serde_wasm_bindgen/lib.rs.html Provides custom bindings to access and set properties on JavaScript objects without relying on the fallible `Reflect` API. ```rust type ObjectExt; #[wasm_bindgen(method, indexing_getter)] fn get_with_ref_key(this: &ObjectExt, key: &JsString) -> JsValue; #[wasm_bindgen(method, indexing_setter)] fn set(this: &ObjectExt, key: JsString, value: JsValue); ``` -------------------------------- ### SeqAccess for JS Iterators Source: https://docs.rs/serde-wasm-bindgen/latest/src/serde_wasm_bindgen/de.rs.html Implements `de::SeqAccess` for JavaScript iterators, allowing deserialization of sequences from JS iterables. ```rust struct SeqAccess { iter: js_sys::IntoIter, } impl<'de> de::SeqAccess<'de> for SeqAccess { type Error = Error; fn next_element_seed>( &mut self, seed: T, ) -> Result> { Ok(match self.iter.next().transpose()? { Some(value) => Some(seed.deserialize(Deserializer::from(value))?), None => None, }) } } ``` -------------------------------- ### Default implementation for Serializer Source: https://docs.rs/serde-wasm-bindgen/latest/serde_wasm_bindgen/struct.Serializer.html Provides the default value for the `Serializer` type, equivalent to calling `Serializer::new()`. ```rust fn default() -> Serializer ``` -------------------------------- ### impl<'s> Serializer for &'s Serializer - serialize_tuple Source: https://docs.rs/serde-wasm-bindgen/latest/serde_wasm_bindgen/struct.Serializer.html Serializes Rust tuples into JavaScript arrays. ```APIDOC ## Serializer::serialize_tuple ### Description Serializes Rust tuples as JS arrays. ### Method `fn serialize_tuple(self, len: usize) -> Result` ``` -------------------------------- ### Convert JS [key, value] pair to Deserializers Source: https://docs.rs/serde-wasm-bindgen/latest/src/serde_wasm_bindgen/de.rs.html Helper function to destructure a JavaScript `[key, value]` pair into a tuple of `Deserializer` instances. This is useful when processing JavaScript objects. ```rust fn convert_pair(pair: JsValue) -> (Deserializer, Deserializer) { let pair = pair.unchecked_into::(); (pair.get(0).into(), pair.get(1).into()) } ``` -------------------------------- ### Serialize Map Key Source: https://docs.rs/serde-wasm-bindgen/latest/src/serde_wasm_bindgen/ser.rs.html Implements `serialize_key` for `MapSerializer`. This method serializes the key of a map entry and stores it temporarily before the value is serialized. ```rust fn serialize_key(&mut self, key: &T) -> Result<()> { debug_assert!(self.next_key.is_none()); self.next_key = Some(key.serialize(self.serializer)?); Ok(()) } ``` -------------------------------- ### serialize_map Source: https://docs.rs/serde-wasm-bindgen/latest/src/serde_wasm_bindgen/ser.rs.html Serializes Rust maps into JS `Map` or plain JS objects. The behavior is controlled by the `serialize_maps_as_objects` setting. ```APIDOC ## serialize_map ### Description Serializes Rust maps into JS `Map` or plain JS objects. ### Signature ```rust fn serialize_map(self, _len: Option) -> Result ``` ### Parameters - `_len`: The number of key-value pairs in the map, if known. ### Returns A `Result` containing a `MapSerializer` implementation or an error. ``` -------------------------------- ### Deserializer Methods Source: https://docs.rs/serde-wasm-bindgen/latest/serde_wasm_bindgen/struct.Deserializer.html These methods are part of the `Deserializer` struct and are used to hint to the `Visitor` what type of value is expected during the deserialization process. ```APIDOC ## fn deserialize_unit_struct>( self, _name: &'static str, visitor: V, ) -> Result Hint that the `Deserialize` type is expecting a unit struct with a particular name. ``` ```APIDOC ## fn deserialize_bool>( self, visitor: V, ) -> Result Hint that the `Deserialize` type is expecting a `bool` value. ``` ```APIDOC ## fn deserialize_f32>(self, visitor: V) -> Result Hint that the `Deserialize` type is expecting a `f32` value. ``` ```APIDOC ## fn deserialize_f64>(self, visitor: V) -> Result Hint that the `Deserialize` type is expecting a `f64` value. ``` ```APIDOC ## fn deserialize_identifier>( self, visitor: V, ) -> Result Hint that the `Deserialize` type is expecting the name of a struct field or the discriminant of an enum variant. ``` ```APIDOC ## fn deserialize_str>(self, visitor: V) -> Result Hint that the `Deserialize` type is expecting a string value and does not benefit from taking ownership of buffered data owned by the `Deserializer`. Read more ``` ```APIDOC ## fn deserialize_string>( self, visitor: V, ) -> Result Hint that the `Deserialize` type is expecting a string value and would benefit from taking ownership of buffered data owned by the `Deserializer`. Read more ``` ```APIDOC ## fn deserialize_i8>(self, visitor: V) -> Result Hint that the `Deserialize` type is expecting an `i8` value. ``` ```APIDOC ## fn deserialize_i16>(self, visitor: V) -> Result Hint that the `Deserialize` type is expecting an `i16` value. ``` ```APIDOC ## fn deserialize_i32>(self, visitor: V) -> Result Hint that the `Deserialize` type is expecting an `i32` value. ``` ```APIDOC ## fn deserialize_u8>(self, visitor: V) -> Result Hint that the `Deserialize` type is expecting a `u8` value. ``` ```APIDOC ## fn deserialize_u16>(self, visitor: V) -> Result Hint that the `Deserialize` type is expecting a `u16` value. ``` ```APIDOC ## fn deserialize_u32>(self, visitor: V) -> Result Hint that the `Deserialize` type is expecting a `u32` value. ``` ```APIDOC ## fn is_human_readable(&self) -> bool Determine whether `Deserialize` implementations should expect to deserialize their human-readable form. Read more ``` -------------------------------- ### TryInto for T Source: https://docs.rs/serde-wasm-bindgen/latest/serde_wasm_bindgen/struct.Deserializer.html Implementation of the TryInto trait for generic types T and U, where U implements TryFrom. This allows for fallible conversions. ```APIDOC ## impl TryInto for T where U: TryFrom, ### type Error = >::Error The type returned in the event of a conversion error. ### fn try_into(self) -> Result>::Error> Performs the conversion. ``` -------------------------------- ### Primitive Type Serialization Source: https://docs.rs/serde-wasm-bindgen/latest/serde_wasm_bindgen/struct.Serializer.html Methods for serializing primitive Rust data types into their JavaScript equivalents. ```APIDOC ## serialize_bool ### Description Serialize a `bool` value. ### Signature `fn serialize_bool(self, v: bool) -> Result` ## serialize_i8 ### Description Serialize an `i8` value. ### Signature `fn serialize_i8(self, v: i8) -> Result` ## serialize_i16 ### Description Serialize an `i16` value. ### Signature `fn serialize_i16(self, v: i16) -> Result` ## serialize_i32 ### Description Serialize an `i32` value. ### Signature `fn serialize_i32(self, v: i32) -> Result` ## serialize_u8 ### Description Serialize a `u8` value. ### Signature `fn serialize_u8(self, v: u8) -> Result` ## serialize_u16 ### Description Serialize a `u16` value. ### Signature `fn serialize_u16(self, v: u16) -> Result` ## serialize_u32 ### Description Serialize a `u32` value. ### Signature `fn serialize_u32(self, v: u32) -> Result` ## serialize_f32 ### Description Serialize an `f32` value. ### Signature `fn serialize_f32(self, v: f32) -> Result` ## serialize_f64 ### Description Serialize an `f64` value. ### Signature `fn serialize_f64(self, v: f64) -> Result` ## serialize_str ### Description Serialize a `&str`. ### Signature `fn serialize_str(self, v: &str) -> Result` ``` -------------------------------- ### Deserialize Bytes - serde-wasm-bindgen Source: https://docs.rs/serde-wasm-bindgen/latest/src/serde_wasm_bindgen/de.rs.html Forwards to `deserialize_byte_buf` as direct references to JS memory are not possible. ```rust fn deserialize_bytes>(self, visitor: V) -> Result { self.deserialize_byte_buf(visitor) } ``` -------------------------------- ### deserialize_bytes Source: https://docs.rs/serde-wasm-bindgen/latest/src/serde_wasm_bindgen/de.rs.html Deserializes byte buffers, forwarding to `deserialize_byte_buf` as references to JS memory cannot be taken. ```APIDOC ## deserialize_bytes>(self, visitor: V) -> Result ### Description We can't take references to JS memory, so this forwards to an owned [`Self::deserialize_byte_buf`](#method.deserialize_byte_buf). ``` -------------------------------- ### to_value Source: https://docs.rs/serde-wasm-bindgen/latest/serde_wasm_bindgen/fn.to_value.html Converts a Rust value into a `JsValue`. ```APIDOC ## to_value ### Description Converts a Rust value into a `JsValue`. ### Signature ```rust pub fn to_value(value: &T) -> Result ``` ### Parameters * `value`: A reference to a value that implements `Serialize`. ### Returns A `Result` containing either a `JsValue` on success or an `Error` on failure. ``` -------------------------------- ### Serialize None Source: https://docs.rs/serde-wasm-bindgen/latest/serde_wasm_bindgen/struct.Serializer.html Serializes `None`. If `serialize_missing_as_null` is enabled, it's serialized as `null`; otherwise, as `undefined`. ```rust fn serialize_none(self) -> Result ``` -------------------------------- ### serialize_unit_struct Source: https://docs.rs/serde-wasm-bindgen/latest/src/serde_wasm_bindgen/ser.rs.html Serializes unit structs into `undefined` or `null`, similar to `serialize_unit`. ```APIDOC ## serialize_unit_struct ### Description Serializes unit structs into `undefined` or `null`. ### Method `serialize_unit_struct(self, _name: &'static str) -> Result` ### Parameters - `_name` (&'static str) - The name of the unit struct (unused in serialization). ### Response - `Result` - A JavaScript `undefined` or `null` value. ``` -------------------------------- ### impl<'s> Serializer for &'s Serializer - serialize_i64 Source: https://docs.rs/serde-wasm-bindgen/latest/serde_wasm_bindgen/struct.Serializer.html Serializes an `i64` value into a JavaScript `BigInt` or a JS number, depending on configuration. ```APIDOC ## Serializer::serialize_i64 ### Description Serializes `i64` into a `BigInt` or a JS number. If `serialize_large_number_types_as_bigints` is set to `false`, `i64` is serialized as a JS number. However, in this mode, only numbers within the safe integer range are supported. ### Method `fn serialize_i64(self, v: i64) -> Result` ``` -------------------------------- ### Serializer::serialize_missing_as_null Source: https://docs.rs/serde-wasm-bindgen/latest/serde_wasm_bindgen/struct.Serializer.html Configures the serializer to represent `()`, unit structs, and `Option::None` as `null` instead of `undefined`. ```APIDOC ## Serializer::serialize_missing_as_null ### Description Set to `true` to serialize `()`, unit structs and `Option::None` to `null` instead of `undefined` in JS. `false` by default. ### Method `const fn serialize_missing_as_null(self, value: bool) -> Self` ``` -------------------------------- ### MapSerializer Source: https://docs.rs/serde-wasm-bindgen/latest/src/serde_wasm_bindgen/ser.rs.html Serializes Rust maps into either JavaScript `Map` objects or plain JavaScript objects. When serializing as plain objects, only string keys are supported. ```APIDOC ## MapSerializer ### Description Serializes Rust maps into JS `Map` or plain JS objects. Plain JS objects are used if `serialize_maps_as_objects` is set to `true`, but then only string keys are supported. ### Type `pub struct MapSerializer<'s>` ### Methods - `pub fn new(serializer: &'s Serializer, as_object: bool) -> Self` ### Implementations - `impl ser::SerializeMap for MapSerializer<'_>` ``` -------------------------------- ### EnumAccess for JS Enums Source: https://docs.rs/serde-wasm-bindgen/latest/src/serde_wasm_bindgen/de.rs.html Provides `de::EnumAccess` for JavaScript values representing enums, using separate deserializers for the tag and payload. ```rust struct EnumAccess { tag: Deserializer, payload: Deserializer, } impl<'de> de::EnumAccess<'de> for EnumAccess { type Error = Error; type Variant = Deserializer; fn variant_seed>( ``` -------------------------------- ### serialize_none Source: https://docs.rs/serde-wasm-bindgen/latest/src/serde_wasm_bindgen/ser.rs.html Serializes `None` into `undefined` or `null`. If `serialize_missing_as_null` is true, `None` is serialized as `null`. ```APIDIDOC ## serialize_none ### Description Serializes `None` into `undefined` or `null`. If `serialize_missing_as_null` is set to `true`, `None` is serialized as `null`. ### Method `serialize_none(self) -> Result` ### Response - `Result` - A JavaScript `undefined` or `null` value. ``` -------------------------------- ### serialize_i64 Source: https://docs.rs/serde-wasm-bindgen/latest/src/serde_wasm_bindgen/ser.rs.html Serializes `i64` into a `BigInt` or a JS number. If `serialize_large_number_types_as_bigints` is false, `i64` is serialized as a JS number, but only if it's within the safe integer range. ```APIDOC ## serialize_i64 ### Description Serializes `i64` into a `BigInt` or a JS number. If `serialize_large_number_types_as_bigints` is set to `false`, `i64` is serialized as a JS number. But in this mode only numbers within the safe integer range are supported. ### Method `serialize_i64(self, v: i64) -> Result` ### Parameters - `v` (i64) - The 64-bit integer to serialize. ### Response - `Result` - A JavaScript value representing the serialized `i64`. ``` -------------------------------- ### serialize_i128 Source: https://docs.rs/serde-wasm-bindgen/latest/src/serde_wasm_bindgen/ser.rs.html Serializes `i128` into a `BigInt`. ```APIDOC ## serialize_i128 ### Description Serializes `i128` into a `BigInt`. ### Method `serialize_i128(self, v: i128) -> Result` ### Parameters - `v` (i128) - The 128-bit integer to serialize. ### Response - `Result` - A JavaScript `BigInt` value representing the serialized `i128`. ``` -------------------------------- ### Serialize unit struct Source: https://docs.rs/serde-wasm-bindgen/latest/src/serde_wasm_bindgen/ser.rs.html Serializes unit structs by calling `serialize_unit`, resulting in `undefined` or `null`. ```rust fn serialize_unit_struct(self, _name: &'static str) -> Result { self.serialize_unit() } ``` -------------------------------- ### deserialize_bytes Source: https://docs.rs/serde-wasm-bindgen/latest/serde_wasm_bindgen/struct.Deserializer.html Forwards to `Self::deserialize_byte_buf` as direct references to JS memory are not possible. ```APIDOC ### fn deserialize_bytes>( self, visitor: V, ) -> Result We can’t take references to JS memory, so forwards to an owned `Self::deserialize_byte_buf`. ``` -------------------------------- ### Creating JavaScript Errors Source: https://docs.rs/serde-wasm-bindgen/latest/src/serde_wasm_bindgen/error.rs.html Provides a constructor `new` for the `Error` type to create a JavaScript `Error` object from a displayable message. This is useful for generating exceptions from Rust. ```rust impl Error { /// Creates a JavaScript `Error` with a given message. pub fn new(msg: T) -> Self { Error(JsError::new(&msg.to_string()).into()) } } ``` -------------------------------- ### impl<'s> Serializer for &'s Serializer - serialize_unit Source: https://docs.rs/serde-wasm-bindgen/latest/serde_wasm_bindgen/struct.Serializer.html Serializes the unit type `()` into JavaScript `undefined` or `null`, based on the `serialize_missing_as_null` configuration. ```APIDOC ## Serializer::serialize_unit ### Description Serializes `()` into `undefined` or `null`. If `serialize_missing_as_null` is set to `true`, `()` is serialized as `null`. ### Method `fn serialize_unit(self) -> Result` ``` -------------------------------- ### impl<'s> Serializer for &'s Serializer - serialize_seq Source: https://docs.rs/serde-wasm-bindgen/latest/serde_wasm_bindgen/struct.Serializer.html Serializes any Rust iterable into a JavaScript Array. ```APIDOC ## Serializer::serialize_seq ### Description Serializes any Rust iterable as a JS Array. ### Method `fn serialize_seq(self, _len: Option) -> Result` ``` -------------------------------- ### impl<'s> Serializer for &'s Serializer - serialize_u64 Source: https://docs.rs/serde-wasm-bindgen/latest/serde_wasm_bindgen/struct.Serializer.html Serializes a `u64` value into a JavaScript `BigInt` or a JS number, depending on configuration. ```APIDOC ## Serializer::serialize_u64 ### Description Serializes `u64` into a `BigInt` or a JS number. If `serialize_large_number_types_as_bigints` is set to `false`, `u64` is serialized as a JS number. However, in this mode, only numbers within the safe integer range are supported. ### Method `fn serialize_u64(self, v: u64) -> Result` ``` -------------------------------- ### Deserialize Str as String Source: https://docs.rs/serde-wasm-bindgen/latest/src/serde_wasm_bindgen/de.rs.html Deserializes a string slice by forwarding to the string deserialization logic. ```rust fn deserialize_str>(self, visitor: V) -> Result { self.deserialize_string(visitor) } ``` -------------------------------- ### Iterator Collection Methods Source: https://docs.rs/serde-wasm-bindgen/latest/serde_wasm_bindgen/struct.Serializer.html Methods for collecting iterators into sequences or maps. ```APIDOC ## collect_seq ### Description Collect an iterator as a sequence. ### Signature `fn collect_seq(self, iter: I) -> Result` where I: IntoIterator, ::Item: Serialize ## collect_map ### Description Collect an iterator as a map. ### Signature `fn collect_map(self, iter: I) -> Result` where K: Serialize, V: Serialize, I: IntoIterator ## collect_str ### Description Serialize a string produced by an implementation of `Display`. ### Signature `fn collect_str(self, value: &T) -> Result` where T: Display + ?Sized ``` -------------------------------- ### ObjectAccess for JS Objects Source: https://docs.rs/serde-wasm-bindgen/latest/src/serde_wasm_bindgen/de.rs.html Implements `de::MapAccess` for JavaScript objects, allowing deserialization by accessing properties based on a predefined list of fields. ```rust struct ObjectAccess { obj: ObjectExt, fields: std::slice::Iter<'static, &'static str>, next_value: Option, } impl ObjectAccess { fn new(obj: ObjectExt, fields: &'static [&'static str]) -> Self { Self { obj, fields: fields.iter(), next_value: None, } } } fn str_deserializer(s: &str) -> de::value::StrDeserializer { de::IntoDeserializer::into_deserializer(s) } impl<'de> de::MapAccess<'de> for ObjectAccess { type Error = Error; fn next_key_seed>(&mut self, seed: K) -> Result> { debug_assert!(self.next_value.is_none()); for field in &mut self.fields { let js_field = static_str_to_js(field); let next_value = self.obj.get_with_ref_key(&js_field); let is_missing_field = next_value.is_undefined() && !js_field.js_in(&self.obj); if !is_missing_field { self.next_value = Some(Deserializer::from(next_value)); return Ok(Some(seed.deserialize(str_deserializer(field))?)); } } Ok(None) } fn next_value_seed>(&mut self, seed: V) -> Result { seed.deserialize(self.next_value.take().unwrap_throw()) } } ``` -------------------------------- ### serialize Source: https://docs.rs/serde-wasm-bindgen/latest/src/serde_wasm_bindgen/lib.rs.html Serializes a value by passing it through as a JsValue when used with the `Serializer` in `serde_wasm_bindgen`. Compatible with `serde(serialize_with)`. ```APIDOC ## serialize(val: &T, ser: S) -> Result ### Description Serializes the value by passing it through as a `JsValue`. ### Parameters - `val` (&T): The value to serialize, which must implement `JsCast`. - `ser` (S): The serde Serializer. ### Returns - `Result`: The result of the serialization. ```