### Install xtask dependencies Source: https://github.com/rust-lang-nursery/rust-cookbook/blob/master/xtask/README.md Install the required tools for building and checking the project documentation. ```bash cargo install mdbook@0.4.43 lychee@0.17.0 ``` -------------------------------- ### Run the application with arguments Source: https://github.com/rust-lang-nursery/rust-cookbook/blob/master/src/cli/arguments/clap-basic.md Example command to execute the application with specific flags. ```bash $ cargo run -- -f myfile.txt -n 251 ``` -------------------------------- ### Clone and build the cookbook Source: https://github.com/rust-lang-nursery/rust-cookbook/blob/master/CONTRIBUTING.md Initial commands to clone the repository and install the required mdBook version. ```bash git clone https://github.com/rust-lang-nursery/rust-cookbook.git cd rust-cookbook ``` ```bash cargo install --version 0.4.43 mdbook ``` ```bash mdbook serve ``` -------------------------------- ### Clone and Serve the Rust Cookbook Source: https://github.com/rust-lang-nursery/rust-cookbook/blob/master/README.md Commands to clone the repository and start the local development server using mdbook. ```bash $ git clone https://github.com/rust-lang-nursery/rust-cookbook $ cd rust-cookbook $ cargo install mdbook --vers "0.4.43" $ mdbook serve --open ``` -------------------------------- ### Install dependencies and add crates Source: https://github.com/rust-lang-nursery/rust-cookbook/blob/master/src/about.md Commands to install the cargo-edit tool and add the rand crate to the project. ```sh cargo install cargo-edit cargo add rand ``` -------------------------------- ### Install Leptos Build Tool and WASM Target Source: https://github.com/rust-lang-nursery/rust-cookbook/blob/master/src/web/leptos.md Installs the cargo-leptos build tool and adds the wasm32-unknown-unknown target for Rust. ```shell cargo install cargo-leptos rustup target add wasm32-unknown-unknown ``` -------------------------------- ### Example stderr output Source: https://github.com/rust-lang-nursery/rust-cookbook/blob/master/src/development_tools/debugging/config_log/log-timestamp.md Shows the expected log format resulting from the custom logger configuration. ```text 2017-05-22T21:57:06 [WARN] - warn 2017-05-22T21:57:06 [INFO] - info ``` -------------------------------- ### Include random number generation example Source: https://github.com/rust-lang-nursery/rust-cookbook/blob/master/src/about.md Example of including a specific code segment from a file for random number generation. ```rust {{#include ../crates/algorithms/randomness/src/bin/rand.rs::7 }} ``` -------------------------------- ### Read and Write Files with Buffered I/O Source: https://context7.com/rust-lang-nursery/rust-cookbook/llms.txt Perform efficient file reading and writing using Rust's standard library and buffered I/O. This example demonstrates writing lines to a file and then reading them back. ```rust use std::fs::File; use std::io::{Write, BufReader, BufRead, Error}; fn main() -> Result<(), Error> { let path = "lines.txt"; // Write to file let mut output = File::create(path)?; write!(output, "Rust\n<3\nFun")?; // Read from file line by line let input = File::open(path)?; let buffered = BufReader::new(input); for line in buffered.lines() { println!("{}", line?); } Ok(()) } ``` -------------------------------- ### Run link and spell checkers Source: https://github.com/rust-lang-nursery/rust-cookbook/blob/master/CONTRIBUTING.md Commands to install and run linters for verifying links and spelling. ```bash cargo install lychee@0.17.0 ``` ```bash cargo xtask book cargo xtask test link ``` ```bash lychee --base . --config ./ci/lychee.toml . ``` ```bash [sudo] apt install aspell -y ``` ```bash brew install aspell ``` ```bash ./ci/spellcheck.sh # or, if you're using a different locale LANG=en_US.UTF-8 ./ci/spellcheck.sh ``` -------------------------------- ### Basic File Download Source: https://github.com/rust-lang-nursery/rust-cookbook/blob/master/src/web/clients/download.md Use the `reqwest` crate for simple GET requests to download files. Ensure the response is successful before attempting to save the content. ```rust use std::io::copy; use std::net::TcpStream; #[tokio::main] async fn main() -> Result<(), Box> { let url = "http://www.google.com"; let mut response = reqwest::get(url).await?; if response.status().is_success() { let mut dest = std::fs::File::create("google.html")?; let content = response.bytes().await?; copy(&mut content.as_ref(), &mut dest)?; } else { eprintln!("Request failed with status: {}", response.status()); } Ok(()) } ``` -------------------------------- ### Compress Directory to Tarball with flate2 and tar Source: https://context7.com/rust-lang-nursery/rust-cookbook/llms.txt Create gzip-compressed tar archives using the `flate2` and `tar` crates. This example compresses the contents of `/var/log` into `archive.tar.gz` under the `backup/logs` path within the archive. ```rust use std::fs::File; use flate2::Compression; use flate2::write::GzEncoder; fn main() -> Result<(), std::io::Error> { let tar_gz = File::create("archive.tar.gz")?; let enc = GzEncoder::new(tar_gz, Compression::default()); let mut tar = tar::Builder::new(enc); // Add directory contents under "backup/logs" path tar.append_dir_all("backup/logs", "/var/log")?; tar.finish()?; Ok(()) } ``` -------------------------------- ### HTTP GET Request (Async) Source: https://context7.com/rust-lang-nursery/rust-cookbook/llms.txt Make asynchronous HTTP GET requests using reqwest with Tokio. Ensure reqwest and tokio are added as dependencies. ```rust // Async version with Tokio use anyhow::Result; #[tokio::main] async fn main() -> Result<()> { let res = reqwest::get("http://httpbin.org/get").await?; println!("Status: {}", res.status()); println!("Headers:\n{:#?}", res.headers()); let body = res.text().await?; println!("Body:\n{}", body); Ok(()) } ``` -------------------------------- ### Implement a Custom Delay Future Source: https://github.com/rust-lang-nursery/rust-cookbook/blob/master/src/concurrency/custom_future/custom-future.md This example demonstrates a basic `Delay` future that resolves after a deadline. It is `Unpin` automatically and calls `wake_by_ref()` immediately to ensure the executor re-polls it. ```rust use std::future::Future; use std::pin::Pin; use std::task::{Context, Poll, Waker}; use std::time::{Duration, Instant}; struct Delay { time: Instant } impl Future for Delay { type Output = (); fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll { if Instant::now() >= self.time { Poll::Ready(()) } else { // Stub: In a real timer, you would register with a reactor. // For this example, we wake immediately so the executor re-polls us. cx.waker().wake_by_ref(); Poll::Pending } } } // Example usage (requires an async runtime to run): // async fn main() { // let deadline = Instant::now() + Duration::from_secs(1); // let delay = Delay { time: deadline }; // delay.await; // println!("Delay finished!"); // } ``` -------------------------------- ### Demonstrate Panic-Free Functions with `#[no_panic]` Source: https://github.com/rust-lang-nursery/rust-cookbook/blob/master/src/safety_critical/no_panic/no-panic.md This example showcases three functions (aggregation, lookup, and sensor normalization) that are guaranteed by the `#[no_panic]` attribute to never panic. This guarantee is verified by the compiler at link time. ```rust use safety_critical::critical_section; #[critical_section] fn aggregate(data: &[i32]) -> i32 { let mut sum = 0; for &val in data { sum += val; } sum } #[critical_section] fn lookup(data: &[i32], index: usize) -> Option { data.get(index).copied() } #[critical_section] fn normalize_sensor(value: f32) -> f32 { // Assume some normalization logic that doesn't panic // For example, clamping the value within a range value.max(0.0).min(100.0) } fn main() { let data = [1, 2, 3, 4, 5]; let sum = aggregate(&data); println!("Sum: {}", sum); match lookup(&data, 2) { Some(val) => println!("Value at index 2: {}", val), None => println!("Index out of bounds"), } let sensor_value = 55.5; let normalized = normalize_sensor(sensor_value); println!("Normalized sensor value: {}", normalized); } ``` -------------------------------- ### Wire Up Axum with Leptos Routes Source: https://github.com/rust-lang-nursery/rust-cookbook/blob/master/src/web/leptos.md Integrate Leptos routing with Axum by using `generate_route_list` and `leptos_routes`. This sets up Axum GET handlers to render the Leptos application shell on each request. ```rust async fn app() -> impl IntoResponse { // Generate a list of all routes defined in the App component. let routes = generate_route_list!(App); // Create an Axum application with the generated routes. let mut app = Route::new().nest("/", leptos_routes(routes)); // Add a handler for static files. app = app.nest_service("/pkg", ServeDir::new("pkg")); // Return the Axum application. app } #[tokio::main] async fn main() { // Initialize logging. // Initialize Leptos. let conf = get_configuration(None).await.unwrap(); // Mount the Leptos application. App::mount_to_body(conf.leptos_options.clone(), move |cx| view::view() // Start the Axum server. let addr = conf.http.addr; println!("Listening on http://{{}}", addr); axum::Server::bind(&addr).serve(app().into_make_service()).await.unwrap(); } ``` -------------------------------- ### Run External Commands with std::process::Command Source: https://context7.com/rust-lang-nursery/rust-cookbook/llms.txt Execute external commands and capture their output using `std::process::Command`. This example runs `git log --oneline` and counts the number of commits. Requires `anyhow` for error handling. ```rust use anyhow::{Result, anyhow}; use std::process::Command; fn main() -> Result<()> { let output = Command::new("git") .arg("log") .arg("--oneline") .output()?; if output.status.success() { let raw_output = String::from_utf8(output.stdout)?; let lines = raw_output.lines(); println!("Found {} commits", lines.count()); Ok(()) } else { Err(anyhow!("Command executed with failing error code")) } } ``` -------------------------------- ### Standalone Workspace Crate Pattern Source: https://github.com/rust-lang-nursery/rust-cookbook/blob/master/CLAUDE.md Preferred pattern for new examples, using mdBook include directives to pull code from independent workspace crates. ```rust {{#include ../../../crates/algorithms/randomness/src/bin/rand.rs }} ``` ```rust {{#include ../../../crates///src/bin/.rs }} ``` -------------------------------- ### Configure REST request headers and parameters Source: https://github.com/rust-lang-nursery/rust-cookbook/blob/master/src/web/clients/requests/header.md Uses reqwest::blocking::Client to send a GET request with custom headers and URL parameters. The response is verified against an echo service. ```rust use anyhow::Result; use reqwest::Url; use reqwest::blocking::Client; use reqwest::header::{AUTHORIZATION, USER_AGENT}; use serde::Deserialize; use std::collections::HashMap; #[derive(Deserialize, Debug)] pub struct HeadersEcho { pub headers: HashMap, } fn main() -> Result<()> { let url = Url::parse_with_params( "http://httpbin.org/headers", &[("lang", "rust"), ("browser", "servo")], )?; let response = Client::new() .get(url) .header(USER_AGENT, "Rust-test-agent") .header(AUTHORIZATION, "Bearer my-token") .header("X-Powered-By", "Rust") .send()?; assert_eq!( response.url().as_str(), "http://httpbin.org/headers?lang=rust&browser=servo" ); let out: HeadersEcho = response.json()?; assert_eq!(out.headers["User-Agent"], "Rust-test-agent"); assert_eq!(out.headers["Authorization"], "Bearer my-token"); assert_eq!(out.headers["X-Powered-By"], "Rust"); Ok(()) } ``` -------------------------------- ### Stack-Allocated Event Log with Heapless Vec Source: https://github.com/rust-lang-nursery/rust-cookbook/blob/master/src/safety_critical/heapless_alloc/heapless-alloc.md Demonstrates building a stack-allocated event log using `heapless::Vec`. This example highlights capacity enforcement, ensuring predictable, constant-memory behavior suitable for embedded systems. Ensure `heapless` is added as a dependency. ```rust use heapless::Vec; fn main() { // Allocate a Vec on the stack with a capacity of 10. let mut event_log: Vec = Vec::new(); // Push elements onto the Vec. for i in 0..5 { if event_log.push(i).is_err() { // Handle the error if the Vec is full. // In this case, it won't happen as we only push 5 elements. println!("Error: Event log is full!"); break; } } // Attempt to push more elements than capacity. for i in 5..15 { match event_log.push(i) { Ok(_) => println!("Pushed event: {}", i), Err(_) => { // This branch will be taken when capacity is exceeded. println!("Error: Event log is full! Cannot push {}.", i); // In a real-time system, you might log this, return an error, or take other corrective action. } } } // Print the contents of the event log. println!("Event log contents: {:?}", event_log); println!("Current length: {}", event_log.len()); println!("Current capacity: {}", event_log.capacity()); } ``` -------------------------------- ### URL Parsing with url crate Source: https://context7.com/rust-lang-nursery/rust-cookbook/llms.txt Parse and manipulate URLs using the `url` crate. This example demonstrates parsing a URL string and extracting its path, host, and query components. Ensure `url` is added to your Cargo.toml. ```rust use url::{Url, ParseError}; fn main() -> Result<(), ParseError> { let s = "https://github.com/rust-lang/rust/issues?labels=E-easy&state=open"; let parsed = Url::parse(s)?; println!("The path part of the URL is: {}", parsed.path()); println!("Host: {:?}", parsed.host_str()); println!("Query: {:?}", parsed.query()); Ok(()) } ``` -------------------------------- ### Build or serve documentation Source: https://github.com/rust-lang-nursery/rust-cookbook/blob/master/xtask/README.md Manage the project documentation using mdbook via the xtask book command. ```bash cargo xtask book [build|serve] ``` -------------------------------- ### HTTP GET Request (Blocking) Source: https://context7.com/rust-lang-nursery/rust-cookbook/llms.txt Make blocking HTTP GET requests using reqwest. Ensure the reqwest crate is added as a dependency. ```rust // Blocking version use anyhow::Result; use std::io::Read; fn main() -> Result<()> { let mut res = reqwest::blocking::get("http://httpbin.org/get")?; let mut body = String::new(); res.read_to_string(&mut body)?; println!("Status: {}", res.status()); println!("Headers:\n{:#?}", res.headers()); println!("Body:\n{}", body); Ok(()) } ``` -------------------------------- ### Local Development and Build Commands Source: https://github.com/rust-lang-nursery/rust-cookbook/blob/master/DEPLOYMENT.md Commands for setting up the development environment and manually executing the build and test pipeline. ```bash # Use the Makefile (recommended) make dev # Or run the development script ./scripts/dev.sh # Or manually: cargo install mdbook --vers "0.4.43" mdbook build cp -r assets/ book/ cargo test ./ci/spellcheck.sh list ``` -------------------------------- ### Using `semver` Command-Line Tool Source: https://github.com/rust-lang-nursery/rust-cookbook/blob/master/src/development_tools/versioning.md Demonstrates how to use the `semver` command-line tool for version manipulation. This tool is useful for scripting and CI/CD pipelines. ```bash # Increment patch version semver -i patch 1.2.3 # Output: 1.2.4 # Increment minor version semver -i minor 1.2.3 # Output: 1.3.0 # Increment major version semver -i major 1.2.3 # Output: 2.0.0 # Add pre-release tag semver -i prerelease 1.2.3 --pre-id beta # Output: 1.2.3-beta.0 ``` -------------------------------- ### Create a new Cargo project Source: https://github.com/rust-lang-nursery/rust-cookbook/blob/master/src/about.md Commands to initialize a new binary project and navigate into its directory. ```sh cargo new my-example --bin cd my-example ``` -------------------------------- ### Example backtrace output Source: https://github.com/rust-lang-nursery/rust-cookbook/blob/master/src/errors/handle/backtrace.md The expected output format when an error occurs during the deserialization process. ```text Error: Cannot read CSV data Caused by: Cannot deserialize RGB color Caused by: CSV deserialize error: record 1 (line: 2, byte: 15): field 1: number too large to fit in target type Caused by: field 1: number too large to fit in target type ``` -------------------------------- ### Open Built Documentation Source: https://github.com/rust-lang-nursery/rust-cookbook/blob/master/README.md Platform-specific commands to open the generated HTML documentation in a web browser. ```bash $ xdg-open ./book/index.html # linux $ start .\book\index.html # windows $ open ./book/index.html # mac ``` -------------------------------- ### Build and Test Commands Source: https://github.com/rust-lang-nursery/rust-cookbook/blob/master/CLAUDE.md Common shell commands for building the book, running tests, and managing development tasks. ```bash # Build the book make build # or: mdbook build # Run all tests (skeptic + spellcheck) make test # or: cargo test && ./ci/spellcheck.sh list # Run only skeptic tests (tests code examples in markdown) cargo test --test skeptic # Serve book locally with live reload make serve # or: mdbook serve --open # Build + test together make dev # xtask alternatives cargo xtask test all # run all tests cargo xtask test cargo # cargo tests only cargo xtask test link # link checking (requires lychee) cargo xtask book # build book cargo xtask book serve # serve book # Link checking cargo xtask test link # or: lychee --base . --config ./ci/lychee.toml . # Spellcheck ./ci/spellcheck.sh # interactive; add words to ci/dictionary.txt ``` -------------------------------- ### Deployment Commands Source: https://github.com/rust-lang-nursery/rust-cookbook/blob/master/README.md Commands for deploying the documentation to GitHub Pages. ```bash # Deploy to GitHub Pages (requires maintainer permissions) make deploy # Or use the script directly ./scripts/deploy.sh ``` -------------------------------- ### Run the project Source: https://github.com/rust-lang-nursery/rust-cookbook/blob/master/src/about.md Command to execute the current Cargo project. ```sh cargo run ``` -------------------------------- ### Example debug output Source: https://github.com/rust-lang-nursery/rust-cookbook/blob/master/src/development_tools/debugging/log/log-debug.md When `RUST_LOG` is set to `debug`, cargo will print debugging information and the formatted log message. ```text DEBUG:main: Executing query: DROP TABLE students ``` -------------------------------- ### Perform Basic HTTP Authentication Source: https://github.com/rust-lang-nursery/rust-cookbook/blob/master/src/web/clients/authentication/basic.md Uses the blocking client to send a GET request with basic authentication credentials. ```rust use reqwest::blocking::Client; use reqwest::Error; fn main() -> Result<(), Error> { let client = Client::new(); let user_name = "testuser".to_string(); let password: Option = None; let response = client .get("https://httpbin.org/") .basic_auth(user_name, password) .send(); println!("{:?}", response); Ok(()) } ``` -------------------------------- ### Makefile Commands for Project Management Source: https://github.com/rust-lang-nursery/rust-cookbook/blob/master/DEPLOYMENT.md Use these commands to manage the build, test, and deployment lifecycle of the project. ```bash make help # Show all available commands make build # Build the book locally make test # Run all tests make dev # Build and test (development workflow) make deploy # Deploy to GitHub Pages make serve # Serve locally with live reload make clean # Clean build artifacts ``` -------------------------------- ### Managing Pre-release Versions Source: https://github.com/rust-lang-nursery/rust-cookbook/blob/master/src/development_tools/versioning.md Shows how to create and manage pre-release versions, which are typically used for beta or release candidate builds. Pre-release versions are considered lower than the associated normal version. ```rust use semver::Version; fn main() { let mut v = Version::parse("1.0.0").unwrap(); // Add a pre-release tag v.pre_release.push("beta".parse().unwrap()); v.pre_release.push(1); assert_eq!(v, Version::parse("1.0.0-beta.1").unwrap()); // Compare versions let normal_version = Version::parse("1.0.0").unwrap(); assert!(v < normal_version); } ``` -------------------------------- ### Transform CSV Data Source: https://github.com/rust-lang-nursery/rust-cookbook/blob/master/src/encoding/csv.md Transforms CSV data by applying a function to each record before writing it. This example converts names to uppercase. ```rust use std::error::Error; fn main() -> Result<(), Box> { let mut rdr = csv::Reader::from_path("people.csv")?; let mut wtr = csv::Writer::from_path("output.csv")?; for result in rdr.records() { let mut record = result?; let name = record[0].to_uppercase(); record[0] = name.as_str(); wtr.write(record.iter().map(|s| s.as_str()))?; } wtr.flush()?; Ok(()) } ``` -------------------------------- ### Make an asynchronous HTTP GET request Source: https://github.com/rust-lang-nursery/rust-cookbook/blob/master/src/web/clients/requests/get.md Uses the tokio runtime to perform an asynchronous request with the non-blocking reqwest API. ```rust use anyhow::Result; #[tokio::main] async fn main() -> Result<()> { let res = reqwest::get("http://httpbin.org/get").await?; println!("Status: {}", res.status()); println!("Headers:\n{:#?}", res.headers()); let body = res.text().await?; println!("Body:\n{}", body); Ok(()) } ``` -------------------------------- ### Initialize and use Unix syslog Source: https://github.com/rust-lang-nursery/rust-cookbook/blob/master/src/development_tools/debugging/log/log-syslog.md Initializes the syslog backend with a facility, log level filter, and application name. Requires the syslog crate and is primarily supported on Linux systems. ```rust # #[cfg(target_os = "linux")] # #[cfg(target_os = "linux")] use syslog::{Facility, Error}; # #[cfg(target_os = "linux")] fn main() -> Result<(), Error> { syslog::init(Facility::LOG_USER, log::LevelFilter::Debug, Some("My app name"))?; log::debug!("this is a debug {}", "message"); log::error!("this is an error!"); Ok(()) } # #[cfg(not(target_os = "linux"))] # fn main() { # println!("So far, only Linux systems are supported."); # } ``` -------------------------------- ### Initialize a SQLite connection Source: https://github.com/rust-lang-nursery/rust-cookbook/blob/master/src/database/sqlite.md Establishes a connection to an in-memory SQLite database. ```rust use rusqlite::{Connection, Result}; fn main() -> Result<()> { let conn = Connection::open_in_memory()?; conn.execute( "CREATE TABLE person (id INTEGER PRIMARY KEY, name TEXT NOT NULL, data BLOB)", [], )?; Ok(()) } ``` -------------------------------- ### Perform a GET request Source: https://github.com/rust-lang-nursery/rust-cookbook/blob/master/src/web/clients/requests.md Uses the reqwest crate to fetch content from a URL. Ensure the reqwest crate is added to your Cargo.toml dependencies. ```rust use std::io::{self, Read}; use reqwest; fn main() -> Result<(), Box> { let mut res = reqwest::get("https://www.rust-lang.org")?; println!("Status: {}", res.status()); let mut body = String::new(); res.read_to_string(&mut body)?; println!("Body:\n{}", body); Ok(()) } ``` -------------------------------- ### Makefile Development Commands Source: https://github.com/rust-lang-nursery/rust-cookbook/blob/master/README.md Common Makefile targets for building, testing, and serving the documentation locally. ```makefile # Show all available commands make help # Build the book locally make build # Run tests make test # Build and test (development workflow) make dev # Serve the book locally with live reload make serve # Clean build artifacts make clean ``` -------------------------------- ### Make a synchronous HTTP GET request Source: https://github.com/rust-lang-nursery/rust-cookbook/blob/master/src/web/clients/requests/get.md Uses reqwest::blocking::get to perform a synchronous request and reads the response body into a String. ```rust use anyhow::Result; use std::io::Read; fn main() -> Result<()> { let mut res = reqwest::blocking::get("http://httpbin.org/get")?; let mut body = String::new(); res.read_to_string(&mut body)?; println!("Status: {}", res.status()); println!("Headers:\n{:#?}", res.headers()); println!("Body:\n{}", body); Ok(()) } ``` -------------------------------- ### Convert Local Time to Different Timezones in Rust Source: https://github.com/rust-lang-nursery/rust-cookbook/blob/master/src/datetime/duration/timezone.md Gets the local time and converts it to UTC, UTC+8, and UTC-2. Requires the chrono crate. ```rust use chrono::{DateTime, FixedOffset, Local, Utc}; fn main() { let local_time = Local::now(); let utc_time = DateTime::::from_utc(local_time.naive_utc(), Utc); let china_timezone = FixedOffset::east(8 * 3600); let rio_timezone = FixedOffset::west(2 * 3600); println!("Local time now is {}", local_time); println!("UTC time now is {}", utc_time); println!( "Time in Hong Kong now is {}", utc_time.with_timezone(&china_timezone) ); println!("Time in Rio de Janeiro now is {}", utc_time.with_timezone(&rio_timezone)); } ``` -------------------------------- ### Run tests Source: https://github.com/rust-lang-nursery/rust-cookbook/blob/master/CONTRIBUTING.md Commands to execute the full test suite or specifically the skeptic documentation tests. ```bash cargo test ``` ```bash cargo test --test skeptic ``` -------------------------------- ### Extract unique hashtags using regex Source: https://github.com/rust-lang-nursery/rust-cookbook/blob/master/src/text/regex/hashtags.md Uses a regular expression to find hashtags starting with a letter. Requires the regex and lazy_static crates. ```rust use lazy_static::lazy_static; use regex::Regex; use std::collections::HashSet; fn extract_hashtags(text: &str) -> HashSet<&str> { lazy_static! { static ref HASHTAG_REGEX : Regex = Regex::new( r"\#[a-zA-Z][0-9a-zA-Z_]*" ).unwrap(); } HASHTAG_REGEX.find_iter(text).map(|mat| mat.as_str()).collect() } fn main() { let tweet = "Hey #world, I just got my new #dog, say hello to Till. #dog #forever #2 #_ "; let tags = extract_hashtags(tweet); assert!(tags.contains("#dog") && tags.contains("#forever") && tags.contains("#world")); assert_eq!(tags.len(), 3); } ``` -------------------------------- ### Create tables with the postgres crate Source: https://github.com/rust-lang-nursery/rust-cookbook/blob/master/src/database/postgres/create_tables.md Connects to a local PostgreSQL database and executes SQL statements to create author and book tables. Requires a running database instance with the specified credentials. ```rust use postgres::{Client, NoTls, Error}; fn main() -> Result<(), Error> { let mut client = Client::connect("postgresql://postgres:postgres@localhost/library", NoTls)?; client.batch_execute(" CREATE TABLE IF NOT EXISTS author ( id SERIAL PRIMARY KEY, name VARCHAR NOT NULL, country VARCHAR NOT NULL ) ")?; client.batch_execute(" CREATE TABLE IF NOT EXISTS book ( id SERIAL PRIMARY KEY, title VARCHAR NOT NULL, author_id INTEGER NOT NULL REFERENCES author ) ")?; Ok(()) } ``` -------------------------------- ### Insert and select data in SQLite Source: https://github.com/rust-lang-nursery/rust-cookbook/blob/master/src/database/sqlite.md Demonstrates inserting rows into a table and retrieving them using prepared statements. ```rust use rusqlite::{params, Connection, Result}; #[derive(Debug)] struct Person { id: i32, name: String, data: Option>, } fn main() -> Result<()> { let conn = Connection::open_in_memory()?; conn.execute( "CREATE TABLE person (id INTEGER PRIMARY KEY, name TEXT NOT NULL, data BLOB)", [], )?; let me = Person { id: 0, name: "Steven".to_string(), data: None, }; conn.execute( "INSERT INTO person (name, data) VALUES (?1, ?2)", params![me.name, me.data], )?; let mut stmt = conn.prepare("SELECT id, name, data FROM person")?; let person_iter = stmt.query_map([], |row| { Ok(Person { id: row.get(0)?, name: row.get(1)?, data: row.get(2)?, }) })?; for person in person_iter { println!("Found person {:?}", person.unwrap()); } Ok(()) } ``` -------------------------------- ### Measure elapsed time with Instant Source: https://github.com/rust-lang-nursery/rust-cookbook/blob/master/src/datetime/duration/profile.md Uses Instant::now to mark the start and elapsed to calculate the duration. This operation does not mutate the original Instant object. ```rust use std::time::{Duration, Instant}; # use std::thread; # # fn expensive_function() { # thread::sleep(Duration::from_secs(1)); # } fn main() { let start = Instant::now(); expensive_function(); let duration = start.elapsed(); println!("Time elapsed in expensive_function() is: {:?}", duration); } ``` -------------------------------- ### Filter CSV Records Source: https://github.com/rust-lang-nursery/rust-cookbook/blob/master/src/encoding/csv.md Filters records from a CSV file based on a condition applied to a specific field. This example filters for records where the first field is 'Alice'. ```rust use std::error::Error; fn main() -> Result<(), Box> { let mut rdr = csv::Reader::from_path("people.csv")?; for result in rdr.records() { let record = result?; if record[0] == "Alice" { println!("{}", record.iter().collect::>().join(",")); } } Ok(()) } ``` -------------------------------- ### Configure Cargo.toml for C++ build Source: https://github.com/rust-lang-nursery/rust-cookbook/blob/master/src/development_tools/build_tools/cc-bundled-cpp.md Define the build script and add the cc crate as a build dependency. ```toml [package] ... build = "build.rs" [build-dependencies] cc = "1" ``` -------------------------------- ### Using the Paginated API Iterator Source: https://github.com/rust-lang-nursery/rust-cookbook/blob/master/src/web/clients/api/paginated.md This `main` function demonstrates how to use the `ReverseDependencies` iterator to fetch and print reverse dependencies for a given crate. It handles potential errors during iteration. ```rust fn main() -> Result<(), Box> { for dep in paginated::ReverseDependencies::of("serde")? { let dependency = dep?; println!("{} depends on {}", dependency.id, dependency.crate_id); } Ok(()) } ``` -------------------------------- ### Create SQLite Database and Tables in Rust Source: https://github.com/rust-lang-nursery/rust-cookbook/blob/master/src/database/sqlite/initialization.md Use `rusqlite::Connection::open` to create a new SQLite database file if it doesn't exist. This snippet also shows how to execute SQL commands to create tables with specified schemas. Ensure the `rusqlite` crate is added as a dependency. ```rust use rusqlite::{Connection, Result}; fn main() -> Result<()> { let conn = Connection::open("cats.db")?; conn.execute( "create table if not exists cat_colors ( id integer primary key, name text not null unique )", (), )?; conn.execute( "create table if not exists cats ( id integer primary key, name text not null, color_id integer not null references cat_colors(id) )", (), )?; Ok(()) } ``` -------------------------------- ### View generated help output Source: https://github.com/rust-lang-nursery/rust-cookbook/blob/master/src/cli/arguments/clap-basic.md Displays the automatically generated help information for the application. ```text Teaches argument parsing Usage: clap-cookbook [OPTIONS] Options: -f, --file A cool file -n, --number Five less than your favorite number -h, --help Print help -V, --version Print version ``` -------------------------------- ### Get current UTC date and time components Source: https://github.com/rust-lang-nursery/rust-cookbook/blob/master/src/datetime/parse/current.md Uses the chrono crate to access hour, minute, second, year, month, and day information from the current UTC time. ```rust use chrono::{Datelike, Timelike, Utc}; fn main() { let now = Utc::now(); let (is_pm, hour) = now.hour12(); println!( "The current UTC time is {:02}:{:02}:{:02} {}", hour, now.minute(), now.second(), if is_pm { "PM" } else { "AM" } ); println!( "And there have been {} seconds since midnight", now.num_seconds_from_midnight() ); let (is_common_era, year) = now.year_ce(); println!( "The current UTC date is {}-{:02}-{:02} {:?} ({})", year, now.month(), now.day(), now.weekday(), if is_common_era { "CE" } else { "BCE" } ); println!( "And the Common Era began {} days ago", now.num_days_from_ce() ); } ``` -------------------------------- ### Read Environment Variables in Rust Source: https://github.com/rust-lang-nursery/rust-cookbook/blob/master/src/os/external.md Access environment variables from within a Rust program. Use `std::env::var` to get a variable's value, which returns an `Option`. ```rust use std::env; fn main() { match env::var("PATH") { Ok(val) => println!("PATH is {}", val), Err(e) => eprintln!("Could not read PATH: {}", e), } match env::var("NON_EXISTENT_VAR") { Ok(val) => println!("NON_EXISTENT_VAR is {}", val), Err(e) => eprintln!("Could not read NON_EXISTENT_VAR: {}", e), } } ``` -------------------------------- ### Get Number of Logical CPU Cores in Rust Source: https://github.com/rust-lang-nursery/rust-cookbook/blob/master/src/hardware/processor/cpu-count.md Retrieves the number of logical CPU cores on the current machine using the `num_cpus` crate. Ensure the `num_cpus` crate is added as a dependency. ```rust fn main() { println!("Number of logical cores is {}", num_cpus::get()); } ``` -------------------------------- ### Cargo.toml configuration for C compilation Source: https://github.com/rust-lang-nursery/rust-cookbook/blob/master/src/development_tools/build_tools/cc-defines.md Specify the build script and add the `cc` crate as a build dependency. ```toml [package] ... version = "1.0.2" build = "build.rs" [build-dependencies] cc = "1" ``` -------------------------------- ### Configure Cargo.toml for build scripts Source: https://github.com/rust-lang-nursery/rust-cookbook/blob/master/src/development_tools/build_tools/cc-bundled-static.md Define the build script path and add the cc crate as a build dependency. ```toml [package] ... build = "build.rs" [build-dependencies] cc = "1" [dependencies] anyhow = "1" ``` -------------------------------- ### SQLite Database Operations in Rust Source: https://context7.com/rust-lang-nursery/rust-cookbook/llms.txt Demonstrates creating SQLite databases, inserting data, and querying results using the `rusqlite` crate. Ensure the `rusqlite` crate is added to your Cargo.toml. ```rust use rusqlite::{params, Connection, Result}; use std::collections::HashMap; #[derive(Debug)] struct Cat { name: String, color: String, } fn main() -> Result<()> { let conn = Connection::open("cats.db")?; // Create tables conn.execute( "CREATE TABLE IF NOT EXISTS cat_colors ( id INTEGER PRIMARY KEY, name TEXT NOT NULL UNIQUE )", ())?; conn.execute( "CREATE TABLE IF NOT EXISTS cats ( id INTEGER PRIMARY KEY, name TEXT NOT NULL, color_id INTEGER NOT NULL REFERENCES cat_colors(id) )", ())?; // Insert data let mut cat_colors = HashMap::new(); cat_colors.insert(String::from("Blue"), vec!["Tigger", "Sammy"]); cat_colors.insert(String::from("Black"), vec!["Oreo", "Biscuit"]); for (color, catnames) in &cat_colors { conn.execute("INSERT INTO cat_colors (name) VALUES (?1)", [color])?; let last_id = conn.last_insert_rowid(); for cat in catnames { conn.execute( "INSERT INTO cats (name, color_id) VALUES (?1, ?2)", params![cat, last_id], )?; } } // Query data let mut stmt = conn.prepare( "SELECT c.name, cc.name FROM cats c INNER JOIN cat_colors cc ON cc.id = c.color_id")?; let cats = stmt.query_map([], |row| { Ok(Cat { name: row.get(0)?, color: row.get(1)? }) })?; for cat in cats { println!("Found cat: {:?}", cat?); } Ok(()) } ``` -------------------------------- ### JSON Serialization and Deserialization in Rust Source: https://context7.com/rust-lang-nursery/rust-cookbook/llms.txt Parses and creates JSON data using `serde_json`. This example shows deserializing a string into a `Value` and comparing it with a `json!` macro-generated value. Ensure `serde_json` is in your Cargo.toml. ```rust use serde_json::json; use serde_json::{Value, Error}; fn main() -> Result<(), Error> { let j = r#"{ "userid": 103609, "verified": true, "access_privileges": ["user", "admin"] }""#; let parsed: Value = serde_json::from_str(j)?; let expected = json!({ "userid": 103609, "verified": true, "access_privileges": ["user", "admin"] }); assert_eq!(parsed, expected); println!("User ID: {}", parsed["userid"]); Ok(()) } ``` -------------------------------- ### Parallel Sort with Rayon Source: https://context7.com/rust-lang-nursery/rust-cookbook/llms.txt Utilize the `rayon` crate to perform parallel sorting on large collections, significantly improving performance on multi-core processors. This example uses `par_sort_unstable` for potentially faster sorting. ```rust use rand::RngExt; use rayon::prelude::*; fn main() { let mut vec = vec![0i32; 1_000_000]; rand::rng().fill(&mut vec[..]); // Parallel unstable sort - typically faster than stable vec.par_sort_unstable(); let first = vec.first().unwrap(); let last = vec.last().unwrap(); assert!(first <= last); } ``` -------------------------------- ### Configure build.rs for C++ compilation Source: https://github.com/rust-lang-nursery/rust-cookbook/blob/master/src/development_tools/build_tools/cc-bundled-cpp.md Use the cc crate to compile a C++ file with the cpp(true) method. ```rust fn main() { cc::Build::new() .cpp(true) .file("src/foo.cpp") .compile("foo"); } ``` -------------------------------- ### Download file to temporary directory Source: https://github.com/rust-lang-nursery/rust-cookbook/blob/master/src/web/clients/download/basic.md Use tempfile::Builder to create a temporary directory and reqwest::blocking::get to download a file. The temporary directory is automatically removed on program exit. ```rust use anyhow::Result; use std::io::Write; use std::fs::File; use tempfile::Builder; fn main() -> Result<()> { let tmp_dir = Builder::new().prefix("example").tempdir()?; let target = "https://www.rust-lang.org/logos/rust-logo-512x512.png"; let response = reqwest::blocking::get(target)?; let mut dest = { let fname = response .url() .path_segments() .and_then(|segments| segments.last()) .and_then(|name| if name.is_empty() { None } else { Some(name) }) .unwrap_or("tmp.bin"); println!("file to download: '{}'", fname); let fname = tmp_dir.path().join(fname); println!("will be located under: '{:?}'", fname); File::create(fname)? }; let content = response.bytes()?; dest.write_all(&content)?; Ok(()) } ``` -------------------------------- ### Calculate e^(2i * pi) using Complex Numbers in Rust Source: https://github.com/rust-lang-nursery/rust-cookbook/blob/master/src/science/mathematics/complex_numbers/mathematical-functions.md Use the `exp()` method on a `Complex` number to calculate its exponential. This example calculates e raised to the power of (2i * pi), which approximates to 1. ```rust use std::f64::consts::PI; use num::complex::Complex; fn main() { let x = Complex::new(0.0, 2.0*PI); println!("e^(2i * pi) = {}", x.exp()); // =~1 } ``` -------------------------------- ### Create a TCP Server Source: https://context7.com/rust-lang-nursery/rust-cookbook/llms.txt Listen for incoming TCP connections and read data from a stream using the standard library. ```rust use std::net::TcpListener; use std::io::{Read, Error}; fn main() -> Result<(), Error> { let listener = TcpListener::bind("localhost:0")?; let port = listener.local_addr()?; println!("Listening on {}", port); let (mut tcp_stream, addr) = listener.accept()?; println!("Connection from {:?}", addr); let mut input = String::new(); tcp_stream.read_to_string(&mut input)?; println!("Received: {}", input); Ok(()) } ``` -------------------------------- ### Regular Expression Matching in Rust Source: https://context7.com/rust-lang-nursery/rust-cookbook/llms.txt Filters and extracts data using regular expressions with the `regex` and `lazy_static` crates. This example defines a regex to extract a login from an email address. Ensure `regex` and `lazy_static` are in your Cargo.toml. ```rust use lazy_static::lazy_static; use regex::Regex; fn extract_login(input: &str) -> Option<&str> { lazy_static! { static ref RE: Regex = Regex::new(r"(?x) ^(?P[^@\s]+)@ ([[:word:]]+\.)* [[:word:]]+$ ").unwrap(); } RE.captures(input).and_then(|cap| { cap.name("login").map(|login| login.as_str()) }) } fn main() { assert_eq!(extract_login("user@example.com"), Some("user")); assert_eq!(extract_login("invalid@email"), None); println!("Email validation works!"); } ``` -------------------------------- ### Parallel Map-Reduce with Rayon Source: https://github.com/rust-lang-nursery/rust-cookbook/blob/master/src/concurrency/parallel/rayon-map-reduce.md Use `rayon::filter`, `rayon::map`, and `rayon::reduce` for parallel data processing. This example calculates the average age of people older than 30. Ensure Rayon is added as a dependency. ```rust use rayon::prelude::*; struct Person { age: u32, } fn main() { let v: Vec = vec![ Person { age: 23 }, Person { age: 19 }, Person { age: 42 }, Person { age: 17 }, Person { age: 17 }, Person { age: 31 }, Person { age: 30 }, ]; let num_over_30 = v.par_iter().filter(|&x| x.age > 30).count() as f32; let sum_over_30 = v.par_iter() .map(|x| x.age) .filter(|&x| x > 30) .reduce(|| 0, |x, y| x + y); let alt_sum_30: u32 = v.par_iter() .map(|x| x.age) .filter(|&x| x > 30) .sum(); let avg_over_30 = sum_over_30 as f32 / num_over_30; let alt_avg_over_30 = alt_sum_30 as f32/ num_over_30; assert!((avg_over_30 - alt_avg_over_30).abs() < std::f32::EPSILON); println!("The average age of people older than 30 is {}", avg_over_30); } ``` -------------------------------- ### Read Lines of Strings from a File in Rust Source: https://github.com/rust-lang-nursery/rust-cookbook/blob/master/src/file/read-write/read-file.md Use `File::create` to open a file for writing and `write!` to write content. Then, use `File::open` and `BufReader::new` to open the file for reading. Iterate over `buffered.lines()` to read the file line by line. Ensure proper error handling with `Result`. ```rust use std::fs::File; use std::io::{Write, BufReader, BufRead, Error}; fn main() -> Result<(), Error> { let path = "lines.txt"; let mut output = File::create(path)?; write!(output, "Rust\nšŸ’–\nFun")?; let input = File::open(path)?; let buffered = BufReader::new(input); for line in buffered.lines() { println!("{}", line?); } Ok(()) } ``` -------------------------------- ### Format Current UTC Time in Rust Source: https://github.com/rust-lang-nursery/rust-cookbook/blob/master/src/datetime/parse/format.md Use the chrono crate to get the current UTC time and print it in RFC 2822, RFC 3339, and a custom format. Ensure the chrono crate is added as a dependency. ```rust use chrono::{DateTime, Utc}; fn main() { let now: DateTime = Utc::now(); println!("UTC now is: {}", now); println!("UTC now in RFC 2822 is: {}", now.to_rfc2822()); println!("UTC now in RFC 3339 is: {}", now.to_rfc3339()); println!("UTC now in a custom format is: {}", now.format("%a %b %e %T %Y")); } ``` -------------------------------- ### Generate Random Values of Custom Type in Rust Source: https://github.com/rust-lang-nursery/rust-cookbook/blob/master/src/algorithms/randomness/rand-custom.md Implement the 'Distribution' trait for a custom type 'Point' to allow random generation. This example shows how to generate random tuples and instances of 'Point'. Requires the 'rand' crate. ```rust use rand::distributions::{Distribution, Standard, StandardUniform}; use rand::Rng; #[derive(Debug, Clone, Copy)] struct Point { x: f64, y: f64, } impl Distribution for StandardUniform { fn sample(&self, rng: &mut R) -> Point { Point { x: rng.gen(), y: rng.gen() } } } fn main() { let mut rng = rand::thread_rng(); // Generate a random tuple let tuple: (i32, bool, f64) = rng.gen(); println!("Random tuple: {:?}", tuple); // Generate a random Point let point: Point = rng.gen(); println!("Random point: {:?}", point); // Generate a random tuple of Points let points: (Point, Point) = rng.gen(); println!("Random points: {:?}", points); } ``` -------------------------------- ### Aggregate Data from Postgres Source: https://github.com/rust-lang-nursery/rust-cookbook/blob/master/src/database/postgres.md Demonstrates an SQL query to aggregate data, specifically counting posts per user. This query joins the users and posts tables. ```sql SELECT u.username, COUNT(p.id) AS post_count FROM users u LEFT JOIN posts p ON u.id = p.user_id GROUP BY u.username ORDER BY post_count DESC; ```