rhai/examples/serde.rs

87 lines
2.0 KiB
Rust
Raw Permalink Normal View History

2022-02-12 05:41:04 +01:00
//! An example to serialize and deserialize Rust types.
#[cfg(feature = "no_object")]
fn main() {
panic!("This example does not run under 'no_object'.")
}
#[cfg(not(feature = "no_object"))]
fn main() {
2020-10-10 09:06:59 +02:00
use rhai::serde::{from_dynamic, to_dynamic};
2020-07-04 16:32:18 +02:00
use rhai::{Dynamic, Engine, Map};
2020-07-04 16:52:45 +02:00
use serde::{Deserialize, Serialize};
2020-07-04 16:32:18 +02:00
2020-12-26 08:41:41 +01:00
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
2020-07-04 16:32:18 +02:00
struct Point {
x: f64,
y: f64,
}
2020-12-26 08:41:41 +01:00
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
2020-07-04 16:32:18 +02:00
struct MyStruct {
a: i64,
b: Vec<String>,
c: bool,
d: Point,
}
pub fn ser() {
let x = MyStruct {
a: 42,
b: vec!["hello".into(), "world".into()],
c: true,
d: Point {
x: 123.456,
y: 999.0,
},
};
println!("Source struct: {x:#?}");
2020-07-04 16:32:18 +02:00
// Convert the 'MyStruct' into a 'Dynamic'
let map: Dynamic = to_dynamic(x).unwrap();
assert!(map.is::<Map>());
println!("Serialized to Dynamic: {map:#?}");
2020-07-04 16:32:18 +02:00
}
pub fn de() {
let engine = Engine::new();
let result: Dynamic = engine
.eval(
r#"
#{
a: 42,
b: [ "hello", "world" ],
c: true,
d: #{ x: 123.456, y: 999.0 }
}
"#,
2020-07-04 16:32:18 +02:00
)
.unwrap();
println!("Source Dynamic: {result:#?}");
2020-07-04 16:32:18 +02:00
// Convert the 'Dynamic' object map into 'MyStruct'
let x: MyStruct = from_dynamic(&result).unwrap();
2020-12-26 08:41:41 +01:00
assert_eq!(
x,
MyStruct {
a: 42,
b: vec!["hello".into(), "world".into()],
c: true,
d: Point {
x: 123.456,
y: 999.0,
},
}
);
println!("Deserialized to struct: {x:#?}");
2020-07-04 16:32:18 +02:00
}
ser();
println!();
de();
2020-07-04 16:32:18 +02:00
}