|
1 | | -# rquickjs-serde |
| 1 | +# rquickjs serde |
2 | 2 |
|
3 | | -This is a serde serializer/deserializer for RQuickJS. |
| 3 | +[](https://github.com/rquickjs/rquickjs-serde) |
| 4 | +[](https://crates.io/crates/rquickjs-serde) |
4 | 5 |
|
5 | | -## 📣 Acknowledgements |
| 6 | +This is a serde serializer/deserializer for [rquickjs](https://github.com/DelSkayn/rquickjs) `Value`. |
| 7 | + |
| 8 | +## Usage |
| 9 | + |
| 10 | +```rust |
| 11 | +use std::error::Error; |
| 12 | + |
| 13 | +use serde::Serialize; |
| 14 | +use rquickjs::{Runtime, Context}; |
| 15 | + |
| 16 | +#[derive(Serialize)] |
| 17 | +struct User { |
| 18 | + fingerprint: String, |
| 19 | + location: String, |
| 20 | +} |
| 21 | + |
| 22 | +fn main() { |
| 23 | + let rt = Runtime::new().unwrap(); |
| 24 | + let ctx = Context::full(&rt).unwrap(); |
| 25 | + |
| 26 | + // Serialize to a Value<'_> |
| 27 | + let u = User { |
| 28 | + fingerprint: "0xF9BA143B95FF6D82".to_owned(), |
| 29 | + location: "Menlo Park, CA".to_owned(), |
| 30 | + }; |
| 31 | + ctx.with(|ctx| { |
| 32 | + let v = rquickjs_serde::to_value(ctx, u).unwrap(); |
| 33 | + let obj = v.into_object().unwrap(); |
| 34 | + |
| 35 | + let fingerprint: String = obj.get("fingerprint").unwrap(); |
| 36 | + assert_eq!(fingerprint, "0xF9BA143B95FF6D82"); |
| 37 | + |
| 38 | + let location: String = obj.get("location").unwrap(); |
| 39 | + assert_eq!(location, "Menlo Park, CA"); |
| 40 | + }); |
| 41 | + |
| 42 | + // Deserialize from a Value<'_> |
| 43 | + let v = ctx.with(|ctx| { |
| 44 | + ctx.eval::<Value<'_>, _>("var a = {fingerprint: '0xF9BA143B95FF6D82', location: 'Menlo Park, CA'};").unwrap(); |
| 45 | + let val = ctx.globals().get("a").unwrap(); |
| 46 | + let u: User = rquickjs_serde::from_value(val).unwrap(); |
| 47 | + u |
| 48 | + }); |
| 49 | + assert_eq!(v.fingerprint, "0xF9BA143B95FF6D82"); |
| 50 | + assert_eq!(v.location, "Menlo Park, CA"); |
| 51 | +} |
| 52 | +``` |
| 53 | + |
| 54 | +## Acknowledgements |
6 | 55 |
|
7 | 56 | This project includes code derived from the [Javy](https://github.com/bytecodealliance/javy) project. See [`NOTICE`](./NOTICE) for more details. |
0 commit comments