On my bucket list for 2024 is to learn a bit of Rust. After reading (well skimming…) THE BOOK and doing a few experiments, I wanted to give it a try to incorporate some Rust code in an R package. I chose to wrap the phonenumber crate to parse phone numbers into R, because I thought thats small enough of a task that I could manage. Note that there is already an R package for that, called dialr, which wraps Google’s libphonenumber Java library. For obvious reasons, my experimental package is called dialrs.
As a small disclaimer, I am far from being an expert with Rust, so don’t take this package of an example of best practices in (wrapped) Rust.
Setup
Setting up a package for Rust code is extremely simple. All you need is the rextendr package which allows to call Rust code from R. A vignette explains how to use it within an R package.
Two commands are enough to get you started with a package.
The function use_extendr() creates a whole bunch of files and directories (see the vignette for help). The most important ones are src/rust/Cargo.toml to include crates as dependencies and src/rust/src/lib.rs where most of the Rust code will live. You can also have the code in different files, say phone.rs, but then there needs to be a line
mod phone
in libs.rs.
To compile the code, we need to run rextendr::document() (similar to devtools::document())
The rest of the f**** packages
Implementing the actual package really felt like that old owl meme. Sure, the setup is incredibly easy, but you still need to write the Rust code yourself. Surprisingly. There was lot of trial and error but eventually, I got the following stack of functions to work properly.