summaryrefslogtreecommitdiff
path: root/core/examples/hello_world.rs
diff options
context:
space:
mode:
authorAaron O'Mullan <aaron.omullan@gmail.com>2021-03-31 16:37:38 +0200
committerGitHub <noreply@github.com>2021-03-31 10:37:38 -0400
commitfec1b2a5a4324a7eecdfbb2471931f3b6b0139c5 (patch)
tree8a650553c2d70e047d9d7365f9ac8702ec9861a5 /core/examples/hello_world.rs
parent6dc3549a818ad49b3907d18c93fd422a9cc743a5 (diff)
refactor: new optimized op-layer using serde_v8 (#9843)
- Improves op performance. - Handle op-metadata (errors, promise IDs) explicitly in the op-layer vs per op-encoding (aka: out-of-payload). - Remove shared queue & custom "asyncHandlers", all async values are returned in batches via js_recv_cb. - The op-layer should be thought of as simple function calls with little indirection or translation besides the conceptually straightforward serde_v8 bijections. - Preserve concepts of json/bin/min as semantic groups of their inputs/outputs instead of their op-encoding strategy, preserving these groups will also facilitate partial transitions over to v8 Fast API for the "min" and "bin" groups
Diffstat (limited to 'core/examples/hello_world.rs')
-rw-r--r--core/examples/hello_world.rs53
1 files changed, 24 insertions, 29 deletions
diff --git a/core/examples/hello_world.rs b/core/examples/hello_world.rs
index c46fc1d98..3b63d2bda 100644
--- a/core/examples/hello_world.rs
+++ b/core/examples/hello_world.rs
@@ -2,11 +2,8 @@
//! This example shows you how to define ops in Rust and then call them from
//! JavaScript.
-use anyhow::anyhow;
use deno_core::json_op_sync;
use deno_core::JsRuntime;
-use deno_core::Op;
-use serde_json::Value;
use std::io::Write;
fn main() {
@@ -21,55 +18,52 @@ fn main() {
//
// The second one just transforms some input and returns it to JavaScript.
- // Register the op for outputting bytes to stdout.
+ // Register the op for outputting a string to stdout.
// It can be invoked with Deno.core.dispatch and the id this method returns
// or Deno.core.dispatchByName and the name provided.
runtime.register_op(
"op_print",
- // The op_fn callback takes a state object OpState
- // and a vector of ZeroCopyBuf's, which are mutable references
- // to ArrayBuffer's in JavaScript.
- |_state, zero_copy| {
+ // The op_fn callback takes a state object OpState,
+ // a structured arg of type `T` and an optional ZeroCopyBuf,
+ // a mutable reference to a JavaScript ArrayBuffer
+ json_op_sync(|_state, msg: Option<String>, zero_copy| {
let mut out = std::io::stdout();
+ // Write msg to stdout
+ if let Some(msg) = msg {
+ out.write_all(msg.as_bytes()).unwrap();
+ }
+
// Write the contents of every buffer to stdout
for buf in zero_copy {
out.write_all(&buf).unwrap();
}
- Op::Sync(Box::new([])) // No meaningful result
- },
+ Ok(()) // No meaningful result
+ }),
);
// Register the JSON op for summing a number array.
- // A JSON op is just an op where the first ZeroCopyBuf is a serialized JSON
- // value, the return value is also a serialized JSON value. It can be invoked
- // with Deno.core.jsonOpSync and the name.
runtime.register_op(
"op_sum",
// The json_op_sync function automatically deserializes
// the first ZeroCopyBuf and serializes the return value
// to reduce boilerplate
- json_op_sync(|_state, json: Vec<f64>, zero_copy| {
- // We check that we only got the JSON value.
- if !zero_copy.is_empty() {
- Err(anyhow!("Expected exactly one argument"))
- } else {
- // And if we did, do our actual task
- let sum = json.iter().fold(0.0, |a, v| a + v);
-
- // Finally we return a JSON value
- Ok(Value::from(sum))
- }
+ json_op_sync(|_state, nums: Vec<f64>, _| {
+ // Sum inputs
+ let sum = nums.iter().fold(0.0, |a, v| a + v);
+ // return as a Result<f64, AnyError>
+ Ok(sum)
}),
);
// Now we see how to invoke the ops we just defined. The runtime automatically
// contains a Deno.core object with several functions for interacting with it.
// You can find its definition in core.js.
- runtime.execute(
- "<init>",
- r#"
+ runtime
+ .execute(
+ "<init>",
+ r#"
// First we initialize the ops cache.
// This maps op names to their id's.
Deno.core.ops();
@@ -78,14 +72,15 @@ Deno.core.ops();
// our op_print op to display the stringified argument.
const _newline = new Uint8Array([10]);
function print(value) {
- Deno.core.dispatchByName('op_print', Deno.core.encode(value.toString()), _newline);
+ Deno.core.dispatchByName('op_print', 0, value.toString(), _newline);
}
// Finally we register the error class used by op_sum
// so that it throws the correct class.
Deno.core.registerErrorClass('Error', Error);
"#,
- ).unwrap();
+ )
+ .unwrap();
// Now we can finally use this in an example.
runtime