2018-04-28 17:26:38 +09:00
|
|
|
#[macro_use]
|
|
|
|
extern crate napi_rs as napi;
|
|
|
|
|
2020-04-17 12:54:17 +09:00
|
|
|
extern crate futures;
|
|
|
|
|
2020-04-21 01:20:35 +09:00
|
|
|
use napi::{Any, Env, Error, Object, Result, Status, Value, CallContext};
|
|
|
|
use napi_derive::js_function;
|
2018-04-28 17:26:38 +09:00
|
|
|
|
|
|
|
register_module!(test_module, init);
|
|
|
|
|
|
|
|
fn init<'env>(
|
|
|
|
env: &'env Env,
|
|
|
|
exports: &'env mut Value<'env, Object>,
|
|
|
|
) -> Result<Option<Value<'env, Object>>> {
|
|
|
|
exports.set_named_property(
|
|
|
|
"testSpawn",
|
2020-04-21 01:20:35 +09:00
|
|
|
env.create_function("testSpawn", test_spawn)?,
|
2018-04-28 17:26:38 +09:00
|
|
|
)?;
|
|
|
|
exports.set_named_property(
|
|
|
|
"testThrow",
|
2020-04-21 01:20:35 +09:00
|
|
|
env.create_function("testThrow", test_throw)?,
|
2018-04-28 17:26:38 +09:00
|
|
|
)?;
|
|
|
|
Ok(None)
|
|
|
|
}
|
|
|
|
|
2020-04-21 01:20:35 +09:00
|
|
|
#[js_function]
|
2018-04-28 17:26:38 +09:00
|
|
|
fn test_spawn<'a>(
|
2020-04-21 01:20:35 +09:00
|
|
|
ctx: CallContext<'a>
|
|
|
|
) -> Result<Value<'a, Object>> {
|
2020-02-18 22:09:17 +09:00
|
|
|
use futures::executor::ThreadPool;
|
|
|
|
use futures::StreamExt;
|
2020-04-21 01:20:35 +09:00
|
|
|
let env = ctx.env;
|
2020-04-03 01:09:44 +09:00
|
|
|
let async_context = env.async_init(None, "test_spawn")?;
|
2020-02-18 22:09:17 +09:00
|
|
|
let pool = ThreadPool::new().expect("Failed to build pool");
|
2020-04-03 01:09:44 +09:00
|
|
|
let (promise, deferred) = env.create_promise()?;
|
2020-02-18 22:09:17 +09:00
|
|
|
let (tx, rx) = futures::channel::mpsc::unbounded::<i32>();
|
|
|
|
let fut_values = async move {
|
|
|
|
let fut_tx_result = async move {
|
|
|
|
(0..100).for_each(|v| {
|
|
|
|
tx.unbounded_send(v).expect("Failed to send");
|
|
|
|
})
|
|
|
|
};
|
|
|
|
pool.spawn_ok(fut_tx_result);
|
|
|
|
let fut_values = rx.map(|v| v * 2).collect::<Vec<i32>>();
|
|
|
|
let results = fut_values.await;
|
2020-02-19 00:05:13 +09:00
|
|
|
if !cfg!(windows) {
|
|
|
|
println!("Collected result lenght {}", results.len());
|
|
|
|
};
|
2018-04-28 17:26:38 +09:00
|
|
|
async_context.enter(|env| {
|
2020-04-03 01:09:44 +09:00
|
|
|
env
|
|
|
|
.resolve_deferred(deferred, env.get_undefined().unwrap())
|
|
|
|
.unwrap();
|
2018-04-28 17:26:38 +09:00
|
|
|
});
|
2020-02-18 22:09:17 +09:00
|
|
|
};
|
2018-04-28 17:26:38 +09:00
|
|
|
|
2020-02-18 22:09:17 +09:00
|
|
|
env.create_executor().execute(fut_values);
|
2018-04-28 17:26:38 +09:00
|
|
|
|
2020-04-21 01:20:35 +09:00
|
|
|
Ok(promise)
|
2018-04-28 17:26:38 +09:00
|
|
|
}
|
|
|
|
|
2020-04-21 01:20:35 +09:00
|
|
|
#[js_function]
|
2018-04-28 17:26:38 +09:00
|
|
|
fn test_throw<'a>(
|
2020-04-21 01:20:35 +09:00
|
|
|
_ctx: CallContext<'a>,
|
|
|
|
) -> Result<Value<'a, Any>> {
|
2018-04-28 17:26:38 +09:00
|
|
|
Err(Error::new(Status::GenericFailure))
|
|
|
|
}
|