Rust is a programming language that is primarily focused on performance and safety. It is syntactically similar to C++ and extremely popular. In fact, Stack Overflow’s annual developer survey has named Rust the most-loved language among developers for five consecutive years.
What I love most about Rust is its static typing, which allows for the concept of null
. Unlike other statically typed programming languages, Rust encodes the null
concept using an optional type, which means the compiler requires you to handle the noncase error preventing the TypeError: Cannot read property 'foo' of null
runtime error. Instead of the above runtime error, you get a compile-time error that can be resolved easily.
With Rust, you can also store your data on the stack or on the heap. This helps you determine what data is no longer needed during compile time.
There is a wide variety of open-source web utilities available to enhance Rust’s functionality. For example, although Rust’s standard library does not contain any regex parser/matcher, the regex
utility provides a regex parser. With regex
, you can search, split, or replace text.
Take a look at the expression below, which enables you to quickly search for a US number.
let re = Regex::new("[0-9]{3}-[0-9]{3}-[0-9]{4}").unwrap(); let mat = re.find("phone: 111-222-3333").unwrap(); assert_eq!((mat.start(), mat.end()), (7, 19));
This is just one example of how web utilities can help you take your Rust app to the next level. In this guide, we’ll introduce you to 19 of the most popular and useful web utilities for Rust:
cookie
clap
heim
tempfile
urlencoded
bodyparser
queryst
scgi
sass-rs
ratelimit_meter
regex
chrono
time
backtrace
docopt
structopt
url
robotparser
multipart
cookie
This utility enhances HTTP cookie parsing and cookie jar management. The cookie
library is licensed under MIT and Apache 2.0. According to crates.io, it has 62 versions, the stable most recent of which is 0.14.2. At the time of writing, cookie
has been downloaded roughly 5.8 million times.
The following features of cookie
are disabled by default.
percent-encode
allows percent encoding of the names and values in cookies. The cookie:: parse_encoded()
method allows percent decoding for the name and value of a cookie while parsing. The cookie:: encoded
method returns a wrapper around cookies and percent-encodes cookies with its Display
implementationsigned
enables cookies to be signed with the CookieJar::signed()
methodprivate
— When you have the private feature enabled with the CookieJar::private()
method, cookies are encrypted, decrypted, and authenticated as they are added and retrievedsigned
and private
features, as well as the Key::derive_from()
method. With the Key::derive_from()
method, you can derive a key structure that would be appropriate for use in the single
or private
jars, which would be shorter in length than a full keysecure
is a meta feature that can toggle between enabling signed
, private
, and key-expansion
. Enable it by adding the following code to your Cargo.toml
file:[dependencies.cookie] features = ["secure", "percent-encode"]
clap
The clap
crate is the best tool for parsing and validating command-line arguments and subcommands while writing console applications with Rust. This library is licensed with MIT and has 211 versions released, the most stable of which is 2.33.3 (version 3.0.0 is still in its beta phase). At the time of writing, it has more than 15 million downloads.
Alternatively, you could build your CLI using a YAML file to keep your Rust source tidy.
The following built-in features are enabled by default.
Did you mean '--myoption'?
To disable the features above, add the following code to your cargo.toml
file.
[dependencies.clap] version = "~2.27.0" default-features = false
You can also enable only the features you would like to use by pasting the code below into your cargo.toml
file.
[dependencies.clap] version = "~2.27.0" default-features = false # Cherry-pick the features you'd like to use features = [ "suggestions", "color" ]
The following are opt-in features; they are not built-in.
.yaml
fileunstable
enables you to use unstable clap featuresheim
heim
is a cross-platform library that can be used for system information fetching. It uses async-first and is cross-platform and modular.
The library’s GitHub page includes a helpful comparison of heim
to other crates.
heim
is licensed under MIT and Apache 2.0. The most stable of 15 versions is 0.0.10, while version 0.10 is in its beta phase.
tempfile
The tempfile
crate includes the tempfile()
and tempdir()
functions, which enable you to create temporary files and directories. Let’s say, for example, that you want to create a file but don’t care about its name since it will be a temporary file that you can delete later. The tempfile
library would make this process this easier because it would delete the file once you’re done.
The tempfile()
function relies on the operating system to remove the temporary file immediately after you close the last handle, while the tempdir()
function relies on Rust destructors for cleanup. The tempdir()
function may fail if destructors do not run, while the tempfile()
function will hardly ever fail since it relies on the computer’s operating system.
This library is licensed under MIT and Apache 2.0 and has 35 versions released, its most recent stable version being 3.1.0.
urlencoded
urlencoded
is a middleware for the Iron web framework that helps you decode URL data from GET and POST requests. It parses a URL query string into a HashMaps
that maps string representations of keys onto a vec of string values. Values are stored in a vec to ensure that no information is lost if a key appears multiple times. The query string d=b&d=c
results in a mapping from d
to [b
, c
]. It parses POST request bodies for web form data (MIME type: application/x-www-form-urlencoded).
This library is licensed under MIT, has nine versions released (most stable version: 0.6.0), and requires the following dependencies.
bodyparser
^0.8plugin
^0.2.6url
^1.6bodyparser
Part of Iron’s core middleware, bodyparser
is, as its name suggests, a parsing middleware for Iron. It contains the following features:
raw
— In Raw, bodyparser
performs body parsing to stringjson
— The bodyparser
framework can parse body into JSONstruct
parses body into a struct using SerdeThis library is licensed under MIT and has 15 versions. Its current, most stable version is 0.8.0
, which requires the following dependencies:
plugin
^0.2serde_json
^1.0serde_derive
^1.0queryst
queryst
is a Rust string parsing library that enables you to parse query strings to their corresponding JSON values.
Enable the queryst
library by adding the following to your cargo.toml
file.
[dependencies] queryst = "1"
With queryst
, the string foo[bar]=baz
can be parsed to:
{ "foo": { "bar": "baz" } }
The URL-encoded string also works and can be parsed as:
parse('a%5Bb%5D=c'); // { "a": { "b": "c" } }
This library is licensed under MIT and has 21 versions published. Its most recent version, 2.0.2
, requires the following dependencies.
serde_json
^1url
^1lazy_static
^1 (optional)regex
^0.2 (optional)scgi
Simple Common Gateway Interface (SCGI) is a protocol for applications to interface with HTTP servers. scgi
is an SCGI connector for Rust.
The library is licensed under MIT and Apache 2.0 and has 16 versions published. The most current version is 0.3.4, which requires bufstream
^0.1.1 as a dependency.
sass-rs
This higher-level binding for the Sass library is a wrapper around libsass
.
sass-rs
is licensed under MIT and has 22 released. The stable, most recent library is 0.2.2
, which requires the following dependencies.
libc
^0.2sass-sys
^0.4ratelimit_meter
ratelimit_meter
is an open-source library that implements the leaky bucket and a variation of the leaky bucket, the generic cell rate algorithm (GCRA) for rate limiting and scheduling. Unlike the token bucket algorithm, the leaky bucket algorithm assumes that all units of work are of the same “weight.” As such, it allows some optimizations, which result in much more concise and fast code.
This library is licensed under MIT and has 17 versions published. The current version of ratelimit_meter
is 5.0.0, which requires the following dependencies.
nonzero_ext
^0.1.5evmap
^6.0.0 optionalparking_lot
^0.9.0 optionalspin
^0.5.0 optionalcriterion
^0.2.11libc
^0.2.41regex
regex
is a Rust library that helps you parse, compile, and execute regular expressions. With regex
, you can match a date in YYYY-MM-DD format to print the year, mont,h and day and even iterate over text using an iterator.
To use regex
, add the following to your cargo.toml
file.
[dependencies] regex = "1"
You’ll need to add this to your crate tool if you’re using Rust 2015:
extern crate regex;
This library is licensed under MIT and Apache 2.0. It has 120 versions, the most recent of which is 1.3.9. This version requires the following dependencies.
regex-syntax
^0.6.18aho-corasick
^0.7.6 optionalmemchr
^2.2.1 optionalthread_local
^1 optionallazy_static
^1quickcheck
^0.8rand
^0.6.5chrono
chrono
is a Rust library for date and time. With chrono
, you can use the time::Duration
type from the time
crate to represent the magnitude of a time span. You can also use the DateTime
type to represent a date and a time in a time zone. The DateTime
type has to be constructed from the TimeZone
object. This will define how the local date is converted to and back from the UTC date.
This library is licensed under MIT or Apache-2.0 and has 66 published versions. The newest most stable version is 0.4.18.
alloc
enables features that depend on allocation (primarily string formatting)std
is a superset of alloc
that adds interoperation with standard library types and traitsclock
allows reading the system time, regardless of whether std::time::SystemTime
is present (it depends on having a libc
)wasmbind
makes integration with wasm-bind
gen and its js-sys
project seamlessserde
allows Rust serialization and deserialization via Serdeunstable-locales
enables localization and adds various methods with a _localized
suffixtime
The time
library is an open-source date and time library that is fully interoperable with the standard library and mostly compatible with #![no_std]
. This library has 70 releases, with it’s newest, most stable version being 0.2.22.
std
enables various other features that depend on the standard librarydeprecated
allows support for certain depreciated functions from time
0.1serde
enables Serde support for all typesrand
enables rand support for all typespanicking-API
allows you to use the unwrap()
method when requiredbacktrace
The backtrace
library is built to support the RUST_BACKTRACE=1
standard library by allowing the acquisition of a backtrace programmatically.
To use backtrace
, add the following to your cargo.toml
file.actu
[dependencies] backtrace = "0.3"
This library has 64 version released. The newest stable version is 0.3.50 which requires the following dependencies.
cfg
-if ^0.1.10libc
^0.2.45rustc-demangle
^0.1.4addr2line
^0.13.0 optionalbacktrace-sys
^0.1.35 optionalcompiler_builtins
^0.1.2 optionalcpp_demangle
^0.3.0 optionalminiz_oxide
^0.4.0 optionalobject
^0.20.0 optionalrustc-serialize
^0.3 optionalrustc-std-workspace-core
^1.0.0 optionalserde
^1.0 optionalwinapi
^0.3.3 optionallibloading
^0.6docopt
docopt
is a command-line argument parser. Unlike other parsers, this one can be derived from the usage string.
To use docopt
, add the following to your cargo.toml
file.
[dependencies] docopt = "1" serde = { version = "1", features = ["derive"] }
docopt
has 86 releases, the latest of which is 1.1.0. This version requires the following dependencies:
lazy_static
^1.3regex
^1.1.5serde
^1.0strsim
^0.9structopt
structopt
combines the clap
library with a custom drive to parse command-line arguments by defining a struct.
To use this library, add structopt
to your cargo.toml
file:
[dependencies] structopt = "0.3"
And then, in your rust file:
use std::path::PathBuf; use structopt::StructOpt; /// A basic example #[derive(StructOpt, Debug)] #[structopt(name = "basic")] struct Opt { /**this will return true if used in the command line. Note doc comment will be used for the help message of the flag. The name of the document by default, will be based on the name of the field.**/ /// Activate debug mode #[structopt(short, long)] debug: bool, /// Verbose mode (-v, -vv, -vvv, etc.) #[structopt(short, long, parse(from_occurrences))] verbose: u8, /// Set speed #[structopt(short, long, default_value = "42")] speed: f64, /// Output file #[structopt(short, long, parse(from_os_str))] output: PathBuf, // the long option will be translated to kebab case by default, // i.e. `--nb-cars`. /// Number of cars #[structopt(short = "c", long)] nb_cars: Option<i32>, /// admin_level to consider #[structopt(short, long)] level: Vec<String>, /// Files to process #[structopt(name = "FILE", parse(from_os_str))] files: Vec<PathBuf>, } fn main() { let opt = Opt::from_args(); println!("{:#?}", opt); }
structopt
has released 52 versions, the most recent being 0.3.18.
url
url
is an implementation of the URL standard for the Rust programming language. The URL Standard defines URLs, domains, IP addresses, the application/x-www-form-urlencoded format, and their API.
This library has 73 versions published. Its most stable version is 2.1.1
.
robotparser
robotparser
is a robots.txt
parser for Rust. robost.txt
files tell search engine crawlers which pages or files they can or can’t crawl. This is to avoid overloading your site with requests.
This library is licensed under MIT and has 18 versions published. The latest stable version is 0.10.2
, which requires the following dependencies.
url
^1reqwest
^0.9 optionalmultipart
multipart
is a client and server-side notion for HTTP file uploads (POST requests with content type multipart/form-data). This library supports various synchronous API HTTP crates, including hyper
and tiny_http
.
multipart
is licensed under MIT and Apache 2.0 and has 18 versions published. The latest stable version is 0.17.0
, which requires the following dependencies.
log
^0.4mime
^0.3.14mime_guess
^2.0.1rand
^0.6tempfile
^3buf_redux
^0.8 optionalclippy
>=0.0, <0.1 optionalhttparse
^1.2 optionalhyper
>=0.9, <0.11 optionaliron
>=0.4, <0.7 optionallazy_static
^1.2.0 optionalnickel
>=0.10.1 optionalquick-error
^1.2 optionalrocket
^0.4 optionalsafemem
^0.3 optionaltiny_http
^0.6 optionaltwoway
^0.1 optionalenv_logger
^0.5That’s a lot of web utilities for Rust! Hopefully, this guide gives you the context you need to select the right mix of solutions to bring your Rust app to the next level.
If you want to parse a command-line argument in Rust, clap
, docopt
, and structopt
are all solid choices. When it comes to implementing date- and time-related features, you can’t go wrong with chrono
and time
. For creating temporary files, tempfile
is the way to go.
The Rust ecosystem provides excellent tools for parsing cookes (cookie
), strings (queryst
), and regular expressions (regex
). To allow Rust to read the body of an incoming request in your application, you may want to try bodyparser
to parse the body portion of the request.
As always, the best solutions for you will depend on the unique goals, requirements, and challenges associated with your Rust project.
Debugging Rust applications can be difficult, especially when users experience issues that are hard to reproduce. If you’re interested in monitoring and tracking the performance of your Rust apps, automatically surfacing errors, and tracking slow network requests and load time, try LogRocket.
LogRocket is like a DVR for web and mobile apps, recording literally everything that happens on your Rust application. Instead of guessing why problems happen, you can aggregate and report on what state your application was in when an issue occurred. LogRocket also monitors your app’s performance, reporting metrics like client CPU load, client memory usage, and more.
Modernize how you debug your Rust apps — start monitoring for free.
Hey there, want to help make our blog better?
Join LogRocket’s Content Advisory Board. You’ll help inform the type of content we create and get access to exclusive meetups, social accreditation, and swag.
Sign up nowBuild scalable admin dashboards with Filament and Laravel using Form Builder, Notifications, and Actions for clean, interactive panels.
Break down the parts of a URL and explore APIs for working with them in JavaScript, parsing them, building query strings, checking their validity, etc.
In this guide, explore lazy loading and error loading as two techniques for fetching data in React apps.
Deno is a popular JavaScript runtime, and it recently launched version 2.0 with several new features, bug fixes, and improvements […]
2 Replies to "19 awesome web utilities for Rust"
This is awesome! Exactly what I needed 🙂
Thanks for sharing.
Am glad you loved it @Yev!