Skip to main content

21  Moving a function to Rust

A typed function’s declaration is its contract: the parameters, their types, defaults, and descriptions, the rules, and the return type. Its body computes the result. In a package with Rust code, the body moves to Rust and the declaration stays in R, so that the function’s callers, its help page, its schema, and the calls from documents see the same function before and after the move.

21.1 The function in R

level() holds a running sum between lo and hi. Each step depends on the one before, so R runs it as a loop:

level <- new_function(
  "level",
  function(
    x = arg_vec(type_double(), description = "Inflows, in order."),
    lo = arg_double(default = 0, description = "The floor."),
    hi = arg_double(description = "The capacity.")
  ) {
    y <- numeric(length(x))
    s <- 0
    for (i in seq_along(x)) {
      s <- min(max(s + x[[i]], lo), hi)
      y[[i]] <- s
    }
    y
  },
  rules = list(order = rule(lo <= hi)),
  return_type = vec(type_double()),
  description = "Holds a running sum between `lo` and `hi`."
)
level(c(2, 3, -9, 4, 1), hi = 4)
[1] 2 4 0 4 4

r8rust_signature() writes the Rust function that the body moves into, from the declaration:

r8rust_signature(level)
/// Holds a running sum between `lo` and `hi`.
///
/// R8 checks, before and after the body:
/// - `x` is vector of double
/// - `lo` is double
/// - `hi` is double
/// - lo <= hi
/// - the result is vector of double
#[r8::function]
fn level(
    x: &[f64],
    lo: f64,
    hi: f64,
) -> Vec<f64> {
    todo!()
}

21.2 The body in Rust

The computation is a plain Rust function over slices, in a crate or a module without R8, which builds for any host:

// src/rust/src/levels.rs
pub fn level(x: &[f64], lo: f64, hi: f64) -> Vec<f64> {
    let mut s = 0.0;
    x.iter()
        .map(|v| {
            s = (s + v).clamp(lo, hi);
            s
        })
        .collect()
}

The package’s Rust code binds it to the declaration, with the signature that r8rust_signature() wrote, and lists it in functions of r8::exports! (Impls and types in Rust):

// src/rust/src/functions.rs
use rtemis_r8_api as r8;

/// Holds a running sum between `lo` and `hi`.
#[r8::function]
pub fn level(x: &[f64], lo: f64, hi: f64) -> Vec<f64> {
    crate::levels::level(x, lo, hi)
}

// src/rust/src/lib.rs
r8::exports! {
    package = "r8pkgR",
    namespace = "pkgr",
    functions = [functions::level],
}

In R, the body becomes rust(), and the rest of the declaration stays as it was:

level <- R8::new_function(
  "level",
  function(
    x = R8::arg_vec(R8::type_double(), description = "Inflows, in order."),
    lo = R8::arg_double(default = 0, description = "The floor."),
    hi = R8::arg_double(description = "The capacity.")
  ) {
    R8::rust()
  },
  rules = list(order = R8::rule(lo <= hi)),
  return_type = R8::vec(R8::type_double()),
  description = "Holds a running sum between `lo` and `hi`."
)

A call checks and converts the arguments, evaluates the defaults, a default written in R such as length(x) included, and checks the rules, as for a body in R; then it passes the value of each parameter to the Rust function, in the order of the declaration, and checks the result. lo <= hi holds before the body runs, so f64::clamp(), which panics when lo > hi, needs no check of its own. The function’s record, its declaration hash, and r8schema(level) are the same as with the body in R.

21.3 Rust types

Each parameter takes the Rust type of its declared type. A vector is borrowed from the R value for the call, without a copy, and leaves the caller’s vector as it is; a result becomes an R vector by one copy.

Declared in R Parameter Result
arg_double(), arg_integer(), arg_logical() f64, i32, bool the same
arg_character() &str String
arg_vec() of a double, integer, or logical &[f64], &[i32], &[bool] Vec<f64>, Vec<i32>, Vec<bool>
arg_raw() &[u8] Vec<u8>
arg_option(T) Option<T>, Option<&[f64]> Option<T>
arg(T), a type declared in Rust &T T
a parameter without a type, or of another type r8::Sexp, the R object r8::Sexp
... r8::Dots

An element of a slice is a value: a vector that admits NA, vec(option(T)), and a vector of strings are r8::Sexp. A logical vector is copied into &[bool], since R stores logicals in 32 bits. A parameter whose R name is not a Rust identifier, such as na.rm, takes #[r8(name = "na.rm")]. A function with an r8::Sexp or r8::Dots parameter runs in R alone; one over the standard types runs in any host whose binding calls it.

21.4 When the package loads

R8 compares each Rust function with its declaration: the parameters have the declaration’s names, in order, and the Rust types of the declared types, and the result fits the return type. A rust() function without a Rust function, a Rust function without a rust() declaration, and a difference are one error, which gives the signature to write:

#> The functions of package 'r8pkgR' whose bodies are in Rust do not match its compiled exports:
#> - `pkgr::level()` in Rust: its parameter `x` is vector of double, and in the declaration vector of integer. Its Rust signature, from r8rust_signature():
#>     ...
#>     fn level(
#>         x: &[i32],
#>         lo: f64,
#>         hi: f64,
#>     ) -> Vec<f64> {
#>         todo!()
#>     }
#> The Rust function or the declaration in R changes [function_signature].

21.5 Errors

An Err(r8::Error::new(code, message)) of the Rust function is an R error of class r8_compiled_error, with the code in e$code and the function’s call, and a panic is an r8_panic. The R body raised the classes of its own code, so a caller of a function whose body moves to Rust handles its errors by their code:

tryCatch(fraction(1, 0), r8_compiled_error = function(e) e$code)
#> [1] "zero_whole"

21.6 Tests

The R body stays in the package’s tests as a plain function, which the tests compare with the function on the same inputs:

level_r <- function(x, lo = 0, hi) {
  y <- numeric(length(x))
  s <- 0
  for (i in seq_along(x)) {
    s <- min(max(s + x[[i]], lo), hi)
    y[[i]] <- s
  }
  y
}
x <- 3 * stats::rnorm(1000)
testthat::expect_identical(level(x, hi = 2), level_r(x, hi = 2))

21.7 When a move pays

The table gives the time of a call in microseconds, for level() and for clip(), whose body is pmin(pmax(x, lo), hi): the plain R function without checks, the typed function with its body in R, and the typed function with its body in Rust, each with the rule lo <= hi and the return type vec(type_double()) (bench/migrate.R in the R8 repository, with the test package r8pkgR; the release build, R 4.6.2, Apple M5, 2026-11-26; minimum of 7 rounds):

Elements clip(), R typed, R typed, Rust level(), R typed, R typed, Rust
1 3.95 4.68 0.71 0.57 1.44 0.74
100 3.98 4.93 0.82 5.26 6.10 0.99
10,000 28.8 34.3 9.09 472 473 29
1,000,000 4,080 4,660 860 47,200 47,900 2,840
  • A loop in R: level() with its body in Rust takes a sixth of the time at 100 elements, and a seventeenth from 10,000.
  • A vectorized body over R functions: pmin() and pmax() take 3.5 µs before any element, and each makes a vector of the length of x, so clip() with its body in Rust takes a fifth of the time at every size.
  • One element: a call of a Rust body takes about 0.7 µs, its checks included; the plain R level() takes 0.57 µs, without checks.
  • 10^6 elements: the checks of the argument and the result take about 0.5 ms with either body, most of clip()’s 0.86 ms with its body in Rust.

A body stays in R when its time is in compiled code that it calls, such as a model fit; when its result depends on R’s state, such as the random numbers that set.seed() fixes; when it reads its call, through substitute(), match.call(), or a formula; or when its package builds no Rust code. A body moves to Rust when its time is in R’s loops and temporary vectors, at the sizes it is called with, or when another host computes the same result: the plain Rust function over slices is that host’s body too.

21.8 In the expressions of tables

In an expression of calc(), and in r8map(v, spread, by = "g"), which is the map of calc(spread(col())), R8’s Rust code calls a body in Rust through the entry that its package registers, with the cells of each group as an R vector and the checks of a direct call, and a body in R through its closure (Summaries). The body runs at most once for each call, and the error of a call is that of a direct call. The table gives the time in ms of r8map(v, calc(spread(col())), by = "g") over 10 columns of 10^6 rows, one call for each group and column, where spread() is the largest value less the smallest, with its body in Rust (r8pkgR) and in R, beside the dialect’s max(col()) - min(col()) (bench/calls.R in the R8 repository; the release build, R 4.6.2, Apple M5, 2026-11-27; medians of 3 runs, one run for the body in R):

Groups Calls typed, Rust typed, R dialect
100 1,000 15 26 30
10,000 100,000 32 285 30
100,000 1,000,000 147 2,942 46

At the size of rtemis’s tuner, 20 groups of 10 rows and 3 columns, the map takes 96 µs with the body in Rust, 233 µs with the body in R, and 87 µs in the dialect. At 10^6 calls, a call of the body in Rust takes about 0.15 µs, the grouping of the rows included, and a call of the body in R about 3 µs.

© 2026 E.D. Gennatas