summaryrefslogtreecommitdiff
path: root/core/examples
diff options
context:
space:
mode:
Diffstat (limited to 'core/examples')
-rw-r--r--core/examples/hello_world.rs53
-rw-r--r--core/examples/http_bench_bin_ops.js11
-rw-r--r--core/examples/http_bench_json_ops.js20
-rw-r--r--core/examples/http_bench_json_ops.rs45
4 files changed, 59 insertions, 70 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
diff --git a/core/examples/http_bench_bin_ops.js b/core/examples/http_bench_bin_ops.js
index 18f98419f..cf5e275b1 100644
--- a/core/examples/http_bench_bin_ops.js
+++ b/core/examples/http_bench_bin_ops.js
@@ -9,14 +9,19 @@ const responseBuf = new Uint8Array(
.map((c) => c.charCodeAt(0)),
);
+// This buffer exists purely to avoid trigerring the bin-op buf assert
+// in practice all deno bin ops accept buffers, this bench is an exception
+// TODO(@AaronO): remove once we drop variadic BufVec compat
+const nopBuffer = new Uint8Array();
+
/** Listens on 0.0.0.0:4500, returns rid. */
function listen() {
- return Deno.core.binOpSync("listen");
+ return Deno.core.binOpSync("listen", 0, nopBuffer);
}
/** Accepts a connection, returns rid. */
function accept(rid) {
- return Deno.core.binOpAsync("accept", rid);
+ return Deno.core.binOpAsync("accept", rid, nopBuffer);
}
/**
@@ -33,7 +38,7 @@ function write(rid, data) {
}
function close(rid) {
- Deno.core.binOpSync("close", rid);
+ Deno.core.binOpSync("close", rid, nopBuffer);
}
async function serve(rid) {
diff --git a/core/examples/http_bench_json_ops.js b/core/examples/http_bench_json_ops.js
index 071df100f..791fcc499 100644
--- a/core/examples/http_bench_json_ops.js
+++ b/core/examples/http_bench_json_ops.js
@@ -11,33 +11,29 @@ const responseBuf = new Uint8Array(
/** Listens on 0.0.0.0:4500, returns rid. */
function listen() {
- const { rid } = Deno.core.jsonOpSync("listen");
- return rid;
+ return Deno.core.jsonOpSync("listen");
}
/** Accepts a connection, returns rid. */
-async function accept(serverRid) {
- const { rid } = await Deno.core.jsonOpAsync("accept", { rid: serverRid });
- return rid;
+function accept(serverRid) {
+ return Deno.core.jsonOpAsync("accept", serverRid);
}
/**
* Reads a packet from the rid, presumably an http request. data is ignored.
* Returns bytes read.
*/
-async function read(rid, data) {
- const { nread } = await Deno.core.jsonOpAsync("read", { rid }, data);
- return nread;
+function read(rid, data) {
+ return Deno.core.jsonOpAsync("read", rid, data);
}
/** Writes a fixed HTTP response to the socket rid. Returns bytes written. */
-async function write(rid, data) {
- const { nwritten } = await Deno.core.jsonOpAsync("write", { rid }, data);
- return nwritten;
+function write(rid, data) {
+ return Deno.core.jsonOpAsync("write", rid, data);
}
function close(rid) {
- Deno.core.jsonOpSync("close", { rid });
+ Deno.core.jsonOpSync("close", rid);
}
async function serve(rid) {
diff --git a/core/examples/http_bench_json_ops.rs b/core/examples/http_bench_json_ops.rs
index bc96ce478..b1116d757 100644
--- a/core/examples/http_bench_json_ops.rs
+++ b/core/examples/http_bench_json_ops.rs
@@ -9,10 +9,8 @@ use deno_core::JsRuntime;
use deno_core::OpState;
use deno_core::RcRef;
use deno_core::Resource;
+use deno_core::ResourceId;
use deno_core::ZeroCopyBuf;
-use serde::Deserialize;
-use serde::Serialize;
-use serde_json::Value;
use std::cell::RefCell;
use std::convert::TryFrom;
use std::env;
@@ -121,11 +119,6 @@ fn create_js_runtime() -> JsRuntime {
runtime
}
-#[derive(Deserialize, Serialize)]
-struct ResourceId {
- rid: u32,
-}
-
fn op_listen(
state: &mut OpState,
_args: (),
@@ -137,71 +130,71 @@ fn op_listen(
std_listener.set_nonblocking(true)?;
let listener = TcpListener::try_from(std_listener)?;
let rid = state.resource_table.add(listener);
- Ok(ResourceId { rid })
+ Ok(rid)
}
fn op_close(
state: &mut OpState,
- args: ResourceId,
+ rid: ResourceId,
_buf: &mut [ZeroCopyBuf],
) -> Result<(), AnyError> {
- log::debug!("close rid={}", args.rid);
+ log::debug!("close rid={}", rid);
state
.resource_table
- .close(args.rid)
+ .close(rid)
.map(|_| ())
.ok_or_else(bad_resource_id)
}
async fn op_accept(
state: Rc<RefCell<OpState>>,
- args: ResourceId,
+ rid: ResourceId,
_bufs: BufVec,
) -> Result<ResourceId, AnyError> {
- log::debug!("accept rid={}", args.rid);
+ log::debug!("accept rid={}", rid);
let listener = state
.borrow()
.resource_table
- .get::<TcpListener>(args.rid)
+ .get::<TcpListener>(rid)
.ok_or_else(bad_resource_id)?;
let stream = listener.accept().await?;
let rid = state.borrow_mut().resource_table.add(stream);
- Ok(ResourceId { rid })
+ Ok(rid)
}
async fn op_read(
state: Rc<RefCell<OpState>>,
- args: ResourceId,
+ rid: ResourceId,
mut bufs: BufVec,
-) -> Result<Value, AnyError> {
+) -> Result<usize, AnyError> {
assert_eq!(bufs.len(), 1, "Invalid number of arguments");
- log::debug!("read rid={}", args.rid);
+ log::debug!("read rid={}", rid);
let stream = state
.borrow()
.resource_table
- .get::<TcpStream>(args.rid)
+ .get::<TcpStream>(rid)
.ok_or_else(bad_resource_id)?;
let nread = stream.read(&mut bufs[0]).await?;
- Ok(serde_json::json!({ "nread": nread }))
+ Ok(nread)
}
async fn op_write(
state: Rc<RefCell<OpState>>,
- args: ResourceId,
+ rid: ResourceId,
bufs: BufVec,
-) -> Result<Value, AnyError> {
+) -> Result<usize, AnyError> {
assert_eq!(bufs.len(), 1, "Invalid number of arguments");
- log::debug!("write rid={}", args.rid);
+ log::debug!("write rid={}", rid);
let stream = state
.borrow()
.resource_table
- .get::<TcpStream>(args.rid)
+ .get::<TcpStream>(rid)
.ok_or_else(bad_resource_id)?;
let nwritten = stream.write(&bufs[0]).await?;
- Ok(serde_json::json!({ "nwritten": nwritten }))
+ Ok(nwritten)
}
fn main() {