From ce8fbe40c4edccc705cca9edbffff1d8599e98fb Mon Sep 17 00:00:00 2001 From: J Henry Waugh Date: Sun, 9 Aug 2020 12:13:02 -0500 Subject: [PATCH] Fold into fully generic form --- tests/macro_unroll.rs | 52 +++++++++++++++++++++++++++++-------------- 1 file changed, 35 insertions(+), 17 deletions(-) diff --git a/tests/macro_unroll.rs b/tests/macro_unroll.rs index f24e2d3b..fd0920ed 100644 --- a/tests/macro_unroll.rs +++ b/tests/macro_unroll.rs @@ -3,41 +3,54 @@ use rhai::plugin::*; use rhai::{Engine, EvalAltResult, INT, Module}; -macro_rules! generate_adds { - ($($type_names:ident),+) => { - $( - pub mod $type_names { - use rhai::plugin::*; - #[export_fn] - pub fn add(x: $type_names, y: $type_names) -> $type_names { - x + y - } +pub fn add_generic>(x: T, y: T) -> T { + x + y +} + +pub fn mul_generic>(x: T, y: T) -> T { + x * y +} + +macro_rules! generate_ops { + ($op_name:ident, $op_fn:ident, $($type_names:ident),+) => { + pub mod $op_name { + $( + pub mod $type_names { + use rhai::plugin::*; + use super::super::$op_fn; + #[export_fn] + pub fn op(x: $type_names, y: $type_names) -> $type_names { + $op_fn(x, y) + } + } + )* } - )* } } -macro_rules! register_adds_in_bulk { - ($mod_name:ident, $($type_names:ident),+) => { +macro_rules! register_in_bulk { + ($mod_name:ident, $op_name:ident, $($type_names:ident),+) => { $( { let type_str = stringify!($type_names); register_exported_fn!($mod_name, - format!("add_{}", type_str), - crate::$type_names::add); + format!(concat!(stringify!($op_name), "_{}"), type_str), + crate::$op_name::$type_names::op); } )* } } -generate_adds!(i8, i16, i32, i64); +generate_ops!(add, add_generic, i8, i16, i32, i64); +generate_ops!(mul, mul_generic, i8, i16, i32, i64); #[test] -fn test_generated_adds() -> Result<(), Box> { +fn test_generated_ops() -> Result<(), Box> { let mut engine = Engine::new(); let mut m = Module::new(); - register_adds_in_bulk!(m, i8, i16, i32, i64); + register_in_bulk!(m, add, i8, i16, i32, i64); + register_in_bulk!(m, mul, i8, i16, i32, i64); engine.load_package(m); @@ -46,5 +59,10 @@ fn test_generated_adds() -> Result<(), Box> { #[cfg(not(feature = "only_i32"))] assert_eq!(engine.eval::("let a = 0; add_i64(a, 1)")?, 1); + #[cfg(feature = "only_i32")] + assert_eq!(engine.eval::("let a = 1; mul_i32(a, 2)")?, 2); + #[cfg(not(feature = "only_i32"))] + assert_eq!(engine.eval::("let a = 1; mul_i64(a, 2)")?, 2); + Ok(()) }