170 breaking releases

new 0.173.0 Feb 21, 2024
0.171.0 Feb 13, 2024
0.149.0 Dec 28, 2023
0.143.0 Nov 29, 2023
0.1.0 Mar 26, 2021

#111 in Encoding

Download history 21181/week @ 2023-11-01 15001/week @ 2023-11-08 22924/week @ 2023-11-15 21855/week @ 2023-11-22 16816/week @ 2023-11-29 17175/week @ 2023-12-06 16384/week @ 2023-12-13 16026/week @ 2023-12-20 5740/week @ 2023-12-27 13104/week @ 2024-01-03 12611/week @ 2024-01-10 13812/week @ 2024-01-17 16770/week @ 2024-01-24 12954/week @ 2024-01-31 17182/week @ 2024-02-07 12874/week @ 2024-02-14

62,908 downloads per month
Used in 121 crates (9 directly)

MIT license

105KB
3K SLoC

serde_v8

Author: Aaron O'Mullan aaron.omullan@gmail.com

Serde support for encoding/decoding (rusty_)v8 values.

Broadly serde_v8 aims to provide an expressive but ~maximally efficient encoding layer to biject rust & v8/js values. It's a core component of deno's op-layer and is used to encode/decode all non-buffer values.

Original issue: denoland/deno#9540

Quickstart

serde_v8 fits naturally into the serde ecosystem, so if you've already used serde or serde_json, serde_v8's API should be very familiar.

serde_v8 exposes two key-functions:

  • to_v8: maps rust->v8, similar to serde_json::to_string, ...
  • from_v8: maps v8->rust, similar to serde_json::from_str, ...

Best practices

Whilst serde_v8 is compatible with serde_json::Value it's important to keep in mind that serde_json::Value is essentially a loosely-typed value (think nested HashMaps), so when writing ops we recommend directly using rust structs/tuples or primitives, since mapping to serde_json::Value will add extra overhead and result in slower ops.

I also recommend avoiding unnecessary "wrappers", if your op takes a single-keyed struct, consider unwrapping that as a plain value unless you plan to add fields in the near-future.

Instead of returning "nothing" via Ok(json!({})), change your return type to rust's unit type () and returning Ok(()), serde_v8 will efficiently encode that as a JS null.

Advanced features

If you need to mix rust & v8 values in structs/tuples, you can use the special serde_v8::Value type, which will passthrough the original v8 value untouched when encoding/decoding.

TODO

  • Experiment with KeyCache to optimize struct keys
  • Experiment with external v8 strings
  • Explore using json-stringifier.cc's fast-paths for arrays
  • Improve tests to test parity with serde_json (should be mostly interchangeable)
  • Consider a Payload type that's deserializable by itself (holds scope & value)
  • Ensure we return errors instead of panicking on .unwrap()s

Dependencies

~75MB
~1.5M SLoC