Ukpai Ugochi I am a female Nigerian with a Bachelor's degree in Marine engineering and Bootcamp certificates in Software development. I'm a full stack JavaScript developer (MEVN) stack. I love to share knowledge about my transition from marine engineering to software development in the form of writing, to encourage people who love software development and don't know where to begin. I also contribute to FOSS in my free time.

19 awesome web utilities for Rust

8 min read 2420

19 Awesome Web Utilities for Rust

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:

  1. cookie
  2. clap
  3. heim
  4. tempfile
  5. urlencoded
  6. bodyparser
  7. queryst
  8. scgi
  9. sass-rs
  10. ratelimit_meter
  11. regex
  12. chrono
  13. time
  14. backtrace
  15. docopt
  16. structopt
  17. url
  18. robotparser
  19. multipart

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.

Features

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 implementation
  • signed enables cookies to be signed with the CookieJar::signed() method
  • private — When you have the private feature enabled with the CookieJar::private() method, cookies are encrypted, decrypted, and authenticated as they are added and retrieved
  • Key expansion automatically enables the signed 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 key
  • secure 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"]

2. 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.

We made a custom demo for .
No really. Click here to check it out.

Features

The following built-in features are enabled by default.

  • Suggestions help users when they make typos by asking, for example, Did you mean '--myoption'?
  • Color — Error messages are more pronounced when they are colored. This feature turns on colored error messagea and functions only on non-Windows operating systems
  • Wrap help — With this feature, help in the terminal is wrapped instead of the 120 characters

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 enables you to build your CLI from a .yaml file
  • unstable enables you to use unstable clap features

3. heim

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.

4. 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.

5. 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.8
  • Iron >=0.5, <0.7
  • plugin ^0.2.6
  • url ^1.6

6. bodyparser

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 string
  • json — The bodyparser framework can parse body into JSON
  • struct parses body into a struct using Serde

This library is licensed under MIT and has 15 versions. Its current, most stable version is 0.8.0, which requires the following dependencies:

  • Iron >=0.5, <0.7
  • Persistent ^0.4
  • plugin ^0.2
  • Serde ^1.0
  • serde_json ^1.0
  • serde_derive ^1.0

7. queryst

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 ^1
  • serde_json ^1
  • url ^1
  • lazy_static ^1 (optional)
  • regex ^0.2 (optional)

8. 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.

9. 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.2
  • sass-sys ^0.4

10. ratelimit_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.5
  • evmap ^6.0.0 optional
  • parking_lot ^0.9.0 optional
  • spin ^0.5.0 optional
  • criterion ^0.2.11
  • libc ^0.2.41

11. regex

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.18
  • aho-corasick ^0.7.6 optional
  • memchr ^2.2.1 optional
  • thread_local ^1 optional
  • lazy_static ^1
  • quickcheck ^0.8
  • rand ^0.6.5

12. chrono

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.

Default features

  • alloc enables features that depend on allocation (primarily string formatting)
  • std is a superset of alloc that adds interoperation with standard library types and traits
  • clock allows reading the system time, regardless of whether std::time::SystemTime is present (it depends on having a libc)

Optional features

  • wasmbind makes integration with wasm-bind gen and its js-sys project seamless
  • serde allows Rust serialization and deserialization via Serde
  • unstable-locales enables localization and adds various methods with a _localized suffix

13. time

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.

Features enabled by default

  • std enables various other features that depend on the standard library
  • deprecated allows support for certain depreciated functions from time 0.1

Features disabled by default

  • serde enables Serde support for all types
  • rand enables rand support for all types
  • panicking-API allows you to use the unwrap() method when required

14. backtrace

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.10
  • libc ^0.2.45
  • rustc-demangle ^0.1.4
  • addr2line ^0.13.0 optional
  • backtrace-sys ^0.1.35 optional
  • compiler_builtins ^0.1.2 optional
  • cpp_demangle ^0.3.0 optional
  • miniz_oxide ^0.4.0 optional
  • object ^0.20.0 optional
  • rustc-serialize ^0.3 optional
  • rustc-std-workspace-core ^1.0.0 optional
  • serde ^1.0 optional
  • winapi ^0.3.3 optional
  • libloading ^0.6

15. docopt

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.3
  • regex ^1.1.5
  • serde ^1.0
  • strsim ^0.9

16. structopt

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.

17. 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.

18. 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 ^1
  • reqwest ^0.9 optional

19. multipart

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.4
  • mime ^0.3.14
  • mime_guess ^2.0.1
  • rand ^0.6
  • tempfile ^3
  • buf_redux ^0.8 optional
  • clippy >=0.0, <0.1 optional
  • httparse ^1.2 optional
  • hyper >=0.9, <0.11 optional
  • iron >=0.4, <0.7 optional
  • lazy_static ^1.2.0 optional
  • nickel >=0.10.1 optional
  • quick-error ^1.2 optional
  • rocket ^0.4 optional
  • safemem ^0.3 optional
  • tiny_http ^0.6 optional
  • twoway ^0.1 optional
  • env_logger ^0.5

Conclusion

That’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.

LogRocket: Full visibility into production Rust apps

Debugging Rust applications can be difficult, especially when users experience issues that are difficult to reproduce. If you’re interested in monitoring and tracking 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 apps, recording literally everything that happens on your Rust app. 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 — .

Ukpai Ugochi I am a female Nigerian with a Bachelor's degree in Marine engineering and Bootcamp certificates in Software development. I'm a full stack JavaScript developer (MEVN) stack. I love to share knowledge about my transition from marine engineering to software development in the form of writing, to encourage people who love software development and don't know where to begin. I also contribute to FOSS in my free time.

2 Replies to “19 awesome web utilities for Rust”

Leave a Reply