summaryrefslogtreecommitdiff
path: root/core/examples
diff options
context:
space:
mode:
authorMatt Mastracci <matthew@mastracci.com>2023-07-01 18:00:14 -0600
committerGitHub <noreply@github.com>2023-07-02 00:00:14 +0000
commite746b6d80654ba4e4e26370fe6e4f784ce841d92 (patch)
tree153ffad92a96126b9ab8e906dcdabf7648755931 /core/examples
parentb9c0e7cd550ab14fa7da7e33ed87cbeeeb9785a0 (diff)
refactor(core): Extract deno_core (#19658)
`deno_core` is moving out! You'll find it at https://github.com/denoland/deno_core/ once this PR lands.
Diffstat (limited to 'core/examples')
-rw-r--r--core/examples/disable_ops.rs27
-rw-r--r--core/examples/eval_js_value.rs48
-rw-r--r--core/examples/fs_module_loader.rs40
-rw-r--r--core/examples/hello_world.rs68
-rw-r--r--core/examples/http_bench_json_ops/http_bench_json_ops.js46
-rw-r--r--core/examples/http_bench_json_ops/main.rs176
-rw-r--r--core/examples/panik.rs36
-rw-r--r--core/examples/schedule_task.rs69
-rw-r--r--core/examples/ts_module_loader.rs128
-rw-r--r--core/examples/wasm.js28
-rw-r--r--core/examples/wasm.rs67
-rw-r--r--core/examples/wasm.ts7
12 files changed, 0 insertions, 740 deletions
diff --git a/core/examples/disable_ops.rs b/core/examples/disable_ops.rs
deleted file mode 100644
index c75af1c3f..000000000
--- a/core/examples/disable_ops.rs
+++ /dev/null
@@ -1,27 +0,0 @@
-// Copyright 2018-2023 the Deno authors. All rights reserved. MIT license.
-//! This example shows you how to define ops in Rust and then call them from
-//! JavaScript.
-
-use deno_core::Extension;
-use deno_core::JsRuntime;
-use deno_core::RuntimeOptions;
-
-fn main() {
- let my_ext = Extension::builder("my_ext")
- .middleware(|op| match op.name {
- "op_print" => op.disable(),
- _ => op,
- })
- .build();
-
- // Initialize a runtime instance
- let mut runtime = JsRuntime::new(RuntimeOptions {
- extensions: vec![my_ext],
- ..Default::default()
- });
-
- // Deno.core.print() will now be a NOP
- runtime
- .execute_script_static("<usage>", r#"Deno.core.print("I'm broken")"#)
- .unwrap();
-}
diff --git a/core/examples/eval_js_value.rs b/core/examples/eval_js_value.rs
deleted file mode 100644
index a752d7100..000000000
--- a/core/examples/eval_js_value.rs
+++ /dev/null
@@ -1,48 +0,0 @@
-// Copyright 2018-2023 the Deno authors. All rights reserved. MIT license.
-//! This example shows you how to evaluate JavaScript expression and deserialize
-//! return value into a Rust object.
-
-// NOTE:
-// Here we are deserializing to `serde_json::Value` but you can
-// deserialize to any other type that implements the `Deserialize` trait.
-
-use deno_core::v8;
-use deno_core::JsRuntime;
-use deno_core::RuntimeOptions;
-
-fn main() {
- let mut runtime = JsRuntime::new(RuntimeOptions::default());
-
- // Evaluate some code
- let code = "let a = 1+4; a*2";
- let output: serde_json::Value =
- eval(&mut runtime, code).expect("Eval failed");
-
- println!("Output: {output:?}");
-
- let expected_output = serde_json::json!(10);
- assert_eq!(expected_output, output);
-}
-
-fn eval(
- context: &mut JsRuntime,
- code: &'static str,
-) -> Result<serde_json::Value, String> {
- let res = context.execute_script_static("<anon>", code);
- match res {
- Ok(global) => {
- let scope = &mut context.handle_scope();
- let local = v8::Local::new(scope, global);
- // Deserialize a `v8` object into a Rust type using `serde_v8`,
- // in this case deserialize to a JSON `Value`.
- let deserialized_value =
- serde_v8::from_v8::<serde_json::Value>(scope, local);
-
- match deserialized_value {
- Ok(value) => Ok(value),
- Err(err) => Err(format!("Cannot deserialize value: {err:?}")),
- }
- }
- Err(err) => Err(format!("Evaling error: {err:?}")),
- }
-}
diff --git a/core/examples/fs_module_loader.rs b/core/examples/fs_module_loader.rs
deleted file mode 100644
index 737ff1d5c..000000000
--- a/core/examples/fs_module_loader.rs
+++ /dev/null
@@ -1,40 +0,0 @@
-// Copyright 2018-2023 the Deno authors. All rights reserved. MIT license.
-
-use anyhow::Context;
-use deno_core::anyhow::Error;
-use deno_core::FsModuleLoader;
-use deno_core::JsRuntime;
-use deno_core::RuntimeOptions;
-use std::rc::Rc;
-
-fn main() -> Result<(), Error> {
- let args: Vec<String> = std::env::args().collect();
- if args.len() < 2 {
- println!("Usage: target/examples/debug/fs_module_loader <path_to_module>");
- std::process::exit(1);
- }
- let main_url = &args[1];
- println!("Run {main_url}");
-
- let mut js_runtime = JsRuntime::new(RuntimeOptions {
- module_loader: Some(Rc::new(FsModuleLoader)),
- ..Default::default()
- });
-
- let runtime = tokio::runtime::Builder::new_current_thread()
- .enable_all()
- .build()?;
-
- let main_module = deno_core::resolve_path(
- main_url,
- &std::env::current_dir().context("Unable to get CWD")?,
- )?;
-
- let future = async move {
- let mod_id = js_runtime.load_main_module(&main_module, None).await?;
- let result = js_runtime.mod_evaluate(mod_id);
- js_runtime.run_event_loop(false).await?;
- result.await?
- };
- runtime.block_on(future)
-}
diff --git a/core/examples/hello_world.rs b/core/examples/hello_world.rs
deleted file mode 100644
index cce6e2218..000000000
--- a/core/examples/hello_world.rs
+++ /dev/null
@@ -1,68 +0,0 @@
-// Copyright 2018-2023 the Deno authors. All rights reserved. MIT license.
-//! This example shows you how to define ops in Rust and then call them from
-//! JavaScript.
-
-use deno_core::op;
-use deno_core::Extension;
-use deno_core::JsRuntime;
-use deno_core::RuntimeOptions;
-
-// This is a hack to make the `#[op]` macro work with
-// deno_core examples.
-// You can remove this:
-use deno_core::*;
-
-#[op]
-fn op_sum(nums: Vec<f64>) -> Result<f64, deno_core::error::AnyError> {
- // Sum inputs
- let sum = nums.iter().fold(0.0, |a, v| a + v);
- // return as a Result<f64, AnyError>
- Ok(sum)
-}
-
-fn main() {
- // Build a deno_core::Extension providing custom ops
- let ext = Extension::builder("my_ext")
- .ops(vec![
- // An op for summing an array of numbers
- // The op-layer automatically deserializes inputs
- // and serializes the returned Result & value
- op_sum::decl(),
- ])
- .build();
-
- // Initialize a runtime instance
- let mut runtime = JsRuntime::new(RuntimeOptions {
- extensions: vec![ext],
- ..Default::default()
- });
-
- // Now we see how to invoke the op 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_script_static(
- "<usage>",
- r#"
-// Print helper function, calling Deno.core.print()
-function print(value) {
- Deno.core.print(value.toString()+"\n");
-}
-
-const arr = [1, 2, 3];
-print("The sum of");
-print(arr);
-print("is");
-print(Deno.core.ops.op_sum(arr));
-
-// And incorrect usage
-try {
- print(Deno.core.ops.op_sum(0));
-} catch(e) {
- print('Exception:');
- print(e);
-}
-"#,
- )
- .unwrap();
-}
diff --git a/core/examples/http_bench_json_ops/http_bench_json_ops.js b/core/examples/http_bench_json_ops/http_bench_json_ops.js
deleted file mode 100644
index a840e4e9f..000000000
--- a/core/examples/http_bench_json_ops/http_bench_json_ops.js
+++ /dev/null
@@ -1,46 +0,0 @@
-// Copyright 2018-2023 the Deno authors. All rights reserved. MIT license.
-// This is not a real HTTP server. We read blindly one time into 'requestBuf',
-// then write this fixed 'responseBuf'. The point of this benchmark is to
-// exercise the event loop in a simple yet semi-realistic way.
-
-// deno-lint-ignore-file camelcase
-
-const { op_listen } = Deno.core.ops;
-const {
- op_accept,
- op_read_socket,
-} = Deno.core.ensureFastOps();
-
-const requestBuf = new Uint8Array(64 * 1024);
-const responseBuf = new Uint8Array(
- "HTTP/1.1 200 OK\r\nContent-Length: 12\r\n\r\nHello World\n"
- .split("")
- .map((c) => c.charCodeAt(0)),
-);
-
-async function serve(rid) {
- try {
- while (true) {
- await op_read_socket(rid, requestBuf);
- if (!ops.op_try_write(rid, responseBuf)) {
- await Deno.core.writeAll(rid, responseBuf);
- }
- }
- } catch {
- // pass
- }
- Deno.core.close(rid);
-}
-
-async function main() {
- /** Listens on 0.0.0.0:4570, returns rid. */
- const listenerRid = op_listen();
- Deno.core.print(`http_bench_ops listening on http://127.0.0.1:4570/\n`);
-
- while (true) {
- const rid = await op_accept(listenerRid);
- serve(rid);
- }
-}
-
-main();
diff --git a/core/examples/http_bench_json_ops/main.rs b/core/examples/http_bench_json_ops/main.rs
deleted file mode 100644
index a4d6afe31..000000000
--- a/core/examples/http_bench_json_ops/main.rs
+++ /dev/null
@@ -1,176 +0,0 @@
-// Copyright 2018-2023 the Deno authors. All rights reserved. MIT license.
-use deno_core::anyhow::Error;
-use deno_core::op;
-use deno_core::AsyncRefCell;
-use deno_core::AsyncResult;
-use deno_core::JsBuffer;
-use deno_core::JsRuntimeForSnapshot;
-use deno_core::OpState;
-use deno_core::Resource;
-use deno_core::ResourceId;
-use std::cell::RefCell;
-use std::env;
-use std::net::SocketAddr;
-use std::rc::Rc;
-use tokio::io::AsyncReadExt;
-use tokio::io::AsyncWriteExt;
-
-// This is a hack to make the `#[op]` macro work with
-// deno_core examples.
-// You can remove this:
-use deno_core::*;
-
-// Note: a `tokio::net::TcpListener` doesn't need to be wrapped in a cell,
-// because it only supports one op (`accept`) which does not require a mutable
-// reference to the listener.
-struct TcpListener {
- inner: tokio::net::TcpListener,
-}
-
-impl TcpListener {
- async fn accept(self: Rc<Self>) -> Result<TcpStream, std::io::Error> {
- let stream = self.inner.accept().await?.0.into();
- Ok(stream)
- }
-}
-
-impl Resource for TcpListener {
- fn close(self: Rc<Self>) {}
-}
-
-impl TryFrom<std::net::TcpListener> for TcpListener {
- type Error = std::io::Error;
- fn try_from(
- std_listener: std::net::TcpListener,
- ) -> Result<Self, Self::Error> {
- tokio::net::TcpListener::try_from(std_listener).map(|tokio_listener| Self {
- inner: tokio_listener,
- })
- }
-}
-
-struct TcpStream {
- rd: AsyncRefCell<tokio::net::tcp::OwnedReadHalf>,
- wr: AsyncRefCell<tokio::net::tcp::OwnedWriteHalf>,
-}
-
-impl TcpStream {
- async fn read(self: Rc<Self>, data: &mut [u8]) -> Result<usize, Error> {
- let mut rd = RcRef::map(&self, |r| &r.rd).borrow_mut().await;
- let nread = rd.read(data).await?;
- Ok(nread)
- }
-
- async fn write(self: Rc<Self>, data: &[u8]) -> Result<usize, Error> {
- let mut wr = RcRef::map(self, |r| &r.wr).borrow_mut().await;
- let nwritten = wr.write(data).await?;
- Ok(nwritten)
- }
-
- fn try_write(self: Rc<Self>, data: &[u8]) -> Result<usize, Error> {
- let wr = RcRef::map(self, |r| &r.wr)
- .try_borrow_mut()
- .ok_or_else(|| Error::msg("Failed to acquire lock on TcpStream"))?;
- let nwritten = wr.try_write(data)?;
- Ok(nwritten)
- }
-}
-
-impl Resource for TcpStream {
- deno_core::impl_readable_byob!();
- deno_core::impl_writable!();
-
- fn close(self: Rc<Self>) {}
-}
-
-impl From<tokio::net::TcpStream> for TcpStream {
- fn from(s: tokio::net::TcpStream) -> Self {
- let (rd, wr) = s.into_split();
- Self {
- rd: rd.into(),
- wr: wr.into(),
- }
- }
-}
-
-fn create_js_runtime() -> JsRuntimeForSnapshot {
- let ext = deno_core::Extension::builder("my_ext")
- .ops(vec![
- op_listen::decl(),
- op_accept::decl(),
- op_try_write::decl(),
- op_read_socket::decl(),
- ])
- .build();
-
- JsRuntimeForSnapshot::new(
- deno_core::RuntimeOptions {
- extensions: vec![ext],
- ..Default::default()
- },
- Default::default(),
- )
-}
-
-#[op]
-async fn op_read_socket(
- state: Rc<RefCell<OpState>>,
- rid: ResourceId,
- mut data: JsBuffer,
-) -> Result<u32, Error> {
- let resource = state.borrow_mut().resource_table.get::<TcpStream>(rid)?;
- let nread = resource.read(&mut data).await?;
- Ok(nread as u32)
-}
-
-#[op]
-fn op_listen(state: &mut OpState) -> Result<ResourceId, Error> {
- let addr = "127.0.0.1:4570".parse::<SocketAddr>().unwrap();
- let std_listener = std::net::TcpListener::bind(addr)?;
- std_listener.set_nonblocking(true)?;
- let listener = TcpListener::try_from(std_listener)?;
- let rid = state.resource_table.add(listener);
- Ok(rid)
-}
-
-#[op]
-async fn op_accept(
- state: Rc<RefCell<OpState>>,
- rid: ResourceId,
-) -> Result<ResourceId, Error> {
- let listener = state.borrow().resource_table.get::<TcpListener>(rid)?;
- let stream = listener.accept().await?;
- let rid = state.borrow_mut().resource_table.add(stream);
- Ok(rid)
-}
-
-#[op(fast)]
-fn op_try_write(
- state: &mut OpState,
- rid: u32,
- value: &[u8],
-) -> Result<bool, Error> {
- let stream = state.resource_table.get::<TcpStream>(rid)?;
- Ok(stream.try_write(value).is_ok())
-}
-
-fn main() {
- // NOTE: `--help` arg will display V8 help and exit
- deno_core::v8_set_flags(env::args().collect());
-
- let mut js_runtime = create_js_runtime();
- let runtime = tokio::runtime::Builder::new_current_thread()
- .enable_io()
- .build()
- .unwrap();
- let future = async move {
- js_runtime
- .execute_script(
- "http_bench_json_ops.js",
- include_ascii_string!("http_bench_json_ops.js"),
- )
- .unwrap();
- js_runtime.run_event_loop(false).await
- };
- runtime.block_on(future).unwrap();
-}
diff --git a/core/examples/panik.rs b/core/examples/panik.rs
deleted file mode 100644
index 54b46d337..000000000
--- a/core/examples/panik.rs
+++ /dev/null
@@ -1,36 +0,0 @@
-// Copyright 2018-2023 the Deno authors. All rights reserved. MIT license.
-//! This example shows that op-panics currently result in UB (likely "failed to initiate panic")
-//! without a custom panic hook that aborts the process or -C panic=abort.
-//!
-//! This happens due to the UB of panicking in an extern "C",
-//! given how ops are reduced via rusty_v8::MapFnTo
-//! See:
-//! - https://github.com/rust-lang/rust/issues/74990
-//! - https://rust-lang.github.io/rfcs/2945-c-unwind-abi.html
-
-use deno_core::op;
-use deno_core::Extension;
-use deno_core::JsRuntime;
-use deno_core::RuntimeOptions;
-
-// This is a hack to make the `#[op]` macro work with
-// deno_core examples.
-// You can remove this:
-use deno_core::*;
-
-fn main() {
- #[op]
- fn op_panik() {
- panic!("panik !!!")
- }
-
- let extensions = vec![Extension::builder("my_ext")
- .ops(vec![op_panik::decl()])
- .build()];
- let mut rt = JsRuntime::new(RuntimeOptions {
- extensions,
- ..Default::default()
- });
- rt.execute_script_static("panik", "Deno.core.ops.op_panik()")
- .unwrap();
-}
diff --git a/core/examples/schedule_task.rs b/core/examples/schedule_task.rs
deleted file mode 100644
index 348ba7666..000000000
--- a/core/examples/schedule_task.rs
+++ /dev/null
@@ -1,69 +0,0 @@
-// Copyright 2018-2023 the Deno authors. All rights reserved. MIT license.
-
-use deno_core::anyhow::Error;
-use deno_core::op;
-use deno_core::Extension;
-use deno_core::JsRuntime;
-use deno_core::OpState;
-use deno_core::RuntimeOptions;
-use futures::channel::mpsc;
-use futures::stream::StreamExt;
-use std::task::Poll;
-
-// This is a hack to make the `#[op]` macro work with
-// deno_core examples.
-// You can remove this:
-use deno_core::*;
-
-type Task = Box<dyn FnOnce()>;
-
-fn main() {
- let my_ext = Extension::builder("my_ext")
- .ops(vec![op_schedule_task::decl()])
- .event_loop_middleware(|state_rc, cx| {
- let mut state = state_rc.borrow_mut();
- let recv = state.borrow_mut::<mpsc::UnboundedReceiver<Task>>();
- let mut ref_loop = false;
- while let Poll::Ready(Some(call)) = recv.poll_next_unpin(cx) {
- call();
- ref_loop = true; // `call` can callback into runtime and schedule new callbacks :-)
- }
- ref_loop
- })
- .state(move |state| {
- let (tx, rx) = mpsc::unbounded::<Task>();
- state.put(tx);
- state.put(rx);
- })
- .build();
-
- // Initialize a runtime instance
- let mut js_runtime = JsRuntime::new(RuntimeOptions {
- extensions: vec![my_ext],
- ..Default::default()
- });
- let runtime = tokio::runtime::Builder::new_current_thread()
- .enable_all()
- .build()
- .unwrap();
-
- let future = async move {
- // Schedule 10 tasks.
- js_runtime
- .execute_script_static(
- "<usage>",
- r#"for (let i = 1; i <= 10; i++) Deno.core.ops.op_schedule_task(i);"#,
- )
- .unwrap();
- js_runtime.run_event_loop(false).await
- };
- runtime.block_on(future).unwrap();
-}
-
-#[op]
-fn op_schedule_task(state: &mut OpState, i: u8) -> Result<(), Error> {
- let tx = state.borrow_mut::<mpsc::UnboundedSender<Task>>();
- tx.unbounded_send(Box::new(move || println!("Hello, world! x{i}")))
- .expect("unbounded_send failed");
- Ok(())
-}
diff --git a/core/examples/ts_module_loader.rs b/core/examples/ts_module_loader.rs
deleted file mode 100644
index 6adb27977..000000000
--- a/core/examples/ts_module_loader.rs
+++ /dev/null
@@ -1,128 +0,0 @@
-// Copyright 2018-2023 the Deno authors. All rights reserved. MIT license.
-//! This example shows how to use swc to transpile TypeScript and JSX/TSX
-//! modules.
-//!
-//! It will only transpile, not typecheck (like Deno's `--no-check` flag).
-
-use std::pin::Pin;
-use std::rc::Rc;
-
-use anyhow::anyhow;
-use anyhow::bail;
-use anyhow::Context;
-use anyhow::Error;
-use deno_ast::MediaType;
-use deno_ast::ParseParams;
-use deno_ast::SourceTextInfo;
-use deno_core::error::AnyError;
-use deno_core::resolve_import;
-use deno_core::resolve_path;
-use deno_core::JsRuntime;
-use deno_core::ModuleLoader;
-use deno_core::ModuleSource;
-use deno_core::ModuleSourceFuture;
-use deno_core::ModuleSpecifier;
-use deno_core::ModuleType;
-use deno_core::ResolutionKind;
-use deno_core::RuntimeOptions;
-use futures::FutureExt;
-
-struct TypescriptModuleLoader;
-
-impl ModuleLoader for TypescriptModuleLoader {
- fn resolve(
- &self,
- specifier: &str,
- referrer: &str,
- _kind: ResolutionKind,
- ) -> Result<ModuleSpecifier, Error> {
- Ok(resolve_import(specifier, referrer)?)
- }
-
- fn load(
- &self,
- module_specifier: &ModuleSpecifier,
- _maybe_referrer: Option<&ModuleSpecifier>,
- _is_dyn_import: bool,
- ) -> Pin<Box<ModuleSourceFuture>> {
- fn load(
- module_specifier: &ModuleSpecifier,
- ) -> Result<ModuleSource, AnyError> {
- let path = module_specifier
- .to_file_path()
- .map_err(|_| anyhow!("Only file:// URLs are supported."))?;
-
- let media_type = MediaType::from_path(&path);
- let (module_type, should_transpile) = match MediaType::from_path(&path) {
- MediaType::JavaScript | MediaType::Mjs | MediaType::Cjs => {
- (ModuleType::JavaScript, false)
- }
- MediaType::Jsx => (ModuleType::JavaScript, true),
- MediaType::TypeScript
- | MediaType::Mts
- | MediaType::Cts
- | MediaType::Dts
- | MediaType::Dmts
- | MediaType::Dcts
- | MediaType::Tsx => (ModuleType::JavaScript, true),
- MediaType::Json => (ModuleType::Json, false),
- _ => bail!("Unknown extension {:?}", path.extension()),
- };
-
- let code = std::fs::read_to_string(&path)?;
- let code = if should_transpile {
- let parsed = deno_ast::parse_module(ParseParams {
- specifier: module_specifier.to_string(),
- text_info: SourceTextInfo::from_string(code),
- media_type,
- capture_tokens: false,
- scope_analysis: false,
- maybe_syntax: None,
- })?;
- parsed.transpile(&Default::default())?.text
- } else {
- code
- };
- Ok(ModuleSource::new(
- module_type,
- code.into(),
- module_specifier,
- ))
- }
-
- futures::future::ready(load(module_specifier)).boxed_local()
- }
-}
-
-fn main() -> Result<(), Error> {
- let args: Vec<String> = std::env::args().collect();
- if args.len() < 2 {
- println!("Usage: target/examples/debug/ts_module_loader <path_to_module>");
- std::process::exit(1);
- }
- let main_url = &args[1];
- println!("Run {main_url}");
-
- let mut js_runtime = JsRuntime::new(RuntimeOptions {
- module_loader: Some(Rc::new(TypescriptModuleLoader)),
- ..Default::default()
- });
-
- let main_module = resolve_path(
- main_url,
- &std::env::current_dir().context("Unable to get CWD")?,
- )?;
-
- let future = async move {
- let mod_id = js_runtime.load_main_module(&main_module, None).await?;
- let result = js_runtime.mod_evaluate(mod_id);
- js_runtime.run_event_loop(false).await?;
- result.await?
- };
-
- tokio::runtime::Builder::new_current_thread()
- .enable_all()
- .build()
- .unwrap()
- .block_on(future)
-}
diff --git a/core/examples/wasm.js b/core/examples/wasm.js
deleted file mode 100644
index cb6a4af52..000000000
--- a/core/examples/wasm.js
+++ /dev/null
@@ -1,28 +0,0 @@
-// Copyright 2018-2023 the Deno authors. All rights reserved. MIT license.
-
-// asc wasm.ts --exportStart --initialMemory 6400 -O -o wasm.wasm
-// deno-fmt-ignore
-const bytes = new Uint8Array([
- 0, 97, 115, 109, 1, 0, 0, 0, 1, 4, 1, 96, 0, 0, 2,
- 15, 1, 3, 111, 112, 115, 7, 111, 112, 95, 119, 97, 115, 109, 0,
- 0, 3, 3, 2, 0, 0, 5, 4, 1, 0, 128, 50, 7, 36, 4,
- 7, 111, 112, 95, 119, 97, 115, 109, 0, 0, 4, 99, 97, 108, 108,
- 0, 1, 6, 109, 101, 109, 111, 114, 121, 2, 0, 6, 95, 115, 116,
- 97, 114, 116, 0, 2, 10, 10, 2, 4, 0, 16, 0, 11, 3, 0,
- 1, 11
- ]);
-
-const { ops } = Deno.core;
-
-const module = new WebAssembly.Module(bytes);
-const instance = new WebAssembly.Instance(module, { ops });
-ops.op_set_wasm_mem(instance.exports.memory);
-
-instance.exports.call();
-
-const memory = instance.exports.memory;
-const view = new Uint8Array(memory.buffer);
-
-if (view[0] !== 69) {
- throw new Error("Expected first byte to be 69");
-}
diff --git a/core/examples/wasm.rs b/core/examples/wasm.rs
deleted file mode 100644
index 5d5c5f6ff..000000000
--- a/core/examples/wasm.rs
+++ /dev/null
@@ -1,67 +0,0 @@
-// Copyright 2018-2023 the Deno authors. All rights reserved. MIT license.
-
-use deno_core::op;
-use deno_core::Extension;
-use deno_core::JsRuntime;
-use deno_core::RuntimeOptions;
-use std::mem::transmute;
-use std::ptr::NonNull;
-
-// This is a hack to make the `#[op]` macro work with
-// deno_core examples.
-// You can remove this:
-
-use deno_core::*;
-
-struct WasmMemory(NonNull<v8::WasmMemoryObject>);
-
-fn wasm_memory_unchecked(state: &mut OpState) -> &mut [u8] {
- let WasmMemory(global) = state.borrow::<WasmMemory>();
- // SAFETY: `v8::Local` is always non-null pointer; the `HandleScope` is
- // already on the stack, but we don't have access to it.
- let memory_object = unsafe {
- transmute::<NonNull<v8::WasmMemoryObject>, v8::Local<v8::WasmMemoryObject>>(
- *global,
- )
- };
- let backing_store = memory_object.buffer().get_backing_store();
- let ptr = backing_store.data().unwrap().as_ptr() as *mut u8;
- let len = backing_store.byte_length();
- // SAFETY: `ptr` is a valid pointer to `len` bytes.
- unsafe { std::slice::from_raw_parts_mut(ptr, len) }
-}
-
-#[op(wasm)]
-fn op_wasm(state: &mut OpState, memory: Option<&mut [u8]>) {
- let memory = memory.unwrap_or_else(|| wasm_memory_unchecked(state));
- memory[0] = 69;
-}
-
-#[op(v8)]
-fn op_set_wasm_mem(
- scope: &mut v8::HandleScope,
- state: &mut OpState,
- memory: serde_v8::Value,
-) {
- let memory =
- v8::Local::<v8::WasmMemoryObject>::try_from(memory.v8_value).unwrap();
- let global = v8::Global::new(scope, memory);
- state.put(WasmMemory(global.into_raw()));
-}
-
-fn main() {
- // Build a deno_core::Extension providing custom ops
- let ext = Extension::builder("my_ext")
- .ops(vec![op_wasm::decl(), op_set_wasm_mem::decl()])
- .build();
-
- // Initialize a runtime instance
- let mut runtime = JsRuntime::new(RuntimeOptions {
- extensions: vec![ext],
- ..Default::default()
- });
-
- runtime
- .execute_script("<usage>", include_ascii_string!("wasm.js"))
- .unwrap();
-}
diff --git a/core/examples/wasm.ts b/core/examples/wasm.ts
deleted file mode 100644
index 4cf364c3a..000000000
--- a/core/examples/wasm.ts
+++ /dev/null
@@ -1,7 +0,0 @@
-// Copyright 2018-2023 the Deno authors. All rights reserved. MIT license.
-
-export declare function op_wasm(): void;
-
-export function call(): void {
- op_wasm();
-}