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