2021-01-10 21:59:07 -05:00
|
|
|
// Copyright 2018-2021 the Deno authors. All rights reserved. MIT license.
|
2020-09-23 10:56:36 -04:00
|
|
|
//! This example shows you how to define ops in Rust and then call them from
|
|
|
|
//! JavaScript.
|
|
|
|
|
2021-04-12 15:55:05 -04:00
|
|
|
use deno_core::op_sync;
|
2020-09-23 10:56:36 -04:00
|
|
|
use deno_core::JsRuntime;
|
|
|
|
|
|
|
|
fn main() {
|
|
|
|
// Initialize a runtime instance
|
|
|
|
let mut runtime = JsRuntime::new(Default::default());
|
|
|
|
|
2021-05-15 09:24:01 -04:00
|
|
|
// Register an op for summing a number array.
|
2020-09-23 10:56:36 -04:00
|
|
|
runtime.register_op(
|
|
|
|
"op_sum",
|
2021-05-15 09:24:01 -04:00
|
|
|
// The op-layer automatically deserializes inputs
|
|
|
|
// and serializes the returned Result & value
|
2021-05-06 13:32:03 -04:00
|
|
|
op_sync(|_state, nums: Vec<f64>, _: ()| {
|
2021-03-31 10:37:38 -04:00
|
|
|
// Sum inputs
|
|
|
|
let sum = nums.iter().fold(0.0, |a, v| a + v);
|
|
|
|
// return as a Result<f64, AnyError>
|
|
|
|
Ok(sum)
|
2020-09-23 10:56:36 -04:00
|
|
|
}),
|
|
|
|
);
|
2021-04-25 16:00:05 -04:00
|
|
|
runtime.sync_ops_cache();
|
2020-09-23 10:56:36 -04:00
|
|
|
|
2021-05-15 09:24:01 -04:00
|
|
|
// Now we see how to invoke the op we just defined. The runtime automatically
|
2020-09-23 10:56:36 -04:00
|
|
|
// contains a Deno.core object with several functions for interacting with it.
|
|
|
|
// You can find its definition in core.js.
|
2021-03-31 10:37:38 -04:00
|
|
|
runtime
|
2021-06-21 19:45:41 -04:00
|
|
|
.execute_script(
|
2021-05-15 09:24:01 -04:00
|
|
|
"<usage>",
|
2021-03-31 10:37:38 -04:00
|
|
|
r#"
|
2021-05-15 09:24:01 -04:00
|
|
|
// Print helper function, calling Deno.core.print()
|
2020-09-23 10:56:36 -04:00
|
|
|
function print(value) {
|
2021-05-15 09:24:01 -04:00
|
|
|
Deno.core.print(value.toString()+"\n");
|
2020-09-23 10:56:36 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
const arr = [1, 2, 3];
|
|
|
|
print("The sum of");
|
|
|
|
print(arr);
|
|
|
|
print("is");
|
2021-04-12 15:55:05 -04:00
|
|
|
print(Deno.core.opSync('op_sum', arr));
|
2020-09-23 10:56:36 -04:00
|
|
|
|
|
|
|
// And incorrect usage
|
|
|
|
try {
|
2021-04-12 15:55:05 -04:00
|
|
|
print(Deno.core.opSync('op_sum', 0));
|
2020-09-23 10:56:36 -04:00
|
|
|
} catch(e) {
|
|
|
|
print('Exception:');
|
|
|
|
print(e);
|
|
|
|
}
|
|
|
|
"#,
|
|
|
|
)
|
|
|
|
.unwrap();
|
|
|
|
}
|