From b6937fd21d9142381466bdd48bfd7712a1567afd Mon Sep 17 00:00:00 2001 From: Tristan Guichaoua Date: Mon, 8 Aug 2022 14:43:06 +0200 Subject: [PATCH] add RhaiCustomType trait and build_type method --- src/api/build_type.rs | 67 +++++++++++++++++++++++++++++++++++++++++++ src/api/mod.rs | 2 ++ src/lib.rs | 2 +- 3 files changed, 70 insertions(+), 1 deletion(-) create mode 100644 src/api/build_type.rs diff --git a/src/api/build_type.rs b/src/api/build_type.rs new file mode 100644 index 00000000..785034e1 --- /dev/null +++ b/src/api/build_type.rs @@ -0,0 +1,67 @@ +use crate::Engine; + +/// Trait to build a custom type for use with the [`Engine`]. +/// i.e. register the type, getters, setters, methods, etc... +/// +/// # Example +/// +/// ``` +/// use rhai::{Engine, RhaiCustomType}; +/// +/// #[derive(Debug, Clone, Eq, PartialEq)] +/// struct TestStruct { +/// field: i64 +/// } +/// +/// impl TestStruct { +/// fn new() -> Self { +/// Self { field: 1 } +/// } +/// fn update(&mut self, offset: i64) { +/// self.field += offset; +/// } +/// } +/// +/// impl RhaiCustomType for TestStruct { +/// fn build(engine: &mut Engine) { +/// engine +/// .register_type::() +/// .register_fn("new_ts", Self::new) +/// .register_fn("update", Self::update); +/// } +/// } +/// +/// # fn main() -> Result<(), Box> { +/// +/// let mut engine = Engine::new(); +/// +/// // Register API for the custom type. +/// engine.build_type::(); +/// +/// # #[cfg(not(feature = "no_object"))] +/// assert_eq!( +/// engine.eval::("let x = new_ts(); x.update(41); x")?, +/// TestStruct { field: 42 } +/// ); +/// # Ok(()) +/// # } +/// ``` +pub trait RhaiCustomType { + /// Builds the custom type for use with the [`Engine`]. + /// i.e. register the type, getters, setters, methods, etc... + fn build(engine: &mut Engine); +} + +impl Engine { + /// Build a custom type for use with the [`Engine`]. + /// i.e. register the type, getters, setters, methods, etc... + /// + /// See [`RhaiCustomType`]. + pub fn build_type(&mut self) -> &mut Self + where + T: RhaiCustomType, + { + T::build(self); + self + } +} diff --git a/src/api/mod.rs b/src/api/mod.rs index f24777c6..635082dd 100644 --- a/src/api/mod.rs +++ b/src/api/mod.rs @@ -28,6 +28,8 @@ pub mod custom_syntax; pub mod deprecated; +pub mod build_type; + #[cfg(feature = "metadata")] pub mod definitions; diff --git a/src/lib.rs b/src/lib.rs index 9ad7317f..0a19d5fc 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -166,7 +166,7 @@ type ExclusiveRange = std::ops::Range; /// An inclusive integer range. type InclusiveRange = std::ops::RangeInclusive; -pub use api::events::VarDefInfo; +pub use api::{build_type::RhaiCustomType, events::VarDefInfo}; pub use ast::{FnAccess, AST}; pub use engine::{Engine, OP_CONTAINS, OP_EQUALS}; pub use eval::EvalContext;