Regex engine internals as a library

Over the last several years, I’ve rewritten Rust’s regex crate to enable better internal composition, and to make it easier to add optimizations while maintaining correctness. In the course of this rewrite I created a new crate, regex-automata, which exposes much of the regex crate internals as their own APIs for others to use. To my knowledge, this is the first regex library to expose its internals to the degree done in regex-automata as a separately versioned library.

This blog post discusses the problems that led to the rewrite, how the rewrite solved them and a guided tour of regex-automata’s API.

Target audience: Rust programmers and anyone with an interest in how one particular finite automata regex engine is implemented. Prior experience with regular expressions is assumed.


A byte string library for Rust

bstr is a byte string library for Rust and its 1.0 version has just been released! It provides string oriented operations on arbitrary sequences of bytes, but is most useful when those bytes are UTF-8. In other words, it provides a string type that is UTF-8 by convention, where as Rust’s built-in string types are guaranteed to be UTF-8.

This blog will briefly describe the API, do a deep dive on the motivation for creating bstr, show some short example programs using bstr and conclude with a few thoughts.

Target audience: Rust programmers with some background knowledge of UTF-8.


Using unwrap() in Rust is Okay

One day before Rust 1.0 was released, I published a blog post covering the fundamentals of error handling. A particularly important but small section buried in the middle of the article is named “unwrapping isn’t evil”. That section briefly described that, broadly speaking, using unwrap() is okay if it’s in test/example code or when panicking indicates a bug.

I generally still hold that belief today. That belief is put into practice in Rust’s standard library and in many core ecosystem crates. (And that practice predates my blog post.) Yet, there still seems to be widespread confusion about when it is and isn’t okay to use unwrap(). This post will talk about that in more detail and respond specifically to a number of positions I’ve seen expressed.

This blog post is written somewhat as a FAQ, but it’s meant to be read in sequence. Each question builds on the one before it.

Target audience: Primarily Rust programmers, but I’ve hopefully provided enough context that the principles espoused here apply to any programmer. Although it may be tricky to apply an obvious mapping to languages with different error handling mechanisms, such as exceptions.


Archlinux on the System76 Darter Pro

This is a quick post reviewing my Archlinux setup on a System76 Darter Pro (model: darp6) with Coreboot, along with some thoughts about the laptop in general. This is my first laptop upgrade since I purchased a ThinkPad T430 in July 2012

Target audience: Archlinux users looking for a compatible Linux laptop.


My FOSS Story

I’d like to break from my normal tradition of focusing almost strictly on technical content and share a bit of my own personal relationship with Free and Open Source Software (FOSS). While everyone is different, my hope is that sharing my perspective will help build understanding, empathy and trust.

This is not meant to be a direct response to the behavior of any other maintainer. Nor should it be read as a prescription on the ideal behavior of someone in FOSS. This is meant more as a personal reflection with the hope that others will use it to reflect on their own relationship with FOSS. There is no one true path to being a good FOSS maintainer. We all have our own coping mechanisms.

This is also emphatically not meant as a call for help. This is about understanding. This is not about a plea to change the economics of FOSS. This is not about brainstorming ways to improve my mental health. This is not about bringing on more maintainers. It’s about sharing my story and attempting to increase empathy among the denizens of FOSS.

Target audience: Anyone involved in FOSS.


Rust and CSV parsing

With csv 1.0 just released, the time is ripe for a tutorial on how to read and write CSV data in Rust. This tutorial is targeted toward beginning Rust programmers, and is therefore full of examples and spends some time on basic concepts. Experienced Rust programmers may find parts of this useful, but would probably be happier with a quick skim.

For an introduction to Rust, please see the official book. If you haven’t written any Rust code yet but have written code in another language, then this tutorial might be accessible to you without needing to read the book first.

The CSV library is available on Github and has comprehensive API documentation.

Finally, a version of this blog post is included as a tutorial in the API documentation, and is more likely to be updated as time passes.

Target audience: Beginning Rust programmers.


ripgrep is faster than {grep, ag, git grep, ucg, pt, sift}

In this article I will introduce a new command line search tool, ripgrep, that combines the usability of The Silver Searcher (an ack clone) with the raw performance of GNU grep. ripgrep is fast, cross platform (with binaries available for Linux, Mac and Windows) and written in Rust.

ripgrep is available on Github.

We will attempt to do the impossible: a fair benchmark comparison between several popular code search tools. Specifically, we will dive into a series of 25 benchmarks that substantiate the following claims:

  • For both searching single files and huge directories of files, no other tool obviously stands above ripgrep in either performance or correctness.
  • ripgrep is the only tool with proper Unicode support that doesn’t make you pay dearly for it.
  • Tools that search many files at once are generally slower if they use memory maps, not faster.

As someone who has worked on text search in Rust in their free time for the last 2.5 years, and as the author of both ripgrep and the underlying regular expression engine, I will use this opportunity to provide detailed insights into the performance of each code search tool. No benchmark will go unscrutinized!

Target audience: Some familiarity with Unicode, programming and some experience with working on the command line.

NOTE: I’m hearing reports from some people that rg isn’t as fast as I’ve claimed on their data. I’d love to help explain what’s going on, but to do that, I’ll need to be able to reproduce your results. If you file an issue with something I can reproduce, I’d be happy to try and explain it.


Index 1,600,000,000 Keys with Automata and Rust

It turns out that finite state machines are useful for things other than expressing computation. Finite state machines can also be used to compactly represent ordered sets or maps of strings that can be searched very quickly.

In this article, I will teach you about finite state machines as a data structure for representing ordered sets and maps. This includes introducing an implementation written in Rust called the fst crate. It comes with complete API documentation. I will also show you how to build them using a simple command line tool. Finally, I will discuss a few experiments culminating in indexing over 1,600,000,000 URLs (134 GB) from the July 2015 Common Crawl Archive.

The technique presented in this article is also how Lucene represents a part of its inverted index.

Along the way, we will talk about memory maps, automaton intersection with regular expressions, fuzzy searching with Levenshtein distance and streaming set operations.

Target audience: Some familiarity with programming and fundamental data structures. No experience with automata theory or Rust is required.


Error Handling in Rust

Like most programming languages, Rust encourages the programmer to handle errors in a particular way. Generally speaking, error handling is divided into two broad categories: exceptions and return values. Rust opts for return values.

In this article, I intend to provide a comprehensive treatment of how to deal with errors in Rust. More than that, I will attempt to introduce error handling one piece at a time so that you’ll come away with a solid working knowledge of how everything fits together.

When done naively, error handling in Rust can be verbose and annoying. This article will explore those stumbling blocks and demonstrate how to use the standard library to make error handling concise and ergonomic.

Target audience: Those new to Rust that don’t know its error handling idioms yet. Some familiarity with Rust is helpful. (This article makes heavy use of some standard traits and some very light use of closures and macros.)

Update (2018/04/14): Examples were converted to ?, and some text was added to give historical context on the change.

Update (2020/01/03): A recommendation to use failure was removed and replaced with a recommendation to use either Box<Error + Send + Sync> or anyhow.


Syntax extensions and regular expressions for Rust

WARNING: 2018-04-12: The code snippets for this post are no longer available. This is just as well anyway, since they all depended on an unstable internal compiler interface, which hasn’t existed for years.

A few weeks ago, I set out to add regular expressions to the Rust distribution with an implementation and feature set heavily inspired by Russ Cox’s RE2. It was just recently added to the Rust distribution.

This regex crate includes a syntax extension that compiles a regular expression to native Rust code when a Rust program is compiled. This can be thought of as “ahead of time” compilation or something similar to compile time function execution. These special natively compiled regexes have the same exact API as regular expressions compiled at runtime.

In this article, I will outline my implementation strategy—including code samples on how to write a Rust syntax extension—and describe how I was able to achieve an identical API between regexes compiled at compile time and regexes compiled at runtime.


Writing type parametric functions in Go

Go’s only method of compile time safe polymorphism is structural subtyping, and this article will do nothing to change that. Instead, I’m going to present a package ty with facilities to write type parametric functions in Go that maintain run time type safety, while also being convenient for the caller to use.


Introducing NFLGame: Programmatic access to live NFL game statistics

As a programmer and a fantasy football addict, I am embarassed by the means through which we must expend ourselves to get data in a machine readable form. This lack of open source software cripples the community with sub-standard tools, and most importantly, detracts from some really cool and fun things that could be done with easily available statistics. Many tools are either out-dated or broken, or if they work, they are closed source and often cost money.

Yesterday I started work on a new library package that I hope will start to improve this sorry state of affairs.


Running Archlinux on the Lenovo Thinkpad T430

In sum, Archlinux is working beautifully. What follows is a rough run down of my notes while installing, configuring, tuning and using Archlinux on the Lenovo Thinkpad T430.


Daemonizing Go Programs (with a BSD-style rc.d example)

Go, by its very nature, is multithreaded. This makes a traditional approach of daemonizing Go programs by forking a bit difficult.

To get around this, you could try something as simple as backgrounding your Go program and instructing it to ignore the HUP signal:


Adding Thread Safety to the X Go Binding

The X Go Binding (XGB) is a low level library that provides an API to interact with running X servers. One can only communicate with an X server by sending data over a network connection; protocol requests, replies and errors need to be perfectly constructed down to the last byte. Xlib did precisely this, and then some. As a result, Xlib became huge and difficult to maintain.

In recent years, the XCB project made things a bit more civilized by generating C code from XML files describing the X client protocol using Python. While the Python to generate said code is no walk in the park, it is typically preferred to the alternative: keeping the X core protocol up to date along with any number of extensions that exist as well. (There are other benefits to XCB, like easier asynchronicity, but that is beyond the scope of this post.)

XGB proceeds in a similar vain; Python is used to generate Go code that provides an API to interact with the X protocol. Unlike its sister project XCB, it is not thread safe. In particular, if X requests are made in parallel, the best case scenario is a jumbled request or reply and the worst case scenario is an X server crash. Parallel requests can be particularly useful when images are being sent to the X server to be painted on the screen; other useful work could be done in the interim.


Dynamic desktop workspaces

Do you have dynamic workspaces in your window manager?

You might be wondering: what in the world are dynamic workspaces? A dynamic workspace model allows one to add, remove or rename workspaces on the fly. Comparatively, in a typical window manager (or desktop environment) configuration, you tell the window manager to have x number of workspaces. When you start your window manager, you’ll have x workspaces, and you can typically cycle between them using some variation of “next workspace” or “previous workspace” commands. The disadvantage with this model is that it’s difficult to have a large number of workspaces—else you might forget which window is on each workspace.