2022-02-12 05:41:04 +01:00
|
|
|
//! An example to serialize and deserialize Rust types.
|
|
|
|
|
2022-07-26 11:05:42 +02:00
|
|
|
#[cfg(feature = "no_object")]
|
2022-01-16 15:50:39 +01:00
|
|
|
fn main() {
|
2022-07-26 11:05:42 +02:00
|
|
|
panic!("This example does not run under 'no_object'.")
|
2022-01-16 15:50:39 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
#[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,
|
|
|
|
},
|
|
|
|
};
|
|
|
|
|
2022-10-27 07:38:21 +02:00
|
|
|
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>());
|
2022-10-27 07:38:21 +02:00
|
|
|
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#"
|
2022-07-26 11:05:42 +02:00
|
|
|
#{
|
|
|
|
a: 42,
|
|
|
|
b: [ "hello", "world" ],
|
|
|
|
c: true,
|
|
|
|
d: #{ x: 123.456, y: 999.0 }
|
|
|
|
}
|
|
|
|
"#,
|
2020-07-04 16:32:18 +02:00
|
|
|
)
|
|
|
|
.unwrap();
|
|
|
|
|
2022-10-27 07:38:21 +02:00
|
|
|
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,
|
|
|
|
},
|
|
|
|
}
|
|
|
|
);
|
2022-10-27 07:38:21 +02:00
|
|
|
println!("Deserialized to struct: {x:#?}");
|
2020-07-04 16:32:18 +02:00
|
|
|
}
|
2022-07-26 11:05:42 +02:00
|
|
|
|
|
|
|
ser();
|
|
|
|
println!();
|
|
|
|
de();
|
2020-07-04 16:32:18 +02:00
|
|
|
}
|