rhai/examples/serde.rs

91 lines
2.2 KiB
Rust
Raw Normal View History

2021-10-23 12:16:51 +02:00
#[cfg(any(not(feature = "serde"), feature = "no_object"))]
2020-07-04 16:32:18 +02:00
fn main() {
2021-02-20 16:46:25 +01:00
println!("This example requires the 'serde' feature to run.");
2020-07-04 16:52:45 +02:00
println!("Try: cargo run --features serde --example serde");
2020-07-04 16:32:18 +02:00
}
#[cfg(feature = "serde")]
2021-10-23 12:16:51 +02:00
#[cfg(not(feature = "no_object"))]
2020-07-04 16:32:18 +02:00
fn main() {
example::ser();
println!();
example::de();
}
#[cfg(feature = "serde")]
2021-10-23 12:16:51 +02:00
#[cfg(not(feature = "no_object"))]
2020-07-04 16:32:18 +02:00
mod example {
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);
// Convert the 'MyStruct' into a 'Dynamic'
let map: Dynamic = to_dynamic(x).unwrap();
assert!(map.is::<Map>());
println!("Serialized to Dynamic: {:#?}", map);
}
pub fn de() {
let engine = Engine::new();
let result: Dynamic = engine
.eval(
r#"
2020-10-07 09:51:00 +02:00
#{
2020-07-04 16:32:18 +02:00
a: 42,
b: [ "hello", "world" ],
c: true,
d: #{ x: 123.456, y: 999.0 }
}
"#,
)
.unwrap();
println!("Source Dynamic: {:#?}", result);
// 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,
},
}
);
2020-07-04 16:32:18 +02:00
println!("Deserialized to struct: {:#?}", x);
}
}