### Rust String Pattern Matching Examples Source: https://docs.rs/starknet/latest/starknet/core/types/alloc/str/pattern/index Demonstrates various ways to use the `Pattern` trait for searching within strings in Rust. It shows examples using string slices, characters, character arrays, and closures as patterns. This API is currently experimental but exposed via stable `str` methods. ```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)); ``` -------------------------------- ### Rust Result expect() Example for Panic and Recommended Usage Source: https://docs.rs/starknet/latest/starknet/core/types/alloc/fmt/type Illustrates the `expect()` method for retrieving the Ok value or panicking with a custom message if the Result is Err. Includes examples of both panicking behavior and recommended usage for clarity in error reporting. ```Rust let x: Result = Err("emergency failure"); x.expect("Testing expect"); // panics with `Testing expect: emergency failure` ``` ```Rust let path = std::env::var("IMPORTANT_PATH") .expect("env variable `IMPORTANT_PATH` should be set by `wrapper_script.sh`"); ``` -------------------------------- ### Dijkstra's Shortest Path Algorithm with BinaryHeap in Rust Source: https://docs.rs/starknet/latest/starknet/core/types/alloc/collections/binary_heap/index Implements Dijkstra's shortest path algorithm using Rust's `BinaryHeap` as a min-priority queue. It defines a `State` struct to hold cost and position, implementing `Ord` and `PartialOrd` for min-heap behavior. The `shortest_path` function takes an adjacency list, start, and goal node, returning the shortest distance or `None` if unreachable. It includes a `main` function with a sample graph and assertions. ```rust use std::cmp::Ordering; use std::collections::BinaryHeap; #[derive(Copy, Clone, Eq, PartialEq)] struct State { cost: usize, position: usize, } // The priority queue depends on `Ord`. // Explicitly implement the trait so the queue becomes a min-heap // instead of a max-heap. impl Ord for State { fn cmp(&self, other: &Self) -> Ordering { // Notice that we flip the ordering on costs. // In case of a tie we compare positions - this step is necessary // to make implementations of `PartialEq` and `Ord` consistent. other.cost.cmp(&self.cost) .then_with(|| self.position.cmp(&other.position)) } } // `PartialOrd` needs to be implemented as well. impl PartialOrd for State { fn partial_cmp(&self, other: &Self) -> Option { Some(self.cmp(other)) } } // Each node is represented as a `usize`, for a shorter implementation. struct Edge { node: usize, cost: usize, } // Dijkstra's shortest path algorithm. // Start at `start` and use `dist` to track the current shortest distance // to each node. This implementation isn't memory-efficient as it may leave duplicate // nodes in the queue. It also uses `usize::MAX` as a sentinel value, // for a simpler implementation. fn shortest_path(adj_list: &Vec>, start: usize, goal: usize) -> Option { // dist[node] = current shortest distance from `start` to `node` let mut dist: Vec<_> = (0..adj_list.len()).map(|_| usize::MAX).collect(); let mut heap = BinaryHeap::new(); // We're at `start`, with a zero cost dist[start] = 0; heap.push(State { cost: 0, position: start }); // Examine the frontier with lower cost nodes first (min-heap) while let Some(State { cost, position }) = heap.pop() { // Alternatively we could have continued to find all shortest paths if position == goal { return Some(cost); } // Important as we may have already found a better way if cost > dist[position] { continue; } // For each node we can reach, see if we can find a way with // a lower cost going through this node for edge in &adj_list[position] { let next = State { cost: cost + edge.cost, position: edge.node }; // If so, add it to the frontier and continue if next.cost < dist[next.position] { heap.push(next); // Relaxation, we have now found a better way dist[next.position] = next.cost; } } } // Goal not reachable None } fn main() { // This is the directed graph we're going to use. // The node numbers correspond to the different states, // and the edge weights symbolize the cost of moving // from one node to another. // Note that the edges are one-way. // // 7 // +-----------------+ // | | // v 1 2 | 2 // 0 -----> 1 -----> 3 ---> 4 // | ^ ^ ^ // | | 1 | | // | | | 3 | 1 // +------> 2 -------+ | // 10 | | // +---------------+ // // The graph is represented as an adjacency list where each index, // corresponding to a node value, has a list of outgoing edges. // Chosen for its efficiency. let graph = vec![ // Node 0 vec![Edge { node: 2, cost: 10 }, Edge { node: 1, cost: 1 }], // Node 1 vec![Edge { node: 3, cost: 2 }], // Node 2 vec![Edge { node: 1, cost: 1 }, Edge { node: 3, cost: 3 }, Edge { node: 4, cost: 1 }], // Node 3 vec![Edge { node: 0, cost: 7 }, Edge { node: 4, cost: 2 }], // Node 4 vec![]]; assert_eq!(shortest_path(&graph, 0, 1), Some(1)); assert_eq!(shortest_path(&graph, 0, 3), Some(3)); assert_eq!(shortest_path(&graph, 3, 0), Some(7)); assert_eq!(shortest_path(&graph, 0, 4), Some(5)); assert_eq!(shortest_path(&graph, 4, 0), None); } ``` -------------------------------- ### Get URL Path in Rust Source: https://docs.rs/starknet/latest/starknet/providers/struct Retrieves the path component of a URL as a percent-encoded ASCII string. Handles different URL types, including those that cannot be a base. The path always starts with a '/' for valid base URLs. ```rust use url::{Url, ParseError}; let url = Url::parse("https://example.com/api/versions?page=2")?; assert_eq!(url.path(), "/api/versions"); let url = Url::parse("https://example.com")?; assert_eq!(url.path(), "/"); let url = Url::parse("https://example.com/countries/việt nam")?; assert_eq!(url.path(), "/countries/vi%E1%BB%87t%20nam"); ``` -------------------------------- ### Rust Result unwrap() Example for Ok and Err Source: https://docs.rs/starknet/latest/starknet/core/types/alloc/fmt/type Demonstrates the `unwrap()` method to get the Ok value or panic if the Result is Err. This method is generally discouraged in favor of safer error handling patterns like pattern matching or `unwrap_or` variants. ```Rust let x: Result = Ok(2); assert_eq!(x.unwrap(), 2); ``` ```Rust let x: Result = Err("emergency failure"); x.unwrap(); // panics with `emergency failure` ``` -------------------------------- ### Example Usage of fmt::Error in Rust Source: https://docs.rs/starknet/latest/starknet/core/types/alloc/fmt/struct Demonstrates how to handle potential formatting errors using `std::fmt::write`. The example shows initializing an output string and using an `if let Err` pattern to catch and panic if the `write` operation returns a `fmt::Error`, indicating a failure in formatting the message into the string. ```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"); } ``` -------------------------------- ### Rust VecDeque Resize Example Source: https://docs.rs/starknet/latest/starknet/core/types/alloc/collections/struct Demonstrates the resize method for VecDeque, showing how to truncate the deque or extend it by appending copies of a given value. ```rust use std::collections::VecDeque; let mut buf = VecDeque::new(); buf.push_back(5); buf.push_back(10); buf.push_back(15); assert_eq!(buf, [5, 10, 15]); buf.resize(2, 0); assert_eq!(buf, [5, 10]); buf.resize(5, 20); assert_eq!(buf, [5, 10, 20, 20, 20]); ``` -------------------------------- ### VecDeque Rotation Example Source: https://docs.rs/starknet/latest/starknet/core/types/alloc/collections/struct Demonstrates the usage of the `rotate_right` method on a VecDeque. ```APIDOC ## VecDeque Rotation ### Description Demonstrates how to rotate elements within a `VecDeque` to the right. ### Method `rotate_right(mid: usize)` ### Endpoint N/A (In-memory data structure) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```rust use std::collections::VecDeque; let mut buf: VecDeque<_> = (0..10).collect(); buf.rotate_right(3); assert_eq!(buf, [7, 8, 9, 0, 1, 2, 3, 4, 5, 6]); for i in 1..10 { assert_eq!(0, buf[i * 3 % 10]); buf.rotate_right(3); } assert_eq!(buf, [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]); ``` ### Response #### Success Response (200) N/A (In-memory operation) #### Response Example N/A ``` -------------------------------- ### Get Element by Index in VecDeque (Rust) Source: https://docs.rs/starknet/latest/starknet/core/types/alloc/collections/struct Provides an example of accessing an element at a specific index in a VecDeque using the `get` method. It returns an `Option` which is `Some` if the index is valid, and `None` otherwise. ```rust use std::collections::VecDeque; let mut buf = VecDeque::new(); buf.push_back(3); buf.push_back(4); buf.push_back(5); buf.push_back(6); assert_eq!(buf.get(1), Some(&4)); ``` -------------------------------- ### SingleOwnerAccount Initialization and Configuration Source: https://docs.rs/starknet/latest/starknet/accounts/struct Details on how to create and configure a SingleOwnerAccount instance, including setting the provider, signer, address, chain ID, and execution encoding. ```APIDOC ## POST /accounts/singleowner ### Description Creates a new `SingleOwnerAccount` controlled by a single signer. This account type is designed for Starknet contracts with a single ECDSA signer on the STARK curve. ### Method POST ### Endpoint `/accounts/singleowner` ### Parameters #### Request Body - **provider** (Provider) - Required - A `Provider` implementation that provides access to the Starknet network. - **signer** (Signer) - Required - A `Signer` implementation that can generate valid signatures for this account. - **address** (Felt) - Required - Account contract address. - **chain_id** (Felt) - Required - Network chain ID. - **encoding** (ExecutionEncoding) - Required - How `__execute__` calldata should be encoded. ### Request Example ```json { "provider": "", "signer": "", "address": "0x12345...", "chain_id": "0x1", "encoding": "ExecutionEncoding::V1" } ``` ### Response #### Success Response (200) - **account** (SingleOwnerAccount) - The newly created `SingleOwnerAccount` instance. #### Response Example ```json { "account": "" } ``` ## PUT /accounts/singleowner/{address}/block_id ### Description Sets a new block ID for the `SingleOwnerAccount`. This block ID will be used for subsequent queries and fee estimations. ### Method PUT ### Endpoint `/accounts/singleowner/{address}/block_id` ### Parameters #### Path Parameters - **address** (Felt) - Required - The address of the account. #### Request Body - **block_id** (BlockId) - Required - The new block ID to set. ### Request Example ```json { "block_id": "latest" } ``` ### Response #### Success Response (200) - **message** (string) - Confirmation that the block ID has been updated. #### Response Example ```json { "message": "Block ID updated successfully." } ``` ``` -------------------------------- ### Rust format! Macro Examples Source: https://docs.rs/starknet/latest/starknet/core/types/alloc/fmt/index Demonstrates various ways to use the `format!` macro in Rust for string interpolation and formatting. It covers basic string output, variable insertion, debugging output, named parameters, and advanced formatting like zero-padding and pretty-printing. ```Rust format!("Hello"); // => "Hello" format!("Hello, {}!", "world"); // => "Hello, world!" format!("The number is {}", 1); // => "The number is 1" format!("{:?}", (3, 4)); // => "(3, 4)" format!("{value}", value=4); // => "4" let people = "Rustaceans"; format!("Hello {people}!"); // => "Hello Rustaceans!" format!("{} {}", 1, 2); // => "1 2" format!("{:04}", 42); // => "0042" with leading zeros format!("{:#?}", (100, 200)); // => "( // 100, // 200, // )" ``` -------------------------------- ### Rust Result iter() Example Source: https://docs.rs/starknet/latest/starknet/core/types/alloc/fmt/type Demonstrates using the `iter()` method on a Result to get an iterator over the contained value. This is useful for iterating when the Result is Ok, and getting an empty iterator when it's Err. ```Rust let x: Result = Ok(7); assert_eq!(x.iter().next(), Some(&7)); let x: Result = Err("nothing!"); assert_eq!(x.iter().next(), None); ``` -------------------------------- ### Rust Basic Formatting with Parameters Source: https://docs.rs/starknet/latest/starknet/core/types/alloc/fmt/index Demonstrates basic formatting parameters like 'e' for exponent and 'p' for pointer addresses in Rust's print macros. It shows how to apply these format specifiers to variables. ```rust let a = 5; let b = &a; println!("{a:e} {b:p}"); // => 5e0 0x7ffe37b7273c ``` -------------------------------- ### Rust Result iter_mut() Example Source: https://docs.rs/starknet/latest/starknet/core/types/alloc/fmt/type Shows how to use `iter_mut()` to get a mutable iterator for modifying the contained value if the Result is Ok. This allows in-place mutation of the Ok value. ```Rust let mut x: Result = Ok(7); match x.iter_mut().next() { Some(v) => *v = 40, None => {}, } assert_eq!(x, Ok(40)); let mut x: Result = Err("nothing!"); assert_eq!(x.iter_mut().next(), None); ``` -------------------------------- ### Create Empty LinkedList - Rust Source: https://docs.rs/starknet/latest/starknet/core/types/alloc/collections/linked_list/struct Shows how to create a new, empty `LinkedList`. This is the standard way to start building a list when the elements are not known beforehand. ```Rust use std::collections::LinkedList; let list: LinkedList = LinkedList::new(); ``` -------------------------------- ### Peek Mutable Reference - Rust Vec Example Source: https://docs.rs/starknet/latest/starknet/core/types/alloc/bstr/struct Demonstrates the use of peek_mut() on a Vec (and by extension, ByteString) to get a mutable reference to the last element. This is a nightly-only experimental API. ```rust #![feature(vec_peek_mut)] let mut vec = Vec::new(); assert!(vec.peek_mut().is_none()); vec.push(1); vec.push(5); vec.push(2); assert_eq!(vec.last(), Some(&2)); if let Some(mut val) = vec.peek_mut() { *val = 0; } assert_eq!(vec.last(), Some(&0)); ``` -------------------------------- ### Rust format! Named Parameters Examples Source: https://docs.rs/starknet/latest/starknet/core/types/alloc/fmt/index Shows the usage of named parameters in Rust's `format!` macro, including direct assignment and referencing variables from the current scope. It also demonstrates how to use named parameters when defining function return strings. ```Rust format!("{argument}", argument = "test"); // => "test" format!("{name} {}", 1, name = 2); // => "2 1" format!("{a} {c} {b}", a="a", b='b', c=3); // => "a 3 b" let argument = 2 + 2; format!("{argument}"); // => "4" fn make_string(a: u32, b: &str) -> String { format!("{b} {a}") } make_string(927, "label"); // => "label 927" ``` -------------------------------- ### LocalWallet Methods Source: https://docs.rs/starknet/latest/starknet/signers/struct Methods available for constructing and interacting with LocalWallet. ```APIDOC ## LocalWallet Methods ### `from_signing_key` #### Description Constructs `LocalWallet` from a `SigningKey`. #### Method `pub fn from_signing_key(key: SigningKey) -> LocalWallet` #### Parameters - **key** (SigningKey) - Required - The signing key to initialize the wallet with. #### Return Value A new `LocalWallet` instance. ### `from` #### Description Converts a `SigningKey` into a `LocalWallet`. #### Method `impl From for LocalWallet` #### Parameters - **value** (SigningKey) - Required - The signing key to convert. #### Return Value A new `LocalWallet` instance. ### `sign_hash` #### Description Requests an ECDSA signature for a message hash. #### Method `async fn sign_hash<'life0, 'life1, 'async_trait>( &'life0 self, hash: &'life1 Felt, ) -> Result` #### Parameters - **self** (&'life0 LocalWallet) - Required - The wallet instance. - **hash** (&'life1 Felt) - Required - The hash of the message to sign. #### Return Value A `Result` containing the `Signature` on success, or a `SignError` on failure. ### `get_public_key` #### Description Retrieves the verifying (public) key from the signer. #### Method `async fn get_public_key<'life0, 'async_trait>( &'life0 self, ) -> Result` #### Parameters - **self** (&'life0 LocalWallet) - Required - The wallet instance. #### Return Value A `Result` containing the `VerifyingKey` on success. `Infallible` indicates this operation is guaranteed not to fail. ### `is_interactive` #### Description Indicates whether the underlying signer implementation is interactive. #### Method `fn is_interactive(&self, _context: SignerInteractivityContext<'_>) -> bool` #### Parameters - **self** (&self) - Required - The wallet instance. - **_context** (SignerInteractivityContext<'_>) - Required - Context for interactivity (unused in this implementation). #### Return Value `false` as `LocalWallet` is not interactive. ``` -------------------------------- ### Pattern Implementations Source: https://docs.rs/starknet/latest/starknet/core/types/alloc/str/pattern/trait Details on how specific types implement the Pattern trait, including examples and their associated Searcher types. ```APIDOC ## Implementors ### impl Pattern for char Searches for chars that are equal to a given `char`. #### §Examples ```rust assert_eq!("Hello world".find('o'), Some(4)); ``` #### type Searcher<'a> = CharSearcher<'a> ### impl<'b> Pattern for &'b str Non-allocating substring search. Will handle the pattern `""` as returning empty matches at each character boundary. #### §Examples ```rust assert_eq!("Hello world".find("world"), Some(6)); ``` #### type Searcher<'a> = StrSearcher<'a, 'b> ### impl<'b> Pattern for &'b String A convenience impl that delegates to the impl for `&str`. #### §Examples ```rust assert_eq!(String::from("Hello world").find("world"), Some(6)); ``` ``` -------------------------------- ### Rust Slice rchunks Example Source: https://docs.rs/starknet/latest/starknet/core/types/alloc/bstr/struct Demonstrates the `rchunks` method which returns an iterator over mutable chunks of a slice, starting from the end. The last chunk may be smaller if the slice length is not divisible by the chunk size. Panics if chunk_size is zero. ```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()); ``` -------------------------------- ### Rust: H160 Constant Methods for Initialization Source: https://docs.rs/starknet/latest/starknet/providers/sequencer/models/type These H160 methods provide constant ways to create new H160 instances. `repeat_byte` fills the hash with a specified byte, `zero` creates a hash of all zeros, and `len_bytes` returns the fixed size of the hash in bytes. These are useful for setting default or specific initial states. ```rust pub const fn repeat_byte(byte: u8) -> H160; pub const fn zero() -> H160; pub const fn len_bytes() -> usize; ``` -------------------------------- ### Create Empty VecDeque (Rust) Source: https://docs.rs/starknet/latest/starknet/core/types/alloc/collections/struct Shows how to create an empty VecDeque using the `new` function. This is the most basic way to start with an empty double-ended queue. ```rust use std::collections::VecDeque; let deque: VecDeque = VecDeque::new(); ``` -------------------------------- ### Construct LocalWallet from SigningKey (Rust) Source: https://docs.rs/starknet/latest/starknet/signers/local_wallet/struct Provides a constructor for the LocalWallet, allowing its creation directly from a SigningKey. This is a common way to initialize a LocalWallet instance. ```rust pub fn from_signing_key(key: SigningKey) -> LocalWallet ``` -------------------------------- ### Rust: Get element offset in a slice using element_offset Source: https://docs.rs/starknet/latest/starknet/core/types/alloc/bstr/struct Illustrates the `element_offset` method, which returns the byte index of an element reference within a slice. This nightly-only API is useful for extending slice iterators and works via pointer arithmetic, not element comparison. It returns `None` if the element is not at the start of another element within the slice. ```rust #![feature(substr_range)] let nums: &[u32] = &[1, 7, 1, 1]; let num = &nums[2]; assert_eq!(num, &1); assert_eq!(nums.element_offset(num), Some(2)); ``` ```rust #![feature(substr_range)] let arr: &[[u32; 2]] = &[[0, 1], [2, 3]]; let flat_arr: &[u32] = arr.as_flattened(); let ok_elm: &[u32; 2] = flat_arr[0..2].try_into().unwrap(); let weird_elm: &[u32; 2] = flat_arr[1..3].try_into().unwrap(); assert_eq!(ok_elm, &[0, 1]); assert_eq!(weird_elm, &[1, 2]); assert_eq!(arr.element_offset(ok_elm), Some(0)); // Points to element 0 assert_eq!(arr.element_offset(weird_elm), None); // Points between element 0 and 1 ``` -------------------------------- ### SingleOwnerAccount Constructor and Configuration Source: https://docs.rs/starknet/latest/starknet/accounts/single_owner/struct Provides details on creating and configuring a SingleOwnerAccount instance. ```APIDOC ## POST /accounts/single_owner/new ### Description Creates a new account controlled by a single signer. ### Method POST ### Endpoint `/accounts/single_owner/new` ### Parameters #### Request Body - **provider** (Provider) - Required - A `Provider` implementation that provides access to the Starknet network. - **signer** (Signer) - Required - A `Signer` implementation that can generate valid signatures for this account. - **address** (Felt) - Required - Account contract address. - **chain_id** (Felt) - Required - Network chain ID. - **encoding** (ExecutionEncoding) - Required - How `__execute__` calldata should be encoded. ### Response #### Success Response (200) - **account** (SingleOwnerAccount) - The newly created SingleOwnerAccount instance. #### Response Example ```json { "account": { "provider": "", "signer": "", "address": "", "chain_id": "", "encoding": "" } } ``` ## PUT /accounts/single_owner/set_block_id ### Description Sets a new block ID to run queries against. ### Method PUT ### Endpoint `/accounts/single_owner/set_block_id` ### Parameters #### Request Body - **block_id** (BlockId) - Required - The new block ID to set. ### Response #### Success Response (200) - **account** (SingleOwnerAccount) - The updated SingleOwnerAccount instance with the new block ID set. #### Response Example ```json { "account": { "provider": "", "signer": "", "address": "", "chain_id": "", "encoding": "", "block_id": "" } } ``` ``` -------------------------------- ### Wasmtime Version for Starknet Benchmarks Source: https://docs.rs/starknet/latest/starknet/core/index Displays the version of the Wasmtime runtime used for benchmarking Starknet operations in a WebAssembly environment. This is crucial for reproducibility. ```bash $ wasmtime --version wasmtime-cli 21.0.1 (cedf9aa0f 2024-05-22) ``` -------------------------------- ### Get Mutable Element by Index in VecDeque (Rust) Source: https://docs.rs/starknet/latest/starknet/core/types/alloc/collections/struct Demonstrates how to get a mutable reference to an element at a specific index in a VecDeque using `get_mut`. This allows in-place modification of the element. ```rust use std::collections::VecDeque; let mut buf = VecDeque::new(); buf.push_back(3); buf.push_back(4); buf.push_back(5); buf.push_back(6); assert_eq!(buf[1], 4); if let Some(elem) = buf.get_mut(1) { *elem = 7; } assert_eq!(buf[1], 7); ``` -------------------------------- ### Rust: ContractFactory Deployment Methods Source: https://docs.rs/starknet/latest/starknet/contract/struct Methods for initiating contract deployments. `deploy_v3` is the recommended method for generating `INVOKE` v3 transactions, while `deploy` is deprecated and uses an unspecified transaction version. ```rust pub const fn deploy_v3( &self, constructor_calldata: Vec, salt: Felt, unique: bool, ) -> DeploymentV3<'_, A> ``` ```rust pub const fn deploy( &self, constructor_calldata: Vec, salt: Felt, unique: bool, ) -> DeploymentV3<'_, A> ``` -------------------------------- ### Add Element to Back and Get Mutable Ref in Rust (Nightly) Source: https://docs.rs/starknet/latest/starknet/core/types/alloc/collections/linked_list/struct Experimental nightly feature `push_mut` to add an element to the back and get a mutable reference to it. This operation is O(1). ```rust #![feature(push_mut)] use std::collections::LinkedList; let mut dl = LinkedList::from([1, 2, 3]); let ptr = dl.push_back_mut(2); *ptr += 4; assert_eq!(dl.back().unwrap(), &6); ``` -------------------------------- ### URL Serialization and Conversion Source: https://docs.rs/starknet/latest/starknet/providers/struct Documentation for URL serialization using Serde and conversion from string slices. ```APIDOC ## URL Serialization and Conversion Documentation for URL serialization using Serde and conversion from string slices. ### `impl Serialize for Url` Serializes this URL into a `serde` stream. This implementation requires the `serde` Cargo feature to be enabled. #### Method `serialize( &self, serializer: S, ) -> Result<::Ok, ::Error>` where S: Serializer, Serializes the URL value into the given Serde serializer. ### `impl<'a> TryFrom<&'a str> for Url` #### Type Alias `type Error = ParseError` The type returned in the event of a conversion error. #### Method `try_from(s: &'a str) -> Result>::Error>` Performs the conversion from a string slice to a URL. ``` -------------------------------- ### U256 Constructors and Accessors Source: https://docs.rs/starknet/latest/starknet/core/types/u256/struct Methods for constructing a U256 from words and for accessing its low and high 128-bit components. ```APIDOC ## Implementations for U256 ### `fn from_words(low: u128, high: u128) -> U256` Constructs a U256 from the low 128 bits and the high 128 bits, similar to how they’re represented in Cairo. ### `fn low(&self) -> u128` Gets the lower (least significant) 128 bits as u128. ### `fn high(&self) -> u128` Gets the higher (most significant) 128 bits as u128. ``` -------------------------------- ### Add Element to Front and Get Mutable Ref in Rust (Nightly) Source: https://docs.rs/starknet/latest/starknet/core/types/alloc/collections/linked_list/struct Experimental nightly feature `push_mut` to add an element to the front and get a mutable reference to it. This operation is O(1). ```rust #![feature(push_mut)] use std::collections::LinkedList; let mut dl = LinkedList::from([1, 2, 3]); let ptr = dl.push_front_mut(2); *ptr += 4; assert_eq!(dl.front().unwrap(), &6); ``` -------------------------------- ### Implement From for LocalWallet (Rust) Source: https://docs.rs/starknet/latest/starknet/signers/local_wallet/struct Details the conversion from a SigningKey type into a LocalWallet. This implementation allows for seamless integration when a SigningKey is already available. ```rust impl From for LocalWallet { fn from(value: SigningKey) -> LocalWallet { // ... implementation details ... } } ``` -------------------------------- ### VarULE Encoding for Cow<'_, T> Source: https://docs.rs/starknet/latest/starknet/core/types/alloc/borrow/enum Details the methods for encoding `Cow<'_, T>` as a `VarULE` (Variable-length Unaligned Little-Endian), including functions to get the encoded length, write to a buffer, and get byte slices. ```Rust impl EncodeAsVarULE for Cow<'_, T> where T: VarULE + ToOwned + ?Sized, fn encode_var_ule_as_slices(&self, cb: impl FnOnce(&[&[u8]]) -> R) -> R fn encode_var_ule_len(&self) -> usize fn encode_var_ule_write(&self, dst: &mut [u8]) ``` -------------------------------- ### Rust: Creating a Vec using the vec! macro Source: https://docs.rs/starknet/latest/starknet/core/types/alloc/index Demonstrates the use of the `vec!` macro to efficiently create a `Vec` (a growable array) with initial elements. This is a common convenience macro provided by the `alloc` crate. ```rust fn main() { // Create a vector with initial elements let v = vec![1, 2, 3, 4, 5]; println!("Vector: {:?}", v); // Create an empty vector let mut empty_v: Vec = vec![]; empty_v.push(10); println!("Empty vector after push: {:?}", empty_v); } ``` -------------------------------- ### Rust Example: Basic FromStr usage with i32 Source: https://docs.rs/starknet/latest/starknet/core/types/alloc/str/trait Shows a simple example of using the `FromStr` trait with the built-in `i32` type. It parses the string "5" into an `i32` value. ```rust use std::str::FromStr; let s = "5"; let x = i32::from_str(s).unwrap(); assert_eq!(5, x); ``` -------------------------------- ### Get Minimum of Two Arc Values Source: https://docs.rs/starknet/latest/starknet/core/types/alloc/sync/struct Provides a method to get the minimum of two Arc values, leveraging the Ord implementation. This is useful for scenarios requiring selection of the smaller of two Arc-wrapped items. ```Rust fn min(self, other: Self) -> Self where Self: Sized ``` -------------------------------- ### Starknet Class Hash Benchmarks (WebAssembly) Source: https://docs.rs/starknet/latest/starknet/core/index Benchmark results for Cairo 0 and Sierra class hash computations using the Wasmtime runtime. These times reflect performance in a WebAssembly environment. ```text cairo0_class_hash time: [36.515 ms 36.526 ms 36.538 ms] sierra_class_hash time: [22.550 ms 22.557 ms 22.567 ms] ``` -------------------------------- ### Get Maximum of Two Arc Values Source: https://docs.rs/starknet/latest/starknet/core/types/alloc/sync/struct Provides a method to get the maximum of two Arc values, leveraging the Ord implementation. This is useful for scenarios requiring selection of the larger of two Arc-wrapped items. ```Rust fn max(self, other: Self) -> Self where Self: Sized ``` -------------------------------- ### LinkedList Creation and Initialization Source: https://docs.rs/starknet/latest/starknet/core/types/alloc/collections/linked_list/struct Provides documentation for creating and initializing a LinkedList. ```APIDOC ## LinkedList ### Description A doubly-linked list with owned nodes. The `LinkedList` allows pushing and popping elements at either end in constant time. A `LinkedList` with a known list of items can be initialized from an array. **Note**: It is almost always better to use `Vec` or `VecDeque` because array-based containers are generally faster, more memory efficient, and make better use of CPU cache. ### Method N/A (Struct definition) ### Endpoint N/A (Struct definition) ### Parameters N/A ### Request Example ```rust use std::collections::LinkedList; let list = LinkedList::from([1, 2, 3]); ``` ### Response N/A (Struct definition) ``` ```APIDOC ## LinkedList::new() ### Description Creates an empty `LinkedList`. ### Method `const fn new() -> LinkedList` ### Endpoint N/A (Associated function) ### Parameters None ### Request Example ```rust use std::collections::LinkedList; let list: LinkedList = LinkedList::new(); ``` ### Response #### Success Response (200) - `LinkedList` - An empty LinkedList. ### Response Example ```rust // No direct response example, as it's a constructor. ``` ``` ```APIDOC ## LinkedList::new_in(alloc: A) ### Description Constructs an empty `LinkedList` with a specified allocator. This is a nightly-only experimental API. ### Method `const fn new_in(alloc: A) -> LinkedList` ### Endpoint N/A (Associated function) ### Parameters - **alloc** (A) - The allocator to use for the LinkedList. ### Request Example ```rust #![feature(allocator_api)] use std::alloc::System; use std::collections::LinkedList; let list: LinkedList = LinkedList::new_in(System); ``` ### Response #### Success Response (200) - `LinkedList` - An empty LinkedList with the specified allocator. ### Response Example ```rust // No direct response example, as it's a constructor. ``` ``` -------------------------------- ### Get Mutable Element or Subslice by Index (Rust) Source: https://docs.rs/starknet/latest/starknet/core/types/alloc/bstr/struct Safely retrieves a mutable reference to an element or a subslice. Similar to `get`, but allows modification. Returns None if the index is out of bounds. Essential for in-place modifications. ```rust let x = &mut [0, 1, 2]; if let Some(elem) = x.get_mut(1) { *elem = 42; } assert_eq!(x, &[0, 42, 2]); ``` -------------------------------- ### Rust Example: `ThreadWaker` and `block_on` Source: https://docs.rs/starknet/latest/starknet/core/types/alloc/task/trait Demonstrates how to implement the `Wake` trait for a custom `ThreadWaker` and utilizes it within a `block_on` function to run a future to completion on the current thread. This example highlights task waking and polling mechanisms. ```rust use std::future::Future; use std::sync::Arc; use std::task::{Context, Poll, Wake}; use std::thread::{self, Thread}; use core::pin::pin; /// A waker that wakes up the current thread when called. struct ThreadWaker(Thread); impl Wake for ThreadWaker { fn wake(self: Arc) { self.0.unpark(); } } /// Run a future to completion on the current thread. fn block_on(fut: impl Future) -> T { // Pin the future so it can be polled. let mut fut = pin!(fut); // Create a new context to be passed to the future. let t = thread::current(); let waker = Arc::new(ThreadWaker(t)).into(); let mut cx = Context::from_waker(&waker); // Run the future to completion. loop { match fut.as_mut().poll(&mut cx) { Poll::Ready(res) => return res, Poll::Pending => thread::park(), } } } block_on(async { println!("Hi from inside a future!"); }); ``` -------------------------------- ### URL Construction from File Path Source: https://docs.rs/starknet/latest/starknet/providers/struct Methods for constructing URL objects from file paths. ```APIDOC ## POST /url/from_file_path ### Description Constructs a `Url` object from a given file path. This method is available when the `std` Cargo feature is enabled. ### Method POST ### Endpoint /url/from_file_path ### Parameters #### Request Body - **path** (string) - Required - The file path to convert into a URL. ### Request Example ```json { "path": "/tmp/foo.txt" } ``` ### Response #### Success Response (200) - **url** (string) - The resulting URL string. #### Response Example ```json { "url": "file:///tmp/foo.txt" } ``` ``` ```APIDOC ## POST /url/from_directory_path ### Description Converts a directory path into a `file` scheme URL, ensuring a trailing slash. This method requires the `std` Cargo feature and returns an error if the path is not absolute or has an invalid prefix on Windows. ### Method POST ### Endpoint /url/from_directory_path ### Parameters #### Request Body - **path** (string) - Required - The directory path to convert. ### Request Example ```json { "path": "/var/www" } ``` ### Response #### Success Response (200) - **url** (string) - The resulting URL with a trailing slash. #### Response Example ```json { "url": "file:///var/www/" } ``` ``` -------------------------------- ### Rust: Example Usage of GetDisjointMutError Source: https://docs.rs/starknet/latest/starknet/core/types/alloc/slice/enum This Rust example demonstrates how to use the get_disjoint_mut function and handle the GetDisjointMutError. It shows cases where an index is out of bounds and where indices overlap, resulting in the respective error variants. ```rust use std::slice::GetDisjointMutError; let v = &mut [1, 2, 3]; assert_eq!(v.get_disjoint_mut([0, 999]), Err(GetDisjointMutError::IndexOutOfBounds)); assert_eq!(v.get_disjoint_mut([1, 1]), Err(GetDisjointMutError::OverlappingIndices)); ``` -------------------------------- ### Generic Blanket Implementations for Rust Types Source: https://docs.rs/starknet/latest/starknet/providers/struct Demonstrates common blanket implementations in Rust that apply to generic types, including `Any`, `Borrow`, `BorrowMut`, `CloneToUninit`, `Comparable`, and `Equivalent`. These implementations provide fundamental functionalities applicable to a wide range of types, including `Url`. ```Rust impl Any for T where T: 'static + ?Sized { fn type_id(&self) -> TypeId } impl Borrow for T where T: ?Sized { fn borrow(&self) -> &T } impl BorrowMut for T where T: ?Sized { fn borrow_mut(&mut self) -> &mut T } impl CloneToUninit for T where T: Clone { unsafe fn clone_to_uninit(&self, dest: *mut u8) } impl Comparable for Q where Q: Ord + ?Sized, K: Borrow + ?Sized { fn compare(&self, key: &K) -> Ordering } impl Equivalent for Q where Q: Eq + ?Sized, K: Borrow + ?Sized { fn equivalent(&self, key: &K) -> bool } ``` -------------------------------- ### Rust print! and println! Macros for Standard Output Source: https://docs.rs/starknet/latest/starknet/core/types/alloc/fmt/index Shows examples of the `print!` and `println!` macros for writing formatted strings to the standard output (stdout). These macros also aim to prevent intermediate allocations. ```rust print!("Hello {}!", "world"); println!("I have a newline {}", "character at the end"); ``` -------------------------------- ### Rust Cow: is_owned() Example (Nightly) Source: https://docs.rs/starknet/latest/starknet/core/types/alloc/borrow/enum Example demonstrating the `is_owned` method for `Cow`, which is currently an unstable (nightly-only) feature. It checks if the `Cow` instance currently holds owned data, returning `true` if it does and `false` if it holds borrowed data. ```rust #![feature(cow_is_borrowed)] use std::borrow::Cow; let cow: Cow<'_, str> = Cow::Owned("moo".to_string()); assert!(cow.is_owned()); let bull = Cow::Borrowed("...moo?"); assert!(!bull.is_owned()); ``` -------------------------------- ### Rust Cow: is_borrowed() Example (Nightly) Source: https://docs.rs/starknet/latest/starknet/core/types/alloc/borrow/enum Example demonstrating the `is_borrowed` method for `Cow`, which is currently an unstable (nightly-only) feature. It checks if the `Cow` instance currently holds borrowed data, returning `true` if it does and `false` if it holds owned data. ```rust #![feature(cow_is_borrowed)] use std::borrow::Cow; let cow = Cow::Borrowed("moo"); assert!(cow.is_borrowed()); let bull: Cow<'_, str> = Cow::Owned("...moo?".to_string()); assert!(!bull.is_borrowed()); ``` -------------------------------- ### StarkNet Utility Methods Source: https://docs.rs/starknet/latest/starknet/core/types/requests/index Utility methods for network information. ```APIDOC ## GET /starknet_chainId ### Description Retrieves the chain ID of the StarkNet network. ### Method GET ### Endpoint /starknet_chainId ### Response #### Success Response (200) - **result** (string) - The chain ID. #### Response Example ```json { "jsonrpc": "2.0", "result": "0x...", "id": 1 } ``` --- ## GET /starknet_specVersion ### Description Retrieves the supported StarkNet spec version. ### Method GET ### Endpoint /starknet_specVersion ### Response #### Success Response (200) - **result** (string) - The spec version string. #### Response Example ```json { "jsonrpc": "2.0", "result": "0.1.0", "id": 1 } ``` ``` -------------------------------- ### Get Port or Default Port from URL (Rust) Source: https://docs.rs/starknet/latest/starknet/providers/struct Explains how to get the port number from a URL, falling back to the known default port for schemes like http, https, ws, wss, and ftp. Returns None for unknown schemes without explicit ports. ```rust use url::Url; let url = Url::parse("foo://example.com")?; assert_eq!(url.port_or_known_default(), None); let url = Url::parse("foo://example.com:1456")?; assert_eq!(url.port_or_known_default(), Some(1456)); let url = Url::parse("https://example.com")?; assert_eq!(url.port_or_known_default(), Some(443)); ``` -------------------------------- ### Rust format! Positional Parameters Example Source: https://docs.rs/starknet/latest/starknet/core/types/alloc/fmt/index Illustrates how positional parameters work within the `format!` macro in Rust, showing both sequential ordering and explicit index referencing. It highlights the behavior when mixing explicit indices with default sequential arguments. ```Rust format!("{1} {} {0} {}", 1, 2); // => "2 1 1 2" ```