Refine side_effects test.
///! 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<Mutex<Command>>,
-}
-
-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<Mutex<Command>>;
#[cfg(not(feature = "no_object"))]
#[test]
@@ -48,18 +31,20 @@ fn test_side_effects_command() -> Result<(), Box<EvalAltResult>> {
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::<CommandWrapper>("CommandType");
- engine.register_fn("action", CommandWrapper::do_action);
- engine.register_get("value", CommandWrapper::get_value);
+ engine.register_type_with_name::<API>("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::<INT>(
@@ -81,9 +66,6 @@ fn test_side_effects_command() -> Result<(), Box<EvalAltResult>> {
#[test]
fn test_side_effects_print() -> Result<(), Box<EvalAltResult>> {
- use std::sync::Arc;
- use std::sync::RwLock;
-
let result = Arc::new(RwLock::new(String::from("")));
let mut engine = Engine::new();
