30 Impls and types in Rust
A package’s Rust code implements R8 traits and declares Rust-stored types through the crate rtemis-r8-api and its macros. A Rust-stored type keeps each value’s fields in a Rust struct, which R8 holds for R: a large vector field is borrowed from R or owned by Rust, never copied into an R list, and the type’s methods run in Rust on that struct. Values in R or in Rust compares Rust-stored and R-stored types and sets out where each fits.
This chapter builds a package, r8pkgR in the namespace pkgr, around a struct, Signal: a name and a series of numbers. Its trait Norm, declared in R, has the methods magnitude(x) and ratio(x, by), both implemented in Rust, as is R8’s standard trait Display. A Rust-stored enum, Resampler, follows.
Figure 30.1 follows a Rust-stored type and its methods from the package’s Rust code to a call in R.
30.1 The package
The package’s Rust code is a static library in src/rust, which R links into the package’s shared object:
r8pkgR/
DESCRIPTION
NAMESPACE
R/
norm.R # the trait Norm, declared in R
r8-types.R # the R declaration of Signal, generated
zzz.R # .onLoad() registers the package with R8
src/
entrypoint.c # R_init_r8pkgR() calls r8_init_r8pkgR()
Makevars # builds src/rust and links it
rust/
Cargo.toml
src/lib.rs # Signal, the impls, and r8::exports!
DESCRIPTION imports R8, names the namespace, and states the Rust toolchain:
Imports: R8 (>= 0.4.0)
SystemRequirements: Cargo (Rust's package manager), rustc
Config/R8/namespace: pkgr
src/rust/Cargo.toml builds a static library and depends on R8’s crates:
[lib]
crate-type = ["staticlib"]
[dependencies]
rtemis-r8 = { version = "0.4", features = ["macros"] }
rtemis-r8-api = "0.4"src/Makevars builds the library and links it:
TARGET_DIR = ./rust/target
LIBDIR = $(TARGET_DIR)/release
STATLIB = $(LIBDIR)/libr8pkgr.a
PKG_LIBS = -L$(LIBDIR) -lr8pkgr
all: $(SHLIB)
# Cargo decides what to rebuild, so make runs it on every build.
.PHONY: $(STATLIB)
$(SHLIB): $(STATLIB)
$(STATLIB):
cargo build --lib --release --manifest-path=./rust/Cargo.toml --target-dir $(TARGET_DIR)
A package for CRAN also vendors its crates, so that the build runs offline, and credits their authors; the rextendr scaffold carries those steps.
30.2 A Rust-stored struct
#[derive(R8)] with #[r8(storage = "rust")] declares the type and its codec, the functions R8 calls to build a value, read a field, and replace a field. The doc comments are the descriptions of the type and its fields:
use rtemis_r8::R8;
use rtemis_r8_api as r8;
use rtemis_r8_api::{Buffer, Dots};
/// A named series of values.
#[derive(R8, Clone)]
#[r8(namespace = "pkgr", version = 1, storage = "rust")]
pub struct Signal {
/// The name.
pub name: String,
/// The values.
pub values: Buffer<f64>,
}A field’s R8 type comes from its Rust type:
| Rust | R8 field type | R value |
|---|---|---|
f64 |
type_double() |
a double |
i32 |
type_integer() |
an integer |
bool |
type_logical() |
TRUE or FALSE |
String |
type_character() |
a string |
Option<T> |
option() of T |
NULL when absent |
Buffer<f64>, Buffer<i32>, Buffer<Logical>, Buffer<u8> |
vec() of a double, integer, logical, or raw |
a vector |
T, a Rust-stored type |
T |
a value of T |
r8::SubtypeValue<P> |
subtype(P) |
a value of P or of a struct that extends it |
r8::ImplementorValue<dyn Trait> |
dyn(Trait) |
a value of a type that implements Trait |
Buffer<T> holds a vector without copying it where it can. A value built from an R vector that has a data array borrows the vector: R keeps it alive while the value lives, and x$values returns the same R object. A vector without a data array, such as a compact sequence, is copied once into memory that Rust owns, and so is a buffer that Rust computes; x$values then returns a view, an R vector that reads Rust’s memory and copies it only when R writes to it.
30.3 A Rust-stored enum
#[r8(storage = "rust")] on an enum keeps every value in Rust, unit variants included. A variant is a unit, has named fields of the types above, or holds one struct, whose own #[derive(R8)] carries #[r8(storage = "rust")]:
/// A train and test split of case indices.
#[derive(R8, Clone)]
#[r8(namespace = "pkgr", version = 1, storage = "rust")]
pub struct Split {
/// The indices of the training cases.
pub train: Buffer<i32>,
/// The indices of the test cases.
pub test: Buffer<i32>,
}
/// A resampling method.
#[derive(R8, Clone)]
#[r8(namespace = "pkgr", version = 1, storage = "rust")]
pub enum Resampler {
/// K-fold cross-validation.
KFold { k: i32, seed: i32 },
/// Bootstrap resampling.
Bootstrap { n: i32 },
/// A fixed set of training cases.
Fixed { train: Buffer<i32> },
/// A given split.
Custom(Split),
}A method of an impl for Resampler receives the enum and matches on its variant. A package with a Rust-stored enum lists R8 (>= 0.4.0) in Imports, and r8document_rust() refuses to write the R declarations when it does not: R8 0.3.0 accepts the codec of an enum and builds plain R values of it.
30.4 A struct that extends another
A Rust struct extends another by embedding it. The parent is declared with extensible, and the child’s first field, marked #[r8(extends)], holds it:
/// A numeric interval.
#[derive(R8, Clone)]
#[r8(namespace = "pkgr", version = 1, storage = "rust", extensible)]
#[r8(rule(id = "ordered", invariant = r#"{"<=": [{"var": "lo"}, {"var": "hi"}]}"#))]
pub struct Interval {
/// The lower end.
pub lo: f64,
/// The upper end.
#[r8(default = "1")]
pub hi: f64,
}
/// A labeled interval with weights.
#[derive(R8, Clone)]
#[r8(namespace = "pkgr", version = 1, storage = "rust", extensible)]
pub struct Band {
#[r8(extends, inherited(lo(default = "0")))]
pub base: Interval,
/// The label.
pub label: String,
/// The weights.
pub weights: Buffer<f64>,
}In R, Band extends Interval (Extending a struct): it has the parent’s fields and rules, then its own, and its constructor is Band(lo = 0, hi = 1, label, weights). inherited(...) beside the mark changes inherited fields: lo(default = "0") gives lo a default, as JSON text, and the default null removes the default of an Option field. A child and its parent are both Rust-stored or both R-stored.
The derive also writes a Rust trait for an extensible struct, named with Like after the struct, with an accessor per field and a method that returns the struct’s value. Interval and every struct that extends it implement IntervalLike, in any crate:
fn width(x: &impl IntervalLike) -> f64 {
x.hi() - x.lo()
}
let b: Band = /* ... */;
width(&b);
let interval: Interval = b.to_interval();
let moved: Band = b.with_interval(Interval { lo: 2.0, hi: 3.0 });to_interval() copies the Interval that the value holds, and with_interval() gives the value with another Interval and its other fields, whose types implement Clone. A child of Band implements BandLike and IntervalLike. rtemis_r8::derive::Subtype gives the embedded parent by reference: let interval: &Interval = b.upcast();.
An impl for Interval applies to its descendants, as in R. The method receives the Interval that the value holds, without a copy, so it reads the parent’s fields only, and a method that returns a new Interval returns an Interval for a Band too. A &Interval parameter after &self takes an Interval exactly, and r8upcast(b, Interval) in R gives one.
30.5 Fields that hold any subtype or implementor
A field may hold a value of a type that the package’s Rust code does not know: a struct that another package extends from Interval, or an implementor of a trait that a user declares in R. r8::SubtypeValue<P> is a field of type subtype(P), and r8::ImplementorValue<dyn Trait> one of type dyn(Trait). Each keeps the R value and gives it back unchanged:
use rtemis_r8_api::{ImplementorValue, SubtypeValue};
/// A plane figure.
#[r8::methods(trait = "pkgr::Figure", dyn)]
pub trait Figure {
fn area(&self) -> f64;
}
/// A panel of a plot.
#[derive(R8, Clone)]
#[r8(namespace = "pkgr", version = 1, storage = "rust")]
pub struct Panel {
/// The range.
pub range: SubtypeValue<Interval>,
/// The frame.
pub frame: Interval,
/// The figure.
pub figure: ImplementorValue<dyn Figure>,
}dyn beside trait makes dyn Figure the name of the R8 trait. The field frame is a nested Rust-stored value, of Interval exactly; Panel owns it.
A SubtypeValue<Interval> holds a value with every field of Interval, and implements IntervalLike, so a function over &impl IntervalLike or &dyn IntervalLike takes it. downcast_ref() gives the value as a type that the code names, when it is of that type, and type_name() the name of any type:
#[r8::methods(trait = "pkgr::title")]
pub trait Title {
fn title(&self) -> r8::Result<String>;
}
impl Title for Panel {
fn title(&self) -> r8::Result<String> {
Ok(match self.range.downcast_ref::<Band>()? {
Some(band) => band.label.clone(),
None => format!("{} of width {}", self.range.type_name(), width(&self.range)),
})
}
}with_interval() gives a holder of the same value with another Interval, which keeps its type and its other fields. R8 checks it against the rules of its own type when it is first read, by R, by downcast_ref(), or for saveRDS(). SubtypeValue::new(band)? and ImplementorValue::new(square)? hold a value that Rust code makes.
In R, a panel holds any interval, such as a Tile of the package r8pkgS (below), and any figure:
t <- r8pkgS::Tile(lo = 1, hi = 3, number = 2L)
p <- Panel(range = t, frame = Interval(lo = 0, hi = 2), figure = Square(side = 2))
p$range$number
#> [1] 2
title(p)
#> [1] "pkgs::Tile of width 2"The declaration of Panel in R/r8-types.R names the trait’s object, R8::dyn(Figure); a file that declares the trait in R precedes R/r8-types.R in the Collate field of DESCRIPTION. A trait of another package is its exported object, R8::dyn(r8pkgR::Figure). A saved panel needs the packages of the values it holds: reading it without r8pkgS is an error that names the package to load.
Rust code outside R holds such values as JSON: rtemis_r8::derive::SubtypeOf<P> and ImplementorOf<dyn Trait> are the field types of a struct without storage = "rust", and to_document_in() and from_document_in() take the declarations of the types they hold.
30.6 Implementing traits
A trait implemented in Rust is declared once, in R or in Rust (below). In R it is declared as for impls written in R, in R/norm.R:
Norm <- R8::new_trait(
"Norm",
methods = list(
magnitude = R8::trait_method(
R8::params(x),
return_type = R8::type_double()
),
ratio = R8::trait_method(
R8::params(x, by = R8::arg_double()),
return_type = R8::type_double()
)
)
)
magnitude <- Norm@magnitude
ratio <- Norm@ratioThe Rust side is an ordinary Rust trait, marked with #[r8::methods], which names the R8 trait, and its impl:
#[r8::methods(trait = "pkgr::Norm")]
pub trait Norm {
fn magnitude(&self) -> f64;
fn ratio(&self, by: f64) -> r8::Result<f64>;
}
impl Norm for Signal {
fn magnitude(&self) -> f64 {
self.values.iter().map(|v| v * v).sum::<f64>().sqrt()
}
fn ratio(&self, by: f64) -> r8::Result<f64> {
if by == 0.0 {
return Err(r8::Error::new("zero_divisor", "`by` is not 0"));
}
Ok(self.values.first().copied().unwrap_or(f64::NAN) / by)
}
}&self is the method’s first argument, x, the R value’s Rust struct, read in place. R8 checks and converts each argument that the trait types before the method runs (Typed arguments and results). The arguments then convert to Rust, and the result to R; it may be a value of a Rust-stored type. A parameter &T of a Rust-stored type, such as fn distance(&self, y: &Signal), reads another value’s struct in place, or builds it from an R-stored value of the type. An Err(r8::Error::new(code, message)) becomes an R error of class r8_compiled_error, whose message ends with the code in brackets and whose field code holds it. A panic becomes an r8_panic, an r8_compiled_error with the code panic. Two failures end the R session, and Rust lets no caller catch them: an allocation that the system refuses, and a destructor that panics while a panic unwinds.
When the package loads, R8 checks that the method in Rust has the signature that the trait declares: the parameters have the declared names, in order, and each has the Rust type of its declared type.
| Declared in R | In Rust |
|---|---|
| the dispatched parameter | &self, and &Y of a type parameter of the trait |
arg_double(), arg_integer(), arg_logical(), arg_character() |
f64, i32, bool, &str or String |
arg_raw(), arg_vec() of a double, integer, or logical |
&[u8], &[f64], &[i32], &[bool], borrowed for the call; or Buffer<u8>, Buffer<f64>, Buffer<i32>, Buffer<Logical>, for a vector that a Rust-stored value keeps |
arg_option(T) |
Option<T>, and Option<&T> of a Rust-stored type |
arg(T), a Rust-stored type |
&T |
arg(subtype(P)), arg(dyn(Trait)) |
SubtypeValue<P>, ImplementorValue<dyn Trait> |
a parameter without a type, and a type without a row here, such as arg_matrix() |
r8::Sexp, the R object |
"..." |
r8::Dots |
R8 checks the bounds and the lengths of the declared type at each call, so the Rust type states none. The result fits the declared return type: type_double(min = 0) takes f64, subtype(Interval) takes Interval, and "Self" the type that the impl is for. A method with another signature is an error at load, with the declaration that it states:
#> The compiled impls of package 'r8pkgR' do not have the signatures that their traits declare:
#> - `ratio` of `pkgr::Norm` for `pkgr::Signal`: its parameter `by` is double, and in the declaration without a type. Its parameters are declared in R as params(x, by = arg_double()).
#> The Rust method or the declaration of its trait changes [impl_signature].R8’s standard traits are Rust traits of the crate: r8::Display (format()), r8::Debug (str()), r8::Shape (dim()), and r8::PartialOrd (partial_cmp(), the comparison operators). Display gives the text that format() returns and print() shows:
impl r8::Display for Signal {
fn format(&self, _dots: Dots) -> String {
format!("Signal {} ({} values)", self.name, self.values.len())
}
}30.6.1 A trait declared in Rust
A trait that traits of r8::exports! lists is declared in Rust. The types of its parameters and results are those of the Rust signature; the attributes of a parameter are its constraints and its default, as JSON text; and its doc comment is its description:
/// A value moved along its axis.
#[r8::methods(trait = "pkgr::shifted")]
pub trait Shifted {
/// Moves a value.
fn shifted(
&self,
/// The distance, in the unit of the value.
#[r8(infinite, default = "1")]
by: f64,
) -> Self;
}
r8::exports! {
package = "r8pkgR",
namespace = "pkgr",
types = [Interval, Band],
traits = [Shifted],
impls = [Interval: Shifted, Band: Shifted],
}r8document_rust() writes its R declaration into R/r8-types.R, as for types, and r8register() checks at each load that the two agree:
#' shifted
#'
#' Moves a value.
#'
#' The generic `pkgr::shifted`, declared in Rust.
#'
#' @param x A value, whose type selects the method.
#' @param by The distance, in the unit of the value.
#' @return A value of the type of `x`.
#' @export
shifted <- R8::generic(
"shifted",
R8::params(x, by = R8::arg_double(infinite = TRUE, default = 1)),
description = "Moves a value.",
return_type = "Self"
)A trait of one method with the trait’s name is a generic, and any other a new_trait() with a binding for each of its generics. tag = "figure" beside trait gives a trait a tag member, and a method marked #[r8(field)] is the accessor of a field that each implementing struct has:
#[r8::methods(trait = "pkgr::Figure", dyn, tag = "figure")]
pub trait Figure {
fn area(&self) -> f64;
#[r8(field)]
fn name(&self) -> &String;
}A type may implement such a trait in R, too: R8::implement(shifted, Window) <- function(x, by) .... A trait whose methods are mostly written in R, and one that maps an existing S3 generic, is declared in R.
30.6.2 An impl that keeps the type of the value
An impl over the interface trait of an extensible struct is an impl for the struct and for each struct that extends it. Its method receives the whole value, so it returns a value of the same type:
impl<T: IntervalLike> Shifted for T {
fn shifted(&self, by: f64) -> Self {
self.with_interval(Interval { lo: self.lo() + by, hi: self.hi() + by })
}
}r8::exports! registers the impl for each type that its rows name: with impls = [Interval: Shifted, Band: Shifted], shifted(b, 1) of a Band is a Band. A struct that extends Band and has no row takes the impl for Band, and gets a Band. Rust accepts such an impl in the crate that declares the trait; a trait of another crate, such as r8::Display, is implemented for each type.
30.6.3 Several dispatched arguments
A generic that dispatches on several arguments (Dispatch on several arguments) is a Rust trait with a type parameter for each dispatched argument after the first. dispatch(x, y) names the arguments, and the method takes the second as &Y:
#[r8::methods(trait = "pkgr::meets", dispatch(x, y))]
pub trait Meets<Y> {
fn meets(&self, y: &Y) -> bool;
}
impl Meets<Interval> for Interval {
fn meets(&self, y: &Interval) -> bool {
self.lo <= y.hi && y.lo <= self.hi
}
}
impl Meets<r8::Any> for Signal {
fn meets(&self, _y: &r8::Any) -> bool {
false
}
}A row of r8::exports! names the types, Interval: Meets<Interval>, and r8::Any stands for any value, an R one among them, which y.sexp() gives. Each argument may be a value of a struct that extends its position’s type, and the method reads the part that the value holds. R8 selects the method as for methods written in R, and refuses a package whose methods leave a call ambiguous, naming the method to add.
30.6.4 Replacement methods
A replacement generic label<- is the trait with_label, whose method takes the value by reference and returns the new one. #[r8(name = "label<-")] gives its name in R, when Rust declares the trait:
#[r8::methods(trait = "pkgr::with_label")]
pub trait WithLabel {
#[r8(name = "label<-")]
fn with_label(&self, value: String) -> Self;
}
impl<T: BandLike> WithLabel for T {
fn with_label(&self, value: String) -> Self {
self.with_band(Band { label: value, ..self.to_band() })
}
}The result has the type of the argument, so an impl for a struct and its descendants is written over the interface trait, with a row per type.
30.6.5 Conversions
r8::From<Source> converts a value of another type of the package, for r8convert(x, Interval) and Interval@from(x):
impl r8::From<Signal> for Interval {
fn from(source: &Signal) -> r8::Result<Self> {
let of = |f: fn(f64, f64) -> f64| source.values.iter().copied().reduce(f);
match (of(f64::min), of(f64::max)) {
(Some(lo), Some(hi)) => Ok(Interval { lo, hi }),
_ => Err(r8::Error::new("no_values", "the signal has values")),
}
}
}Its row is Interval: r8::From<Signal>.
30.7 Exports
r8::exports! lists the package’s Rust-stored types, the traits it declares in Rust, and its impls, and builds the table R8 reads at load: the declarations, the codecs, and the impl functions with their signatures. The declarations include every type of the namespace that the listed types reach, such as Split:
r8::exports! {
package = "r8pkgR",
namespace = "pkgr",
types = [Signal, Resampler],
impls = [Signal: Norm, Signal: r8::Display, Resampler: r8::Display],
}It also defines r8_init_r8pkgR(), named after the package with an underscore for a period, which the package’s initialization routine calls in src/entrypoint.c:
#include <stddef.h>
#include <R_ext/Rdynload.h>
void r8_init_r8pkgR(void *dll);
void R_init_r8pkgR(DllInfo *dll) {
R_registerRoutines(dll, NULL, NULL, NULL, NULL);
R_useDynamicSymbols(dll, FALSE);
r8_init_r8pkgR(dll);
}.onLoad() registers the package, as every package that declares R8 types does (R8 in a package):
.onLoad <- function(libname, pkgname) {
R8::r8register()
}30.7.1 A crate that depends on another package’s crate
The crate of a package with exports is a dependency of another package’s crate, when its Cargo.toml builds a Rust library too (crate-type = ["staticlib", "lib"]). The package r8pkgS declares a struct that extends Interval, and registers for it the impl of Shifted above:
use r8pkgr::{Interval, IntervalLike, Shifted};
/// A numbered interval.
#[derive(R8, Clone)]
#[r8(namespace = "pkgs", version = 1, storage = "rust")]
pub struct Tile {
#[r8(extends)]
pub base: Interval,
/// The number.
pub number: i32,
}
r8::exports! {
package = "r8pkgS",
namespace = "pkgs",
types = [Tile],
impls = [Tile: Shifted],
}Each shared object holds its own compilation of Interval, and Rust fixes the layout of a struct within one compilation only. R8 therefore lends a value’s struct to the shared object that built it: the Rust code of r8pkgS reads an Interval of r8pkgR by its fields, as a &Interval built from them, and a method of r8pkgS that returns an Interval gives R a value that r8pkgR builds from its fields. r8pkgS lists r8pkgR in the Imports of its DESCRIPTION and imports from it in its NAMESPACE, so that r8pkgR registers its traits first.
The Rust code of r8pkgS is compiled against the declaration of Interval as it was, and a user may update r8pkgR alone. R8 finds the fields by name, and reads a value when every value that the declaration of the installed r8pkgR admits is one that the compiled declaration admits. Fields may be added and reordered, bounds tightened, and rules added. Any other difference is a warning of class r8_declaration_warning when r8pkgS loads, which names it, and an error of a method that reads an Interval:
#> Error in gap(t, x) :
#> `y`: package 'r8pkgS' was compiled against another declaration of `pkgr::Interval` than the registered one: the rule `ordered` is compiled, and not declared. Install versions of 'r8pkgS' and of package 'r8pkgR' that were built for each other [declaration_changed]r8pkgS states in Imports the version of r8pkgR whose crate it was compiled with, and r8pkgR changes a type that others use in coordination with them (Changing a type that other packages use).
30.8 The R declaration of a Rust type
R needs the type object Signal when the package is installed, before the shared object loads, so that the constructor, its documentation, and other declarations that name the type work. The package commits its R declaration in R/r8-types.R, which r8document_rust() writes from the Rust declarations:
# r8-types.R
# ::r8pkgR::
# R8::r8document_rust() writes this file from the R8 declarations in
# the package's Rust code, and replaces it when they change.
#' Signal
#'
#' A named series of values.
#'
#' The struct `pkgr::Signal`, declared in Rust.
#'
#' @param name The name.
#' @param values The values.
#' @return A `pkgr::Signal` value.
#' @export
Signal <- R8::new_struct(
"Signal",
fields = list(
name = R8::field(R8::type_character(), description = "The name."),
values = R8::field(R8::vec(R8::type_double()), description = "The values.")
),
description = "A named series of values.",
version = 1L,
storage = "rust"
)storage = "rust" marks a Rust-stored type: its constructor builds values through the codec once the package’s exports are registered. A field whose type another package declares renders as that package’s exported type object, such as r8resample::Resampler, and the generator requires the package in Imports. With the roclet R8::r8rd() (Documentation with roxygen2), each method implemented in Rust gets an entry in the help page of its generic or of its type, as an implement() call does.
r8document_rust() reads the declarations from the compiled shared object without loading the package, so it runs while R/r8-types.R is missing or out of date. It declares what it renders and compares each type’s declaration hash with the Rust declaration’s before it writes. It runs in an R session of its own, after the shared object is compiled and before roxygen2 loads the package, as in a package’s tools/document.R:
pkgbuild::compile_dll()
system2(file.path(R.home("bin"), "Rscript"), c("-e", shQuote("R8::r8document_rust()")))
roxygen2::roxygenise()R8::r8document_rust(check = TRUE) reports a committed file that differs from the Rust declarations, without writing it, for continuous integration.
r8register() checks the same agreement each time the package loads. It signals an error that lists every type of the exports without an R declaration or with a different one, every codec whose type lacks storage = "rust", and every storage = "rust" type without a codec.
A rule or a default written in Rust renders as the R expression or value that declares it. One without an R form, such as an and of three conditions or a default that is an enum variant with fields, renders as json_ir(), which carries the JSON into the declaration as written:
R8::rule(
R8::json_ir('{"and":[{">":[{"var":"cost"},0]},{"<=":[{"var":"cost"},100]},{"!==":[{"var":"name"},""]}]}'),
message = "cost is in (0, 100] and name is not empty.",
id = "COST_RANGE"
)30.9 Using the type
In R, a Rust-stored value behaves as any R8 value; the methods run in Rust:
library(r8pkgR)
s <- Signal(name = "a", values = c(3, 4))
s
#> Signal a (2 values)
s$values
#> [1] 3 4
magnitude(s)
#> [1] 5
ratio(s, 2)
#> [1] 1.5
ratio(s, 0)
#> Error in ratio(s, 0) : `by` is not 0 [zero_divisor]
ratio(s, "a")
#> Error : Invalid arguments of `ratio()`: 1 problem
#> - `by` must be a numeric vector; found a character vector. [r_type]Construction validates each field as for any R8 value:
Signal(name = "a", values = "x")
#> Error : Invalid `pkgr::Signal`: 1 problem
#> - `values` must be a numeric vector; found a character vector. [r_type]x$name <- v returns a new value with the field replaced, and the other fields are shared, not copied. Values have documents, equality, and hashes, survive saveRDS(), and travel to mirai and future workers that load the package. A value is saved as its fields, which read without the package; R8 checks them before Rust code takes the value:
t <- s
t$name <- "b"
t
#> Signal b (2 values)
cat(R8::r8to_json(s))
#> {"$type":"pkgr::Signal","$types":{"pkgr::Signal":1},"name":"a","values":[3,4]}
f <- tempfile(fileext = ".rds")
saveRDS(s, f)
R8::r8equal(readRDS(f), s)
#> [1] TRUEA Rust-stored enum’s values behave as the values of an R-stored enum, each variant with its own fields:
k <- Resampler@KFold(k = 5L, seed = 1L)
k
#> KFold (k = 5, seed = 1)
k$k
#> [1] 5
k$k <- 10L
k
#> KFold (k = 10, seed = 1)
k$train
#> Error : `train` is not a field of `pkgr::Resampler@KFold`. Fields: k, seed.
Resampler@Custom(train = c(1L, 2L), test = 3L)
#> Custom (2 train, 1 test)
cat(R8::r8to_json(Resampler@Custom(train = c(1L, 2L), test = 3L)))
#> {"$type":"pkgr::Resampler","$types":{"pkgr::Resampler":1,"pkgr::Split":1},"train":[1,2],"test":[3],"type":"Custom"}r8size() reports the memory a value holds: the Rust struct’s own memory and the fields read into R that are not views of it. A compact sequence is copied once into Rust, 8 bytes per element:
big <- Signal(name = "big", values = as.numeric(seq_len(1e6)))
R8::r8size(big)
#> [1] 8000051Without a Display impl, the header of a Rust-stored value shows the memory of its state, and str() adds the fields read into R:
str(big)
#> <pkgr::Signal> 7.63 MiB
#> name: "big"
#> values: double[1,000,000] 1 2 3 4 5 6 7 8 ...R does not see memory that compiled code allocates, so R8 counts the memory of Rust-stored values and starts R’s garbage collector when it grows, which frees the values that nothing in R refers to.
30.10 C and C++
A package with C or C++ code calls it from an R method. The method passes the fields that the code needs, by name, and R8 checks the arguments and the result of a typed generic as it does for any method:
ratio <- R8::generic(
"ratio",
R8::params(x, by = R8::arg_double()),
return_type = R8::type_double()
)
R8::implement(ratio, Point) <- function(x, by) {
.Call(c_ratio, x$x, by)
}The C routine receives R vectors and needs nothing of R8. A Rust crate may also wrap a C or C++ library, whose types then hold its data in Rust. Types whose values compiled code holds, and methods that R8 calls without an R function, are written in Rust.