| 1 | use std::convert::TryFrom; |
| 2 | |
| 3 | use super::Value; |
| 4 | use crate::bindgen_runtime::{TypeName, ValidateNapiValue}; |
| 5 | use crate::{check_status, ValueType}; |
| 6 | use crate::{sys, Error, Result}; |
| 7 | |
| 8 | #[derive (Clone, Copy)] |
| 9 | pub struct JsNumber(pub(crate) Value); |
| 10 | |
| 11 | impl TypeName for JsNumber { |
| 12 | fn type_name() -> &'static str { |
| 13 | "f64" |
| 14 | } |
| 15 | |
| 16 | fn value_type() -> crate::ValueType { |
| 17 | ValueType::Number |
| 18 | } |
| 19 | } |
| 20 | |
| 21 | impl ValidateNapiValue for JsNumber {} |
| 22 | |
| 23 | impl JsNumber { |
| 24 | pub fn get_uint32(&self) -> Result<u32> { |
| 25 | let mut result = 0; |
| 26 | check_status!(unsafe { sys::napi_get_value_uint32(self.0.env, self.0.value, &mut result) })?; |
| 27 | Ok(result) |
| 28 | } |
| 29 | |
| 30 | pub fn get_int32(&self) -> Result<i32> { |
| 31 | let mut result = 0; |
| 32 | check_status!(unsafe { sys::napi_get_value_int32(self.0.env, self.0.value, &mut result) })?; |
| 33 | Ok(result) |
| 34 | } |
| 35 | |
| 36 | pub fn get_int64(&self) -> Result<i64> { |
| 37 | let mut result = 0; |
| 38 | check_status!(unsafe { sys::napi_get_value_int64(self.0.env, self.0.value, &mut result) })?; |
| 39 | Ok(result) |
| 40 | } |
| 41 | |
| 42 | pub fn get_double(&self) -> Result<f64> { |
| 43 | let mut result = 0_f64; |
| 44 | check_status!(unsafe { sys::napi_get_value_double(self.0.env, self.0.value, &mut result) })?; |
| 45 | Ok(result) |
| 46 | } |
| 47 | } |
| 48 | |
| 49 | impl TryFrom<JsNumber> for u32 { |
| 50 | type Error = Error; |
| 51 | |
| 52 | fn try_from(value: JsNumber) -> Result<u32> { |
| 53 | let mut result: u32 = 0; |
| 54 | check_status!(unsafe { sys::napi_get_value_uint32(value.0.env, value.0.value, &mut result) })?; |
| 55 | Ok(result) |
| 56 | } |
| 57 | } |
| 58 | |
| 59 | impl TryFrom<JsNumber> for i32 { |
| 60 | type Error = Error; |
| 61 | |
| 62 | fn try_from(value: JsNumber) -> Result<i32> { |
| 63 | let mut result: i32 = 0; |
| 64 | check_status!(unsafe { sys::napi_get_value_int32(value.0.env, value.0.value, &mut result) })?; |
| 65 | Ok(result) |
| 66 | } |
| 67 | } |
| 68 | |
| 69 | impl TryFrom<JsNumber> for i64 { |
| 70 | type Error = Error; |
| 71 | |
| 72 | fn try_from(value: JsNumber) -> Result<i64> { |
| 73 | let mut result: i64 = 0; |
| 74 | check_status!(unsafe { sys::napi_get_value_int64(value.0.env, value.0.value, &mut result) })?; |
| 75 | Ok(result) |
| 76 | } |
| 77 | } |
| 78 | |
| 79 | impl TryFrom<JsNumber> for f64 { |
| 80 | type Error = Error; |
| 81 | |
| 82 | fn try_from(value: JsNumber) -> Result<f64> { |
| 83 | let mut result: f64 = 0_f64; |
| 84 | check_status!(unsafe { sys::napi_get_value_double(value.0.env, value.0.value, &mut result) })?; |
| 85 | Ok(result) |
| 86 | } |
| 87 | } |
| 88 | |