Filtering all posts in Rust

26 August 2017

I always enjoy these sorts of posts: A developer starts with a specific goal in mind and an idea of how it might be accomplished. They proceed to run into a problem and rather than glossing over it, they document their debugging → understanding → fixing process. In this post the goal is to implement a binary tree data structure in Rust.

I particularly liked the optimisation section at the end. In my experience, it’s not uncommon for the first implementation that compiles and runs as expected to be fairly verbose. From there, optimising for usability and readability can be done fairly quickly though.

15 August 2017
25 July 2017

How to find an available TCP port in Rust

Let’s say you’re writing your own deployment solution in Rust. The basic flow you have in mind might go something like this:

  1. Pull the latest commits down onto the server
  2. Build the app (if it’s written in a compiled language)
  3. Start the app
  4. Move traffic to the new version of the app
  5. Remove the old version

The problem is that you’ve already got the old version of the app running so the new version will fail to start because the port it requires is already taken. What you need is a way to find a port that’s available, tell the app to start on that port, and then redirect traffic upstream to it.

Continue Reading →

3 July 2017
1 July 2017

Introducing iron-middlefiddle: Route specific middleware made easy in Iron

Route specific middleware is a fairly common need in web apps. As soon as you introduce something like authentication into the mix, you’ll probably want a way to apply middleware to routes you only want users to be able to access if they’re logged in.

As things stand, route specific middleware in Iron is a repetitive and messy business, which is where iron_middlefiddle comes in. It provides a macro which turns the tricky into the trivial, allowing you to add middleware to any number of routes within a Router easily.

Continue Reading →

30 June 2017

DeltaE 0.2.0

In the wee hours of this morning I released DeltaE 0.2.0, my Rust implementation of the CIEDE2000 colour differentiation algorithm. The update brings 2 main improvements:

  1. A new from_rgb method which will handle the conversions to LAB values for you and return the colour difference.

  2. An extensive test suite based on the data in Table 1 of “The CIEDE2000 Color-Difference Formula: implementation Notes, Supplementary Test Data, and Mathematical Observations”

With the addition of those tests, the library has reached a point where I feel comfortable in the thought of others using it. If no issues arise in the next month or so, I’ll bump this release to 1.0.0.

You’ll find DeltaE 0.2.0 in the usual places: & GitHub.

29 June 2017

Setting Iron’s response MIME type with middleware

If your JSON API is powered by Iron, you may well have a lot of duplicate code that sets the MIME type of each Response. Something like this:

use iron::mime::Mime;

pub fn example_handler(req: &mut Request) -> IronResult<Response> {
    let mime = "application/json".parse::<Mime>().unwrap();

    // …

    Ok(Response::with((mime, status::Ok, some_json)))

As we can see above, the code for setting a MIME type is generic and doesn’t need anything except a Response to modify. It is therefore a prime AfterMiddleware candidate, which once implemented will remove the need for the code repetition in each and every one of our routes’ handlers. Here’s a very brief AfterMiddleware description from the docs:

AfterMiddleware receive both a Request and a Response and are responsible for doing any response post-processing.

Continue Reading →

26 May 2017

Now in beta: DeltaE – a library for quantifying the difference between two colors

I have just published the first beta of my first public crate. DeltaE is a pure-Rust implementation of the International Commission on Illumination’s CIEDE2000 algorithm.

The goal of the algorithm is to put a number on the difference our eyes perceive when looking at two colours. If you’re interested in the details, then I recommend this rundown. In short though:

  • If the returned value is less than 1, then the human eye can’t distinguish between the two colours.
  • If the returned value is greater than 1, then we humans can see a difference when presented with the two colours.
  • The greater the return value, the more difference the human eye perceives.

This crate was written to be used in a project I’m currently tinkering with. It’ll come out of beta once I, and hopefully others, have used it some more and I have improved the test suite.

It is entirely based on Zachary Schuessler’s Javascript implementation of the algorithm. He is also the author of the aforementioned rundown so a huge thank you goes out to him for his work.

1 May 2017

Back in February 2016, Jimmy Cuadra wrote a post about “The highs and lows of Rust”. He too came to Rust from dynamic web-focused languages and he too “clicked” with it:

Rust has a reputation of having a much higher learning curve [than Go], which of course affects its popularity. I really haven’t been able to understand why, but somehow Rust just clicks with my mental model of programming […]

I’ve been wondering what helped make Rust click for me. The best answer I have come up with is that its basic function structure is relatively familiar to anyone who’s worked with Javascript. function becomes fn, and the parameter and return types are typed but other than that it’s more or less the same. I think that that familiarity with such a core and highly used part of the language helps a lot.

The low points he addresses are interesting to look back on a year and a bit down the line. Serde has matured a lot, having recently reached 1.0.0, passed the 2 million downloads mark, reached number 9 on the “most downloaded” list and become the favoured serialization crate of the core Rust team who have deprecated their own serialization crate.

As for cryptography, all of the popular crates still rely on C libraries. There are pure implementations for things like argon2 and rust-crypto is “mostly pure” but there’s still plenty of work to be done in that domain.

His thoughts once again echo my own when it comes to Rust’s usefulness:

While the language is described as a “systems language” and is generally intended for lower level applications, my domain is in higher level applications, and I’ve found Rust to be just as suitable and strong for my purposes. It really is a fantastic general purpose language.

Compiling to a binary, and thus taking away the need to setup a whole environment to run Ruby, Python, etc. programs, adds a level of portability and flexibility that (amongst other reasons) has made Rust my go-to even for for day-to-day scripts.

14 April 2017

How to set up environment varying code in your Rust web app

There are times when you’ll want your app to run different code depending on which environment it’s in: development, production, etc.

For example: You provide your templating engine with a baseurl variable. In production, you want it to point to, but in development you want it to point to http://localhost:8888.

We can accomplish this in Rust-y web apps with environment variables and the dotenv crate, as demonstrated in the following post.

Continue Reading →

2 April 2017
20 March 2017

Deleting the contents of a directory in Rust

There are various ways to delete the contents of a directory. You could, for example, delete the directory itself with fs::remove_dir_all and then create a new directory with the same name.

A more refined solution, which will go through the contents of a directory and delete each child without actually destroying and recreating the parent, looks like this:

use std::fs::{self, ReadDir};
use std::io::Error;

fn main() {
    let demo_dir = fs::read_dir("/path/to/dir");

fn delete_dir_contents(read_dir_res: Result<ReadDir, Error>) {
    if let Ok(dir) = read_dir_res {
        for entry in dir {
            if let Ok(entry) = entry {
                let path = entry.path();

                if path.is_dir() {
                    fs::remove_dir_all(path).expect("Failed to remove a dir");
                } else {
                    fs::remove_file(path).expect("Failed to remove a file");

ReadDir provides an iterator over the contents of a directory. It’s worth noting that it’s a non-recursive iterator, which is why we’re using fs::remove_dir_all here. That standard function will delete a directory along with all of it’s contents, which avoids us having to recursively walk and delete. As I’m here, I’ll recommend the walkdir crate for all of your recursive walking needs though.

Note: In production, the delete_dir_contents function is the sort of thing you’d probably want to break out into a utils module.

10 March 2017

Matching, saving and replacing text with the regex crate

Work continued on flyingV, one of my side-projects, last week. An interesting challenge I came up against was to find all of the matches to a particular regex across multiple files. For each match, I needed to save a specific portion of it then replace a specific portion of it with a new string.

The following uses the regex crate and is written in Rust. Captures are a feature of the regex language, not the regex crate itself though so if you aren’t familiar with them, there should still be something in this post for you.

To business then. The pattern I was matching against was any tera for loop containing quotes. Here’s an example loop I’d want to match:

{% for page in "20*/**/*" %}

Continue Reading →

24 February 2017

The building blocks of a healthy community

Over the course of my time on the internet I have been a part of many different communities, from the household names to the highly niche.

If one thing can be learnt from them it’s that building a community is hard; building a welcoming, helpful, ludicrously smart community is nigh-on impossible.

Building one such community is something Mozilla has managed to do with Rust however. My first month using the language and interacting with it’s community has set a new gold-standard in my eyes for what a healthy community looks like.

Continue Reading →

22 January 2017
You can keep up to date with new posts by subscribing to the RSS Feed or by following me on