### Example Usage Source: https://docs.rs/rquickjs/latest/rquickjs/alloc/ffi/struct.CString.html A practical example demonstrating the creation of a CString and passing its raw pointer to an external C function. ```APIDOC ## Examples ⓘ``` use std::ffi::CString; use std::os::raw::c_char; extern "C" { fn my_printer(s: *const c_char); } // We are certain that our string doesn't have 0 bytes in the middle, // so we can .expect() let c_to_print = CString::new("Hello, world!").expect("CString::new failed"); unsafe { my_printer(c_to_print.as_ptr()); } ``` ``` -------------------------------- ### Option::as_slice Inverse Example Source: https://docs.rs/rquickjs/latest/rquickjs/qjs/type.JS_MarkFunc.html Demonstrates the inverse relationship between Option::as_slice and slice::first, showing how to get the first element of a slice from an Option. ```rust for i in [Some(1234_u16), None] { assert_eq!(i.as_ref(), i.as_slice().first()); } ``` -------------------------------- ### fmt Method Example Source: https://docs.rs/rquickjs/latest/rquickjs/alloc/fmt/trait.Debug.html Provides an example of manually implementing the `fmt` method for a struct using `debug_tuple`. ```APIDOC ##### §Examples ```rust use std::fmt; struct Position { longitude: f32, latitude: f32, } impl fmt::Debug for Position { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_tuple("") .field(&self.longitude) .field(&self.latitude) .finish() } } let position = Position { longitude: 1.987, latitude: 2.983 }; assert_eq!(format!("{position:?}"), "(1.987, 2.983)"); assert_eq!(format!("{position:#?}"), "( 1.987, 2.983, )"); ``` ``` -------------------------------- ### Example Usage of fmt::write Source: https://docs.rs/rquickjs/latest/rquickjs/alloc/fmt/struct.Error.html This example demonstrates how to use `std::fmt::write` and handle potential `fmt::Error`. ```APIDOC ## §Examples ```rust use std::fmt::{self, write}; let mut output = String::new(); if let Err(fmt::Error) = write(&mut output, format_args!("Hello {}!", "world")) { panic!("An error occurred"); } ``` ``` -------------------------------- ### LocalWake Example: Executor with Spawn and BlockOn Source: https://docs.rs/rquickjs/latest/rquickjs/alloc/task/trait.LocalWake.html A simplified executor example demonstrating spawn and block_on functions using LocalWake. Tasks are managed in a thread-local run queue. This example prioritizes simplicity over absolute correctness and would require interleaving I/O reactor calls in a real-world scenario. ```rust #![feature(local_waker)] use std::task::{LocalWake, ContextBuilder, LocalWaker, Waker}; use std::future::Future; use std::pin::Pin; use std::rc::Rc; use std::cell::RefCell; use std::collections::VecDeque thread_local! { // A queue containing all tasks ready to do progress static RUN_QUEUE: RefCell>> = RefCell::default(); } type BoxedFuture = Pin>>; struct Task(RefCell); impl LocalWake for Task { fn wake(self: Rc) { RUN_QUEUE.with_borrow_mut(|queue| { queue.push_back(self) }) } } fn spawn(future: F) where F: Future + 'static + Send + Sync { let task = RefCell::new(Box::pin(future)); RUN_QUEUE.with_borrow_mut(|queue| { queue.push_back(Rc::new(Task(task))); }); } fn block_on(future: F) where F: Future + 'static + Sync + Send { spawn(future); loop { let Some(task) = RUN_QUEUE.with_borrow_mut(|queue| queue.pop_front()) else { // we exit, since there are no more tasks remaining on the queue return; }; // cast the Rc into a `LocalWaker` let local_waker: LocalWaker = task.clone().into(); // Build the context using `ContextBuilder` let mut cx = ContextBuilder::from_waker(Waker::noop()) .local_waker(&local_waker) .build(); // Poll the task let _ = task.0 .borrow_mut() .as_mut() .poll(&mut cx); } } block_on(async { println!("hello world"); }); ``` -------------------------------- ### Panics when range is out of bounds (start > end) Source: https://docs.rs/rquickjs/latest/rquickjs/alloc/slice/fn.range.html This example demonstrates a panic scenario where the start of the range is greater than the end, which is invalid for slice indexing. ```rust #![feature(slice_range)] use std::slice; let _ = slice::range(2..1, ..3); ``` -------------------------------- ### BinaryHeap Basic Usage Source: https://docs.rs/rquickjs/latest/rquickjs/alloc/collections/struct.BinaryHeap.html Demonstrates the basic usage of BinaryHeap, including creating a new heap, pushing elements, peeking at the top element, checking the length, iterating, and popping elements in order. It also shows how to clear the heap and check if it's empty. ```APIDOC ## BinaryHeap Basic Usage ### Description Demonstrates the basic usage of `BinaryHeap`, including creating a new heap, pushing elements, peeking at the top element, checking the length, iterating, and popping elements in order. It also shows how to clear the heap and check if it's empty. ### Method `new()` ### Endpoint N/A (SDK Method) ### Parameters None ### Request Example ```rust use std::collections::BinaryHeap; let mut heap = BinaryHeap::new(); heap.push(1); heap.push(5); heap.push(2); assert_eq!(heap.peek(), Some(&5)); assert_eq!(heap.len(), 3); for x in &heap { println!("{x}"); } assert_eq!(heap.pop(), Some(5)); assert_eq!(heap.pop(), Some(2)); assert_eq!(heap.pop(), Some(1)); assert_eq!(heap.pop(), None); heap.clear(); assert!(heap.is_empty()); ``` ### Response N/A (SDK Method) ``` -------------------------------- ### Get Remainder of Split String Source: https://docs.rs/rquickjs/latest/rquickjs/alloc/str/struct.SplitAsciiWhitespace.html This example demonstrates how to use the `remainder` method to get the remaining part of the string after splitting. Note that this API is experimental and requires the `str_split_whitespace_remainder` feature flag. ```rust #![feature(str_split_whitespace_remainder)] let mut split = "Mary had a little lamb".split_ascii_whitespace(); assert_eq!(split.remainder(), Some("Mary had a little lamb")); split.next(); assert_eq!(split.remainder(), Some("had a little lamb")); split.by_ref().for_each(drop); assert_eq!(split.remainder(), None); ``` -------------------------------- ### Basic Usage of fmt::format Source: https://docs.rs/rquickjs/latest/rquickjs/alloc/fmt/fn.format.html Demonstrates how to use `std::fmt::format` with `format_args!` to create a formatted string. This is useful when you need to construct a string from formatted arguments. ```rust use std::fmt; let s = fmt::format(format_args!("Hello, {}!", "world")); assert_eq!(s, "Hello, world!"); ``` -------------------------------- ### ArrayWindows Usage Example Source: https://docs.rs/rquickjs/latest/rquickjs/alloc/slice/struct.ArrayWindows.html Demonstrates how to create and use an ArrayWindows iterator to get overlapping windows from a slice. ```APIDOC ## ArrayWindows Example This example shows how to use the `array_windows` method to create an iterator that yields overlapping slices of a fixed size. ### Method Signature ```rust slice.array_windows::() -> ArrayWindows<'_, T, N> ``` ### Example Usage ```rust let slice = [0, 1, 2, 3]; let mut iter = slice.array_windows::<2>(); assert_eq!(iter.next(), Some(&[0, 1])); assert_eq!(iter.next(), Some(&[1, 2])); assert_eq!(iter.next(), Some(&[2, 3])); assert_eq!(iter.next(), None); ``` ### Iterator Methods `ArrayWindows` implements the `Iterator` trait, providing standard iteration methods such as `next()`, `size_hint()`, `count()`, `nth()`, and `last()`. It also implements `DoubleEndedIterator`, allowing iteration from both ends using `next_back()` and `nth_back()`. Additionally, it implements `ExactSizeIterator` for precise length information. ``` -------------------------------- ### Get CString Pointer (Unsafe Example) Source: https://docs.rs/rquickjs/latest/rquickjs/alloc/ffi/struct.CString.html Demonstrates obtaining a raw pointer to a CString's internal buffer. This example shows a common pitfall leading to undefined behavior due to premature deallocation of the CString. ```rust use std::ffi::{CStr, CString}; // 💀 The meaning of this entire program is undefined, // 💀 and nothing about its behavior is guaranteed, // 💀 not even that its behavior resembles the code as written, // 💀 just because it contains a single instance of undefined behavior! // 🚨 creates a dangling pointer to a temporary `CString` // 🚨 that is deallocated at the end of the statement let ptr = CString::new("Hi!".to_uppercase()).unwrap().as_ptr(); // without undefined behavior, you would expect that `ptr` equals: dbg!(CStr::from_bytes_with_nul(b"HI!\0").unwrap()); // 🙏 Possibly the program behaved as expected so far, // 🙏 and this just shows `ptr` is now garbage..., but // 💀 this violates `CStr::from_ptr`'s safety contract // 💀 leading to a dereference of a dangling pointer, // 💀 which is immediate undefined behavior. // 💀 *BOOM*, you're dead, your entire program has no meaning. dbg!(unsafe { CStr::from_ptr(ptr) }); ``` -------------------------------- ### Vec Initialization with vec! Macro Source: https://docs.rs/rquickjs/latest/rquickjs/alloc/vec/struct.Vec.html Shows how to use the vec! macro for convenient initialization of a Vec with elements and how to compare it with a Vec created using Vec::from. ```rust let mut vec1 = vec![1, 2, 3]; vec1.push(4); let vec2 = Vec::from([1, 2, 3, 4]); assert_eq!(vec1, vec2); ``` -------------------------------- ### Vec Initialization and Basic Operations Source: https://docs.rs/rquickjs/latest/rquickjs/alloc/vec/struct.Vec.html Demonstrates the creation of a Vec, adding elements, checking its length, and removing elements. ```APIDOC ## Vec::new, Vec::push, Vec::len, Vec::pop ### Description Creates a new, empty vector and demonstrates adding and removing elements, along with checking the vector's length. ### Method Signature ```rust pub fn new(allocator: A) -> Vec pub fn push(&mut self, value: T) pub fn len(&self) -> usize pub fn pop(&mut self) -> Option ``` ### Example ```rust let mut vec = Vec::new(); vec.push(1); vec.push(2); assert_eq!(vec.len(), 2); assert_eq!(vec[0], 1); assert_eq!(vec.pop(), Some(2)); assert_eq!(vec.len(), 1); ``` ``` -------------------------------- ### Vec::capacity Example Source: https://docs.rs/rquickjs/latest/rquickjs/alloc/bstr/struct.ByteString.html Demonstrates how to get the total capacity of a vector. For zero-sized elements, the capacity is usize::MAX. ```rust let mut vec: Vec = Vec::with_capacity(10); vec.push(42); assert!(vec.capacity() >= 10); ``` ```rust #[derive(Clone)] struct ZeroSized; fn main() { assert_eq!(std::mem::size_of::(), 0); let v = vec![ZeroSized; 0]; assert_eq!(v.capacity(), usize::MAX); } ``` -------------------------------- ### Module::load Source: https://docs.rs/rquickjs/latest/rquickjs/struct.Module.html Loads a module from QuickJS bytecode. ```APIDOC ## load ### Description Load a module from quickjs bytecode. ### Method `pub unsafe fn load(ctx: Ctx<'js>, bytes: &[u8]) -> Result, Error>` ### Parameters - `ctx`: The JavaScript context. - `bytes`: A slice of bytes representing the QuickJS bytecode. ### Returns - `Result, Error>`: A Module instance loaded from bytecode. ### Safety User must ensure that bytes handed to this function contain valid bytecode. ``` -------------------------------- ### Get Function Value from ParamsAccessor Source: https://docs.rs/rquickjs/latest/rquickjs/function/struct.ParamsAccessor.html Returns the value of the function itself that was called. For example, in `obj.method()`, this would return the `method` value. ```rust pub fn function(&self) -> Value<'js> ``` -------------------------------- ### Runtime::new Source: https://docs.rs/rquickjs/latest/rquickjs/runtime/struct.Runtime.html Creates a new QuickJS runtime. This operation may fail if insufficient memory is available. ```APIDOC ## pub fn new() -> Result ### Description Create a new runtime. Will generally only fail if not enough memory was available. ### Features _If the`"rust-alloc"` feature is enabled the Rust’s global allocator will be used in favor of libc’s one._ ``` -------------------------------- ### BTreeMap upper_bound_mut Example Source: https://docs.rs/rquickjs/latest/rquickjs/alloc/collections/btree_map/struct.BTreeMap.html Demonstrates using `upper_bound_mut` with different bounds to get a mutable cursor. Requires the `btree_cursors` feature. ```rust #![feature(btree_cursors)] use std::collections::BTreeMap; use std::ops::Bound; let mut map = BTreeMap::from([ (1, "a"), (2, "b"), (3, "c"), (4, "d"), ]); let mut cursor = map.upper_bound_mut(Bound::Included(&3)); assert_eq!(cursor.peek_prev(), Some((&3, &mut "c"))); assert_eq!(cursor.peek_next(), Some((&4, &mut "d"))); let mut cursor = map.upper_bound_mut(Bound::Excluded(&3)); assert_eq!(cursor.peek_prev(), Some((&2, &mut "b"))); assert_eq!(cursor.peek_next(), Some((&3, &mut "c"))); let mut cursor = map.upper_bound_mut(Bound::Unbounded); assert_eq!(cursor.peek_prev(), Some((&4, &mut "d"))); assert_eq!(cursor.peek_next(), None); ``` -------------------------------- ### BTreeMap upper_bound Example Source: https://docs.rs/rquickjs/latest/rquickjs/alloc/collections/btree_map/struct.BTreeMap.html Demonstrates using `upper_bound` with different bounds to get an immutable cursor. Requires the `btree_cursors` feature. ```rust #![feature(btree_cursors)] use std::collections::BTreeMap; use std::ops::Bound; let map = BTreeMap::from([ (1, "a"), (2, "b"), (3, "c"), (4, "d"), ]); let cursor = map.upper_bound(Bound::Included(&3)); assert_eq!(cursor.peek_prev(), Some((&3, &"c"))); assert_eq!(cursor.peek_next(), Some((&4, &"d"))); let cursor = map.upper_bound(Bound::Excluded(&3)); assert_eq!(cursor.peek_prev(), Some((&2, &"b"))); assert_eq!(cursor.peek_next(), Some((&3, &"c"))); let cursor = map.upper_bound(Bound::Unbounded); assert_eq!(cursor.peek_prev(), Some((&4, &"d"))); assert_eq!(cursor.peek_next(), None); ``` -------------------------------- ### Initializing BinaryHeap from an Array Source: https://docs.rs/rquickjs/latest/rquickjs/alloc/collections/struct.BinaryHeap.html Shows how to initialize a `BinaryHeap` directly from an array of elements. ```APIDOC ## Initializing BinaryHeap from an Array ### Description Shows how to initialize a `BinaryHeap` directly from an array of elements. ### Method `from()` ### Endpoint N/A (SDK Method) ### Parameters - `array`: An array or slice of elements to initialize the heap with. ### Request Example ```rust use std::collections::BinaryHeap; let heap = BinaryHeap::from([1, 5, 2]); ``` ### Response N/A (SDK Method) ``` -------------------------------- ### BTreeMap lower_bound_mut Example Source: https://docs.rs/rquickjs/latest/rquickjs/alloc/collections/btree_map/struct.BTreeMap.html Demonstrates using `lower_bound_mut` with different bounds to get a mutable cursor. Requires the `btree_cursors` feature. ```rust #![feature(btree_cursors)] use std::collections::BTreeMap; use std::ops::Bound; let mut map = BTreeMap::from([ (1, "a"), (2, "b"), (3, "c"), (4, "d"), ]); let mut cursor = map.lower_bound_mut(Bound::Included(&2)); assert_eq!(cursor.peek_prev(), Some((&1, &mut "a"))); assert_eq!(cursor.peek_next(), Some((&2, &mut "b"))); let mut cursor = map.lower_bound_mut(Bound::Excluded(&2)); assert_eq!(cursor.peek_prev(), Some((&2, &mut "b"))); assert_eq!(cursor.peek_next(), Some((&3, &mut "c"))); let mut cursor = map.lower_bound_mut(Bound::Unbounded); assert_eq!(cursor.peek_prev(), None); assert_eq!(cursor.peek_next(), Some((&1, &mut "a"))); ``` -------------------------------- ### Basic Usage Examples Source: https://docs.rs/rquickjs/latest/rquickjs/alloc/fmt/trait.Binary.html Demonstrates the basic usage of the Binary trait with an `i32` for standard binary formatting and with the alternate flag '#'. ```APIDOC ## Examples Basic usage with `i32`: ```rust let x = 42; // 42 is '101010' in binary assert_eq!(format!("{x:b}"), "101010"); assert_eq!(format!("{x:#b}"), "0b101010"); assert_eq!(format!("{:b}", -16), "11111111111111111111111111110000"); ``` ``` -------------------------------- ### Iterating over a ByteStr slice Source: https://docs.rs/rquickjs/latest/rquickjs/alloc/bstr/struct.ByteStr.html Use `iter()` to get an iterator that yields immutable references to each item in the slice from start to end. ```rust let x = &[1, 2, 4]; let mut iterator = x.iter(); assert_eq!(iterator.next(), Some(&1)); assert_eq!(iterator.next(), Some(&2)); assert_eq!(iterator.next(), Some(&4)); assert_eq!(iterator.next(), None); ``` -------------------------------- ### BTreeMap::new and Basic Usage Source: https://docs.rs/rquickjs/latest/rquickjs/alloc/collections/struct.BTreeMap.html Demonstrates how to create a new BTreeMap, insert key-value pairs, check for key existence, remove entries, and retrieve values. ```APIDOC ## BTreeMap::new and Basic Usage ### Description Demonstrates how to create a new BTreeMap, insert key-value pairs, check for key existence, remove entries, and retrieve values. ### Method Signature `pub fn new() -> BTreeMap` ### Example ```rust use std::collections::BTreeMap; let mut movie_reviews = BTreeMap::new(); movie_reviews.insert("Office Space", "Deals with real issues in the workplace."); movie_reviews.insert("Pulp Fiction", "Masterpiece."); movie_reviews.insert("The Godfather", "Very enjoyable."); movie_reviews.insert("The Blues Brothers", "Eye lyked it a lot."); if !movie_reviews.contains_key("Les Misérables") { println!("We've got {} reviews, but Les Misérables ain't one.", movie_reviews.len()); } movie_reviews.remove("The Blues Brothers"); let to_find = ["Up!", "Office Space"]; for movie in &to_find { match movie_reviews.get(movie) { Some(review) => println!("{movie}: {review}"), None => println!("{movie} is unreviewed.") } } println!("Movie review: {}", movie_reviews["Office Space"]); for (movie, review) in &movie_reviews { println!("{movie}: \"{review}\""); } ``` ``` -------------------------------- ### Creating a BinaryHeap with capacity Source: https://docs.rs/rquickjs/latest/rquickjs/alloc/collections/struct.BinaryHeap.html Shows how to create an empty `BinaryHeap` with a specified initial capacity using `BinaryHeap::with_capacity()`. ```APIDOC ## Creating a BinaryHeap with capacity ### Description Shows how to create an empty `BinaryHeap` with a specified initial capacity using `BinaryHeap::with_capacity()`. ### Method `with_capacity()` ### Endpoint N/A (SDK Method) ### Parameters - `capacity`: The minimum number of elements the heap should be able to hold without reallocating. ### Request Example ```rust use std::collections::BinaryHeap; let mut heap = BinaryHeap::with_capacity(10); heap.push(4); ``` ### Response N/A (SDK Method) ``` -------------------------------- ### BTreeMap::upper_bound_mut Example Source: https://docs.rs/rquickjs/latest/rquickjs/alloc/collections/struct.BTreeMap.html Demonstrates the usage of `upper_bound_mut` with different bounds (Included, Excluded, Unbounded) to get mutable cursors for navigating a BTreeMap. ```APIDOC ## BTreeMap::upper_bound_mut Example ### Description Demonstrates the usage of `upper_bound_mut` with different bounds (Included, Excluded, Unbounded) to get mutable cursors for navigating a BTreeMap. ### Code ```rust #![feature(btree_cursors)] use std::collections::BTreeMap; use std::ops::Bound; let mut map = BTreeMap::from([ (1, "a"), (2, "b"), (3, "c"), (4, "d"), ]); let mut cursor = map.upper_bound_mut(Bound::Included(&3)); assert_eq!(cursor.peek_prev(), Some((&3, &mut "c"))); assert_eq!(cursor.peek_next(), Some((&4, &mut "d"))); let mut cursor = map.upper_bound_mut(Bound::Excluded(&3)); assert_eq!(cursor.peek_prev(), Some((&2, &mut "b"))); assert_eq!(cursor.peek_next(), Some((&3, &mut "c"))); let mut cursor = map.upper_bound_mut(Bound::Unbounded); assert_eq!(cursor.peek_prev(), Some((&4, &mut "d"))); assert_eq!(cursor.peek_next(), None); ``` ``` -------------------------------- ### Basic Usage Example Source: https://docs.rs/rquickjs/latest/rquickjs/alloc/fmt/trait.Pointer.html Demonstrates basic usage of the Pointer trait with a reference to an i32. ```APIDOC ## §Examples Basic usage with `&i32`: ```rust let x = &42; let address = format!("{x:p}"); // this produces something like '0x7f06092ac6d0' ``` ``` -------------------------------- ### BTreeSet upper_bound_mut cursor example Source: https://docs.rs/rquickjs/latest/rquickjs/alloc/collections/btree_set/struct.BTreeSet.html Demonstrates using `upper_bound_mut` with different `Bound` types to get a mutable cursor. Requires the `btree_cursors` feature. ```rust #![feature(btree_cursors)] use std::collections::BTreeSet; use std::ops::Bound; let mut set = BTreeSet::from([1, 2, 3, 4]); let mut cursor = set.upper_bound_mut(Bound::Included(&3)); assert_eq!(cursor.peek_prev(), Some(&3)); assert_eq!(cursor.peek_next(), Some(&4)); let mut cursor = set.upper_bound_mut(Bound::Excluded(&3)); assert_eq!(cursor.peek_prev(), Some(&2)); assert_eq!(cursor.peek_next(), Some(&3)); let mut cursor = set.upper_bound_mut(Bound::Unbounded); assert_eq!(cursor.peek_prev(), Some(&4)); assert_eq!(cursor.peek_next(), None); ``` -------------------------------- ### BTreeSet lower_bound_mut cursor example Source: https://docs.rs/rquickjs/latest/rquickjs/alloc/collections/btree_set/struct.BTreeSet.html Demonstrates using `lower_bound_mut` with different `Bound` types to get a mutable cursor. Requires the `btree_cursors` feature. ```rust #![feature(btree_cursors)] use std::collections::BTreeSet; use std::ops::Bound; let mut set = BTreeSet::from([1, 2, 3, 4]); let mut cursor = set.lower_bound_mut(Bound::Included(&2)); assert_eq!(cursor.peek_prev(), Some(&1)); assert_eq!(cursor.peek_next(), Some(&2)); let mut cursor = set.lower_bound_mut(Bound::Excluded(&2)); assert_eq!(cursor.peek_prev(), Some(&2)); assert_eq!(cursor.peek_next(), Some(&3)); let mut cursor = set.lower_bound_mut(Bound::Unbounded); assert_eq!(cursor.peek_prev(), None); assert_eq!(cursor.peek_next(), Some(&1)); ``` -------------------------------- ### Creating a Min-Heap Source: https://docs.rs/rquickjs/latest/rquickjs/alloc/collections/struct.BinaryHeap.html Explains how to configure `BinaryHeap` to function as a min-heap instead of the default max-heap, using `std::cmp::Reverse`. ```APIDOC ## Creating a Min-Heap ### Description Explains how to configure `BinaryHeap` to function as a min-heap instead of the default max-heap, using `std::cmp::Reverse`. ### Method `new()` and `push()` ### Endpoint N/A (SDK Method) ### Parameters None for `new()`. Elements pushed must be wrapped in `std::cmp::Reverse`. ### Request Example ```rust use std::collections::BinaryHeap; use std::cmp::Reverse; let mut heap = BinaryHeap::new(); heap.push(Reverse(1)); heap.push(Reverse(5)); heap.push(Reverse(2)); assert_eq!(heap.pop(), Some(Reverse(1))); assert_eq!(heap.pop(), Some(Reverse(2))); assert_eq!(heap.pop(), Some(Reverse(5))); assert_eq!(heap.pop(), None); ``` ### Response N/A (SDK Method) ``` -------------------------------- ### Using format_args! with Debug and Display Source: https://docs.rs/rquickjs/latest/rquickjs/alloc/fmt/struct.Arguments.html Demonstrates how to use the `format_args!` macro to create an Arguments instance and then format it using both Debug and Display traits. The output shows that both formatting methods produce the same interpolated string. ```rust let debug = format!("{:?}", format_args!("{} foo 2", 1)); let display = format!("{}", format_args!("{} foo 2", 1)); assert_eq!("1 foo 2", display); assert_eq!(display, debug); ``` -------------------------------- ### BTreeMap Usage Examples Source: https://docs.rs/rquickjs/latest/rquickjs/alloc/collections/btree_map/struct.BTreeMap.html Demonstrates common operations such as insertion, checking for keys, removal, retrieval, and iteration. ```APIDOC ## BTreeMap Usage Examples ### Description This section provides examples of how to use the `BTreeMap` data structure, including common operations like insertion, checking for key existence, removal, retrieval of values, and iterating over the map's contents. ### Methods Demonstrated - `new()` - `insert()` - `contains_key()` - `len()` - `remove()` - `get()` - `[]` (indexing for retrieval) - Iteration using `&movie_reviews` ### Request Example ```rust use std::collections::BTreeMap; // type inference lets us omit an explicit type signature (which // would be `BTreeMap<&str, &str>` in this example). let mut movie_reviews = BTreeMap::new(); // review some movies. movie_reviews.insert("Office Space", "Deals with real issues in the workplace."); movie_reviews.insert("Pulp Fiction", "Masterpiece."); movie_reviews.insert("The Godfather", "Very enjoyable."); movie_reviews.insert("The Blues Brothers", "Eye lyked it a lot."); // check for a specific one. if !movie_reviews.contains_key("Les Misérables") { println!("We've got {} reviews, but Les Misérables ain't one.", movie_reviews.len()); } // oops, this review has a lot of spelling mistakes, let's delete it. movie_reviews.remove("The Blues Brothers"); // look up the values associated with some keys. let to_find = ["Up!", "Office Space"]; for movie in &to_find { match movie_reviews.get(movie) { Some(review) => println!("{movie}: {review}"), None => println!("{movie} is unreviewed.") } } // Look up the value for a key (will panic if the key is not found). println!("Movie review: {}", movie_reviews["Office Space"]); // iterate over everything. for (movie, review) in &movie_reviews { println!("{movie}: \"{review}\""); } ``` ### Response (No specific response structure for examples, output is printed to console.) ``` -------------------------------- ### Get vector capacity Source: https://docs.rs/rquickjs/latest/rquickjs/prelude/struct.Rest.html Returns the total number of elements the vector can hold without reallocating. This example demonstrates checking the capacity after pushing an element. ```rust let mut vec: Vec = Vec::with_capacity(10); vec.push(42); assert!(vec.capacity() >= 10); ``` -------------------------------- ### Share Immutable Data Between Threads Source: https://docs.rs/rquickjs/latest/rquickjs/alloc/sync/struct.Arc.html Example of sharing immutable data (an integer) across multiple threads using Arc. Each thread gets its own clone of the Arc. ```rust use std::sync::Arc; use std::thread; let five = Arc::new(5); for _ in 0..10 { let five = Arc::clone(&five); thread::spawn(move || { println!("{five:?}"); }); } ``` -------------------------------- ### Implement Display for Foo with Formatter Options Source: https://docs.rs/rquickjs/latest/rquickjs/alloc/fmt/struct.Formatter.html This example shows how to implement the `fmt::Display` trait for a custom struct `Foo`. It demonstrates checking formatter options like `sign_aware_zero_pad` and `width`, although in this case, they are ignored for the final output. Use this when you need fine-grained control over how your type is displayed. ```rust use std::fmt; struct Foo(i32); impl fmt::Display for Foo { fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { assert!(formatter.sign_aware_zero_pad()); assert_eq!(formatter.width(), Some(4)); // We ignore the formatter's options. write!(formatter, "{}", self.0) } } assert_eq!(format!("{:04}", Foo(23)), "23"); ``` -------------------------------- ### BTreeSet upper_bound cursor example Source: https://docs.rs/rquickjs/latest/rquickjs/alloc/collections/btree_set/struct.BTreeSet.html Demonstrates using `upper_bound` with different `Bound` types to get a cursor pointing to a specific position. Requires the `btree_cursors` feature. ```rust #![feature(btree_cursors)] use std::collections::BTreeSet; use std::ops::Bound; let set = BTreeSet::from([1, 2, 3, 4]); let cursor = set.upper_bound(Bound::Included(&3)); assert_eq!(cursor.peek_prev(), Some(&3)); assert_eq!(cursor.peek_next(), Some(&4)); let cursor = set.upper_bound(Bound::Excluded(&3)); assert_eq!(cursor.peek_prev(), Some(&2)); assert_eq!(cursor.peek_next(), Some(&3)); let cursor = set.upper_bound(Bound::Unbounded); assert_eq!(cursor.peek_prev(), Some(&4)); assert_eq!(cursor.peek_next(), None); ``` -------------------------------- ### Basic BTreeSet Usage Source: https://docs.rs/rquickjs/latest/rquickjs/alloc/collections/struct.BTreeSet.html Demonstrates creating a BTreeSet, inserting elements, checking for containment, and removing elements. Iteration over the set is also shown. ```rust use std::collections::BTreeSet; // Type inference lets us omit an explicit type signature (which // would be `BTreeSet<&str>` in this example). let mut books = BTreeSet::new(); // Add some books. books.insert("A Dance With Dragons"); books.insert("To Kill a Mockingbird"); books.insert("The Odyssey"); books.insert("The Great Gatsby"); // Check for a specific one. if !books.contains("The Winds of Winter") { println!("We have {} books, but The Winds of Winter ain't one.", books.len()); } // Remove a book. books.remove("The Odyssey"); // Iterate over everything. for book in &books { println!("{book}"); } ``` -------------------------------- ### BTreeMap Entry API Examples Source: https://docs.rs/rquickjs/latest/rquickjs/alloc/collections/btree_map/struct.BTreeMap.html Demonstrates the use of the Entry API for conditional insertion, insertion with a function, updating existing entries, and modifying entries before insertion. ```rust use std::collections::BTreeMap; // type inference lets us omit an explicit type signature ( // which would be `BTreeMap<&str, u8>` in this example). let mut player_stats = BTreeMap::new(); fn random_stat_buff() -> u8 { // could actually return some random value here - let's just return // some fixed value for now 42 } // insert a key only if it doesn't already exist player_stats.entry("health").or_insert(100); // insert a key using a function that provides a new value only if it // doesn't already exist player_stats.entry("defence").or_insert_with(random_stat_buff); // update a key, guarding against the key possibly not being set let stat = player_stats.entry("attack").or_insert(100); *stat += random_stat_buff(); // modify an entry before an insert with in-place mutation player_stats.entry("mana").and_modify(|mana| *mana += 200).or_insert(100); ``` -------------------------------- ### Rc::get_mut_unchecked Example Source: https://docs.rs/rquickjs/latest/rquickjs/alloc/rc/struct.Rc.html Demonstrates using the unsafe `get_mut_unchecked` function to get a mutable reference without checks. This requires careful handling to avoid undefined behavior. ```rust #![feature(get_mut_unchecked)] use std::rc::Rc; let mut x = Rc::new(String::new()); unsafe { Rc::get_mut_unchecked(&mut x).push_str("foo") } assert_eq!(*x, "foo"); ``` -------------------------------- ### BTreeSet lower_bound cursor example Source: https://docs.rs/rquickjs/latest/rquickjs/alloc/collections/btree_set/struct.BTreeSet.html Demonstrates using `lower_bound` with different `Bound` types to get a cursor pointing to a specific position in the set. Requires the `btree_cursors` feature. ```rust #![feature(btree_cursors)] use std::collections::BTreeSet; use std::ops::Bound; let set = BTreeSet::from([1, 2, 3, 4]); let cursor = set.lower_bound(Bound::Included(&2)); assert_eq!(cursor.peek_prev(), Some(&1)); assert_eq!(cursor.peek_next(), Some(&2)); let cursor = set.lower_bound(Bound::Excluded(&2)); assert_eq!(cursor.peek_prev(), Some(&2)); assert_eq!(cursor.peek_next(), Some(&3)); let cursor = set.lower_bound(Bound::Unbounded); assert_eq!(cursor.peek_prev(), None); assert_eq!(cursor.peek_next(), Some(&1)); ``` -------------------------------- ### Basic Usage of rquickjs::alloc::fmt::write Source: https://docs.rs/rquickjs/latest/rquickjs/alloc/fmt/fn.write.html Demonstrates basic usage of `rquickjs::alloc::fmt::write` to format a string into a `String` output. Ensure the `expect` call handles potential errors during writing. ```rust use std::fmt; let mut output = String::new(); fmt::write(&mut output, format_args!("Hello {}!", "world")) .expect("Error occurred while trying to write in String"); assert_eq!(output, "Hello world!"); ``` -------------------------------- ### RSplit Remainder Example Source: https://docs.rs/rquickjs/latest/rquickjs/alloc/str/struct.RSplit.html Demonstrates how to get the remainder of the split string using the `remainder()` method. This API is nightly-only and requires the `str_split_remainder` feature. The remainder is `None` once the iterator is exhausted. ```rust #![feature(str_split_remainder)] let mut split = "Mary had a little lamb".rsplit(' '); assert_eq!(split.remainder(), Some("Mary had a little lamb")); split.next(); assert_eq!(split.remainder(), Some("Mary had a little")); split.by_ref().for_each(drop); assert_eq!(split.remainder(), None); ``` -------------------------------- ### Creating an empty BinaryHeap Source: https://docs.rs/rquickjs/latest/rquickjs/alloc/collections/struct.BinaryHeap.html Demonstrates how to create an empty `BinaryHeap` using `BinaryHeap::new()`. ```APIDOC ## Creating an empty BinaryHeap ### Description Demonstrates how to create an empty `BinaryHeap` using `BinaryHeap::new()`. ### Method `new()` ### Endpoint N/A (SDK Method) ### Parameters None ### Request Example ```rust use std::collections::BinaryHeap; let mut heap = BinaryHeap::new(); heap.push(4); ``` ### Response N/A (SDK Method) ``` -------------------------------- ### Rc::get_mut Example Source: https://docs.rs/rquickjs/latest/rquickjs/alloc/rc/struct.Rc.html Shows how to safely get a mutable reference to the inner value of an Rc if it's the only strong reference. If other Rc or Weak pointers exist, it returns None. ```rust use std::rc::Rc; let mut x = Rc::new(3); *Rc::get_mut(&mut x).unwrap() = 4; assert_eq!(*x, 4); let _y = Rc::clone(&x); assert!(Rc::get_mut(&mut x).is_none()); ``` -------------------------------- ### Creating FromVecWithNulError Source: https://docs.rs/rquickjs/latest/rquickjs/alloc/ffi/c_str/struct.FromVecWithNulError.html This example demonstrates how to obtain a `FromVecWithNulError` by attempting to create a `CString` from a vector with an incorrectly placed nul byte. It shows how to use `unwrap_err()` to get the error value. ```rust use std::ffi::{CString, FromVecWithNulError}; let _: FromVecWithNulError = CString::from_vec_with_nul(b"f\0oo".to_vec()).unwrap_err(); ``` -------------------------------- ### Module::load Source: https://docs.rs/rquickjs/latest/rquickjs/module/struct.Module.html Loads a JavaScript module from QuickJS bytecode. ```APIDOC ## Module::load ### Description Load a module from quickjs bytecode. ### Safety User must ensure that bytes handed to this function contain valid bytecode. ### Signature ```rust pub unsafe fn load(ctx: Ctx<'js>, bytes: &[u8]) -> Result, Error> ``` ``` -------------------------------- ### Create RChunksExactMut Iterator Source: https://docs.rs/rquickjs/latest/rquickjs/alloc/slice/struct.RChunksExactMut.html This example demonstrates how to create an RChunksExactMut iterator from a mutable slice. The iterator yields mutable slices of size 2, starting from the end of the original slice. ```rust let mut slice = ['l', 'o', 'r', 'e', 'm']; let iter = slice.rchunks_exact_mut(2); ``` -------------------------------- ### Get Mutable Pointer Range of ByteString Source: https://docs.rs/rquickjs/latest/rquickjs/alloc/bstr/struct.ByteString.html Retrieve the start and end mutable raw pointers of a slice. The end pointer is one past the last element. Useful for C-style interfaces. ```rust let mut a = [1, 2, 3]; let x = &mut a[1] as *mut _; let y = &mut 5 as *mut _; let ptr_range = a.as_mut_ptr_range(); // Example usage: checking if a mutable pointer is within the range // Note: This is a conceptual example, direct pointer comparison might be complex. // The primary use is for FFI or low-level memory manipulation. ``` -------------------------------- ### Basic String Formatting Source: https://docs.rs/rquickjs/latest/rquickjs/alloc/macro.format.html Demonstrates the simplest usage of format! with a literal string. ```rust format!("test"); // => "test" ``` -------------------------------- ### Strip prefix from ByteStr Source: https://docs.rs/rquickjs/latest/rquickjs/alloc/bstr/struct.ByteStr.html Use `strip_prefix` to get a subslice with a prefix removed. Returns `None` if the slice does not start with the specified prefix. Handles empty prefixes and prefixes equal to the slice. ```rust let v = &[10, 40, 30]; assert_eq!(v.strip_prefix(&[10]), Some(&[40, 30][..])); assert_eq!(v.strip_prefix(&[10, 40]), Some(&[30][..])); assert_eq!(v.strip_prefix(&[10, 40, 30]), Some(&[][..])); assert_eq!(v.strip_prefix(&[50]), None); assert_eq!(v.strip_prefix(&[10, 50]), None); ``` ```rust let prefix : &str = "he"; assert_eq!(b"hello".strip_prefix(prefix.as_bytes()), Some(b"llo".as_ref())); ``` -------------------------------- ### Get Remainder of SplitInclusive Iterator Source: https://docs.rs/rquickjs/latest/rquickjs/alloc/str/struct.SplitInclusive.html This example demonstrates how to use the `remainder` method on a `SplitInclusive` iterator. It shows how to access the remaining part of the string after each `next()` call. Note that this API is currently nightly-only. ```rust #![feature(str_split_inclusive_remainder)] let mut split = "Mary had a little lamb".split_inclusive(' '); assert_eq!(split.remainder(), Some("Mary had a little lamb")); split.next(); assert_eq!(split.remainder(), Some("had a little lamb")); split.by_ref().for_each(drop); assert_eq!(split.remainder(), None); ``` -------------------------------- ### Repeat Layout Example Source: https://docs.rs/rquickjs/latest/rquickjs/alloc/alloc/struct.Layout.html Demonstrates creating a layout for `n` instances of a given layout, including necessary padding for alignment. Useful for arrays of structs where each element needs its own alignment. ```rust #![feature(alloc_layout_extra)] use std::alloc::Layout; // All rust types have a size that's a multiple of their alignment. let normal = Layout::from_size_align(12, 4).unwrap(); let repeated = normal.repeat(3).unwrap(); assert_eq!(repeated, (Layout::from_size_align(36, 4).unwrap(), 12)); // But you can manually make layouts which don't meet that rule. let padding_needed = Layout::from_size_align(6, 4).unwrap(); let repeated = padding_needed.repeat(3).unwrap(); assert_eq!(repeated, (Layout::from_size_align(24, 4).unwrap(), 8)); ``` -------------------------------- ### Vec Initialization Macros (`vec!`) Source: https://docs.rs/rquickjs/latest/rquickjs/alloc/vec/struct.Vec.html Illustrates the use of the `vec!` macro for convenient vector initialization. ```APIDOC ## vec! macro ### Description Provides a convenient syntax for initializing vectors, including initializing with repeated values. ### Usage ```rust // Initialize with elements let mut vec1 = vec![1, 2, 3]; vec1.push(4); // Initialize from an array let vec2 = Vec::from([1, 2, 3, 4]); assert_eq!(vec1, vec2); // Initialize with a repeated value let vec = vec![0; 5]; assert_eq!(vec, [0, 0, 0, 0, 0]); ``` ``` -------------------------------- ### Get Remainder of Split String Source: https://docs.rs/rquickjs/latest/rquickjs/alloc/str/struct.RSplitTerminator.html This example demonstrates how to retrieve the remaining part of the string after splitting using `rsplit_terminator`. It shows that the full string is initially returned, and `None` is returned when the iterator is exhausted. ```rust #![feature(str_split_remainder)] let mut split = "A..B..".rsplit_terminator('.'); assert_eq!(split.remainder(), Some("A..B..")); split.next(); assert_eq!(split.remainder(), Some("A..B")); split.by_ref().for_each(drop); assert_eq!(split.remainder(), None); ``` -------------------------------- ### RSplitN Remainder Example Source: https://docs.rs/rquickjs/latest/rquickjs/alloc/str/struct.RSplitN.html Demonstrates how to use the `remainder` method of RSplitN to get the remaining part of the string after splits. This API is experimental and requires the `str_split_remainder` feature. It returns `None` if the iterator is exhausted. ```rust #![feature(str_split_remainder)] let mut split = "Mary had a little lamb".rsplitn(3, ' '); assert_eq!(split.remainder(), Some("Mary had a little lamb")); split.next(); assert_eq!(split.remainder(), Some("Mary had a little")); split.by_ref().for_each(drop); assert_eq!(split.remainder(), None); ``` -------------------------------- ### Creating and Using ThinBox Source: https://docs.rs/rquickjs/latest/rquickjs/alloc/boxed/struct.ThinBox.html Demonstrates creating a ThinBox for a primitive type and a dynamically sized slice. It also verifies that the size of the ThinBox is equivalent to the size of a raw pointer. ```rust #![feature(thin_box)] use std::boxed::ThinBox; let five = ThinBox::new(5); let thin_slice = ThinBox::<[i32]>::new_unsize([1, 2, 3, 4]); let size_of_ptr = size_of::<*const ()>(); assert_eq!(size_of_ptr, size_of_val(&five)); assert_eq!(size_of_ptr, size_of_val(&thin_slice)); ``` -------------------------------- ### Creating an empty BinaryHeap with a specific allocator Source: https://docs.rs/rquickjs/latest/rquickjs/alloc/collections/struct.BinaryHeap.html Demonstrates how to create an empty `BinaryHeap` using a specific allocator, available as a nightly-only experimental API. ```APIDOC ## Creating an empty BinaryHeap with a specific allocator ### Description Demonstrates how to create an empty `BinaryHeap` using a specific allocator, available as a nightly-only experimental API. ### Method `new_in()` ### Endpoint N/A (SDK Method) ### Parameters - `alloc`: The allocator to use for the heap. ### Request Example ```rust #![feature(allocator_api)] use std::alloc::System; use std::collections::BinaryHeap; let mut heap = BinaryHeap::new_in(System); heap.push(4); ``` ### Response N/A (SDK Method) ``` -------------------------------- ### Get CString Pointer (Safe Example) Source: https://docs.rs/rquickjs/latest/rquickjs/alloc/ffi/struct.CString.html Illustrates the correct way to obtain and use a pointer from a CString by ensuring the CString remains in scope for the pointer's lifetime. This avoids undefined behavior. ```rust use std::ffi::{CStr, CString}; let c_str = CString::new("Hi!".to_uppercase()).unwrap(); let ptr = c_str.as_ptr(); assert_eq!(unsafe { CStr::from_ptr(ptr) }, c"HI!"); ``` -------------------------------- ### Get Mutable Cursor Before Smallest Key in Map Source: https://docs.rs/rquickjs/latest/rquickjs/alloc/collections/struct.BTreeMap.html Use `lower_bound_mut` with `Bound::Unbounded` to obtain a mutable cursor positioned before the smallest key in the map. This allows for modifications starting from the first element. ```rust #![feature(btree_cursors)] use std::collections::BTreeMap; use std::ops::Bound; let mut map = BTreeMap::from([ (1, "a"), (2, "b"), (3, "c"), (4, "d"), ]); let mut cursor = map.lower_bound_mut(Bound::Unbounded); assert_eq!(cursor.peek_prev(), None); assert_eq!(cursor.peek_next(), Some((&1, &mut "a"))); ``` -------------------------------- ### Example: Convert Cow<'_, str> to Box (Borrowed) Source: https://docs.rs/rquickjs/latest/rquickjs/alloc/borrow/enum.Cow.html Demonstrates converting a `Cow::Borrowed` string into a `Box`, which involves heap allocation and copying. ```rust use std::borrow::Cow; let unboxed = Cow::Borrowed("hello"); let boxed: Box = Box::from(unboxed); println!("{boxed}"); ``` -------------------------------- ### String Pattern Matching Examples Source: https://docs.rs/rquickjs/latest/rquickjs/alloc/str/pattern/index.html Demonstrates various ways to use the `find` method with different pattern types: &str, char, array of chars, slice of chars, and a closure. This API is unstable but available on stable `str`. ```rust let s = "Can you find a needle in a haystack?"; // &str pattern assert_eq!(s.find("you"), Some(4)); // char pattern assert_eq!(s.find('n'), Some(2)); // array of chars pattern assert_eq!(s.find(&['a', 'e', 'i', 'o', 'u']), Some(1)); // slice of chars pattern assert_eq!(s.find(&['a', 'e', 'i', 'o', 'u'][..]), Some(1)); // closure pattern assert_eq!(s.find(|c: char| c.is_ascii_punctuation()), Some(35)); ``` -------------------------------- ### Iterating over slice chunks from the end Source: https://docs.rs/rquickjs/latest/rquickjs/alloc/bstr/struct.ByteStr.html Use `rchunks` to get an iterator over mutable slices of a specified size, starting from the end. The last chunk may be smaller if the slice length is not divisible by `chunk_size`. ```rust let slice = ['l', 'o', 'r', 'e', 'm']; let mut iter = slice.rchunks(2); assert_eq!(iter.next().unwrap(), &['e', 'm']); assert_eq!(iter.next().unwrap(), &['o', 'r']); assert_eq!(iter.next().unwrap(), &['l']); assert!(iter.next().is_none()); ```