1use crate::*;
2use mech_core::*;
3use libm::{tanh, tanhf};
4use num_traits::*;
5#[cfg(feature = "matrix")]
6use mech_core::matrix::Matrix;
7
8macro_rules! tanh_op {
10 ($arg:expr, $out:expr) => {
11 unsafe { (*$out) = tanh((*$arg)); }
12 };
13}
14
15macro_rules! tanh_vec_op {
16 ($arg:expr, $out:expr) => {
17 unsafe {
18 for i in 0..(*$arg).len() {
19 ((&mut (*$out))[i]) = tanh(((&(*$arg))[i]));
20 }
21 }
22 };
23}
24
25macro_rules! tanhf_op {
26 ($arg:expr, $out:expr) => {
27 unsafe { (*$out) = tanhf((*$arg)); }
28 };
29}
30
31macro_rules! tanhf_vec_op {
32 ($arg:expr, $out:expr) => {
33 unsafe {
34 for i in 0..(*$arg).len() {
35 ((&mut (*$out))[i]) = tanhf(((&(*$arg))[i]));
36 }
37 }
38 };
39}
40
41#[cfg(feature = "f32")]
42impl_math_unop!(MathTanh, f32, tanhf, FeatureFlag::Custom(hash_str("math/tanh")));
43#[cfg(feature = "f64")]
44impl_math_unop!(MathTanh, f64, tanh, FeatureFlag::Custom(hash_str("math/tanh")));
45
46fn impl_tanh_fxn(lhs_value: Value) -> MResult<Box<dyn MechFunction>> {
47 impl_urnop_match_arms2!(
48 MathTanh,
49 (lhs_value),
50 F32 => MatrixF32, F32, f32::zero(), "f32";
51 F64 => MatrixF64, F64, f64::zero(), "f64";
52 )
53}
54
55pub struct MathTanh {}
56
57impl NativeFunctionCompiler for MathTanh {
58 fn compile(&self, arguments: &Vec<Value>) -> MResult<Box<dyn MechFunction>> {
59 if arguments.len() != 1 {
60 return Err(MechError2::new(IncorrectNumberOfArguments { expected: 1, found: arguments.len() },None).with_compiler_loc());
61 }
62 let input = arguments[0].clone();
63 match impl_tanh_fxn(input.clone()) {
64 Ok(fxn) => Ok(fxn),
65 Err(_) => match input {
66 Value::MutableReference(input) => impl_tanh_fxn(input.borrow().clone()),
67 _ => Err(MechError2::new(
68 UnhandledFunctionArgumentKind1 { arg: input.kind(), fxn_name: "math/tanh".to_string() },
69 None
70 ).with_compiler_loc()
71 ),
72 },
73 }
74 }
75}
76
77register_descriptor! {
78 FunctionCompilerDescriptor {
79 name: "math/tanh",
80 ptr: &MathTanh{},
81 }
82}