Skip to content

Commit

Permalink
feat: impl Date API (closes #70)
Browse files Browse the repository at this point in the history
  • Loading branch information
amilajack committed Nov 21, 2020
1 parent 6a3848b commit 0999e56
Show file tree
Hide file tree
Showing 3 changed files with 71 additions and 0 deletions.
14 changes: 14 additions & 0 deletions crates/neon-runtime/src/napi/date.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
use nodejs_sys as napi;
use raw::{Env, Local};

pub unsafe extern "C" fn new_date(env: Env, out: *mut Local, num: f64) {
let status = napi::napi_create_date(env, num, out);
assert_eq!(status, napi::napi_status::napi_ok);
}

pub unsafe extern "C" fn value(env: Env, p: Local) -> f64 {
let mut value = 0.0;
let status = napi::napi_get_date_value(env, p, &mut value as *mut f64);
assert_eq!(status, napi::napi_status::napi_ok);
return value;
}
1 change: 1 addition & 0 deletions crates/neon-runtime/src/napi/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,3 +16,4 @@ pub mod string;
pub mod tag;
pub mod task;
pub mod handler;
pub mod date;
56 changes: 56 additions & 0 deletions src/types/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -424,6 +424,62 @@ impl ValueInternal for JsNumber {
}
}

/// A JavaScript Date object.
#[repr(C)]
#[derive(Clone, Copy)]
pub struct JsDate(raw::Local);

impl Value for JsDate { }

impl Managed for JsDate {
fn to_raw(self) -> raw::Local { self.0 }

fn from_raw(_: Env, h: raw::Local) -> Self { JsDate(h) }
}

impl JsDate {
pub const MIN_VALID_VALUE: f64 = -8640000000000000.0;
pub const MAX_VALID_VALUE: f64 = 8640000000000000.0;

#[cfg(feature = "napi-runtime")]
pub(crate) fn new_internal<'a>(env: Env, value: f64) -> Handle<'a, JsDate> {
unsafe {
let mut local: raw::Local = std::mem::zeroed();
neon_runtime::date::new_date( env.to_raw(), &mut local, value);
Handle::new_internal(JsDate(local))
}
}

#[cfg(feature = "napi-runtime")]
pub fn new<'a, C: Context<'a>, T: Into<f64>>(cx: &mut C, x: T) -> Handle<'a, JsDate> {
JsDate::new_internal(cx.env(), x.into())
}

#[cfg(feature = "napi-runtime")]
pub fn value<'a, C: Context<'a>>(self, cx: &mut C) -> f64 {
let env = cx.env().to_raw();
unsafe {
neon_runtime::date::value(env, self.to_raw())
}
}

#[cfg(feature = "napi-runtime")]
pub fn is_valid<'a, C: Context<'a>>(self, cx: &mut C) -> bool {
let value = self.value(cx);
return value < JsDate::MAX_VALID_VALUE && value > JsDate::MIN_VALID_VALUE;
}
}

impl ValueInternal for JsDate {
fn name() -> String { "object".to_string() }

fn is_typeof<Other: Value>(env: Env, other: Other) -> bool {
unsafe { neon_runtime::tag::is_object(env.to_raw(), other.to_raw()) }
}
}

impl Object for JsDate { }

/// A JavaScript object.
#[repr(C)]
#[derive(Clone, Copy)]
Expand Down

0 comments on commit 0999e56

Please sign in to comment.