My rust cookbook, a list of good, useful crates (with thoughts and comments) + boilerplate snippets.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
rusty-snake 191c8a12b8 Remove snippets, not worth maintaining 6 months ago
.gitignore Initial commit 1 year ago
COPYING Initial commit 1 year ago
README.md Update README.md 6 months ago

README.md

Rust Cookbook

My rust cookbook. A list of good, useful crates (with thoughts and comments) + boilerplate snippets.
Have a look at the "official" cookbook too.

Beginner

  • beginner_tools – Useful library designed for new Rustacens, provides good examples that are useful in simple projects

The python like input() function it provides is very good for beginners while learning Rust.

use beginner_tools::input;

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let name: String = input("Your name: ")?;
    println!("Hello {}!", name);
}

If you need a input function for other tasks then learning, it's often better to hack your own one. Examples can be found at snippets/src/input.rs.

Command line argument parsing

  • clap – A simple to use, efficient, and full-featured Command Line Argument Parser
  • clap_complete – Generate shell completion scripts for your clap::Command

Concurrency, Parallelism and async/.await

  • async-std – Async version of the Rust standard library
  • crossbeam – Tools for concurrent programming
  • futures – An implementation of futures and streams featuring zero allocations, composability, and iterator-like interfaces.
  • parking_lot – More compact and efficient implementations of the standard synchronization primitives.
  • rayon – Simple work-stealing parallelism for Rust
  • smol – A small and fast async runtime
  • tokio – An event-driven, non-blocking I/O platform for writing asynchronous I/O backed applications.

D-Bus

  • zbus – API for D-Bus communication
  • zvariant – D-Bus & GVariant encoding & decoding

Errors

  • anyhow – Flexible concrete Error type built on std::error::Error
  • thiserror – derive(Error)

Which own should I use?

TL;DR: Use thiserror if the error should be handled by other Rust code (e.g. libraries and library like code) and anyhow for anthing else (where you just care about the representation that is shown to the user).

Comparison to thiserror

Use Anyhow if you don't care what error type your functions return, you just want it to be easy. This is common in application code. Use thiserror if you are a library that wants to design your own dedicated error type(s) so that on failures the caller gets exactly the information that you choose.

src: https://github.com/dtolnay/anyhow#comparison-to-thiserror

Comparison to anyhow

Use thiserror if you care about designing your own dedicated error type(s) so that the caller receives exactly the information that you choose in the event of failure. This most often applies to library-like code. Use Anyhow if you don't care what error type your functions return, you just want it to be easy. This is common in application-like code.

src: https://github.com/dtolnay/thiserror#comparison-to-anyhow

FFI

  • bindgen – Automatically generates Rust FFI bindings to C and C++ libraries.
  • cbindgen – A tool for generating C bindings to Rust code.
  • cc – A build-time dependency for Cargo build scripts to assist in invoking the native C compiler to compile native C code into a static archive to be linked into Rust code.
  • pkg-config – A library to run the pkg-config system tool at build time in order to be used in Cargo build scripts.
  • pyo3 – Bindings to Python interpreter

libc

  • libc – Raw FFI bindings to platform libraries like libc.
  • nix – Rust friendly bindings to *nix APIs
Pros of nix (negation is con of libc)
  • Rust friendly API
  • Safe where possible
Cons of nix (negation is pro of libc)
  • Not every libc function is implemented

HTTP

  • hyper – A fast and correct HTTP library.
  • reqwest – higher level HTTP client library

Logging

  • env_logger – A logging implementation for log which is configured via an environment variable.
  • log – A lightweight logging facade for Rust

Miscellaneous

  • ahash – A non-cryptographic hash function using AES-NI for high performance
  • bitflags – A macro to generate structures which behave like bitflags.
  • bytes – Types and traits for working with bytes
  • cfg-if – A macro to ergonomically define an item depending on a large number of #[cfg] parameters. Structured like an if-else chain, the first matching branch is the item that gets emitted.
  • chrono – Date and time library for Rust
  • compact_str – A memory efficient immutable string type that transparently stores strings on the stack, when possible
  • dirs – A tiny low-level library that provides platform-specific standard locations of directories for config, cache and other data on Linux, Windows, macOS and Redox by leveraging the mechanisms defined by the XDG base/user directory specifications on Linux, the Known Folder API on Windows, and the Standard Directory guidelines on macOS.
  • either – The enum Either with variants Left and Right is a general purpose sum type with two cases.
  • glob – Support for matching file paths against Unix shell style patterns.
  • heaplessstatic friendly data structures that don't require dynamic memory allocation
  • itertools – Extra iterator adaptors, iterator methods, free functions, and macros.
  • itoa – Fast integer primitive to string conversion
  • lazy_static – A macro for declaring lazily evaluated statics in Rust.
  • libseccomp – Rust Language Bindings for the libseccomp Library
  • once_cell – Single assignment cells and lazy values.
  • rand – Random number generators and other randomness functionality.
  • regex – An implementation of regular expressions for Rust. This implementation uses finite automata and guarantees linear time matching on all inputs.
  • smol_str – small-string optimized string type with O(1) clone
  • udev – libudev bindings for Rust

thoughts, comments and remarks

either

either is good for quick-and-dirty code, however for anything else it is better to write an own enum with more meaningful variants or to use a Trait Object.

lazy_static

For single-thread code you can also use thread_local!.

Parsing

  • addr – A library for parsing domain names
  • cargo-lock – Self-contained Cargo.lock parser with optional dependency graph analysis
  • semver – Semantic version parsing and comparison.
  • serde – A generic serialization/deserialization framework
  • serde_json – A JSON serialization file format
  • toml – A native Rust encoder and decoder of TOML-formatted files and streams. Provides implementations of the standard Serialize/Deserialize traits for TOML data to facilitate deserializing and serializing Rust structures.
  • url – URL library for Rust, based on the WHATWG URL Standard

Rust procedural macros

  • syn – Parser for Rust source code
  • quote – Quasi-quoting macro quote!(...)
  • proc-macro2 – A substitute implementation of the compiler's proc_macro API to decouple token-based libraries from the procedural macro use case.

Terminal output

  • color-backtrace – Colorful panic backtraces
  • termcolor – A simple cross platform library for writing colored text to a terminal.
  • textwrap – Powerful library for word wrapping, indenting, and dedenting strings