mech_math/rounding/
trunc.rs

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