hello.neon.js/native/src/lib.rs

65 lines
1.7 KiB
Rust

#[macro_use]
extern crate neon;
extern crate num_cpus;
extern crate rand;
use neon::prelude::*;
fn hello(mut cx: FunctionContext) -> JsResult<JsString> {
Ok(cx.string("hello node"))
}
fn thread_count(mut cx: FunctionContext) -> JsResult<JsNumber> {
Ok(cx.number(num_cpus::get() as f64))
}
fn noop(mut cx: FunctionContext) -> JsResult<JsUndefined> {
Ok(cx.undefined())
}
fn throw_panic(mut _cx: FunctionContext) -> JsResult<JsError> {
panic!("this is just a test");
//Ok(cx.error("this is just a test"));
}
fn throw_err(mut cx: FunctionContext) -> JsResult<JsError> {
cx.error("this is just a test")
}
fn greet(mut cx: FunctionContext) -> JsResult<JsString> {
//cx.check_argument::<JsString>(0)?;
let str = cx.argument::<JsString>(0)?.value();
Ok(cx.string(str))
}
fn any(mut cx: FunctionContext) -> JsResult<JsValue> {
use rand::prelude::*;
//let mut rng = rand::thread_rng();
//let i = rng.gen::<u32>() % 5;
let mut rng = rand::rngs::OsRng::new().unwrap();
let i = rng.next_u32() % 5;
let val: Handle<JsValue> = match i {
0 => cx.string("foobar").upcast(),
1 => cx.number(42).upcast(),
2 => cx.boolean(true).upcast(),
3 => cx.empty_array().upcast(),
4 => cx.null().upcast(),
_ => cx.undefined().upcast(),
};
//cx.check_argument::<JsString>(0)?;
//let str = cx.argument::<JsString>(0)?.value();
Ok(val)
}
register_module!(mut cx, {
cx.export_function("hello", hello)?;
cx.export_function("threadCount", thread_count)?;
cx.export_function("throw", throw_err)?;
cx.export_function("panic", throw_panic)?;
cx.export_function("greet", greet)?;
cx.export_function("noop", noop)?;
cx.export_function("any", any)?;
Ok(())
});