### Set up a new Cargo Project in Rust Source: https://rust-lang-nursery.github.io/rust-cookbook/about These commands show how to create a new binary Cargo project, navigate into its directory, install the 'cargo-edit' tool, and add the 'rand' crate as a dependency. This is a prerequisite for running the random number generation example. ```bash cargo new my-example --bin cd my-example ``` ```bash cargo install cargo-edit cargo add rand ``` ```bash cargo run ``` -------------------------------- ### Setting up a Rust Project with Cargo and Adding Dependencies Source: https://rust-lang-nursery.github.io/rust-cookbook/print Provides instructions for creating a new Rust project using Cargo, navigating to the project directory, installing `cargo-edit` for dependency management, and adding the `rand` crate to `Cargo.toml`. ```bash cargo new my-example --bin cd my-example cargo install cargo-edit cargo add rand cargo run ``` -------------------------------- ### Link C Library with Rust using cc crate Source: https://rust-lang-nursery.github.io/rust-cookbook/print This example shows how to compile a C source file and link it into a Rust project. The `build.rs` script uses the `cc` crate to compile `src/hello.c` into a static library that Rust can then call. ```toml [package] ... build = "build.rs" [build-dependencies] cc = "1" ``` ```rust fn main() { cc::Build::new() .file("src/hello.c") .compile("hello"); // outputs `libhello.a` } ``` ```c #include void hello() { printf("Hello from C!\n"); } void greet(const char* name) { printf("Hello, %s\n", name); } ``` ```rust use anyhow::Result; use std::ffi::CString; use std::os::raw::c_char; fn prompt(s: &str) -> Result { use std::io::Write; print!("{}", s); std::io::stdout().flush()?; let mut input = String::new(); std::io::stdin().read_line(&mut input)?; Ok(input.trim().to_string()) } extern { fn hello(); fn greet(name: *const c_char); } fn main() -> Result<()> { unsafe { hello() } let name = prompt("What's your name? ")?; let c_name = CString::new(name)?; unsafe { greet(c_name.as_ptr()) } Ok(()) } ``` -------------------------------- ### Link C Library with Custom Defines using cc crate Source: https://rust-lang-nursery.github.io/rust-cookbook/print This example shows how to compile a C source file with custom preprocessor defines. The `cc::Build::define` method is used in `build.rs` to set macros like `APP_NAME`, `VERSION`, and `WELCOME`. ```toml [package] ... version = "1.0.2" build = "build.rs" [build-dependencies] cc = "1" ``` ```rust fn main() { cc::Build::new() .define("APP_NAME", "\"foo\"") .define("VERSION", format!("\"{{}}\"", env!("CARGO_PKG_VERSION")).as_str()) .define("WELCOME", None) .file("src/foo.c") .compile("foo"); } ``` ```c #include void print_app_info() { #ifdef WELCOME printf("Welcome to "); #endif printf("%s - version %s\n", APP_NAME, VERSION); } ``` ```rust extern { fn print_app_info(); } fn main(){ unsafe { print_app_info(); } } ``` -------------------------------- ### Boxing Errors in Rust Source: https://rust-lang-nursery.github.io/rust-cookbook/errors/handle Demonstrates the basic strategy of boxing errors using `Box` for straightforward error handling, as recommended in Rust by Example. This is a simple approach for getting started with error management. ```rust use std::error::Error; fn main() -> Result<(), Box> { // Example of boxing errors let result: Result<(), Box> = Ok(()); result } ``` -------------------------------- ### Control Module Logging with RUST_LOG Source: https://rust-lang-nursery.github.io/rust-cookbook/development_tools/debugging/config_log Demonstrates how to control logging verbosity for different modules in a Rust application using the `RUST_LOG` environment variable. The example defines nested modules `foo` and `foo::bar` and shows how to set individual log levels for each. ```rust mod foo { mod bar { pub fn run() { log::warn!("[bar] warn"); log::info!("[bar] info"); log::debug!("[bar] debug"); } } pub fn run() { log::warn!("[foo] warn"); log::info!("[foo] info"); log::debug!("[foo] debug"); bar::run(); } } fn main() { env_logger::init(); log::warn!("[root] warn"); log::info!("[root] info"); log::debug!("[root] debug"); foo::run(); } ``` ```bash RUST_LOG="warn,test::foo=info,test::foo::bar=debug" ./test ``` ```text WARN:test: [root] warn WARN:test::foo: [foo] warn INFO:test::foo: [foo] info WARN:test::foo::bar: [bar] warn INFO:test::foo::bar: [bar] info DEBUG:test::foo::bar: [bar] debug ``` -------------------------------- ### Create and Query SQLite Database with rusqlite in Rust Source: https://rust-lang-nursery.github.io/rust-cookbook/print Demonstrates how to use the `rusqlite` crate in Rust to open an SQLite database and create two tables: `cat_colors` and `cats`. The `Connection::open` function creates the database file if it does not exist. This example focuses on table creation and assumes the database file will be named 'cats.db'. ```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(()) } ``` -------------------------------- ### Set HTTP Headers and URL Parameters in Rust using reqwest Source: https://rust-lang-nursery.github.io/rust-cookbook/web/clients/requests This Rust code snippet demonstrates how to set both standard and custom HTTP headers, along with URL parameters for a HTTP GET request. It utilizes the `reqwest` crate for making HTTP requests and `Url::parse_with_params` for building the URL. The `serde` crate is used for deserializing the JSON response. The example sends a request to `http://httpbin.org/headers` and asserts that the custom and standard headers, as well as the URL parameters, are correctly set and received by the server. ```rust use anyhow::Result; use reqwest::Url; use reqwest::blocking::Client; use reqwest::header::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("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["X-Powered-By"], "Rust"); Ok(()) } ``` -------------------------------- ### Manage SQLite Transactions in Rust with rusqlite Source: https://rust-lang-nursery.github.io/rust-cookbook/database/sqlite Demonstrates managing SQLite transactions using `rusqlite`. It shows how to initiate a transaction with `Connection::transaction`, commit it with `Transaction::commit`, and how operations within a transaction are rolled back if an error occurs or if not explicitly committed. ```rust use rusqlite::{Connection, Result}; fn main() -> Result<()> { let mut conn = Connection::open("cats.db")?; successful_tx(&mut conn)?; let res = rolled_back_tx(&mut conn); assert!(res.is_err()); Ok(()) } fn successful_tx(conn: &mut Connection) -> Result<()> { let tx = conn.transaction()?; tx.execute("delete from cat_colors", [])?; tx.execute("insert into cat_colors (name) values (?1)", ["lavender"])?; tx.execute("insert into cat_colors (name) values (?1)", ["blue"])?; tx.commit() } fn rolled_back_tx(conn: &mut Connection) -> Result<()> { let tx = conn.transaction()?; tx.execute("delete from cat_colors", [])?; tx.execute("insert into cat_colors (name) values (?1)", ["lavender"])?; tx.execute("insert into cat_colors (name) values (?1)", ["blue"])?; tx.execute("insert into cat_colors (name) values (?1)", ["lavender"])?; tx.commit() } ``` -------------------------------- ### Log to Unix Syslog using syslog crate Source: https://rust-lang-nursery.github.io/rust-cookbook/print Logs messages to the Unix syslog service. It utilizes the `syslog` crate for integration. Configuration includes the syslog facility, log level filter, and an optional application name. This example is conditional and only runs on Linux. ```rust #[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."); } ``` -------------------------------- ### Custom Rust Logging Format with Timestamp Source: https://rust-lang-nursery.github.io/rust-cookbook/print Illustrates creating a custom log formatter using `env_logger::Builder::format`. This example includes a timestamp obtained with `chrono::Local::now()` and formats it along with the log level and message, demonstrating advanced customization of log output. ```rust use std::io::Write; use chrono::Local; use env_logger::Builder; use log::LevelFilter; fn main() { Builder::new() .format(|buf, record| { writeln!(buf, "{} [{}] - {}", Local::now().format("%Y-%m-%dT%H:%M:%S"), record.level(), record.args() ) }) .filter(None, LevelFilter::Info) .init(); log::warn!("warn"); log::info!("info"); log::debug!("debug"); } ``` -------------------------------- ### Create SQLite Database and Tables in Rust with rusqlite Source: https://rust-lang-nursery.github.io/rust-cookbook/database/sqlite Opens or creates an SQLite database file and defines tables for cat colors and cats. It uses the `rusqlite` crate and the `Connection::open` and `Connection::execute` methods. The tables include primary keys and foreign key constraints. ```rust use rusqlite::{Connection, Result}; fn main() -> Result<()> { let conn = Connection::open("cats.db")?; conn.execute( "create table if not exists cat_colors (\n id integer primary key,\n name text not null unique\n )", (), )?; conn.execute( "create table if not exists cats (\n id integer primary key,\n name text not null,\n color_id integer not null references cat_colors(id)\n )", (), )?; Ok(()) } ``` -------------------------------- ### Insert and Query Data in SQLite with rusqlite Source: https://rust-lang-nursery.github.io/rust-cookbook/database/sqlite Inserts data into 'cat_colors' and 'cats' tables and then queries this data using `Connection::execute`, `Connection::last_insert_rowid`, `Connection::prepare`, and `statement::query_map`. It demonstrates handling relationships between tables and retrieving structured results. ```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")?; 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], )?; } } let mut stmt = conn.prepare( "SELECT c.name, cc.name FROM cats c\n INNER JOIN cat_colors cc\n 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 { if let Ok(found_cat) = cat { println!( "Found cat {:?} {} is " , found_cat, found_cat.name, found_cat.color, ); } } Ok(()) } ``` -------------------------------- ### Link C++ Library with Rust using cc crate Source: https://rust-lang-nursery.github.io/rust-cookbook/print This example demonstrates linking a C++ library into a Rust project. It involves setting the `cpp(true)` option in `build.rs` and using `extern "C"` in the C++ source to prevent name mangling. ```toml [package] ... build = "build.rs" [build-dependencies] cc = "1" ``` ```rust fn main() { cc::Build::new() .cpp(true) .file("src/foo.cpp") .compile("foo"); } ``` ```cpp extern "C" { int multiply(int x, int y); } int multiply(int x, int y) { return x*y; } ``` ```rust extern { fn multiply(x : i32, y : i32) -> i32; } fn main(){ unsafe { println!("{}", multiply(5,7)); } } ``` -------------------------------- ### Configure File Logging with log4rs Source: https://rust-lang-nursery.github.io/rust-cookbook/development_tools/debugging/config_log Sets up logging to a file named `output.log` using the `log4rs` crate. It configures a file appender with a custom pattern encoder and builds a configuration that directs all `Info` level logs and above to the specified file. ```rust use anyhow::Result; use log::LevelFilter; use log4rs::append::file::FileAppender; use log4rs::encode::pattern::PatternEncoder; use log4rs::config::{Appender, Config, Root}; fn main() -> Result<()> { let logfile = FileAppender::builder() .encoder(Box::new(PatternEncoder::new("{l} - {m}\n"))) .build("log/output.log")?; let config = Config::builder() .appender(Appender::builder().build("logfile", Box::new(logfile))) .build(Root::builder() .appender("logfile") .build(LevelFilter::Info))?; log4rs::init_config(config)?; log::info!("Hello, world!"); Ok(()) } ``` -------------------------------- ### Insert and Query Data in PostgreSQL using Rust Source: https://rust-lang-nursery.github.io/rust-cookbook/database/postgres This example shows how to insert data into the 'author' table and then query it using the `postgres` crate. It utilizes the `execute` method for inserts and the `query` method for retrieving data. Data is read into a custom `Author` struct. ```rust use postgres::{Client, NoTls, Error}; use std::collections::HashMap; struct Author { _id: i32, name: String, country: String } fn main() -> Result<(), Error> { let mut client = Client::connect("postgresql://postgres:postgres@localhost/library", NoTls)?; let mut authors = HashMap::new(); authors.insert(String::from("Chinua Achebe"), "Nigeria"); authors.insert(String::from("Rabindranath Tagore"), "India"); authors.insert(String::from("Anita Nair"), "India"); for (key, value) in &authors { let author = Author { _id: 0, name: key.to_string(), country: value.to_string() }; client.execute( "INSERT INTO author (name, country) VALUES ($1, $2)", &[&author.name, &author.country], )?; } for row in client.query("SELECT id, name, country FROM author", &[])? { let author = Author { _id: row.get(0), name: row.get(1), country: row.get(2), }; println!("Author {} is from {}", author.name, author.country); } Ok(()) } ``` -------------------------------- ### Test File Equality with same_file::Handle in Rust Source: https://rust-lang-nursery.github.io/rust-cookbook/print Demonstrates how to use `same_file::Handle` to test if two file handles refer to the same file. This is useful for preventing accidental reads and writes to the same file, potentially causing data corruption. The example creates a file, obtains handles for it and standard output, and compares them. ```rust use same_file::Handle; use std::io::{BufRead, BufReader, Error, ErrorKind, Write}; use std::fs::File; use std::path::Path; fn main() -> Result<(), Error> { // Create a test file let mut file = File::create("new.txt")?; writeln!(file, "test content")?; let path_to_read = Path::new("new.txt"); let stdout_handle = Handle::stdout()?; let handle = Handle::from_path(path_to_read)?; if stdout_handle == handle { return Err(Error::new( ErrorKind::Other, "You are reading and writing to the same file", )); } else { let file = File::open(&path_to_read)?; let file = BufReader::new(file); for (num, line) in file.lines().enumerate() { println!("{} : {}", num, line?.to_uppercase()); } } Ok(()) } ``` -------------------------------- ### Create Tables in PostgreSQL using postgres crate Source: https://rust-lang-nursery.github.io/rust-cookbook/print Shows how to connect to a PostgreSQL database and create tables using the `postgres` crate. It demonstrates using `Client::connect` with a connection URL and `batch_execute` to run multiple SQL statements for table creation. ```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(()) } ``` -------------------------------- ### Synchronous HTTP GET Request with reqwest Source: https://rust-lang-nursery.github.io/rust-cookbook/web/clients/requests Makes a synchronous HTTP GET request to a specified URL using `reqwest::blocking::get`. It then reads the response status, headers, and body into a string. This example requires the `reqwest` crate with the `blocking` feature enabled. ```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(()) } ``` -------------------------------- ### Listen on a TCP port and accept connections in Rust Source: https://rust-lang-nursery.github.io/rust-cookbook/print This example demonstrates setting up a TCP listener in Rust. It binds to a random available port (port 0) and prints the listening address. The program then waits for an incoming connection, reads data from the stream, and prints it to the console. It utilizes `std::net::TcpListener` for network operations and `std::io::Read` for data input. ```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 {}, access this port to end the program", port); let (mut tcp_stream, addr) = listener.accept()?; //block until requested println!("Connection received! {:?}", addr); let mut input = String::new(); let _ = tcp_stream.read_to_string(&mut input)?; println!("{:?} says {}", addr, input); Ok(()) } ``` -------------------------------- ### Calculate Total File Size Within Depth Limit (Rust) Source: https://rust-lang-nursery.github.io/rust-cookbook/file/dir Calculates the sum of sizes for all files up to 3 subdirectory levels deep, starting from the current directory. It uses `WalkDir::max_depth` to limit the traversal depth and `metadata().len()` to get file sizes. Files in the root directory are ignored. Requires the `walkdir` crate. ```rust use walkdir::WalkDir; fn main() { let total_size = WalkDir::new(".") .max_depth(3) .into_iter() .filter_map(|entry| entry.ok()) .filter_map(|entry| entry.metadata().ok()) .filter(|metadata| metadata.is_file()) .fold(0, |acc, m| acc + m.len()); println!("Total size: {} bytes.", total_size); } ``` -------------------------------- ### Get Logical CPU Cores Count in Rust Source: https://rust-lang-nursery.github.io/rust-cookbook/hardware/processor This snippet shows how to get the number of logical CPU cores using the `num_cpus::get()` function. It requires the `num_cpus` crate to be added as a dependency. The function returns an integer representing the core count. ```rust fn main() { println!("Number of logical cores is {}", num_cpus::get()); } ``` -------------------------------- ### Insert and Query Data in SQLite using rusqlite Source: https://rust-lang-nursery.github.io/rust-cookbook/print Demonstrates how to open a SQLite database, insert data into multiple tables (`cat_colors`, `cats`), retrieve the last inserted row ID, and then query the combined data. It uses `Connection::open`, `execute`, `last_insert_rowid`, `prepare`, and `query_map`. ```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")?; 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], )?; } } 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 { if let Ok(found_cat) = cat { println!( "Found cat {:?} {} is {}", found_cat, found_cat.name, found_cat.color, ); } } Ok(()) } ``` -------------------------------- ### Parallel Sorting of Strings with Rayon Source: https://rust-lang-nursery.github.io/rust-cookbook/concurrency/parallel An example of parallel sorting for a vector of Strings using `rayon::par_sort_unstable`. This method is generally faster than stable sorting algorithms. The example also shows populating a large vector with random values in parallel. Requires `rayon` and `rand` crates. ```rust use rand::Rng; use rayon::prelude::*; fn main() { let mut vec = vec![0; 1_000_000]; rand::thread_rng().fill(&mut vec[..]); vec.par_sort_unstable(); let first = vec.first().unwrap(); let last = vec.last().unwrap(); assert!(first <= last); } ``` -------------------------------- ### Asynchronous HTTP GET Request with Tokio and reqwest Source: https://rust-lang-nursery.github.io/rust-cookbook/web/clients/requests Performs an asynchronous HTTP GET request using `tokio` as the executor and `reqwest::get`. It retrieves the response status, headers, and body asynchronously. This requires `tokio` and `reqwest` crates, with `tokio` configured with the `full` feature. ```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(()) } ``` -------------------------------- ### Upload File Content to Paste.rs with Rust Source: https://rust-lang-nursery.github.io/rust-cookbook/web/clients/download Opens a local file named 'message', reads its content into a string, and then uploads this content to the paste.rs service using `reqwest::blocking::Client::post`. It prints the URL of the created paste returned by the server. This example demonstrates sending POST requests with a request body. ```rust use anyhow::Result; use std::fs::File; use std::io::Read; fn main() -> Result<()> { let paste_api = "https://paste.rs"; let mut file = File::open("message")?; let mut contents = String::new(); file.read_to_string(&mut contents)?; let client = reqwest::blocking::Client::new(); let res = client.post(paste_api) .body(contents) .send()?; let response_text = res.text()?; println!("Your paste is located at: {}",response_text ); Ok(()) } ``` -------------------------------- ### Percent-Encode and Decode String with percent-encoding crate Source: https://rust-lang-nursery.github.io/rust-cookbook/print This example demonstrates how to percent-encode and decode strings using the `percent-encoding` crate in Rust. It utilizes `utf8_percent_encode` and `percent_decode` functions with a custom ASCII set for encoding. ```rust use percent_encoding::{utf8_percent_encode, percent_decode, AsciiSet, CONTROLS}; use std::str::Utf8Error; /// https://url.spec.whatwg.org/#fragment-percent-encode-set const FRAGMENT: &AsciiSet = &CONTROLS.add(b' ').add(b'"').add(b'<').add(b'>').add(b'`'); fn main() -> Result<(), Utf8Error> { let input = "confident, productive systems programming"; let iter = utf8_percent_encode(input, FRAGMENT); let encoded: String = iter.collect(); assert_eq!(encoded, "confident,%20productive%20systems%20programming"); let iter = percent_decode(encoded.as_bytes()); let decoded = iter.decode_utf8()?; assert_eq!(decoded, "confident, productive systems programming"); Ok(()) } ``` -------------------------------- ### Parse Command-Line Arguments with Clap Builder Style in Rust Source: https://rust-lang-nursery.github.io/rust-cookbook/print Demonstrates how to parse command-line arguments using clap's builder pattern in Rust. It handles file paths using PathBuf and numerical inputs, providing default values and error handling for invalid inputs. Dependencies include the 'clap' crate. ```rust use std::path::PathBuf; use clap::{Arg, Command, builder::PathBufValueParser}; fn main() { let matches = Command::new("My Test Program") .version("0.1.0") .about("Teaches argument parsing") .arg(Arg::new("file") .short('f') .long("file") .help("A cool file") .value_parser(PathBufValueParser::default())) .arg(Arg::new("num") .short('n') .long("number") .help("Five less than your favorite number")) .get_matches(); let default_file = PathBuf::from("input.txt"); let myfile: &PathBuf = matches.get_one("file").unwrap_or(&default_file); println!("The file passed is: {}", myfile.display()); let num_str: Option<&String> = matches.get_one("num"); match num_str { None => println!("No idea what your favorite number is."), Some(s) => { let parsed: Result = s.parse(); match parsed { Ok(n) => println!("Your favorite number must be {}.", n + 5), Err(_) => println!("That's not a number! {}", s), } } } } ``` -------------------------------- ### Set HTTP Headers and URL Parameters with Reqwest in Rust Source: https://rust-lang-nursery.github.io/rust-cookbook/print This Rust code snippet shows how to construct a URL with query parameters and set custom and standard HTTP headers for a GET request using the reqwest library. It verifies the request URL and the sent headers against the response from httpbin.org/headers. Dependencies include anyhow, reqwest, and serde. ```rust use anyhow::Result; use reqwest::Url; use reqwest::blocking::Client; use reqwest::header::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("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["X-Powered-By"], "Rust"); Ok(()) } ``` -------------------------------- ### Create PostgreSQL Tables using Rust Source: https://rust-lang-nursery.github.io/rust-cookbook/database/postgres This snippet demonstrates how to connect to a PostgreSQL database and create tables using the `postgres` crate. It uses `Client::connect` with a URL string and `batch_execute` for SQL commands. Assumes a database named 'library' and default 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(()) } ``` -------------------------------- ### Convert Timezones with Chrono Source: https://rust-lang-nursery.github.io/rust-cookbook/datetime/duration Gets the current local time and converts it to UTC using `DateTime::from_utc`. It then demonstrates converting UTC time to other timezones like UTC+8 (China) and UTC-2 (Rio de Janeiro) using `FixedOffset`. ```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)); } ``` -------------------------------- ### Generate Thumbnails in Parallel using Rayon and Glob Source: https://rust-lang-nursery.github.io/rust-cookbook/print Generates thumbnails for all .jpg files in the current directory and saves them into a 'thumbnails' folder. Uses `glob::glob_with` to find files and Rayon's `par_iter` with `DynamicImage::resize` for parallel image resizing. ```rust use anyhow::Result; use std::path::Path; use std::fs::create_dir_all; use glob::{glob_with, MatchOptions}; use image::imageops::FilterType; use rayon::prelude::*; fn main() -> Result<()> { let options: MatchOptions = Default::default(); let files: Vec<_> = glob_with("*.jpg", options)? .filter_map(|x| x.ok()) .collect(); if files.len() == 0 { anyhow::bail!("No .jpg files found in current directory"); } let thumb_dir = "thumbnails"; create_dir_all(thumb_dir)?; println!("Saving {} thumbnails into '{}'...", files.len(), thumb_dir); let image_failures: Vec<_> = files .par_iter() .map(|path| { make_thumbnail(path, thumb_dir, 300) .map_err(|e| anyhow::anyhow!("Failed to process {}: {}", path.display(), e)) }) .filter_map(|x| x.err()) .collect(); image_failures.iter().for_each(|x| println!("{}", x)); println!("{} thumbnails saved successfully", files.len() - image_failures.len()); Ok(()) } fn make_thumbnail(original: PA, thumb_dir: PB, longest_edge: u32) -> Result<()> where PA: AsRef, PB: AsRef, { let img = image::open(original.as_ref())?; let file_path = thumb_dir.as_ref().join(original); Ok(img.resize(longest_edge, longest_edge, FilterType::Nearest) .save(file_path)?) } ``` -------------------------------- ### Perform Addition on Complex Numbers in Rust using num::complex Source: https://rust-lang-nursery.github.io/rust-cookbook/print Illustrates how to perform addition on complex numbers using the `num::complex::Complex` type. The example emphasizes that both operands must be of the same numeric type (e.g., both floats) for the operation to be valid. ```rust fn main() { let complex_num1 = num::complex::Complex::new(10.0, 20.0); // Must use floats let complex_num2 = num::complex::Complex::new(3.1, -4.2); let sum = complex_num1 + complex_num2; println!("Sum: {}", sum); } ``` -------------------------------- ### Execute Python statement and parse output in Rust Source: https://rust-lang-nursery.github.io/rust-cookbook/print This Rust example demonstrates how to execute Python code as an external command. It spawns a Python interpreter, pipes a Python statement to its standard input, and captures both standard output and standard error. The output is then parsed into a `HashSet` of unique words, ignoring case. This allows for leveraging Python's scripting capabilities within a Rust program. ```rust use anyhow::{Result, anyhow}; use std::collections::HashSet; use std::io::Write; use std::process::{Command, Stdio}; fn main() -> Result<()> { let mut child = Command::new("python").stdin(Stdio::piped()) .stderr(Stdio::piped()) .stdout(Stdio::piped()) .spawn()?; child.stdin .as_mut() .ok_or_else(|| anyhow!("Child process stdin has not been captured!"))?; child.stdin.as_mut().unwrap().write_all(b"import this; copyright(); credits(); exit()")?; let output = child.wait_with_output()?; if output.status.success() { let raw_output = String::from_utf8(output.stdout)?; let words = raw_output.split_whitespace() .map(|s| s.to_lowercase()) .collect::>(); println!("Found {} unique words:", words.len()); println!("{:#?}", words); Ok(()) } else { let err = String::from_utf8(output.stderr)?; return Err(anyhow!("External command failed:\n {}", err)); } } ``` -------------------------------- ### Initialize Logger from Environment Variable with env_logger Source: https://rust-lang-nursery.github.io/rust-cookbook/development_tools/debugging/config_log Initializes the `env_logger` with configuration parsed from the `MY_APP_LOG` environment variable. This allows runtime control over logging levels without recompiling. The logger then processes standard log messages. ```rust use env_logger::Builder; fn main() { Builder::from_env("MY_APP_LOG").init(); log::info!("informational message"); log::warn!("warning message"); log::error!("this is an error {}", "message"); } ``` -------------------------------- ### Measure Elapsed Time in Rust Source: https://rust-lang-nursery.github.io/rust-cookbook/print Measures the time elapsed during the execution of a function using `std::time::Instant`. It captures the start time, executes a function that simulates work (by sleeping), and then calculates the duration using `elapsed()`. The result is printed to the console. ```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); } ``` -------------------------------- ### Download Large Files with Progress in Rust using Reqwest Source: https://rust-lang-nursery.github.io/rust-cookbook/print Demonstrates how to download large files in chunks using `reqwest::blocking::Client::get` to manage memory usage and allow for resumable downloads. It first retrieves the file size using a HEAD request and then iterates through byte ranges, printing progress messages. Dependencies include `anyhow` and `reqwest`. ```rust __ use anyhow::{Result, anyhow}; use reqwest::header::{HeaderValue, CONTENT_LENGTH, RANGE}; use reqwest::StatusCode; use std::fs::File; use std::str::FromStr; struct PartialRangeIter { start: u64, end: u64, buffer_size: u32, } impl PartialRangeIter { pub fn new(start: u64, end: u64, buffer_size: u32) -> Result { if buffer_size == 0 { return Err(anyhow!("invalid buffer_size, give a value greater than zero.")); } Ok(PartialRangeIter { start, end, buffer_size, }) } } impl Iterator for PartialRangeIter { type Item = HeaderValue; fn next(&mut self) -> Option { if self.start > self.end { None } else { let prev_start = self.start; self.start += std::cmp::min(self.buffer_size as u64, self.end - self.start + 1); Some(HeaderValue::from_str(&format!("bytes={}- மூல{}", prev_start, self.start - 1)).expect("string provided by format!")) } } } fn main() -> Result<()> { let url = "https://httpbin.org/range/102400?duration=2"; const CHUNK_SIZE: u32 = 10240; let client = reqwest::blocking::Client::new(); let response = client.head(url).send()?; let length = response .headers() .get(CONTENT_LENGTH) .ok_or_else(|| anyhow!("response doesn't include the content length"))?; let length = u64::from_str(length.to_str()?).map_err(|_| anyhow!("invalid Content-Length header"))?; let mut output_file = File::create("download.bin")?; println!("starting download..."); for range in PartialRangeIter::new(0, length - 1, CHUNK_SIZE)? { println!("range {:?}", range); let mut response = client.get(url).header(RANGE, range).send()?; let status = response.status(); if !(status == StatusCode::OK || status == StatusCode::PARTIAL_CONTENT) { return Err(anyhow!("Unexpected server response: {}", status)); } std::io::copy(&mut response, &mut output_file)?; } let content = response.text()?; std::io::copy(&mut content.as_bytes(), &mut output_file)?; println!("Finished with success!"); Ok(()) } ``` -------------------------------- ### Custom Error Handling with error-chain in Rust Source: https://rust-lang-nursery.github.io/rust-cookbook/print Provides an example of using the `error-chain` crate to handle errors, specifically focusing on I/O operations and parsing. It defines custom error types that can automatically convert from standard library errors like `std::io::Error`. ```rust use error_chain::error_chain; use std::fs::File; use std::io::Read; error_chain!{ foreign_links { Io(std::io::Error); ParseInt(::std::num::ParseIntError); } } fn read_uptime() -> Result { let mut uptime = String::new(); File::open("/proc/uptime")?.read_to_string(&mut uptime)?; Ok(uptime .split('.') .next() .ok_or("Cannot parse uptime data")? .parse()?) } fn main() { match read_uptime() { Ok(uptime) => println!("uptime: {} seconds", uptime), Err(err) => eprintln!("error: {}", err), }; } ``` -------------------------------- ### Compile and Link Bundled C Code using 'cc' Crate in Rust Source: https://rust-lang-nursery.github.io/rust-cookbook/development_tools/build_tools This snippet demonstrates how to compile bundled C code into a static library and link it with a Rust project. It utilizes the 'cc' crate in a build script (build.rs) to compile a C file (src/hello.c) and then calls the compiled C functions (hello and greet) from Rust (src/main.rs). ```toml [package] ... build = "build.rs" [build-dependencies] cc = "1" [dependencies] anyhow = "1" ``` ```rust fn main() { cc::Build::new() .file("src/hello.c") .compile("hello"); // outputs `libhello.a` } ``` ```c #include void hello() { printf("Hello from C!\n"); } void greet(const char* name) { printf("Hello, %s\n", name); } ``` ```rust use anyhow::Result; use std::ffi::CString; use std::os::raw::c_char; fn prompt(s: &str) -> Result { use std::io::Write; print!("{}", s); std::io::stdout().flush()?; let mut input = String::new(); std::io::stdin().read_line(&mut input)?; Ok(input.trim().to_string()) } extern { fn hello(); fn greet(name: *const c_char); } fn main() -> Result<()> { unsafe { hello() } let name = prompt("What's your name? ")?; let c_name = CString::new(name)?; unsafe { greet(c_name.as_ptr()) } Ok(()) } ``` -------------------------------- ### Parse TOML String to Custom Struct (Rust) Source: https://rust-lang-nursery.github.io/rust-cookbook/print Parses a TOML formatted string directly into custom Rust structs using Serde. This provides type-safe access to TOML configuration data. The example defines `Config` and `Package` structs that match the TOML structure. ```rust use serde::Deserialize; use toml::de::Error; use std::collections::HashMap; #[derive(Deserialize)] struct Config { package: Package, dependencies: HashMap, } #[derive(Deserialize)] struct Package { name: String, version: String, authors: Vec, } fn main() -> Result<(), Error> { let toml_content = r#" [package] name = "your_package" version = "0.1.0" authors = ["You! "] [dependencies] serde = "1.0" "#; let package_info: Config = toml::from_str(toml_content)?; assert_eq!(package_info.package.name, "your_package"); assert_eq!(package_info.package.version, "0.1.0"); assert_eq!(package_info.package.authors, vec!["You! "]); assert_eq!(package_info.dependencies["serde"], "1.0"); Ok(()) } ``` -------------------------------- ### Execute Git Version Command and Parse (Rust) Source: https://rust-lang-nursery.github.io/rust-cookbook/development_tools/versioning Runs `git --version` using `std::process::Command`, captures its output, and parses the version string into a `semver::Version`. It then validates this version against a `semver::VersionReq`, returning an error if the command fails or the version doesn't match. ```rust use anyhow::{Result, anyhow}; use std::process::Command; use semver::{Version, VersionReq}; fn main() -> Result<()> { let version_constraint = "> 1.12.0"; let version_test = VersionReq::parse(version_constraint)?; let output = Command::new("git").arg("--version").output()?; if !output.status.success() { return Err(anyhow!("Command executed with failing error code")); } let stdout = String::from_utf8(output.stdout)?; let version = stdout.split(" ").last().ok_or_else(|| { anyhow!("Invalid command output") })?; let parsed_version = Version::parse(version)?; if !version_test.matches(&parsed_version) { return Err(anyhow!("Command version lower than minimum supported version (found {}, need {})", parsed_version, version_constraint)); } Ok(()) } ```