Cookin' with Rust

This Rust Cookbook is a collection of simple examples that demonstrate good practices to accomplish common programming tasks, using the crates of the Rust ecosystem.

Read more about Rust Cookbook, including tips for how to read the book, how to use the examples, and notes on conventions.

Contributing

This project is intended to be easy for new Rust programmers to contribute to, and an easy way to get involved with the Rust community. It needs and welcomes help. For details see CONTRIBUTING.md.

Algorithms

RecipeCratesCategories
Generate random numbersrand-badgecat-science-badge
Generate random numbers within a rangerand-badgecat-science-badge
Generate random numbers with given distributionrand-badge rand_distr-badgecat-science-badge
Generate random values of a custom typerand-badgecat-science-badge
Create random passwords from a set of alphanumeric charactersrand-badgecat-os-badge
Create random passwords from a set of user-defined charactersrand-badgecat-os-badge
Sort a Vector of Integersstd-badgecat-science-badge
Sort a Vector of Floatsstd-badgecat-science-badge
Sort a Vector of Structsstd-badgecat-science-badge

Command Line

RecipeCratesCategories
Parse command line argumentsclap-badgecat-command-line-badge
ANSI Terminalansi_term-badgecat-command-line-badge

Compression

RecipeCratesCategories
Decompress a tarballflate2-badge tar-badgecat-compression-badge
Compress a directory into a tarballflate2-badge tar-badgecat-compression-badge
Decompress a tarball while removing a prefix from the pathsflate2-badge tar-badgecat-compression-badge

Concurrency

RecipeCratesCategories
Spawn a short-lived threadcrossbeam-badgecat-concurrency-badge
Create a parallel data pipelinecrossbeam-badgecat-concurrency-badge
Pass data between two threadscrossbeam-badgecat-concurrency-badge
Maintain global mutable statelazy_static-badgecat-rust-patterns-badge
Calculate SHA1 sum of *.iso files concurrentlythreadpool-badge walkdir-badge num_cpus-badge ring-badgecat-concurrency-badgecat-filesystem-badge
Draw fractal dispatching work to a thread poolthreadpool-badge num-badge num_cpus-badge image-badgecat-concurrency-badgecat-science-badgecat-rendering-badge
Mutate the elements of an array in parallelrayon-badgecat-concurrency-badge
Test in parallel if any or all elements of a collection match a given predicaterayon-badgecat-concurrency-badge
Search items using given predicate in parallelrayon-badgecat-concurrency-badge
Sort a vector in parallelrayon-badge rand-badgecat-concurrency-badge
Map-reduce in parallelrayon-badgecat-concurrency-badge
Generate jpg thumbnails in parallelrayon-badge glob-badge image-badgecat-concurrency-badgecat-filesystem-badge

Cryptography

RecipeCratesCategories
Calculate the SHA-256 digest of a filering-badge data-encoding-badgecat-cryptography-badge
Sign and verify a message with an HMAC digestring-badgecat-cryptography-badge
Salt and hash a password with PBKDF2ring-badge data-encoding-badgecat-cryptography-badge

Data Structures

RecipeCratesCategories
Define and operate on a type represented as a bitfieldbitflags-badgecat-no-std-badge

Database

RecipeCratesCategories
Create a SQLite databaserusqlite-badgecat-database-badge
Insert and Query datarusqlite-badgecat-database-badge
Create tables in a Postgres databasepostgres-badgecat-database-badge
Insert and Query datapostgres-badgecat-database-badge
Aggregate datapostgres-badgecat-database-badge

Date and Time

RecipeCratesCategories
Measure elapsed timestd-badgecat-time-badge
Perform checked date and time calculationschrono-badgecat-date-and-time-badge
Convert a local time to another timezonechrono-badgecat-date-and-time-badge
Examine the date and timechrono-badgecat-date-and-time-badge
Convert date to UNIX timestamp and vice versachrono-badgecat-date-and-time-badge
Display formatted date and timechrono-badgecat-date-and-time-badge
Parse string into DateTime structchrono-badgecat-date-and-time-badge

Development Tools

Debugging

RecipeCratesCategories
Log a debug message to the consolelog-badge env_logger-badgecat-debugging-badge
Log an error message to the consolelog-badge env_logger-badgecat-debugging-badge
Log to stdout instead of stderrlog-badge env_logger-badgecat-debugging-badge
Log messages with a custom loggerlog-badgecat-debugging-badge
Log to the Unix sysloglog-badge syslog-badgecat-debugging-badge
Enable log levels per modulelog-badge env_logger-badgecat-debugging-badge
Use a custom environment variable to set up logginglog-badge env_logger-badgecat-debugging-badge
Include timestamp in log messageslog-badge env_logger-badge chrono-badgecat-debugging-badge
Log messages to a custom locationlog-badge log4rs-badgecat-debugging-badge

Versioning

RecipeCratesCategories
Parse and increment a version stringsemver-badgecat-config-badge
Parse a complex version stringsemver-badgecat-config-badge
Check if given version is pre-releasesemver-badgecat-config-badge
Find the latest version satisfying given rangesemver-badgecat-config-badge
Check external command version for compatibilitysemver-badgecat-text-processing-badge cat-os-badge

Build Time

RecipeCratesCategories
Compile and link statically to a bundled C librarycc-badgecat-development-tools-badge
Compile and link statically to a bundled C++ librarycc-badgecat-development-tools-badge
Compile a C library while setting custom definescc-badgecat-development-tools-badge

Encoding

RecipeCratesCategories
Percent-encode a stringpercent-encoding-badgecat-encoding-badge
Encode a string as application/x-www-form-urlencodedurl-badgecat-encoding-badge
Encode and decode hexdata-encoding-badgecat-encoding-badge
Encode and decode base64base64-badgecat-encoding-badge
Read CSV recordscsv-badgecat-encoding-badge
Read CSV records with different delimitercsv-badgecat-encoding-badge
Filter CSV records matching a predicatecsv-badgecat-encoding-badge
Handle invalid CSV data with Serdecsv-badge serde-badgecat-encoding-badge
Serialize records to CSVcsv-badgecat-encoding-badge
Serialize records to CSV using Serdecsv-badge serde-badgecat-encoding-badge
Transform one column of a CSV filecsv-badge serde-badgecat-encoding-badge
Serialize and deserialize unstructured JSONserde-json-badgecat-encoding-badge
Deserialize a TOML configuration filetoml-badgecat-encoding-badge
Read and write integers in little-endian byte orderbyteorder-badgecat-encoding-badge

File System

RecipeCratesCategories
Read lines of strings from a filestd-badgecat-filesystem-badge
Avoid writing and reading from a same filesame_file-badgecat-filesystem-badge
Access a file randomly using a memory mapmemmap-badgecat-filesystem-badge
File names that have been modified in the last 24 hoursstd-badgecat-filesystem-badge cat-os-badge
Find loops for a given pathsame_file-badgecat-filesystem-badge
Recursively find duplicate file nameswalkdir-badgecat-filesystem-badge
Recursively find all files with given predicatewalkdir-badgecat-filesystem-badge
Traverse directories while skipping dotfileswalkdir-badgecat-filesystem-badge
Recursively calculate file sizes at given depthwalkdir-badgecat-filesystem-badge
Find all png files recursivelyglob-badgecat-filesystem-badge
Find all files with given pattern ignoring filename caseglob-badgecat-filesystem-badge

Hardware Support

RecipeCratesCategories
Check number of logical cpu coresnum_cpus-badgecat-hardware-support-badge

Memory Management

RecipeCratesCategories
Declare lazily evaluated constantlazy_static-badgecat-caching-badge cat-rust-patterns-badge

Networking

RecipeCratesCategories
Listen on unused port TCP/IPstd-badgecat-net-badge

Operating System

RecipeCratesCategories
Run an external command and process stdoutregex-badgecat-os-badge cat-text-processing-badge
Run an external command passing it stdin and check for an error coderegex-badgecat-os-badge cat-text-processing-badge
Run piped external commandsstd-badgecat-os-badge
Redirect both stdout and stderr of child process to the same filestd-badgecat-os-badge
Continuously process child process' outputsstd-badgecat-os-badgecat-text-processing-badge
Read environment variablestd-badgecat-os-badge

Science

Mathematics

RecipeCratesCategories
Vector Normndarray-badgecat-science-badge
Adding matricesndarray-badgecat-science-badge
Multiplying matricesndarray-badgecat-science-badge
Multiply a scalar with a vector with a matrixndarray-badgecat-science-badge
Invert matrixnalgebra-badgecat-science-badge
Calculating the side length of a trianglestd-badgecat-science-badge
Verifying tan is equal to sin divided by cosstd-badgecat-science-badge
Distance between two points on the Earthstd-badgecat-science-badge
Creating complex numbersnum-badgecat-science-badge
Adding complex numbersnum-badgecat-science-badge
Mathematical functions on complex numbersnum-badgecat-science-badge
Measures of central tendencystd-badgecat-science-badge
Computing standard deviationstd-badgecat-science-badge
Big integersnum-badgecat-science-badge

Text Processing

RecipeCratesCategories
Collect Unicode Graphemesunicode-segmentation-badgecat-encoding-badge
Verify and extract login from an email addressregex-badge lazy_static-badgecat-text-processing-badge
Extract a list of unique #Hashtags from a textregex-badge lazy_static-badgecat-text-processing-badge
Extract phone numbers from textregex-badgecat-text-processing-badge
Filter a log file by matching multiple regular expressionsregex-badgecat-text-processing-badge
Replace all occurrences of one text pattern with another pattern.regex-badge lazy_static-badgecat-text-processing-badge
Implement the FromStr trait for a custom structstd-badgecat-text-processing-badge

Web Programming

Scraping Web Pages

RecipeCratesCategories
Extract all links from a webpage HTMLreqwest-badge select-badgecat-net-badge
Check webpage for broken linksreqwest-badge select-badge url-badgecat-net-badge
Extract all unique links from a MediaWiki markupreqwest-badge regex-badgecat-net-badge

Uniform Resource Locations (URL)

RecipeCratesCategories
Parse a URL from a string to a Url typeurl-badgecat-net-badge
Create a base URL by removing path segmentsurl-badgecat-net-badge
Create new URLs from a base URLurl-badgecat-net-badge
Extract the URL origin (scheme / host / port)url-badgecat-net-badge
Remove fragment identifiers and query pairs from a URLurl-badgecat-net-badge

Media Types (MIME)

RecipeCratesCategories
Get MIME type from stringmime-badgecat-encoding-badge
Get MIME type from filenamemime-badgecat-encoding-badge
Parse the MIME type of a HTTP responsemime-badge reqwest-badgecat-net-badge cat-encoding-badge

Clients

RecipeCratesCategories
Make a HTTP GET requestreqwest-badgecat-net-badge
Query the GitHub APIreqwest-badge serde-badgecat-net-badge cat-encoding-badge
Check if an API resource existsreqwest-badgecat-net-badge
Create and delete Gist with GitHub APIreqwest-badge serde-badgecat-net-badge cat-encoding-badge
Consume a paginated RESTful APIreqwest-badge serde-badgecat-net-badge cat-encoding-badge
Download a file to a temporary directoryreqwest-badge tempdir-badgecat-net-badge cat-filesystem-badge
Make a partial download with HTTP range headersreqwest-badgecat-net-badge
POST a file to paste-rsreqwest-badgecat-net-badge

Web Authentication

RecipeCratesCategories
Basic Authenticationreqwest-badgecat-net-badge