edon/napi/bindgen_runtime/js_values/
number.rs

1use super::check_status;
2use crate::napi::bindgen_prelude::ToNapiValue;
3use crate::napi::type_of;
4use crate::napi::Error;
5use crate::napi::Result;
6
7macro_rules! impl_number_conversions {
8  ( $( ($name:literal, $t:ty as $st:ty, $get:ident, $create:ident) ,)* ) => {
9    $(
10      impl $crate::napi::bindgen_prelude::TypeName for $t {
11        fn type_name() -> &'static str {
12          $name
13        }
14
15        fn value_type() -> crate::napi::ValueType {
16          crate::napi::ValueType::Number
17        }
18      }
19
20      impl $crate::napi::bindgen_prelude::ValidateNapiValue for $t { }
21
22      impl ToNapiValue for $t {
23        unsafe fn to_napi_value(env: libnode_sys::napi_env, val: $t) -> Result<libnode_sys::napi_value> {
24          let mut ptr = std::ptr::null_mut();
25          let val: $st = val.into();
26
27          check_status!(
28            unsafe { libnode_sys::$create(env, val, &mut ptr) },
29            "Failed to convert rust type `{}` into napi value",
30            $name,
31          )?;
32
33          Ok(ptr)
34        }
35      }
36
37      impl $crate::napi::bindgen_prelude::FromNapiValue for $t {
38        unsafe fn from_napi_value(env: libnode_sys::napi_env, napi_val: libnode_sys::napi_value) -> Result<Self> {
39          let mut ret = 0 as $st;
40
41          check_status!(
42            unsafe { libnode_sys::$get(env, napi_val, &mut ret) },
43            "Failed to convert napi value {:?} into rust type `{}`",
44            type_of!(env, napi_val)?,
45            $name,
46          )?;
47
48          ret.try_into().map_err(|_| Error::from_reason(concat!("Failed to convert ", stringify!($st), " to ", stringify!($t))))
49        }
50      }
51    )*
52  };
53}
54
55impl_number_conversions!(
56  ("u8", u8 as u32, napi_get_value_uint32, napi_create_uint32),
57  ("i8", i8 as i32, napi_get_value_int32, napi_create_int32),
58  ("u16", u16 as u32, napi_get_value_uint32, napi_create_uint32),
59  ("i16", i16 as i32, napi_get_value_int32, napi_create_int32),
60  ("u32", u32 as u32, napi_get_value_uint32, napi_create_uint32),
61  ("i32", i32 as i32, napi_get_value_int32, napi_create_int32),
62  ("i64", i64 as i64, napi_get_value_int64, napi_create_int64),
63  ("f64", f64 as f64, napi_get_value_double, napi_create_double),
64);
65
66impl ToNapiValue for f32 {
67  unsafe fn to_napi_value(
68    env: libnode_sys::napi_env,
69    val: f32,
70  ) -> Result<libnode_sys::napi_value> {
71    let mut ptr = std::ptr::null_mut();
72
73    check_status!(
74      unsafe { libnode_sys::napi_create_double(env, val.into(), &mut ptr) },
75      "Failed to convert rust type `f32` into napi value",
76    )?;
77
78    Ok(ptr)
79  }
80}