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
use std::marker::{Send, Sized};
use std::mem;
use std::os::raw::c_void;
use types::{Value, JsFunction};
use result::JsResult;
use handle::{Handle, Managed};
use context::TaskContext;
use neon_runtime;
use neon_runtime::raw;
pub trait Task: Send + Sized + 'static {
type Output: Send + 'static;
type Error: Send + 'static;
type JsEvent: Value;
fn perform(&self) -> Result<Self::Output, Self::Error>;
fn complete<'a>(self, cx: TaskContext<'a>, result: Result<Self::Output, Self::Error>) -> JsResult<Self::JsEvent>;
fn schedule(self, callback: Handle<JsFunction>) {
let boxed_self = Box::new(self);
let self_raw = Box::into_raw(boxed_self);
let callback_raw = callback.to_raw();
unsafe {
neon_runtime::task::schedule(mem::transmute(self_raw),
perform_task::<Self>,
complete_task::<Self>,
callback_raw);
}
}
}
unsafe extern "C" fn perform_task<T: Task>(task: *mut c_void) -> *mut c_void {
let task: Box<T> = Box::from_raw(mem::transmute(task));
let result = task.perform();
Box::into_raw(task);
mem::transmute(Box::into_raw(Box::new(result)))
}
unsafe extern "C" fn complete_task<T: Task>(task: *mut c_void, result: *mut c_void, out: &mut raw::Local) {
let result: Result<T::Output, T::Error> = *Box::from_raw(mem::transmute(result));
let task: Box<T> = Box::from_raw(mem::transmute(task));
TaskContext::with(|cx| {
if let Ok(result) = task.complete(cx, result) {
*out = result.to_raw();
}
})
}