-
Notifications
You must be signed in to change notification settings - Fork 147
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
feat(gloo-utils): Lift serde-serialization from wasm-bindgen #242
Merged
ranile
merged 11 commits into
rustwasm:master
from
andoriyu:feat/add_serde_serialiation
Aug 21, 2022
Merged
Changes from 7 commits
Commits
Show all changes
11 commits
Select commit
Hold shift + click to select a range
bd52da5
feat(gloo-utils): Lift serde-serialization from wasm-bindgen
andoriyu f3149b0
Update crates/utils/Cargo.toml
andoriyu 75a9560
Update crates/utils/src/json.rs
andoriyu 91476dc
Update crates/utils/src/json.rs
andoriyu ecd3e55
Address the feedback
andoriyu 3b06f25
only re-export if feature is enable
andoriyu f34da81
address the feedback
andoriyu d06c888
Update json.rs
andoriyu 81791fa
Update json.rs
andoriyu 6f8067c
Update json.rs
andoriyu 8cac0bf
cargo fmt
andoriyu File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,114 @@ | ||
#![cfg(feature = "serde")] | ||
|
||
use js_sys::JsString; | ||
use wasm_bindgen::{prelude::wasm_bindgen, JsValue, UnwrapThrowExt}; | ||
mod private { | ||
pub trait Sealed {} | ||
impl Sealed for wasm_bindgen::JsValue {} | ||
} | ||
|
||
// Turns out `JSON.stringify(undefined) === undefined`, so if | ||
// we're passed `undefined` reinterpret it as `null` for JSON | ||
// purposes. | ||
#[wasm_bindgen( | ||
inline_js = "export function serialize(obj) { return JSON.stringify(obj === undefined ? null : obj) }" | ||
)] | ||
extern "C" { | ||
#[wasm_bindgen(catch)] | ||
fn serialize(obj: &JsValue) -> Result<JsString, JsValue>; | ||
} | ||
|
||
/// Extenstion trait to provide conversion between [`JsValue`](wasm_bindgen::JsValue) and [`serde`]. | ||
/// | ||
/// Usage of this API requires activating the `serde` feature of the `gloo-utils` crate. | ||
ranile marked this conversation as resolved.
Show resolved
Hide resolved
|
||
#[cfg_attr(docsrs, doc(cfg(feature = "serde")))] | ||
pub trait JsValueSerdeExt: private::Sealed { | ||
/// Creates a new `JsValue` from the JSON serialization of the object `t` | ||
/// provided. | ||
/// | ||
/// This function will serialize the provided value `t` to a JSON string, | ||
/// send the JSON string to JS, parse it into a JS object, and then return | ||
/// a handle to the JS object. This is unlikely to be super speedy so it's | ||
/// not recommended for large payloads, but it's a nice to have in some | ||
/// situations! | ||
/// | ||
/// Usage of this API requires activating the `serde` feature of | ||
/// the `gloo-utils` crate. | ||
/// # Example | ||
/// | ||
/// ```rust | ||
/// use wasm_bindgen::JsValue; | ||
/// use gloo_utils::format::JsValueSerdeExt; | ||
/// | ||
/// # fn no_run() { | ||
/// assert_eq!(JsValue::from("bar").into_serde::<String>().unwrap(), "bar"); | ||
/// # } | ||
/// ``` | ||
/// # Errors | ||
/// | ||
/// Returns any error encountered when serializing `T` into JSON. | ||
/// | ||
/// # Panics | ||
/// | ||
/// Panics if [`serde_json`](serde_json::to_string) generated JSON that couldn't be parsed by [`js_sys`]. | ||
/// Uses [`unwrap_throw`](UnwrapThrowExt::unwrap_throw) from [`wasm_bindgen::UnwrapThrowExt`]. | ||
#[cfg_attr(docsrs, doc(cfg(feature = "serde")))] | ||
fn from_serde<T>(t: &T) -> serde_json::Result<JsValue> | ||
where | ||
T: serde::ser::Serialize + ?Sized; | ||
|
||
/// Invokes `JSON.stringify` on this value and then parses the resulting | ||
/// JSON into an arbitrary Rust value. | ||
/// | ||
/// This function will first call `JSON.stringify` on the `JsValue` itself. | ||
/// The resulting string is then passed into Rust which then parses it as | ||
/// JSON into the resulting value. If given `undefined`, object will be silentrly changed to | ||
/// null to avoid panic. | ||
/// | ||
/// Usage of this API requires activating the `serde` feature of | ||
/// the `gloo-utils` crate. | ||
/// | ||
/// # Example | ||
/// | ||
/// ```rust | ||
/// use wasm_bindgen::JsValue; | ||
/// use gloo_utils::format::JsValueSerdeExt; | ||
/// | ||
/// # fn no_run() { | ||
/// let array = vec![1,2,3]; | ||
/// let obj = JsValue::from_serde(&array); | ||
/// # } | ||
/// ``` | ||
/// | ||
/// # Errors | ||
/// | ||
/// Returns any error encountered when parsing the JSON into a `T`. | ||
/// | ||
/// # Panics | ||
/// | ||
/// Panics if [`js_sys`] couldn't stringify the JsValue. Uses [`unwrap_throw`](UnwrapThrowExt::unwrap_throw) | ||
/// from [`wasm_bindgen::UnwrapThrowExt`]. | ||
#[cfg_attr(docsrs, doc(cfg(feature = "serde")))] | ||
#[allow(clippy::wrong_self_convention)] | ||
fn into_serde<T>(&self) -> serde_json::Result<T> | ||
where | ||
T: for<'a> serde::de::Deserialize<'a>; | ||
} | ||
|
||
impl JsValueSerdeExt for JsValue { | ||
fn from_serde<T>(t: &T) -> serde_json::Result<JsValue> | ||
where | ||
T: serde::ser::Serialize + ?Sized, | ||
{ | ||
let s = serde_json::to_string(t)?; | ||
Ok(js_sys::JSON::parse(&s).unwrap_throw()) | ||
} | ||
|
||
fn into_serde<T>(&self) -> serde_json::Result<T> | ||
where | ||
T: for<'a> serde::de::Deserialize<'a>, | ||
{ | ||
let s = serialize(self).map(String::from).unwrap_throw(); | ||
serde_json::from_str(&s) | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,25 @@ | ||
function deepStrictEqual(left, right) { | ||
var left_json = JSON.stringify(left); | ||
var right_json = JSON.stringify(right); | ||
if (left_json !== right_json) { | ||
throw Error(`${left_json} != ${right_json}`) | ||
} | ||
} | ||
|
||
export function verify_serde (a) { | ||
deepStrictEqual(a, { | ||
a: 0, | ||
b: 'foo', | ||
c: null, | ||
d: { a: 1 } | ||
}); | ||
}; | ||
|
||
export function make_js_value() { | ||
return { | ||
a: 2, | ||
b: 'bar', | ||
c: { a: 3 }, | ||
d: { a: 4 }, | ||
} | ||
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,68 @@ | ||
#![cfg(target_arch = "wasm32")] | ||
#![cfg(feature = "serde")] | ||
extern crate wasm_bindgen; | ||
extern crate wasm_bindgen_test; | ||
|
||
use wasm_bindgen::prelude::*; | ||
use wasm_bindgen_test::*; | ||
|
||
use gloo_utils::format::JsValueSerdeExt; | ||
|
||
use serde_derive::{Deserialize, Serialize}; | ||
|
||
wasm_bindgen_test_configure!(run_in_browser); | ||
|
||
#[wasm_bindgen(start)] | ||
pub fn start() { | ||
panic!(); | ||
} | ||
|
||
#[wasm_bindgen(module = "/tests/serde.js")] | ||
extern "C" { | ||
fn verify_serde(val: JsValue); | ||
fn make_js_value() -> JsValue; | ||
} | ||
|
||
#[derive(Deserialize, Serialize, Debug)] | ||
pub struct SerdeFoo { | ||
a: u32, | ||
b: String, | ||
c: Option<SerdeBar>, | ||
d: SerdeBar, | ||
} | ||
|
||
#[derive(Deserialize, Serialize, Debug)] | ||
pub struct SerdeBar { | ||
a: u32, | ||
} | ||
|
||
#[wasm_bindgen_test] | ||
fn from_serde() { | ||
let js = JsValue::from_serde("foo").unwrap(); | ||
assert_eq!(js.as_string(), Some("foo".to_string())); | ||
|
||
verify_serde( | ||
JsValue::from_serde(&SerdeFoo { | ||
a: 0, | ||
b: "foo".to_string(), | ||
c: None, | ||
d: SerdeBar { a: 1 }, | ||
}) | ||
.unwrap(), | ||
); | ||
} | ||
|
||
#[wasm_bindgen_test] | ||
fn into_serde() { | ||
let js_value = make_js_value(); | ||
let foo = js_value.into_serde::<SerdeFoo>().unwrap(); | ||
assert_eq!(foo.a, 2); | ||
assert_eq!(foo.b, "bar"); | ||
assert!(foo.c.is_some()); | ||
assert_eq!(foo.c.as_ref().unwrap().a, 3); | ||
assert_eq!(foo.d.a, 4); | ||
|
||
assert_eq!(JsValue::from("bar").into_serde::<String>().unwrap(), "bar"); | ||
assert_eq!(JsValue::undefined().into_serde::<i32>().ok(), None); | ||
assert_eq!(JsValue::null().into_serde::<i32>().ok(), None); | ||
} |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Inline JS snippets could cause issues for non-ES module targets.
no-modules
target is still the only target supported bygloo-worker
.See: https://rustwasm.github.io/docs/wasm-bindgen/examples/without-a-bundler.html#using-the-older---target-no-modules
Instead of going through
JSON::stringify
andserde_json
, I would suggest usingserde-wasm-bindgen
. It supports non-serializable types (e.g.: ES2015Map
) and has a smaller bundle footprint thanserde_json
.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@futursolo oh well, back to what I had before.
So if you use
serde_wasm_bindgen
, then you don't really need this. The goal is to provide a drop-in replacement forJsValue::{from_serde/to_serde}
and an easier way to usejs_sys::JSON::
.Plus, in the deprecation thread, someone said they had a bad time with
serde-wasm-bindgen
. I think it makes sense: it calls to JS for every field which is slow.