1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
use std::mem;
use std::os::raw::c_void;
use neon_runtime;
use neon_runtime::raw;
use context::{CallbackInfo, FunctionContext};
use context::internal::Env;
use types::error::convert_panics;
use types::{JsObject, Handle, Managed};
use result::JsResult;
use object::class::Callback;
use super::Value;
pub trait ValueInternal: Managed + 'static {
fn name() -> String;
fn is_typeof<Other: Value>(env: Env, other: Other) -> bool;
fn downcast<Other: Value>(env: Env, other: Other) -> Option<Self> {
if Self::is_typeof(env, other) {
Some(Self::from_raw(other.to_raw()))
} else {
None
}
}
fn cast<'a, T: Value, F: FnOnce(raw::Local) -> T>(self, f: F) -> Handle<'a, T> {
Handle::new_internal(f(self.to_raw()))
}
}
#[repr(C)]
pub struct FunctionCallback<T: Value>(pub fn(FunctionContext) -> JsResult<T>);
#[cfg(feature = "legacy-runtime")]
impl<T: Value> Callback<()> for FunctionCallback<T> {
extern "C" fn invoke(env: Env, info: CallbackInfo<'_>) {
unsafe {
info.with_cx::<JsObject, _, _>(env, |cx| {
let data = info.data(env);
let dynamic_callback: fn(FunctionContext) -> JsResult<T> =
mem::transmute(neon_runtime::fun::get_dynamic_callback(env.to_raw(), data));
if let Ok(value) = convert_panics(env, || { dynamic_callback(cx) }) {
info.set_return(value);
}
})
}
}
fn as_ptr(self) -> *mut c_void {
unsafe { mem::transmute(self.0) }
}
}
#[cfg(feature = "napi-runtime")]
impl<T: Value> Callback<raw::Local> for FunctionCallback<T> {
extern "C" fn invoke(env: Env, info: CallbackInfo<'_>) -> raw::Local {
unsafe {
info.with_cx::<JsObject, _, _>(env, |cx| {
let data = info.data(env);
let dynamic_callback: fn(FunctionContext) -> JsResult<T> =
mem::transmute(neon_runtime::fun::get_dynamic_callback(env.to_raw(), data));
if let Ok(value) = convert_panics(env, || { dynamic_callback(cx) }) {
value.to_raw()
} else {
std::ptr::null_mut()
}
})
}
}
fn as_ptr(self) -> *mut c_void {
unsafe { mem::transmute(self.0) }
}
}