From b08f85a8b1741937271b5b9dc00ad1c98031773e Mon Sep 17 00:00:00 2001 From: Stephen Chung Date: Mon, 22 Jun 2020 09:46:36 +0800 Subject: [PATCH] Refine side_effects test. --- tests/side_effects.rs | 48 ++++++++++++++----------------------------- 1 file changed, 15 insertions(+), 33 deletions(-) diff --git a/tests/side_effects.rs b/tests/side_effects.rs index a5725b08..bee1cb2f 100644 --- a/tests/side_effects.rs +++ b/tests/side_effects.rs @@ -1,9 +1,10 @@ ///! This test simulates an external command object that is driven by a script. use rhai::{Engine, EvalAltResult, RegisterFn, Scope, INT}; -use std::sync::{Arc, Mutex}; +use std::sync::{Arc, Mutex, RwLock}; -/// External command. +/// Simulate a command object. struct Command { + /// Simulate an external state. state: i64, } @@ -18,25 +19,7 @@ impl Command { } } -/// Wrapper object to wrap a command object. -#[derive(Clone)] -struct CommandWrapper { - command: Arc>, -} - -impl CommandWrapper { - /// Delegate command action. - pub fn do_action(&mut self, x: i64) { - let mut command = self.command.lock().unwrap(); - let val = command.get(); - command.action(val + x); - } - /// Delegate get value action. - pub fn get_value(&mut self) -> i64 { - let command = self.command.lock().unwrap(); - command.get() - } -} +type API = Arc>; #[cfg(not(feature = "no_object"))] #[test] @@ -48,18 +31,20 @@ fn test_side_effects_command() -> Result<(), Box> { let command = Arc::new(Mutex::new(Command { state: 12 })); assert_eq!(command.lock().unwrap().get(), 12); - // Create the wrapper. - let wrapper = CommandWrapper { - command: command.clone(), // Notice this clones the `Arc` only - }; + // Create the API object. + let api = command.clone(); // Notice this clones the `Arc` only - // Make the wrapper a singleton in the script environment. - scope.push_constant("Command", wrapper); + // Make the API object a singleton in the script environment. + scope.push_constant("Command", api); // Register type. - engine.register_type_with_name::("CommandType"); - engine.register_fn("action", CommandWrapper::do_action); - engine.register_get("value", CommandWrapper::get_value); + engine.register_type_with_name::("CommandType"); + engine.register_fn("action", |api: &mut API, x: i64| { + let mut command = api.lock().unwrap(); + let val = command.get(); + command.action(val + x); + }); + engine.register_get("value", |command: &mut API| command.lock().unwrap().get()); assert_eq!( engine.eval_with_scope::( @@ -81,9 +66,6 @@ fn test_side_effects_command() -> Result<(), Box> { #[test] fn test_side_effects_print() -> Result<(), Box> { - use std::sync::Arc; - use std::sync::RwLock; - let result = Arc::new(RwLock::new(String::from(""))); let mut engine = Engine::new();