Skip to content

Commit

Permalink
feature: demo rhai
Browse files Browse the repository at this point in the history
  • Loading branch information
tyrchen committed May 24, 2024
1 parent 28af9e0 commit c314e0d
Show file tree
Hide file tree
Showing 3 changed files with 246 additions and 0 deletions.
168 changes: 168 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -22,4 +22,6 @@ chrono = { version = "0.4.38", features = ["serde"] }
pest = { version = "2.7.10", features = ["pretty-print"] }
pest_derive = "2.7.10"
regex = "1.10.4"
rhai = { version = "1.18.0", features = ["serde"] }
serde = { version = "1.0.202", features = ["derive"] }
winnow = { version = "0.6.8", features = ["simd"] }
76 changes: 76 additions & 0 deletions examples/rhai.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
use rhai::serde::{from_dynamic, to_dynamic};
use rhai::{Dynamic, Engine, Map};
use serde::{Deserialize, Serialize};

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
struct Point {
x: f64,
y: f64,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
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#"
#{
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();

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:#?}");
}
fn main() {
ser();
println!();
de();
}

0 comments on commit c314e0d

Please sign in to comment.