### Example extension usage Source: https://docs.rs/deno_core/latest/deno_core/macro.extension.html A basic example showing how to define an extension with an op and an ESM file. ```rust #[op] fn op_xyz() { } deno_core::extension!( my_extension, ops = [ op_xyz ], esm = [ "my_script.js" ], docs = "A small sample extension" ); ``` -------------------------------- ### FastString Construction Example Source: https://docs.rs/deno_core/latest/src/deno_core/fast_string.rs.html Example showing how to construct a FastString. ```rust 168/// ```rust 169/// # use deno_core::{ascii_str, FastString}; 170/// ``` -------------------------------- ### Trim start matches example Source: https://docs.rs/deno_core/latest/deno_core/stats/struct.RuntimeActivityTrace.html Demonstrates trimming characters from the start of a string using a slice of characters. ```rust let x: &[_] = &['1', '2']; assert_eq!("12foo1bar12".trim_start_matches(x), "foo1bar12"); ``` -------------------------------- ### Box::from_raw Examples Source: https://docs.rs/deno_core/latest/deno_core/type.CustomModuleEvaluationCb.html Examples demonstrating how to reconstruct a Box from a raw pointer. ```rust let x = Box::new(5); let ptr = Box::into_raw(x); let x = unsafe { Box::from_raw(ptr) }; ``` ```rust use std::alloc::{alloc, Layout}; unsafe { let ptr = alloc(Layout::new::()) as *mut i32; // In general .write is required to avoid attempting to destruct // the (uninitialized) previous contents of `ptr`, though for this // simple example `*ptr = 5` would have worked as well. ptr.write(5); let x = Box::from_raw(ptr); } ``` -------------------------------- ### Box::from_non_null Examples Source: https://docs.rs/deno_core/latest/deno_core/type.CustomModuleEvaluationCb.html Examples demonstrating how to reconstruct a Box from a NonNull pointer using experimental nightly APIs. ```rust #![feature(box_vec_non_null)] let x = Box::new(5); let non_null = Box::into_non_null(x); let x = unsafe { Box::from_non_null(non_null) }; ``` ```rust #![feature(box_vec_non_null)] use std::alloc::{alloc, Layout}; use std::ptr::NonNull; unsafe { let non_null = NonNull::new(alloc(Layout::new::()).cast::()) .expect("allocation failed"); // In general .write is required to avoid attempting to destruct // the (uninitialized) previous contents of `non_null`. non_null.write(5); let x = Box::from_non_null(non_null); } ``` -------------------------------- ### Async Operation Examples Source: https://docs.rs/deno_core/latest/src/deno_core/runtime/ops.rs.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Examples of defining and testing asynchronous operations in Deno Core. ```rust #[op2] async fn op_async_void() {} #[tokio::test] pub async fn test_op_async_void() -> Result<(), Box> { run_async_test(JIT_ITERATIONS, "op_async_void", "await op_async_void()") .await?; Ok(()) } ``` ```rust #[op2] async fn op_async_number(x: u32) -> u32 { x } #[op2] async fn op_async_add(x: u32, y: u32) -> u32 { x.wrapping_add(y) } // Note: #[smi] parameters are signed in JS regardless of the sign in Rust. Overflow and underflow // of valid ranges result in automatic wrapping. #[op2] #[smi] async fn op_async_add_smi(#[smi] x: u32, #[smi] y: u32) -> u32 { tokio::time::sleep(Duration::from_millis(10)).await; x.wrapping_add(y) } #[tokio::test] pub async fn test_op_async_number() -> Result<(), Box> { run_async_test( JIT_ITERATIONS, "op_async_number", "assert(await op_async_number(__index__) == __index__)", ) .await?; run_async_test( JIT_ITERATIONS, "op_async_add", "assert(await op_async_add(__index__, 100) == __index__ + 100)", ) .await?; run_async_test( ``` -------------------------------- ### uv_idle_start Source: https://docs.rs/deno_core/latest/deno_core/uv_compat/fn.uv_idle_start.html Starts the given idle handle with the provided callback function. ```APIDOC ## uv_idle_start ### Signature `pub unsafe extern "C" fn uv_idle_start(handle: *mut uv_idle_t, cb: uv_idle_cb) -> c_int` ### Description Starts the idle handle. The callback will be called once per loop iteration, right before the prepare handles. ### Safety `handle` must be a valid pointer to a `uv_idle_t` initialized by `uv_idle_init`. ### Parameters - **handle** (*mut uv_idle_t) - Required - A pointer to an initialized idle handle. - **cb** (uv_idle_cb) - Required - The callback function to be executed when the handle is active. ### Returns - **c_int** - Returns 0 on success, or a negative error code on failure. ``` -------------------------------- ### uv_prepare_start Source: https://docs.rs/deno_core/latest/deno_core/uv_compat/fn.uv_prepare_start.html?search=std%3A%3Avec Starts the prepare handle. The provided callback will be called once per loop iteration, right before blocking for I/O. ```APIDOC ## Function: uv_prepare_start ### Description Starts the prepare handle. The callback will be called once per loop iteration, right before blocking for I/O. ### Signature `pub unsafe extern "C" fn uv_prepare_start(handle: *mut uv_prepare_t, cb: uv_prepare_cb) -> c_int` ### Parameters - **handle** (*mut uv_prepare_t) - A pointer to a uv_prepare_t handle that must be initialized by uv_prepare_init. - **cb** (uv_prepare_cb) - The callback function to be executed. ### Safety This function is unsafe. The `handle` must be a valid pointer to a `uv_prepare_t` initialized by `uv_prepare_init`. ``` -------------------------------- ### Retrieve match indices in strings Source: https://docs.rs/deno_core/latest/deno_core/stats/struct.RuntimeActivityTrace.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Use match_indices or rmatch_indices to get both the start index and the matched content. ```rust let v: Vec<_> = "abcXXXabcYYYabc".match_indices("abc").collect(); assert_eq!(v, [(0, "abc"), (6, "abc"), (12, "abc")]); let v: Vec<_> = "1abcabc2".match_indices("abc").collect(); assert_eq!(v, [(1, "abc"), (4, "abc")]); let v: Vec<_> = "ababa".match_indices("aba").collect(); assert_eq!(v, [(0, "aba")]); // only the first `aba` ``` ```rust let v: Vec<_> = "abcXXXabcYYYabc".rmatch_indices("abc").collect(); assert_eq!(v, [(12, "abc"), (6, "abc"), (0, "abc")]); let v: Vec<_> = "1abcabc2".rmatch_indices("abc").collect(); assert_eq!(v, [(4, "abc"), (1, "abc")]); let v: Vec<_> = "ababa".rmatch_indices("aba").collect(); assert_eq!(v, [(2, "aba")]); // only the last `aba` ``` -------------------------------- ### uv_prepare_start Source: https://docs.rs/deno_core/latest/deno_core/uv_compat/fn.uv_prepare_start.html?search= Starts the prepare handle. The callback will be called once per loop iteration, right before blocking for I/O. ```APIDOC ## uv_prepare_start ### Signature `pub unsafe extern "C" fn uv_prepare_start(handle: *mut uv_prepare_t, cb: uv_prepare_cb) -> c_int` ### Description Starts the prepare handle. The callback will be called once per loop iteration, right before blocking for I/O. ### Safety `handle` must be a valid pointer to a `uv_prepare_t` initialized by `uv_prepare_init`. ### Parameters - **handle** (*mut uv_prepare_t) - Required - A pointer to a `uv_prepare_t` handle. - **cb** (uv_prepare_cb) - Required - The callback function to be executed. ### Returns - **c_int** - Returns 0 on success, or an error code on failure. ``` -------------------------------- ### Test V8 task spawner Source: https://docs.rs/deno_core/latest/src/deno_core/tasks.rs.html?search= Example test setup for the V8 task spawner using a multi-threaded runtime. ```rust #[test] #[cfg(not(all(miri, target_os = "linux")))] fn test_spawner_serial() { let runtime = tokio::runtime::Builder::new_multi_thread() .worker_threads(1) .build() .unwrap(); runtime.block_on(async { let factory = Arc::::default(); let cross_thread_spawner = factory.clone().new_cross_thread_spawner(); let local_set = LocalSet::new(); const COUNT: usize = 1000; ``` -------------------------------- ### uv_prepare_start Source: https://docs.rs/deno_core/latest/deno_core/uv_compat/fn.uv_prepare_start.html?search=u32+-%3E+bool Starts the handle with the given callback. The handle must be a valid pointer to a uv_prepare_t initialized by uv_prepare_init. ```APIDOC ## Function: uv_prepare_start ### Description Starts a libuv prepare handle. This function is unsafe and requires a valid pointer to a `uv_prepare_t` that has been previously initialized. ### Signature `pub unsafe extern "C" fn uv_prepare_start(handle: *mut uv_prepare_t, cb: uv_prepare_cb) -> c_int` ### Parameters - **handle** (*mut uv_prepare_t) - Required - A pointer to a `uv_prepare_t` handle initialized by `uv_prepare_init`. - **cb** (uv_prepare_cb) - Required - The callback function to be executed. ### Returns - **c_int** - Returns 0 on success, or a negative error code on failure. ``` -------------------------------- ### Test V8 task spawner Source: https://docs.rs/deno_core/latest/src/deno_core/tasks.rs.html Example test setup for the V8 task spawner using a multi-threaded Tokio runtime. ```rust #[test] #[cfg(not(all(miri, target_os = "linux")))] fn test_spawner_serial() { let runtime = tokio::runtime::Builder::new_multi_thread() .worker_threads(1) .build() .unwrap(); runtime.block_on(async { let factory = Arc::::default(); let cross_thread_spawner = factory.clone().new_cross_thread_spawner(); ``` -------------------------------- ### uv_prepare_start Source: https://docs.rs/deno_core/latest/deno_core/uv_compat/fn.uv_prepare_start.html Starts the handle with the given callback. The handle must be a valid pointer to a uv_prepare_t initialized by uv_prepare_init. ```APIDOC ## uv_prepare_start ### Signature `pub unsafe extern "C" fn uv_prepare_start(handle: *mut uv_prepare_t, cb: uv_prepare_cb) -> c_int` ### Description Starts the libuv prepare handle. This function is unsafe as it requires a valid pointer to a `uv_prepare_t` that has been previously initialized by `uv_prepare_init`. ### Parameters - **handle** (*mut uv_prepare_t) - Required - A pointer to a libuv prepare handle. - **cb** (uv_prepare_cb) - Required - The callback function to be executed when the prepare handle is triggered. ### Returns - **c_int** - Returns 0 on success, or a negative error code on failure. ``` -------------------------------- ### uv_prepare_start Source: https://docs.rs/deno_core/latest/deno_core/uv_compat/fn.uv_prepare_start.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Starts the handle with the given callback. The handle must be a valid pointer to a uv_prepare_t initialized by uv_prepare_init. ```APIDOC ## uv_prepare_start ### Signature `pub unsafe extern "C" fn uv_prepare_start(handle: *mut uv_prepare_t, cb: uv_prepare_cb) -> c_int` ### Description Starts the prepare handle. The handle must be a valid pointer to a `uv_prepare_t` initialized by `uv_prepare_init`. ### Parameters - **handle** (*mut uv_prepare_t) - Required - A pointer to a libuv prepare handle. - **cb** (uv_prepare_cb) - Required - The callback function to be invoked. ### Returns - **c_int** - Returns 0 on success, or a negative error code on failure. ``` -------------------------------- ### Basic Box initialization Source: https://docs.rs/deno_core/latest/deno_core/type.CustomModuleEvaluationCb.html Demonstrates basic Box creation and pinning. ```rust let foo = Box::new(()); let bar = Pin::from(foo); ``` -------------------------------- ### Start Timer Handle Source: https://docs.rs/deno_core/latest/src/deno_core/uv_compat.rs.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Starts a timer with a specified timeout and repeat interval. ```rust /// ### Safety /// `handle` must be a valid pointer to a `uv_timer_t` initialized by `uv_timer_init`. #[cfg_attr(feature = "uv_compat_export", unsafe(no_mangle))] pub unsafe extern "C" fn uv_timer_start( handle: *mut uv_timer_t, cb: uv_timer_cb, timeout: u64, repeat: u64, ) -> c_int { // SAFETY: Caller guarantees handle was initialized by uv_timer_init. unsafe { if (*handle).flags & UV_HANDLE_CLOSING != 0 { return UV_EINVAL; } let loop_ = (*handle).loop_; let inner = get_inner(loop_); if (*handle).flags & UV_HANDLE_ACTIVE != 0 { inner.stop_timer(handle); } let id = inner.alloc_timer_id(); let now = inner.now_ms(); let deadline = now.saturating_add(timeout); (*handle).cb = Some(cb); (*handle).timeout = timeout; (*handle).repeat = repeat; (*handle).internal_id = id; (*handle).internal_deadline = deadline; (*handle).flags |= UV_HANDLE_ACTIVE; let key = TimerKey { deadline_ms: deadline, id, }; inner.timers.borrow_mut().insert(key); inner.timer_handles.borrow_mut().insert(id, handle); } 0 } ``` -------------------------------- ### Prepare Handle Lifecycle Management Source: https://docs.rs/deno_core/latest/src/deno_core/uv_compat.rs.html Initialize, start, and stop libuv prepare handles. ```rust /// ### Safety /// `loop_` must be initialized by `uv_loop_init`. `handle` must be a valid, writable pointer. #[cfg_attr(feature = "uv_compat_export", unsafe(no_mangle))] pub unsafe extern "C" fn uv_prepare_init( loop_: *mut uv_loop_t, handle: *mut uv_prepare_t, ) -> c_int { // SAFETY: Caller guarantees both pointers are valid. unsafe { (*handle).r#type = uv_handle_type::UV_PREPARE; (*handle).loop_ = loop_; (*handle).data = std::ptr::null_mut(); (*handle).flags = UV_HANDLE_REF; (*handle).cb = None; } 0 } ``` ```rust /// ### Safety /// `handle` must be a valid pointer to a `uv_prepare_t` initialized by `uv_prepare_init`. #[cfg_attr(feature = "uv_compat_export", unsafe(no_mangle))] pub unsafe extern "C" fn uv_prepare_start( handle: *mut uv_prepare_t, cb: uv_prepare_cb, ) -> c_int { // SAFETY: Caller guarantees handle was initialized by `uv_prepare_init`. unsafe { // Match libuv: no-op if already active. if (*handle).flags & UV_HANDLE_ACTIVE != 0 { return 0; } (*handle).cb = Some(cb); (*handle).flags |= UV_HANDLE_ACTIVE; let loop_ = (*handle).loop_; let inner = get_inner(loop_); inner.prepare_handles.borrow_mut().push(handle); } 0 } ``` ```rust /// ### Safety /// `handle` must be a valid pointer to a `uv_prepare_t` initialized by `uv_prepare_init`. #[cfg_attr(feature = "uv_compat_export", unsafe(no_mangle))] pub unsafe extern "C" fn uv_prepare_stop(handle: *mut uv_prepare_t) -> c_int { // SAFETY: Caller guarantees handle was initialized by `uv_prepare_init`. unsafe { if (*handle).flags & UV_HANDLE_ACTIVE == 0 { return 0; } let loop_ = (*handle).loop_; let inner = get_inner(loop_); inner.stop_prepare(handle); (*handle).cb = None; } 0 } ``` -------------------------------- ### Startup Phase Tracing Utilities Source: https://docs.rs/deno_core/latest/src/deno_core/runtime/jsruntime.rs.html?search= Helper functions to track and log startup performance phases when the DENO_STARTUP_PHASES environment variable is enabled. ```rust fn startup_phases_enabled() -> bool { static ENABLED: OnceLock = OnceLock::new(); *ENABLED.get_or_init(|| { // Diagnostic env var β€” only consulted once per process. Bypassing // `sys_traits` here is intentional: the snapshot/runtime layers don't // thread an `EnvProvider` through this code path, and this opt-in // tracing is only useful when running an actual `deno` binary anyway. #[allow( clippy::disallowed_methods, reason = "diagnostic env var; not part of the sys_traits surface" )] let v = std::env::var_os("DENO_STARTUP_PHASES"); v.is_some_and(|v| !v.is_empty() && v != "0") }) } #[inline] fn startup_phase_begin() -> Option { if startup_phases_enabled() { Some(Instant::now()) } else { None } } #[inline] fn startup_phase_end(t: Option, label: &str) { if let Some(start) = t { let elapsed = start.elapsed(); #[allow(clippy::print_stderr, reason = "diagnostic")] { eprintln!("[startup] {label:>32} {elapsed:?}"); } } } ``` -------------------------------- ### Startup Phase Tracking Utilities Source: https://docs.rs/deno_core/latest/src/deno_core/runtime/jsruntime.rs.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Functions to enable, begin, and end tracking of startup phases for diagnostic purposes. ```rust fn startup_phases_enabled() -> bool { static ENABLED: OnceLock = OnceLock::new(); *ENABLED.get_or_init(|| { // Diagnostic env var β€” only consulted once per process. Bypassing // `sys_traits` here is intentional: the snapshot/runtime layers don't // thread an `EnvProvider` through this code path, and this opt-in // tracing is only useful when running an actual `deno` binary anyway. #[allow( clippy::disallowed_methods, reason = "diagnostic env var; not part of the sys_traits surface" )] let v = std::env::var_os("DENO_STARTUP_PHASES"); v.is_some_and(|v| !v.is_empty() && v != "0") }) } ``` ```rust #[inline] fn startup_phase_begin() -> Option { if startup_phases_enabled() { Some(Instant::now()) } else { None } } ``` ```rust #[inline] fn startup_phase_end(t: Option, label: &str) { if let Some(start) = t { let elapsed = start.elapsed(); #[allow(clippy::print_stderr, reason = "diagnostic")] { eprintln!("[startup] {label:>32} {elapsed:?}"); } } } ``` -------------------------------- ### Start a libuv check handle Source: https://docs.rs/deno_core/latest/src/deno_core/uv_compat.rs.html?search= Starts a previously initialized check handle. If the handle is already active, this is a no-op. ```rust #[cfg_attr(feature = "uv_compat_export", unsafe(no_mangle))] pub unsafe extern "C" fn uv_check_start( handle: *mut uv_check_t, cb: uv_check_cb, ) -> c_int { // SAFETY: Caller guarantees handle was initialized by uv_check_init. unsafe { // Match libuv: no-op if already active. if (*handle).flags & UV_HANDLE_ACTIVE != 0 { return 0; } (*handle).cb = Some(cb); (*handle).flags |= UV_HANDLE_ACTIVE; let loop_ = (*handle).loop_; let inner = get_inner(loop_); inner.check_handles.borrow_mut().push(handle); } 0 } ``` -------------------------------- ### get(i: I) Source: https://docs.rs/deno_core/latest/deno_core/struct.FastString.html?search=u32+-%3E+bool Returns a subslice of the string safely. ```APIDOC ## pub fn get(&self, i: I) -> Option<&>::Output> ### Description Returns a subslice of the string. This is the non-panicking alternative to indexing, returning None if the index is out of bounds or not on a UTF-8 boundary. ``` -------------------------------- ### BufMutView::reset_cursor Source: https://docs.rs/deno_core/latest/src/deno_core/io/buffers.rs.html?search=u32+-%3E+bool Resets the cursor to the start of the buffer. ```APIDOC ## BufMutView::reset_cursor(&mut self) -> usize ### Description Resets the internal cursor to the beginning of the buffer and returns the previous cursor position. ``` -------------------------------- ### uv_prepare_init Source: https://docs.rs/deno_core/latest/deno_core/uv_compat/fn.uv_prepare_init.html?search=std%3A%3Avec Initializes a prepare handle. The loop must be initialized by uv_loop_init, and the handle must be a valid, writable pointer. ```APIDOC ## Function: uv_prepare_init ### Signature `pub unsafe extern "C" fn uv_prepare_init(loop_: *mut uv_loop_t, handle: *mut uv_prepare_t) -> c_int` ### Description Initializes the handle. This function is unsafe as it requires valid pointers for the loop and the handle. ### Safety - `loop_` must be initialized by `uv_loop_init`. - `handle` must be a valid, writable pointer. ### Parameters - **loop_** (*mut uv_loop_t) - The event loop to associate with the handle. - **handle** (*mut uv_prepare_t) - The prepare handle to initialize. ### Returns - **c_int** - Returns 0 on success, or a negative error code on failure. ``` -------------------------------- ### uv_prepare_init Source: https://docs.rs/deno_core/latest/deno_core/uv_compat/fn.uv_prepare_init.html?search= Initializes a prepare handle. This function is part of the libuv compatibility layer in deno_core. ```APIDOC ## uv_prepare_init ### Signature `pub unsafe extern "C" fn uv_prepare_init(loop_: *mut uv_loop_t, handle: *mut uv_prepare_t) -> c_int` ### Description Initializes the handle to be used with a libuv prepare watcher. This function must be called before the handle is used in any other libuv functions. ### Safety - `loop_` must be initialized by `uv_loop_init`. - `handle` must be a valid, writable pointer. ### Parameters - **loop_** (*mut uv_loop_t) - Required - A pointer to an initialized libuv loop. - **handle** (*mut uv_prepare_t) - Required - A pointer to the prepare handle to initialize. ### Returns - **c_int** - Returns 0 on success, or a negative error code on failure. ``` -------------------------------- ### Sort a slice Source: https://docs.rs/deno_core/latest/deno_core/convert/struct.ByteString.html Example of sorting a mutable slice of integers. ```rust let mut v = [4, -5, 1, -3, 2]; ``` -------------------------------- ### uv_prepare_init Source: https://docs.rs/deno_core/latest/deno_core/uv_compat/fn.uv_prepare_init.html?search=u32+-%3E+bool Initializes a libuv prepare handle. This function is unsafe and requires valid pointers to an initialized loop and a writable handle. ```APIDOC ## uv_prepare_init ### Signature `pub unsafe extern "C" fn uv_prepare_init(loop_: *mut uv_loop_t, handle: *mut uv_prepare_t) -> c_int` ### Description Initializes the handle for a prepare watcher. This function must be called before the handle is used in any other libuv functions. ### Safety - `loop_` must be initialized by `uv_loop_init`. - `handle` must be a valid, writable pointer. ``` -------------------------------- ### uv_listen Source: https://docs.rs/deno_core/latest/deno_core/uv_compat/fn.uv_listen.html?search= Starts listening for incoming connections on a libuv stream. ```APIDOC ## uv_listen ### Signature `pub unsafe fn uv_listen(stream: *mut uv_stream_t, backlog: c_int, cb: Option) -> c_int` ### Description Starts listening for incoming connections on the provided stream. This function is unsafe and requires the stream to be properly initialized and bound. ### Safety `stream` must be a valid pointer to a `uv_tcp_t` (cast as `uv_stream_t`) initialized by `uv_tcp_init`, with a bind address set via `uv_tcp_bind`. ### Parameters - **stream** (*mut uv_stream_t) - Required - A pointer to the libuv stream to listen on. - **backlog** (c_int) - Required - The maximum length of the queue of pending connections. - **cb** (Option) - Required - The callback function to be invoked when a new connection is available. ### Returns - **c_int** - Returns 0 on success, or a negative error code on failure. ``` -------------------------------- ### starts_with Source: https://docs.rs/deno_core/latest/deno_core/convert/struct.BigUint64Array.html?search=std%3A%3Avec Returns true if the slice starts with the provided needle. ```APIDOC ## pub fn starts_with(&self, needle: &[T]) -> bool ### Description Returns `true` if `needle` is a prefix of the slice or equal to the slice. ``` -------------------------------- ### uv_prepare_init Source: https://docs.rs/deno_core/latest/deno_core/uv_compat/fn.uv_prepare_init.html Initializes a prepare handle. This function is part of the libuv compatibility layer. ```APIDOC ## uv_prepare_init ### Signature `pub unsafe extern "C" fn uv_prepare_init(loop_: *mut uv_loop_t, handle: *mut uv_prepare_t) -> c_int` ### Description Initializes the given `uv_prepare_t` handle to be used with the specified `uv_loop_t`. ### Safety - `loop_` must be initialized by `uv_loop_init`. - `handle` must be a valid, writable pointer. ``` -------------------------------- ### Get URL username Source: https://docs.rs/deno_core/latest/deno_core/type.ModuleSpecifier.html?search=std%3A%3Avec Retrieve the percent-encoded username from the URL. ```rust use url::Url; let url = Url::parse("ftp://rms@example.com")?; assert_eq!(url.username(), "rms"); let url = Url::parse("ftp://:secret123@example.com")?; assert_eq!(url.username(), ""); let url = Url::parse("https://example.com")?; assert_eq!(url.username(), ""); ``` -------------------------------- ### Op Registration and State Management Source: https://docs.rs/deno_core/latest/src/deno_core/runtime/ops.rs.html Example of defining op lists and initializing state within a runtime configuration. ```rust op_arraybuffer_slice, op_test_get_cppgc_resource, op_test_get_cppgc_resource_option, op_test_make_cppgc_resource, op_test_make_cppgc_resource_option, op_external_make, op_external_process, op_external_make_ptr, op_external_process_ptr, op_typed_external, op_typed_external_process, op_typed_external_take, op_isolate_queue_microtask, op_isolate_run_microtasks, op_async_void, op_async_number, op_async_add, op_async_add_smi, op_async_sleep, op_async_sleep_impl, op_async_sleep_error, op_async_deferred_error, op_async_deferred_success, op_async_lazy_error, op_async_lazy_success, op_async_result_impl, op_async_state_rc, op_async_buffer, op_async_buffer_vec, op_async_buffer_impl, op_async_external, op_async_serde_option_v8, op_smi_to_from_v8, op_number_to_from_v8, op_bool_to_from_v8, op_create_buf_u8, op_create_buf_u16, op_create_buf_u32, op_create_buf_u64, op_create_buf_i8, op_create_buf_i16, op_create_buf_i32, op_create_buf_i64, op_create_buf_f32, op_create_buf_f64, ], state = |state| { state.put(1234u32); state.put(10000u16); } ); ``` -------------------------------- ### Get Source Line Source: https://docs.rs/deno_core/latest/deno_core/struct.SourceMapper.html?search= Retrieves a specific line from the source. ```rust pub fn get_source_line( &mut self, file_name: &str, line_number: i64, ) -> Option ``` -------------------------------- ### as_array Source: https://docs.rs/deno_core/latest/deno_core/struct.BufMutView.html?search=u32+-%3E+bool Gets a reference to the underlying array if the length matches. ```APIDOC ## pub fn as_array(&self) -> Option<&[T; N]> ### Description Gets a reference to the underlying array. If N is not exactly equal to the length of the slice, this method returns None. ``` -------------------------------- ### Initialize Deno core namespace Source: https://docs.rs/deno_core/latest/src/deno_core/runtime/bindings.rs.html Sets up the globalThis.Deno object structure, including ops and console bindings. ```rust globalThis.Deno = { core: { ops: {}, }, // console from V8 console, // wrapper fn to forward message to V8 console callConsole, }; ``` ```rust pub(crate) fn initialize_deno_core_namespace<'s, 'i>( scope: &mut v8::PinScope<'s, 'i>, context: v8::Local<'s, v8::Context>, init_mode: InitMode, ) { let global = context.global(scope); let deno_str = DENO.v8_string(scope).unwrap(); let maybe_deno_obj_val = global.get(scope, deno_str.into()); // If `Deno.core` is already set up, let's exit early. if let Some(deno_obj_val) = maybe_deno_obj_val && !deno_obj_val.is_undefined() { return; } let deno_obj = v8::Object::new(scope); let deno_core_key = CORE.v8_string(scope).unwrap(); // Set up `Deno.core.ops` object let deno_core_ops_obj = v8::Object::new(scope); let deno_core_ops_key = OPS.v8_string(scope).unwrap(); let deno_core_obj = v8::Object::new(scope); deno_core_obj .set(scope, deno_core_ops_key.into(), deno_core_ops_obj.into()) .unwrap(); // If we're initializing fresh context set up the console if init_mode == InitMode::New { // Bind `call_console` to Deno.core.callConsole let call_console_fn = v8::Function::new(scope, call_console).unwrap(); let call_console_key = CALL_CONSOLE.v8_string(scope).unwrap(); deno_core_obj.set(scope, call_console_key.into(), call_console_fn.into()); // Bind v8 console object to Deno.core.console let extra_binding_obj = context.get_extras_binding_object(scope); let console_obj: v8::Local = get( scope, extra_binding_obj, CONSOLE, "ExtrasBindingObject.console", ); let console_key = CONSOLE.v8_string(scope).unwrap(); deno_core_obj.set(scope, console_key.into(), console_obj.into()); } deno_obj.set(scope, deno_core_key.into(), deno_core_obj.into()); global.set(scope, deno_str.into(), deno_obj.into()); } ``` -------------------------------- ### Other Module Type Usage Source: https://docs.rs/deno_core/latest/deno_core/enum.RequestedModuleType.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Example of importing a custom module type. ```javascript import url from "./style.css" with { type: "url" }; const imgData = await import(`./images/${name}.png`, { with: { type: "image" }}); ``` -------------------------------- ### uv_idle_start Source: https://docs.rs/deno_core/latest/deno_core/uv_compat/fn.uv_idle_start.html?search= Starts the idle handle. The provided callback will be called once per loop iteration, right before the prepare handles. ```APIDOC ## uv_idle_start ### Signature `pub unsafe extern "C" fn uv_idle_start(handle: *mut uv_idle_t, cb: uv_idle_cb) -> c_int` ### Description Starts the idle handle. The provided callback will be called once per loop iteration, right before the prepare handles. ### Safety `handle` must be a valid pointer to a `uv_idle_t` initialized by `uv_idle_init`. ### Parameters - **handle** (*mut uv_idle_t) - Required - A pointer to an initialized idle handle. - **cb** (uv_idle_cb) - Required - The callback function to be invoked. ### Returns - **c_int** - Returns 0 on success, or a negative error code on failure. ``` -------------------------------- ### uv_timer_start Source: https://docs.rs/deno_core/latest/deno_core/uv_compat/fn.uv_timer_start.html?search= Starts the timer handle with the specified timeout and repeat interval. ```APIDOC ## uv_timer_start ### Signature `pub unsafe extern "C" fn uv_timer_start(handle: *mut uv_timer_t, cb: uv_timer_cb, timeout: u64, repeat: u64) -> c_int` ### Description Starts the timer handle. The callback `cb` will be triggered after `timeout` milliseconds. If `repeat` is non-zero, the timer will repeat every `repeat` milliseconds. ### Safety `handle` must be a valid pointer to a `uv_timer_t` initialized by `uv_timer_init`. ### Parameters - **handle** (*mut uv_timer_t) - The timer handle to start. - **cb** (uv_timer_cb) - The callback function to be executed when the timer expires. - **timeout** (u64) - The initial delay in milliseconds. - **repeat** (u64) - The repeat interval in milliseconds. Set to 0 to disable repetition. ### Returns - **c_int** - Returns 0 on success, or a negative error code on failure. ``` -------------------------------- ### Initialize Deno Core Ops Bindings Source: https://docs.rs/deno_core/latest/src/deno_core/runtime/bindings.rs.html?search= Sets up JavaScript bindings for ops by injecting functions into the Deno.core.ops object and configuring templates. ```rust pub(crate) fn initialize_deno_core_ops_bindings<'s, 'i>( scope: &mut v8::PinScope<'s, 'i>, context: v8::Local<'s, v8::Context>, op_ctxs: &[OpCtx], op_method_decls: &[OpMethodDecl], methods_ctx_offset: usize, fn_template_store: &mut FunctionTemplateData, will_snapshot: bool, ) { let global = context.global(scope); // Set up JavaScript bindings for the defined op - this will insert proper // `v8::Function` into `Deno.core.ops` object. For async ops, there a bit // more machinery involved, see comment below. let deno_obj = get(scope, global, DENO, "Deno"); let deno_core_obj = get(scope, deno_obj, CORE, "Deno.core"); let deno_core_ops_obj: v8::Local = get(scope, deno_core_obj, OPS, "Deno.core.ops"); let set_up_async_stub_fn: v8::Local = get( scope, deno_core_obj, SET_UP_ASYNC_STUB, "Deno.core.setUpAsyncStub", ); let prototype_key = v8::String::new(scope, "prototype").unwrap(); let undefined = v8::undefined(scope); let mut index = 0; for decl in op_method_decls { if index == methods_ctx_offset { break; } let tmpl = if decl.constructor.is_some() { let constructor_ctx = &op_ctxs[index]; let tmpl = op_ctx_template( scope, constructor_ctx, v8::ConstructorBehavior::Allow, will_snapshot, ); index += 1; tmpl } else { crate::cppgc::make_cppgc_template(scope) }; let key = decl.name.1.v8_string(scope).unwrap(); let method_ctxs = &op_ctxs[index..index + decl.methods.len()]; let accessor_store = create_accessor_store(method_ctxs); if !will_snapshot { let prototype = tmpl.prototype_template(scope); for method in method_ctxs.iter() { // Skip async methods, we are going to register them later. if method.decl.is_async { continue; } op_ctx_template_or_accessor( &accessor_store, set_up_async_stub_fn, scope, prototype, tmpl, method, will_snapshot, ); } } index += decl.methods.len(); let static_method_ctxs = &op_ctxs[index..index + decl.static_methods.len()]; if !will_snapshot { for method in static_method_ctxs.iter() { let op_fn = op_ctx_template( scope, method, v8::ConstructorBehavior::Throw, will_snapshot, ); let method_key = name_key(scope, &method.decl); tmpl.set(method_key, op_fn.into()); } } index += decl.static_methods.len(); if !will_snapshot { let prototype = tmpl.prototype_template(scope); // Register async methods at the end since we need to create the template instance. for method in method_ctxs.iter() { if method.decl.is_async { op_ctx_template_or_accessor( &accessor_store, set_up_async_stub_fn, scope, prototype, tmpl, method, will_snapshot, ); } } } if let Some(e) = (decl.inherits_type_name)() { let parent = fn_template_store.get_raw(e).unwrap(); tmpl.inherit(v8::Local::new(scope, parent)); } let op_fn = tmpl.get_function(scope).unwrap(); op_fn.set_name(key); if will_snapshot { let prototype = op_fn .get(scope, prototype_key.into()) .and_then(|p| v8::Local::::try_from(p).ok()) .unwrap(); for method in method_ctxs.iter() { op_ctx_function_or_accessor( &accessor_store, set_up_async_stub_fn, scope, prototype, op_fn, method, ); } for method in static_method_ctxs.iter() { let method_fn = op_ctx_plain_function(scope, method, v8::ConstructorBehavior::Throw); let method_key = name_key(scope, &method.decl); op_fn.set(scope, method_key.into(), method_fn.into()); } } deno_core_ops_obj.set(scope, key.into(), op_fn.into()); } } ``` -------------------------------- ### uv_prepare_init Source: https://docs.rs/deno_core/latest/deno_core/uv_compat/fn.uv_prepare_init.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Initializes a prepare handle. This function is unsafe and requires valid pointers to an initialized loop and a writable handle. ```APIDOC ## Function: uv_prepare_init ### Signature `pub unsafe extern "C" fn uv_prepare_init(loop_: *mut uv_loop_t, handle: *mut uv_prepare_t) -> c_int` ### Description Initializes the handle to be used with a libuv prepare watcher. ### Safety - `loop_` must be initialized by `uv_loop_init`. - `handle` must be a valid, writable pointer. ``` -------------------------------- ### uv_timer_start Source: https://docs.rs/deno_core/latest/deno_core/uv_compat/fn.uv_timer_start.html?search=std%3A%3Avec Starts the timer handle with the specified timeout and repeat interval. ```APIDOC ## Function: uv_timer_start ### Description Starts the timer handle. The timer will expire after the `timeout` period, and if `repeat` is non-zero, it will repeat at the given interval. ### Signature `pub unsafe extern "C" fn uv_timer_start(handle: *mut uv_timer_t, cb: uv_timer_cb, timeout: u64, repeat: u64) -> c_int` ### Parameters - **handle** (*mut uv_timer_t) - A pointer to a `uv_timer_t` handle. Must be initialized by `uv_timer_init`. - **cb** (uv_timer_cb) - The callback function to be invoked when the timer expires. - **timeout** (u64) - The initial delay before the timer expires in milliseconds. - **repeat** (u64) - The repeat interval in milliseconds. If 0, the timer will not repeat. ### Safety This function is unsafe. The `handle` must be a valid pointer to a `uv_timer_t` initialized by `uv_timer_init`. ``` -------------------------------- ### uv_timer_start Source: https://docs.rs/deno_core/latest/deno_core/uv_compat/fn.uv_timer_start.html?search=u32+-%3E+bool Starts the timer handle with the specified timeout and repeat interval. ```APIDOC ## uv_timer_start ### Signature `pub unsafe extern "C" fn uv_timer_start(handle: *mut uv_timer_t, cb: uv_timer_cb, timeout: u64, repeat: u64) -> c_int` ### Description Starts the timer handle. The callback will be triggered after the specified timeout, and if repeat is non-zero, it will repeat at the given interval. ### Safety `handle` must be a valid pointer to a `uv_timer_t` initialized by `uv_timer_init`. ### Parameters - **handle** (*mut uv_timer_t) - Required - A pointer to an initialized libuv timer handle. - **cb** (uv_timer_cb) - Required - The callback function to be executed when the timer expires. - **timeout** (u64) - Required - The initial delay in milliseconds. - **repeat** (u64) - Required - The repeat interval in milliseconds. ### Returns - **c_int** - Returns 0 on success, or a negative error code on failure. ``` -------------------------------- ### Module Loading Entrypoints Source: https://docs.rs/deno_core/latest/src/deno_core/modules/recursive_load.rs.html Methods to initiate the loading process for different types of modules. ```rust /// Starts a new asynchronous load of the module graph for given specifier. /// /// The module corresponding for the given `specifier` will be marked as // "the main module" (`import.meta.main` will return `true` for this module). pub(crate) async fn main( specifier: String, module_map_rc: Rc, ) -> Result { let mut load = Self::new(LoadInit::Main(specifier), module_map_rc); load.prepare().await?; Ok(load) } /// Starts a new asynchronous load of the module graph for given specifier. pub(crate) async fn side( specifier: String, module_map_rc: Rc, kind: SideModuleKind, code: Option, ) -> Result { let mut load = Self::new( LoadInit::Side { specifier, kind, code, }, module_map_rc, ); load.prepare().await?; Ok(load) } pub(crate) fn new_dynamic_import( specifier: String, referrer: String, requested_module_type: RequestedModuleType, phase: ModuleImportPhase, module_map_rc: Rc, resolved_specifier: Result, ) -> Self { Self::new_with_resolved_specifier( LoadInit::DynamicImport( specifier, referrer, requested_module_type, phase, ), module_map_rc, resolved_specifier, ) } ``` -------------------------------- ### uv_timer_start Source: https://docs.rs/deno_core/latest/deno_core/uv_compat/fn.uv_timer_start.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Starts the timer handle with the specified timeout and repeat interval. ```APIDOC ## Function: uv_timer_start ### Description Starts the timer handle. The callback will be triggered after the specified timeout, and if repeat is non-zero, it will repeat at the given interval. ### Signature `pub unsafe extern "C" fn uv_timer_start(handle: *mut uv_timer_t, cb: uv_timer_cb, timeout: u64, repeat: u64) -> c_int` ### Parameters - **handle** (*mut uv_timer_t) - A pointer to a uv_timer_t handle initialized by uv_timer_init. - **cb** (uv_timer_cb) - The callback function to be executed when the timer expires. - **timeout** (u64) - The initial delay in milliseconds. - **repeat** (u64) - The repeat interval in milliseconds. ### Safety This function is unsafe. The `handle` must be a valid pointer to a `uv_timer_t` initialized by `uv_timer_init`. ``` -------------------------------- ### uv_idle_start Source: https://docs.rs/deno_core/latest/deno_core/uv_compat/fn.uv_idle_start.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Starts the idle handle. The callback will be called once per loop iteration, right before the prepare handles. ```APIDOC ## Function: uv_idle_start ### Signature `pub unsafe extern "C" fn uv_idle_start(handle: *mut uv_idle_t, cb: uv_idle_cb) -> c_int` ### Description Starts the idle handle. The callback will be called once per loop iteration, right before the prepare handles. ### Safety `handle` must be a valid pointer to a `uv_idle_t` initialized by `uv_idle_init`. ### Parameters - **handle** (*mut uv_idle_t) - Required - A pointer to a valid `uv_idle_t` handle. - **cb** (uv_idle_cb) - Required - The callback function to be executed. ### Returns - **c_int** - Returns 0 on success, or an error code on failure. ``` -------------------------------- ### Format File Names Source: https://docs.rs/deno_core/latest/src/deno_core/error.rs.html?search=std%3A%3Avec Examples of formatting file paths with optional base URLs. ```rust assert_eq!(file_name.file_name, expected); let file_name = format_file_name("file:///foo/bar.ts", None); assert_eq!(file_name.file_name, "file:///foo/bar.ts"); let file_name = format_file_name( "file:///foo/bar.ts", Some(&Url::parse("file:///foo/").unwrap()), ); assert_eq!(file_name.file_name, "./bar.ts"); let file_name = format_file_name("file:///%E6%9D%B1%E4%BA%AC/%F0%9F%A6%95.ts", None); assert_eq!(file_name.file_name, "file:///東京/πŸ¦•.ts"); ``` -------------------------------- ### uv_timer_start Source: https://docs.rs/deno_core/latest/deno_core/uv_compat/fn.uv_timer_start.html Starts a timer handle with a specified timeout and repeat interval. ```APIDOC ## uv_timer_start ### Description Starts the timer handle. `timeout` and `repeat` are in milliseconds. If `timeout` is zero, the callback fires on the next event loop iteration. If `repeat` is non-zero, the timer will repeat after the timeout expires. ### Signature `pub unsafe extern "C" fn uv_timer_start(handle: *mut uv_timer_t, cb: uv_timer_cb, timeout: u64, repeat: u64) -> c_int` ### Parameters - **handle** (*mut uv_timer_t) - Required - A valid pointer to a uv_timer_t initialized by uv_timer_init. - **cb** (uv_timer_cb) - Required - The callback function to be invoked when the timer expires. - **timeout** (u64) - Required - The initial delay in milliseconds. - **repeat** (u64) - Required - The repeat interval in milliseconds. ### Safety `handle` must be a valid pointer to a `uv_timer_t` initialized by `uv_timer_init`. ``` -------------------------------- ### uv_pipe_connect Source: https://docs.rs/deno_core/latest/deno_core/uv_compat/fn.uv_pipe_connect.html?search= Starts an async connect to a Unix domain socket path. ```APIDOC ## uv_pipe_connect ### Description Starts an async connect to a Unix domain socket path. ### Signature `pub unsafe fn uv_pipe_connect(req: *mut uv_connect_t, pipe: *mut uv_pipe_t, path: &str, cb: Option) -> c_int` ### Safety `pipe` must be a valid pointer to an initialized `uv_pipe_t`. `req` must be a valid pointer to a `uv_connect_t`. ``` -------------------------------- ### uv_tcp_init Source: https://docs.rs/deno_core/latest/deno_core/uv_compat/fn.uv_tcp_init.html Initializes a TCP handle using a libuv loop. ```APIDOC ## uv_tcp_init ### Signature `pub unsafe fn uv_tcp_init(loop_: *mut uv_loop_t, tcp: *mut uv_tcp_t) -> c_int` ### Description Initializes a TCP handle. This function is part of the libuv compatibility layer. ### Safety - `loop_` must be initialized by `uv_loop_init`. - `tcp` must be a valid, writable pointer. ```