### Setup Rust Build Environment Source: https://www.rustmax.net/library/rustc-dev-guide/building/quickstart Sets up the build environment for the Rust compiler using the 'x' wrapper script. This command creates a default configuration necessary for building the compiler and its components. ```bash ./x setup ``` -------------------------------- ### Run Embedded Example with Cargo Source: https://www.rustmax.net/library/embedded-book/start/qemu This command compiles and runs the 'hello' example using Cargo, leveraging the configured custom runner. The `--release` flag enables optimizations for the build. ```bash cargo run --example hello --release ``` -------------------------------- ### Compile Embedded Rust Example Source: https://www.rustmax.net/library/embedded-book/start/qemu This command compiles a Rust example named 'hello' for an embedded target. The compilation process generates an executable binary file. ```bash cargo build --example hello ``` -------------------------------- ### Example: Routing POST and GET Requests with Services in Rust Source: https://www.rustmax.net/api/axum/routing/method_routing/struct.MethodRouter Demonstrates routing POST requests to one service and GET requests to another using `post_service` and `get_service`. ```rust use axum::{ extract::Request, Router, routing::post_service, body::Body, }; use http::Response; use std::convert::Infallible; let service = tower::service_fn(|request: Request| async { Ok::<_, Infallible>(Response::new(Body::empty())) }); let other_service = tower::service_fn(|request: Request| async { Ok::<_, Infallible>(Response::new(Body::empty())) }); // Requests to `POST /` will go to `service` and `GET /` will go to // `other_service`. let app = Router::new().route("/", post_service(service).get_service(other_service)); ``` -------------------------------- ### Install and Get Help for Rustmax CLI Source: https://www.rustmax.net/book/cli This snippet shows how to install the Rustmax CLI using Cargo and how to access its help information to see available commands and options. It's the first step to using the CLI. ```bash cargo install rustmax-cli rustmax --help ``` -------------------------------- ### Download and Extract Project Template Source: https://www.rustmax.net/library/embedded-book/start/qemu Manually downloads the latest snapshot of the `cortex-m-quickstart` template as a ZIP archive and extracts it. This is an alternative to using `cargo-generate` or `git clone`. ```bash curl -LO https://github.com/rust-embedded/cortex-m-quickstart/archive/master.zip unzip master.zip mv cortex-m-quickstart-master app cd app ``` -------------------------------- ### Get Current Instant in Rust Source: https://www.rustmax.net/api/std/time/struct.Instant A simple example demonstrating how to obtain the current `Instant` using `Instant::now()`. This is the fundamental starting point for any time measurement using `Instant`. ```rust use std::time::Instant; let now = Instant::now(); ``` -------------------------------- ### Clone Rust Compiler Repository Source: https://www.rustmax.net/library/rustc-dev-guide/building/quickstart Clones the official Rust compiler repository from GitHub and navigates into the cloned directory. This is the first step to start working with the compiler source code. ```bash git clone https://github.com/rust-lang/rust.git cd rust ``` -------------------------------- ### Parse and Get URI Query String (Rust) Source: https://www.rustmax.net/api/http/uri/struct Provides an example of extracting the query string from a `Uri`. The query string starts after the '?' and ends before the '#' or the end of the URI. Requires `http::Uri`. ```rust use http::Uri; let uri: Uri = "http://example.org/path?key=value".parse().unwrap(); assert_eq!(uri.query(), Some("key=value")); ``` -------------------------------- ### Basic `Command` Usage Example (Rust) Source: https://www.rustmax.net/api/tokio/process/struct.Command Demonstrates the basic usage of creating a `Command` instance and preparing it for execution, specifically showing how to initialize it with a program name. ```rust use tokio::process::Command; let mut command = Command::new("sh"); # let _ = command.output(); // assert borrow checker ``` -------------------------------- ### Book Configuration Example (book.toml) Source: https://www.rustmax.net/library/mdbook/format/configuration/general An example of a complete book.toml file demonstrating various configuration sections including book metadata, Rust settings, build options, and preprocessors. ```toml [book] title = "Example book" authors = ["John Doe"] description = "The example book covers examples." [rust] edition = "2018" [build] build-dir = "my-example-book" create-missing = false [preprocessor.index] [preprocessor.links] [output.html] additional-css = ["custom.css"] [output.html.search] limit-results = 15 ``` -------------------------------- ### Rust Embedded 'Hello, World!' Example Source: https://www.rustmax.net/library/embedded-book/start/qemu This Rust code snippet demonstrates a basic embedded program that prints 'Hello, world!' to the host console using semihosting. It requires the `cortex-m-rt`, `panic-halt`, and `cortex-m-semihosting` crates. The program uses `hprintln!` for output and `debug::exit` to terminate the QEMU session. ```rust #![no_main] #![no_std] use panic_halt as _; use cortex_m_rt::entry; use cortex_m_semihosting::{debug, hprintln}; #[entry] fn main() -> ! { hprintln!("Hello, world!").unwrap(); // exit QEMU // NOTE do not run this on hardware; it can corrupt OpenOCD state debug::exit(debug::EXIT_SUCCESS); loop {} } ``` -------------------------------- ### Open Local Rust Documentation Source: https://www.rustmax.net/library/trpl/ch01-01-installation Opens the locally installed Rust documentation in the default web browser, allowing offline access to API references and guides. ```shell rustup doc ``` -------------------------------- ### Install Latest OpenOCD with Homebrew on macOS Source: https://www.rustmax.net/library/embedded-book/intro/install/macos Installs the latest development version of OpenOCD using Homebrew. This is a troubleshooting step recommended if the standard OpenOCD installation crashes. It requires Homebrew to be installed. ```bash brew install --HEAD openocd ``` -------------------------------- ### Serve Connection Example Source: https://www.rustmax.net/api/hyper/server/conn/http1/struct.Builder An example demonstrating how to use `serve_connection` to handle an HTTP connection. It shows the creation of an HTTP builder, serving the connection, and handling potential errors. ```rust # use hyper::{body::Incoming, Request, Response}; # use hyper::service::Service; # use hyper::server::conn::http1::Builder; # use hyper::rt::{Read, Write}; # async fn run(some_io: I, some_service: S) # where # I: Read + Write + Unpin + Send + 'static, # S: Service, Response=hyper::Response> + Send + 'static, # S::Error: Into>, # S::Future: Send, # { let http = Builder::new(); let conn = http.serve_connection(some_io, some_service); if let Err(e) = conn.await { eprintln!("server connection error: {}", e); } # } # fn main() {} ``` -------------------------------- ### Axum Hello World Example Source: https://www.rustmax.net/api/axum/index A basic 'Hello, World!' example demonstrating how to set up a simple Axum application with a single route. It requires Tokio's 'macros' and 'rt-multi-thread' features. ```rust use axum::{ routing::get, Router, }; #[tokio::main] async fn main() { // build our application with a single route let app = Router::new().route("/", get(|| async { "Hello, World!" })); // run our app with hyper, listening globally on port 3000 let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap(); axum::serve(listener, app).await.unwrap(); } ``` -------------------------------- ### Get Start of ClassBytesRange in Rust Source: https://www.rustmax.net/api/regex_syntax/hir/struct.ClassBytesRange Returns the starting byte of the `ClassBytesRange`. The start value is guaranteed to be less than or equal to the end value. ```rust fn start(self: &Self) -> u8 ``` -------------------------------- ### Update Rust Installation Source: https://www.rustmax.net/library/trpl/ch01-01-installation Updates the installed Rust toolchain, including the compiler and other components, to the latest available stable version using rustup. ```shell $ rustup update ``` -------------------------------- ### Install Tools with MacPorts on macOS Source: https://www.rustmax.net/library/embedded-book/intro/install/macos Installs GDB, OpenOCD, and QEMU using the MacPorts package manager. This is an alternative to Homebrew for users who prefer MacPorts. Requires MacPorts to be installed and updated. ```bash # GDB sudo port install arm-none-eabi-gcc # OpenOCD sudo port install openocd # QEMU sudo port install qemu ``` -------------------------------- ### Example: Add Multiple Arguments and Execute (Rust) Source: https://www.rustmax.net/api/tokio/process/struct.Command Shows how to use the `args` method to provide multiple arguments to a command and then execute it asynchronously using `output().await`. ```rust use tokio::process::Command; let output = Command::new("ls") .arg("-l") .arg("-a") .output().await.unwrap(); ``` -------------------------------- ### More Examples Source: https://www.rustmax.net/api/axum/routing/struct Illustrative examples showcasing various routing configurations including captures, wildcards, and multiple methods. ```APIDOC ## More Examples ```apidoc use axum::{Router, routing::{get, delete}, extract::Path}; let app = Router::new() .route("/", get(root)) .route("/users", get(list_users).post(create_user)) .route("/users/{id}", get(show_user)) .route("/api/{version}/users/{id}/action", delete(do_users_action)) .route("/assets/{*path}", get(serve_asset)); async fn root() {} async fn list_users() {} async fn create_user() {} async fn show_user(Path(id): Path) {} async fn do_users_action(Path((version, id)): Path<(String, u64)>) {} async fn serve_asset(Path(path): Path) {} ``` ``` -------------------------------- ### Example: Reverse Automaton for Match Start Position Source: https://www.rustmax.net/api/regex_automata/hybrid/dfa/struct Illustrates using `MatchKind::All` to construct a reverse automaton for finding the start of the longest possible match. This approach is useful for determining the leftmost starting position. The example compares forward and reverse searches and requires importing types from `regex_automata`. ```rust use regex_automata::{ hybrid::dfa::DFA, nfa::thompson::NFA, Anchored, HalfMatch, Input, MatchKind, }; let input = Input::new("123foobar456"); let pattern = r"[a-z]+r"; let dfa_fwd = DFA::new(pattern)?; let dfa_rev = DFA::builder() .thompson(NFA::config().reverse(true)) .configure(DFA::config().match_kind(MatchKind::All)) .build(pattern)?; let mut cache_fwd = dfa_fwd.create_cache(); let mut cache_rev = dfa_rev.create_cache(); let expected_fwd = HalfMatch::must(0, 9); let expected_rev = HalfMatch::must(0, 3); let got_fwd = dfa_fwd.try_search_fwd(&mut cache_fwd, &input)?.unwrap(); // Here we don't specify the pattern to search for since there's only // one pattern and we're doing a leftmost search. But if this were an // overlapping search, you'd need to specify the pattern that matched // in the forward direction. (Otherwise, you might wind up finding the // starting position of a match of some other pattern.) That in turn // requires building the reverse automaton with starts_for_each_pattern // enabled. let input = input .clone() .range(..got_fwd.offset()) .anchored(Anchored::Yes); let got_rev = dfa_rev.try_search_rev(&mut cache_rev, &input)?.unwrap(); assert_eq!(expected_fwd, got_fwd); assert_eq!(expected_rev, got_rev); ``` -------------------------------- ### Verify Rust Installation Source: https://www.rustmax.net/library/trpl/ch01-01-installation Checks if Rust is installed correctly by displaying the version of the Rust compiler. Successful output shows the version number, commit hash, and date. ```shell $ rustc --version ``` -------------------------------- ### Define a basic router and serve requests (Rust) Source: https://www.rustmax.net/api/axum/routing/struct.Router Demonstrates how to create a new `Router` instance, define a simple GET route, and then serve incoming requests using `axum::serve`. This is a fundamental example for setting up a web server with Axum. ```rust use axum::{ routing::get, Router, }; let app = Router::new().route("/", get(|| async { "Hi!" })); # async { let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap(); axum::serve(listener, app).await.unwrap(); # }; ``` -------------------------------- ### Install rustup on Linux/macOS Source: https://www.rustmax.net/library/trpl/ch01-01-installation Installs the rustup toolchain manager and the latest stable version of Rust on Linux and macOS systems using curl. Requires an internet connection. ```shell $ curl --proto '=https' --tlsv1.2 https://sh.rustup.rs -sSf | sh ``` -------------------------------- ### Stepping Through Code and Observing Output Source: https://www.rustmax.net/library/embedded-book/start/hardware This example shows how to step into functions (`step`) and advance execution line by line (`next`) in GDB. It also includes the expected output on the OpenOCD console after the program runs, demonstrating the 'Hello, world!' message. ```gdb (gdb) step halted: PC: 0x08000496 hello::__cortex_m_rt_main () at examples/hello.rs:13 13 hprintln!("Hello, world!").unwrap(); $ openocd (..) Info : halted: PC: 0x08000502 Hello, world! Info : halted: PC: 0x080004ac ``` -------------------------------- ### Install Tools with Homebrew on macOS Source: https://www.rustmax.net/library/embedded-book/intro/install/macos Installs GDB, OpenOCD, and QEMU using the Homebrew package manager. This method is straightforward for users who have Homebrew set up. Ensure Homebrew is installed and updated before running these commands. ```bash # GDB brew install arm-none-eabi-gdb # OpenOCD brew install openocd # QEMU brew install qemu ``` -------------------------------- ### UEFI Hello World with std (Rust) Source: https://www.rustmax.net/library/rustc-book/platform-support/unknown-uefi An example UEFI application in Rust that utilizes the standard library, including `println!` for output and `Vec` for string manipulation. It demonstrates how to compile and run a UEFI application with `std` support using `cargo`. This example showcases a more idiomatic Rust approach to UEFI development by leveraging familiar standard library features. ```rust #![feature(uefi_std)] use r_efi::{efi, protocols::simple_text_output}; use std:: ffi::OsString, os::uefi::{env, ffi::OsStrExt} ; pub fn main() { println!("Starting Rust Application..."); // Use System Table Directly let st = env::system_table().as_ptr() as *mut efi::SystemTable; let mut s: Vec = OsString::from("Hello World!\n").encode_wide().collect(); s.push(0); let r = unsafe { let con_out: *mut simple_text_output::Protocol = (*st).con_out; let output_string: extern "efiapi" fn(_: *mut simple_text_output::Protocol, *mut u16) -> efi::Status = (*con_out).output_string; output_string(con_out, s.as_ptr() as *mut efi::Char16) }; assert!(!r.is_error()) } ``` -------------------------------- ### Get Specialize Start States Source: https://www.rustmax.net/api/regex_automata/hybrid/dfa/struct.Config Checks if the lazy DFA is configured to specialize start states for optimization. ```APIDOC ## GET /config/specialize_start_states ### Description Returns whether this configuration will instruct the lazy DFA to "specialize" start states. When enabled, the lazy DFA will tag start states so that search routines using the lazy DFA can detect when it's in a start state and do some kind of optimization (like run a prefilter). ### Method GET ### Endpoint /config/specialize_start_states ### Parameters No parameters required. ### Response #### Success Response (200) - **bool** (bool) - True if specializing start states is enabled, false otherwise. #### Response Example ```json { "enabled": true } ``` ``` -------------------------------- ### Install C Compiler on macOS Source: https://www.rustmax.net/library/trpl/ch01-01-installation Installs Xcode command line tools on macOS, which include a C compiler and linker necessary for Rust development and some C-dependent Rust packages. ```shell $ xcode-select --install ``` -------------------------------- ### Example: Initializing AtomicI64 Source: https://www.rustmax.net/api/portable_atomic/struct.AtomicI64 Demonstrates how to create and initialize an AtomicI64 with a specific value using the `new` constructor. ```rust use portable_atomic::AtomicI64; let atomic_forty_two = AtomicI64::new(42); ``` -------------------------------- ### Get Starts For Each Pattern Source: https://www.rustmax.net/api/regex_automata/dfa/onepass/struct.Config Retrieves whether anchored starting states are enabled for every pattern in the DFA. ```APIDOC ## GET /config/starts_for_each_pattern ### Description Returns a boolean indicating whether this configuration has enabled anchored starting states for every pattern in the DFA. ### Method GET ### Endpoint /config/starts_for_each_pattern ### Parameters No parameters. ### Response #### Success Response (200) - **bool** (boolean) - `true` if anchored starting states are enabled for all patterns, `false` otherwise. #### Response Example ``` { "starts_for_each_pattern": true } ``` ``` -------------------------------- ### Install LLVM Coverage Tools via Rustup Source: https://www.rustmax.net/library/rustc-book/instrument-coverage This snippet shows the recommended method for installing LLVM coverage tools by using the `rustup` component `llvm-tools-preview`. This component provides `llvm-profdata` and `llvm-cov`, which are necessary for processing coverage data. Note that the exact tools and their interfaces are not subject to Rust's stability guarantees. ```bash rustup component add llvm-tools-preview ``` -------------------------------- ### Chain Handler for GET Method Source: https://www.rustmax.net/api/axum/routing/method_routing/struct.MethodRouter Provides an example of chaining a handler for `GET` requests using `MethodRouter::get`. It demonstrates routing `POST /` to one handler and `GET /` to another within the same route. ```rust use axum::{routing::post, Router}; async fn handler() {} async fn other_handler() {} // Requests to `POST /` will go to `handler` and `GET /` will go to // `other_handler`. let app = Router::new().route("/", post(handler).get(other_handler)); ``` -------------------------------- ### Get Data Start Offset of ZipFile in Rust Source: https://www.rustmax.net/api/zip/read/struct.ZipFile Returns the starting byte offset within the archive where the compressed data for this file begins. ```rust fn data_start(self: &Self) -> u64 ``` -------------------------------- ### Rust: Example of Configuring and Handshaking Server Builder Source: https://www.rustmax.net/api/h2/server/struct.Builder Demonstrates how to configure server connection settings like initial window size, max concurrent streams, and then initiate the HTTP/2 handshake with a given I/O handle. ```rust # use tokio::io::{AsyncRead, AsyncWrite}; # use h2::server::*; # # fn doc(my_io: T) # -> Handshake # { // `server_fut` is a future representing the completion of the HTTP/2 // handshake. let server_fut = Builder::new() .initial_window_size(1_000_000) .max_concurrent_streams(1000) .handshake(my_io); # server_fut # } # # pub fn main() {} ``` -------------------------------- ### Install 'basic-http-server' for Static File Serving Source: https://www.rustmax.net/book/tools Installs 'basic-http-server', a simple and efficient HTTP server for serving static files. It's useful for local development and testing. ```bash cargo install basic-http-server ``` -------------------------------- ### Test Rust Documentation Examples Source: https://www.rustmax.net/library/rand-book/contrib-doc Command to test all documentation examples within a Rust crate. This ensures that code snippets in the documentation are functional. ```bash cargo test --doc ``` -------------------------------- ### Example of `rfind_iter` Usage in Rust Source: https://www.rustmax.net/api/memchr/memmem/struct.FinderRev Illustrates how to use `rfind_iter` to get a reverse iterator over all occurrences of a needle in a haystack. The example shows iterating through multiple matches. ```rust use memchr::memmem::FinderRev; let haystack = b"foo bar foo baz foo"; let finder = FinderRev::new(b"foo"); let mut it = finder.rfind_iter(haystack); assert_eq!(Some(16), it.next()); assert_eq!(Some(8), it.next()); assert_eq!(Some(0), it.next()); assert_eq!(None, it.next()); ``` -------------------------------- ### Install Rust and System Dependencies (Shell) Source: https://www.rustmax.net/library/rust-forge/docs-rs/self-hosting Installs Rust using rustup and essential system packages required for building and running docs.rs. Assumes an Ubuntu system. ```shell $ curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y --default-toolchain nightly $ source $HOME/.cargo/env # apt install build-essential git curl cmake gcc g++ pkg-config libmagic-dev libssl-dev zlib1g-dev postgresql lxc-utils ``` -------------------------------- ### Clone Project Template with Git Source: https://www.rustmax.net/library/embedded-book/start/qemu Clones the `cortex-m-quickstart` project template from its Git repository into a specified directory. This method requires manual editing of the `Cargo.toml` file afterward. ```bash git clone https://github.com/rust-embedded/cortex-m-quickstart app cd app ``` -------------------------------- ### Get Header Start Offset of ZipFile in Rust Source: https://www.rustmax.net/api/zip/read/struct.ZipFile Returns the starting byte offset within the archive where the local file header for this entry is located. ```rust fn header_start(self: &Self) -> u64 ``` -------------------------------- ### Running Coverage Tests in Rust Source: https://www.rustmax.net/library/rustc-dev-guide/tests/compiletest Provides command-line examples for executing Rust coverage tests. It demonstrates how to run all tests in all coverage modes, specific tests, or tests in a single coverage mode using the './x test' command. ```bash ./x test coverage # runs all of tests/coverage in all coverage modes ./x test tests/coverage # same as above ./x test tests/coverage/if.rs # runs the specified test in all coverage modes ./x test coverage-map # runs all of tests/coverage in "coverage-map" mode only ./x test coverage-run # runs all of tests/coverage in "coverage-run" mode only ./x test coverage-map -- tests/coverage/if.rs # runs the specified test in "coverage-map" mode only ``` -------------------------------- ### GET /rustc/print/target-list Source: https://www.rustmax.net/library/rustc-book/command-line-arguments/print-options Lists all targets known to the current `rustc` installation. ```APIDOC ## `target-list` ### Description List of known targets. The target may be selected with the `--target` flag. ### Method GET ### Endpoint `/rustc/print/target-list` ### Parameters #### Query Parameters - **file** (string) - Optional - The input Rust source file. ### Response #### Success Response (200) - **targets** (array of strings) - A list of available target triples. #### Response Example ```json { "targets": ["x86_64-unknown-linux-gnu", "aarch64-apple-darwin"] } ``` ``` -------------------------------- ### Initialize a new mdBook project Source: https://www.rustmax.net/library/mdbook/cli/init This command initializes a new mdBook project in the current directory. It sets up the basic file structure including 'book' and 'src' directories, and a SUMMARY.md file. It can also parse an existing SUMMARY.md to generate missing chapter files. ```bash mdbook init ``` -------------------------------- ### Get Central Header Start Offset of ZipFile in Rust Source: https://www.rustmax.net/api/zip/read/struct.ZipFile Returns the starting byte offset within the archive where the central directory header for this entry is located. ```rust fn central_header_start(self: &Self) -> u64 ``` -------------------------------- ### Example Usage of Salsa Database Source: https://www.rustmax.net/library/rustc-dev-guide/queries/salsa This snippet shows a basic example of how to use a Salsa database. It demonstrates creating a default database instance, setting input values using generated setter methods (e.g., `set_manifest`), and invoking derived queries (e.g., `ast`). The example highlights how Salsa reuses results for previously computed queries. ```rust fn main() { let db = MyDatabase::default(); db.set_manifest(...); db.set_source_text(...); loop { db.ast(...); //will reuse results db.set_source_text(...); } } ``` -------------------------------- ### Check PATH Environment Variable Source: https://www.rustmax.net/library/trpl/ch01-01-installation Displays the system's PATH environment variable to verify if the Rust installation directory is included, which is crucial for running Rust commands. ```shell > echo %PATH% (Windows CMD) ``` ```shell > echo $env:Path (PowerShell) ``` ```shell $ echo $PATH (Linux/macOS) ``` -------------------------------- ### Documenting Rust Functions/Methods: Examples Source: https://www.rustmax.net/library/std-dev-guide/development/how-to-write-documentation Demonstrates how to provide usage examples for Rust functions and methods within documentation. Examples should be clearly marked with an 'Example' or 'Examples' heading and ideally use assertion macros to verify correctness and illustrate the function's behavior. ```rust # Example ``` let s = MyType::new("hello "); assert_eq!("hello Georges", s.concat_str("Georges").as_str()); ``` ``` -------------------------------- ### UEFI Hello World without std (Rust) Source: https://www.rustmax.net/library/rustc-book/platform-support/unknown-uefi A basic UEFI application written in Rust that prints 'Hello World!' to the console and waits for user input. It uses the `r-efi` crate for direct UEFI protocol access and demonstrates handling UTF-16 strings required by UEFI. This example is suitable for understanding the fundamentals of UEFI application development in Rust without relying on the standard library. ```rust #![no_main] #![no_std] use r_efi::efi; #[panic_handler] fn panic_handler(_info: &core::panic::PanicInfo) -> ! { loop {} } #[export_name = "efi_main"] pub extern "C" fn main(_h: efi::Handle, st: *mut efi::SystemTable) -> efi::Status { let s = [ 0x0048u16, 0x0065u16, 0x006cu16, 0x006cu16, 0x006fu16, // "Hello" 0x0020u16, // " " 0x0057u16, 0x006fu16, 0x0072u16, 0x006cu16, 0x0064u16, // "World" 0x0021u16, // "!" 0x000au16, // "\n" 0x0000u16, // NUL ]; // Print "Hello World!". let r = unsafe { ((*(*st).con_out).output_string)((*st).con_out, s.as_ptr() as *mut efi::Char16) }; if r.is_error() { return r; } // Wait for key input, by waiting on the `wait_for_key` event hook. let r = unsafe { let mut x: usize = 0; ((*(*st).boot_services).wait_for_event)(1, &mut (*(*st).con_in).wait_for_key, &mut x) }; if r.is_error() { return r; } efi::Status::SUCCESS } ``` -------------------------------- ### Rust Stream Length Method Example Source: https://www.rustmax.net/api/std/io/trait.Seek Demonstrates how to get the length of a stream using the `stream_len` method from the `Seek` trait in Rust. This example requires the `seek_stream_len` feature. ```rust #![feature(seek_stream_len)] use std::{ io::{self, Seek}, fs::File, }; fn main() -> io::Result<()> { let mut f = File::open("foo.txt")?; let len = f.stream_len()?; println!("The file is currently {len} bytes long"); Ok(()) } ``` -------------------------------- ### Example: Reverse Automaton for Match Start Source: https://www.rustmax.net/api/regex_automata/hybrid/dfa/struct Illustrates using `MatchKind::All` to construct a reverse automaton for finding the start of a match, particularly the longest possible match. ```APIDOC # Example: reverse automaton to find start of match Another example for using `MatchKind::All` is for constructing a reverse automaton to find the start of a match. `All` semantics are used for this in order to find the longest possible match, which corresponds to the leftmost starting position. Note that if you need the starting position then `hybrid::regex::Regex` will handle this for you, so it's usually not necessary to do this yourself. ```rust use regex_automata::{ hybrid::dfa::DFA, nfa::thompson::NFA, Anchored, HalfMatch, Input, MatchKind, }; let input = Input::new("123foobar456"); let pattern = r"[a-z]+r"; let dfa_fwd = DFA::new(pattern)?; let dfa_rev = DFA::builder() .thompson(NFA::config().reverse(true)) .configure(DFA::config().match_kind(MatchKind::All)) .build(pattern)?; let mut cache_fwd = dfa_fwd.create_cache(); let mut cache_rev = dfa_rev.create_cache(); let expected_fwd = HalfMatch::must(0, 9); let expected_rev = HalfMatch::must(0, 3); let got_fwd = dfa_fwd.try_search_fwd(&mut cache_fwd, &input)?.unwrap(); // Here we don't specify the pattern to search for since there's only // one pattern and we're doing a leftmost search. But if this were an // overlapping search, you'd need to specify the pattern that matched // in the forward direction. (Otherwise, you might wind up finding the // starting position of a match of some other pattern.) That in turn // requires building the reverse automaton with starts_for_each_pattern // enabled. let input = input .clone() .range(..got_fwd.offset()) .anchored(Anchored::Yes); let got_rev = dfa_rev.try_search_rev(&mut cache_rev, &input)?.unwrap(); assert_eq!(expected_fwd, got_fwd); assert_eq!(expected_rev, got_rev); ``` ``` -------------------------------- ### Connection Initialization Example Source: https://www.rustmax.net/api/h2/client/struct.Connection Example demonstrating how to initiate an HTTP/2 connection using `h2::client::handshake` and submit the connection to an executor. ```APIDOC ## Examples ```rust # use tokio::io::{AsyncRead, AsyncWrite}; # use h2::client; # use h2::client::*; # # async fn doc(my_io: T) -> Result<(), h2::Error> # where T: AsyncRead + AsyncWrite + Send + Unpin + 'static, # { let (send_request, connection) = client::handshake(my_io).await?; // Submit the connection handle to an executor. tokio::spawn(async {{ connection.await.expect("connection failed"); }}); // Now, use `send_request` to initialize HTTP/2 streams. // ... # Ok(()) # } # # pub fn main() {} ``` ``` -------------------------------- ### Rust: Span - Get Start Span Source: https://www.rustmax.net/api/proc_macro/struct.Span Creates an empty `Span` that points to the position directly before the start of the current span. This can be used for precise positioning or range calculations. ```rust fn start(self: &Self) -> Span ``` -------------------------------- ### Run Example with Arguments - Rust Source: https://www.rustmax.net/library/cargo-book/commands/cargo-run Builds and runs a specific example target named 'exname' from the current Rust package. It also demonstrates how to pass additional arguments ('--exoption exarg1 exarg2') to the executed example binary. ```rust cargo run --example exname -- --exoption exarg1 exarg2 ``` -------------------------------- ### Rust: Example of Creating a GET Request Source: https://www.rustmax.net/api/http/request/struct Shows how to use `Request::get()` to quickly create a GET request builder, followed by setting the body to finalize the request. ```rust # use http::*; let request = Request::get("https://www.rust-lang.org/") .body(()) .unwrap(); ``` -------------------------------- ### Execute Rust Code Example Source: https://www.rustmax.net/library/mdbook/guide/reading Demonstrates how to execute Rust code samples within an mdBook. This feature allows users to run code directly and see the compiler output, facilitating learning and experimentation. ```rust println!("Hello, World!"); ``` -------------------------------- ### Router Creation and Basic Usage Source: https://www.rustmax.net/api/axum/routing/struct Demonstrates how to create a new Router and add a simple GET route. ```APIDOC ## POST /api/users ### Description Creates a new user with the provided information. ### Method POST ### Endpoint /api/users ### Parameters #### Query Parameters - **name** (string) - Required - The name of the user. - **email** (string) - Required - The email address of the user. ### Request Body ```json { "name": "John Doe", "email": "john.doe@example.com" } ``` ### Response #### Success Response (200) - **id** (string) - The unique identifier of the newly created user. - **message** (string) - A confirmation message. #### Response Example ```json { "id": "user-12345", "message": "User created successfully." } ``` ``` -------------------------------- ### Get VecDeque Length in Rust Source: https://www.rustmax.net/api/alloc/collections/vec_deque/struct.VecDeque Shows how to get the number of elements in a `VecDeque` using the `len()` method. It includes examples of checking the length of an empty deque and a deque after adding an element. ```rust use std::collections::VecDeque; let mut deque = VecDeque::new(); assert_eq!(deque.len(), 0); deque.push_back(1); assert_eq!(deque.len(), 1); ``` -------------------------------- ### Example: Add Multiple Arguments Using `args` (Rust) Source: https://www.rustmax.net/api/tokio/process/struct.Command Demonstrates the usage of the `args` method to pass a collection of arguments to a command and execute it asynchronously. ```rust use tokio::process::Command; let output = Command::new("ls") .args(&["-l", "-a"]) .output().await.unwrap(); ``` -------------------------------- ### Get Atomic Access from Mutable u32 in Rust Source: https://www.rustmax.net/api/core/sync/atomic/struct.AtomicU32 Demonstrates how to get atomic access to a `&mut u32` using `from_mut`. This allows atomic operations on a mutable integer. The example initializes an integer, gets atomic access, stores a new value, and then asserts that the value has been updated. ```rust #![feature(atomic_from_mut)] use std::sync::atomic::{AtomicU32, Ordering}; let mut some_int = 123; let a = AtomicU32::from_mut(&mut some_int); a.store(100, Ordering::Relaxed); assert_eq!(some_int, 100); ``` -------------------------------- ### Example: Using from_mut to atomically access a pointer Source: https://www.rustmax.net/api/core/sync/atomic/struct.AtomicPtr Illustrates using `from_mut` to get atomic access to a mutable pointer and then performing an atomic store operation. This example requires the `atomic_from_mut` feature. ```rust #![feature(atomic_from_mut)] use std::sync::atomic::{AtomicPtr, Ordering}; let mut data = 123; let mut some_ptr = &mut data as *mut i32; let a = AtomicPtr::from_mut(&mut some_ptr); let mut other_data = 456; a.store(&mut other_data, Ordering::Relaxed); assert_eq!(unsafe { *some_ptr }, 456); ``` -------------------------------- ### Setup Rust Development Environment Source: https://www.rustmax.net/library/rust-forge/infra/docs/dev-desktop This script, `/usr/local/bin/setup_rust.sh`, is used to set up a local Rust development environment. It clones a personal fork of the `rust-lang/rust` repository, compiles the latest version, and links stages for local work. ```bash /usr/local/bin/setup_rust.sh ``` -------------------------------- ### Rustdoc Table Example Source: https://www.rustmax.net/library/rustdoc-book/how-to-write-documentation Illustrates how to create tables in Rustdoc using pipes and dashes to define rows and columns. This syntax is based on the GitHub Tables extension. ```markdown | Header1 | Header2 | |---------|---------| | abc | def | ``` -------------------------------- ### Rust `offset_of` Macro Examples Source: https://www.rustmax.net/api/core/mem/macro Provides practical examples of using the `offset_of` macro in Rust. It shows how to get the offsets of individual fields in a struct and how to access the offset of a nested field. ```rust use std::mem; #[repr(C)] struct FieldStruct { first: u8, second: u16, third: u8 } assert_eq!(mem::offset_of!(FieldStruct, first), 0); assert_eq!(mem::offset_of!(FieldStruct, second), 2); assert_eq!(mem::offset_of!(FieldStruct, third), 4); #[repr(C)] struct NestedA { b: NestedB } #[repr(C)] struct NestedB(u8); assert_eq!(mem::offset_of!(NestedA, b.0), 0); ``` -------------------------------- ### Rustdoc Example with Error Handling using `?` Source: https://www.rustmax.net/library/api-guidelines/documentation Illustrates how to structure fallible example code in Rustdoc using the `?` operator for error propagation. Lines starting with `#` are hidden from the rendered documentation but are compiled during testing. ```rust /// ```rust /// # use std::error::Error; /// # /// # fn main() -> Result<(), Box> { /// your; /// example?; /// code; /// # /// # Ok(()) /// # } /// ``` ``` -------------------------------- ### Compile Rust to LLVM IR with optimizations Source: https://www.rustmax.net/library/rustc-dev-guide/backend/debugging This example shows how to compile a Rust file to LLVM IR with specific optimization flags enabled. It uses `rustc` with `--emit=llvm-ir`, `-O`, `-C no-prepopulate-passes`, and `-C codegen-units=1`. It then demonstrates using the `opt` tool to further process the generated LLVM IR. ```bash $ rustc +local my-file.rs --emit=llvm-ir -O -C no-prepopulate-passes \ -C codegen-units=1 $ OPT=./build/$TRIPLE/llvm/bin/opt $ $OPT -S -O2 < my-file.ll > my ```