Skip to main content

Crate miniextendr_api

Crate miniextendr_api 

Source
Expand description

miniextendr-api: core runtime for Rust <-> R interop.

This crate provides the FFI surface, safety wrappers, and macro re-exports used by most miniextendr users. It is the primary dependency for building Rust-powered R packages and exposing Rust types to R.

At a glance:

  • FFI bindings + checked wrappers for R’s C API (sys, r_ffi_checked).
  • Conversions between Rust and R types (IntoR, TryFromSexp, Coerce).
  • ALTREP traits, registration helpers, and iterator-backed ALTREP data types.
  • Wrapper generation from Rust signatures (#[miniextendr], automatic registration via linkme).
  • Main-thread unwind protection plus optional worker dispatch (worker).
  • Class system support (S3, S4, S7, R6, env-style impl blocks).
  • Cross-package trait ABI for type-erased dispatch (trait_abi).

Most users should depend on this crate directly. For embedding R in standalone binaries or integration tests, see miniextendr-engine.

§Quick start

ⓘ
use miniextendr_api::miniextendr;

#[miniextendr]
fn add(a: i32, b: i32) -> i32 {
    a + b
}

That’s it — #[miniextendr] handles everything. Items self-register at link time; miniextendr_init! generates the R_init_* function that calls package_init() to register all routines with R. Wrapper R code is produced from Rust doc comments (roxygen tags are extracted) by loading the freshly linked package library and calling the registry writer. R/miniextendr-wrappers.R is regenerated during development installs, kept out of git, and shipped from disk in release tarballs; roxygen2 derives the tracked NAMESPACE and man/*.Rd files.

§Choosing the right API

miniextendr has several places where two or more APIs reach the same goal with different tradeoffs — a stricter / safer / more validated option, and a looser / easier / less protective one. The most common pairs are:

I’m reaching for…Consider alsoWhy
default IntoR for i64 / u64 / isize / usize (silently widens to REALSXP on overflow)#[miniextendr(strict)] → crate::strict helpers (panic on overflow)strict catches the truncation bugs caused by R having no native 64-bit integer type
Coerce (infallible widening)TryCoerce (fallible)the source range can exceed the target type
Rf_*_unchecked FFIchecked variantsunchecked is only safe inside ALTREP callbacks, with_r_unwind_protect, or with_r_thread — MXL301 lint enforces
panic!(msg)miniextendr_api::error!("msg", class = "...")typed conditions let R-side tryCatch handlers route by class
raw _dots: &Dots#[miniextendr(dots = typed_list!(...))]validation moves from runtime to macro call site
#[derive(AltrepInteger)] field-based#[altrep(manual)] + handwritten traitswhen custom storage or computed-on-access can’t fit the derive
hand-rolled TryFromSexp + IntoR#[derive(RSerializeNative)] (serde feature)serde is ergonomic for nested structs; hand-rolled is zero-overhead and fully controlled

Project-wide defaults are controlled by mutually-exclusive cargo features — see the “Project-wide Defaults” feature table below.

§Default opinion

When in doubt, pick the stricter path. The framework’s default stance is “fail loudly, leave a trail.” The looser variants exist for cases where the cost is measured or the looser semantics are correct for your data — they are not the default.

§GC protection and ownership

R’s garbage collector can reclaim any SEXP that isn’t protected. miniextendr provides three complementary protection mechanisms:

StrategyModuleLifetimeRelease OrderUse Case
PROTECT stackgc_protectWithin .CallLIFO (stack)Temporary allocations
VECSXP poolprotect_poolUntil released or the pool dropsAny orderValues a struct owns; many values; cross-call roots
R ownershipExternalPtrUntil R GCsR decidesRust data owned by R

Quick guide:

Temporary allocations during computation -> ProtectScope

ⓘ
unsafe fn compute(x: SEXP) -> SEXP {
    let scope = ProtectScope::new();
    let temp = scope.protect(Rf_allocVector(REALSXP, 100));
    // ... work with temp ...
    result.into_raw()
} // UNPROTECT(n) called automatically

Values a struct owns, many values, or any drop order -> ProtectPool

ⓘ
// The per-call root set: keep each value until the pool drops.
let mut roots = ProtectPool::new(ProtectPool::DEFAULT_CAPACITY);
let ids = roots.root(vec![1, 2, 3]);

// Or release one value at a time, in any order, even across `.Call`s.
let key = roots.insert(backing_vec);
roots.release(key);

One long-lived object -> Preserved (one R_PreserveObject root)

Rust data owned by R -> ExternalPtr

ⓘ
#[miniextendr]
fn create_model() -> ExternalPtr<MyModel> {
    ExternalPtr::new(MyModel::new())
} // R owns it; Drop runs when R GCs

Note: ALTREP trait methods receive raw SEXP pointers from R’s runtime. These are safe to dereference because R guarantees valid SEXPs in ALTREP callbacks.

§Threading and safety

R uses longjmp for errors, which can bypass Rust destructors. Generated wrappers run inline on R’s main thread inside R_UnwindProtect by default. Opt-in #[miniextendr(worker)] functions (or crates using worker-default) run Rust logic on the worker and marshal R API calls back through with_r_thread. Most FFI wrappers are main-thread routed via #[r_ffi_checked]. Use unchecked variants only when you have arranged a safe context.

The nonapi feature exposes legacy controls for R’s process-global stack bounds. Disabling that check does not make R’s API safe off the main thread; package code must keep R API work on the recorded main thread.

§Feature Flags

§Core Features

FeatureDescription
nonapiNon-API R symbols (stack controls, mutable DATAPTR). May break with R updates.
rayonParallel iterators via Rayon. Adds RParallelIterator, RParallelExtend.
connectionsExperimental R connection framework. Unstable R API.
indicatifProgress bars routed through R connections. Requires nonapi + connections.
vctrsvctrs class construction (new_vctr, new_rcrd, new_list_of) and #[derive(Vctrs)].
worker-threadWorker dispatch infrastructure. It does not change proc-macro defaults by itself; without it, worker APIs are inline stubs.

§Type Conversions (Scalars & Vectors)

FeatureRust TypeR TypeNotes
eitherEither<L, R>Tries L then RUnion-like dispatch
uuidUuid, Vec<Uuid>characterUUID ↔ string
regexRegexcharacter(1)Compiles pattern from R
urlUrl, Vec<Url>characterValidated URLs
timeOffsetDateTime, DatePOSIXct, DateDate/time conversions
jiffTimestamp, Zoned, civil typesR date/time classesIANA timezone-aware conversions
ordered-floatOrderedFloat<f64>numericNaN-orderable floats
num-bigintBigInt, BigUintcharacterArbitrary precision via strings
rust_decimalDecimalcharacterFixed-point decimals
num-complexComplex<f64>complexNative R complex support
indexmapIndexMap<String, T>named listPreserves insertion order
bitflagsRFlags<T>integerBitflags ↔ integer
bitvecRBitVeclogicalBit vectors ↔ logical
tinyvecTinyVec<[T; N]>, ArrayVec<[T; N]>vectorsSmall-vector optimization

§Matrix & Array Libraries

FeatureTypesConversions
ndarrayArray1–Array6, ArrayD, viewsR vectors/matrices ↔ ndarray
nalgebraDVector, DMatrixR vectors/matrices ↔ nalgebra
blas-lapacklinalg::{matrix_product, solve}, sys::{dgemm_, dgesv_}R’s own BLAS/LAPACK (links $(LAPACK_LIBS) $(BLAS_LIBS) $(FLIBS))

§Serialization

FeatureTraits/ModulesDescription
serdeRSerializeNative, RDeserializeNativeDirect Rust ↔ R native serialization
serde_jsonRSerialize, RDeserializeJSON string serialization (includes serde)
borshBorsh<T>Binary serialization ↔ raw vectors via Borsh

§Adapter Traits (Generic Operations)

FeatureTraitsUse Case
num-traitsRNum, RSigned, RFloatGeneric numeric operations
bytesRBuf, RBufMutByte buffer operations

§Text & Data Processing

FeatureTypes/FunctionsDescription
aho-corasickAhoCorasick, aho_compileFast multi-pattern string search
tomlTomlValue, toml_from_strTOML parsing and serialization
tabledtable_to_stringASCII/Unicode table formatting
sha2sha256_str, sha512_bytesCryptographic hashing
blake3blake3_str, blake3_bytesBLAKE3 hashing (fast, 32-byte digests)
md5md5_str, md5_bytesMD5 hashing (interop only — broken crypto)
globsetGlobSet, build_globsetShell-style glob matching (path-aware)
zstdzstd_compress, zstd_decompresszstd whole-buffer compression

§Random Number Generation

FeatureTypesDescription
randRRng, RDistributionsWraps R’s RNG with rand traits
rand_distrRe-exports rand_distrAdditional distributions (Normal, Exp, etc.)

§Binary Data

FeatureTypesDescription
raw_conversionsRaw<T>, RawSlice<T>POD types ↔ raw vectors via bytemuck

§Project-wide Defaults (mutually exclusive where noted)

FeatureDescription
r6-defaultDefault class system: R6 (mutually exclusive with s7-default)
s7-defaultDefault class system: S7 (mutually exclusive with r6-default)
worker-defaultDefault to worker thread dispatch (implies worker-thread)
strict-defaultDefault to strict mode for lossy integer conversions
coerce-defaultDefault to coerce mode for type conversions
no-preconditions-defaultDrop the R-side type checks by default (preconditions keeps them per item)

§Development / Diagnostics

FeatureDescription
doc-lintWarn on roxygen doc comment mismatches (enabled by default)
macro-coverageExpose macro coverage test module for cargo expand auditing
growth-debugTrack and report collection growth events (zero-cost when off)
full-integrationsEvery optional dependency integration (maintenance aggregate)
full-codegenCodegen/runtime selectors using r6-default (maintenance aggregate)
full-codegen-s7Codegen/runtime selectors using s7-default (maintenance aggregate)
fullIntegrations + full-codegen + diagnostics for local checks

Re-exports§

pub use linkme; 👻
pub use miniextendr_macros::__mx_trait_impl_expand; 👻
pub use sexp::SEXP;
pub use sexp::SEXPREC;
pub use sexp_ext::PairListArgs;
pub use sexp_ext::PairListExt;
pub use sexp_ext::SexpExt;
pub use sexp_types::IsNA;
pub use sexp_types::R_CFinalizer_t;
pub use sexp_types::R_xlen_t;
pub use sexp_types::RLogical;
pub use sexp_types::RNativeType;
pub use sexp_types::Rboolean;
pub use sexp_types::Rbyte;
pub use sexp_types::Rcomplex;
pub use sexp_types::SEXPTYPE;
pub use sexp_types::cetype_t;
pub use altrep_data::AltComplexData;
pub use altrep_data::AltIntegerData;
pub use altrep_data::AltListData;
pub use altrep_data::AltLogicalData;
pub use altrep_data::AltRawData;
pub use altrep_data::AltRealData;
pub use altrep_data::AltStringData;
pub use altrep_data::AltrepBuffer;
pub use altrep_data::AltrepDataptr;
pub use altrep_data::AltrepExtract;
pub use altrep_data::AltrepIteratorExt;
pub use altrep_data::AltrepIteratorItem;
pub use altrep_data::AltrepLen;
pub use altrep_data::IterComplexData;
pub use altrep_data::IterIntCoerceData;
pub use altrep_data::IterIntData;
pub use altrep_data::IterIntFromBoolData;
pub use altrep_data::IterListData;
pub use altrep_data::IterLogicalData;
pub use altrep_data::IterRLogicalData;
pub use altrep_data::IterRawData;
pub use altrep_data::IterRealCoerceData;
pub use altrep_data::IterRealData;
pub use altrep_data::IterState;
pub use altrep_data::IterStringData;
pub use altrep_data::Logical;
pub use altrep_data::Sortedness;
pub use altrep_data::SparseIterComplexData;
pub use altrep_data::SparseIterIntData;
pub use altrep_data::SparseIterLogicalData;
pub use altrep_data::SparseIterRawData;
pub use altrep_data::SparseIterRealData;
pub use altrep_data::SparseIterState;
pub use altrep_data::StreamingIntData;
pub use altrep_data::StreamingRealData;
pub use altrep_data::WindowedIterIntData;
pub use altrep_data::WindowedIterRealData;
pub use altrep_data::WindowedIterState;
pub use altrep::RBase;
pub use altrep_sexp::AltrepSexp;
pub use altrep_sexp::ensure_materialized;
pub use altrep_traits::AltrepGuard;
pub use into_r::Altrep;
pub use into_r::IntoR;
pub use into_r::IntoRAltrep;
pub use into_r_error::IntoRError;
pub use newtype::IntoRNewtype;
pub use newtype::IntoRVecElement;
pub use newtype::TryFromSexpElement;
pub use into_r_as::IntoRAs;
pub use into_r_as::StorageCoerceError;
pub use worker::Sendable;
pub use worker::is_r_main_thread;
pub use worker::with_r_thread;
pub use worker::miniextendr_runtime_init;
pub use thread::DEFAULT_R_STACK_SIZE;
pub use thread::RThreadBuilder;
pub use ffi_guard::GuardMode;
pub use ffi_guard::guarded_ffi_call;
pub use ffi_guard::guarded_ffi_call_with_fallback;
pub use dataframe::BuiltDataFrame;
pub use dataframe::ColumnarFrame;
pub use dataframe::DataFrame;
pub use dataframe::DataFrameError;
pub use dataframe::DataFrameShape;
pub use dataframe::FromDataFrame;
pub use dataframe::GroupDeclaration;
pub use dataframe::GroupKey;
pub use dataframe::GroupedDataFrame;
pub use dataframe::IntoDataFrame;
pub use dataframe::IntoDataFrameSplit;
pub use dataframe::RealKey;
pub use dataframe::SplitResults;
pub use dataframe::group_rows;
pub use dataframe_builder::RDataFrameBuilder;
pub use error::r_warning;
pub use rng::RngGuard;
pub use rng::with_rng;
pub use from_r::SexpClassError;
pub use from_r::SexpError;
pub use from_r::SexpLengthError;
pub use from_r::SexpNaError;
pub use from_r::SexpTypeError;
pub use from_r::TryFromRoot;
pub use from_r::TryFromSexp;
pub use expression::RCall;
pub use expression::REnv;
pub use expression::REvalError;
pub use expression::RSymbol;
pub use expression::r_eval_str;
pub use expression::r_eval_str_global;
pub use coerce::Coerce;
pub use coerce::CoerceError;
pub use coerce::Coerced;
pub use coerce::TryCoerce;
pub use r_coerce::RCoerceCharacter;
pub use r_coerce::RCoerceComplex;
pub use r_coerce::RCoerceDataFrame;
pub use r_coerce::RCoerceDate;
pub use r_coerce::RCoerceEnvironment;
pub use r_coerce::RCoerceError;
pub use r_coerce::RCoerceFactor;
pub use r_coerce::RCoerceFunction;
pub use r_coerce::RCoerceInteger;
pub use r_coerce::RCoerceList;
pub use r_coerce::RCoerceLogical;
pub use r_coerce::RCoerceMatrix;
pub use r_coerce::RCoerceNumeric;
pub use r_coerce::RCoercePOSIXct;
pub use r_coerce::RCoerceRaw;
pub use r_coerce::RCoerceVector;
pub use r_coerce::SUPPORTED_AS_GENERICS;
pub use r_coerce::is_supported_as_generic;
pub use condition::ArgError;
pub use condition::AsRError;
pub use condition::RCondition;
pub use deferred_condition::defer_condition;
pub use deferred_condition::defer_message;
pub use deferred_condition::defer_warning;
pub use visibility::Invisible;
pub use visibility::Visible;
pub use nullable::Nullable;
pub use call_marker::Call;
pub use call_marker::CallerCall;
pub use nargs::NArgs;
pub use quoted::Quosure;
pub use quoted::Quoted;
pub use lazy_dots::LazyDots;
pub use precondition_marker::Checked;
pub use precondition_marker::Unchecked;
pub use wrap_as::ConvertFrom;
pub use wrap_as::ConvertTo;
pub use wrap_as::WrapAsEnv;
pub use wrap_as::WrapAsR6;
pub use wrap_as::WrapAsS3;
pub use wrap_as::WrapAsS4;
pub use wrap_as::WrapAsS7;
pub use wrap_as::WrapAsVctrs;
pub use rvalue::RValue;
pub use convert::AsCharacter;
pub use convert::AsCharacterVec;
pub use convert::AsDataFrame;
pub use convert::AsDataFrameExt;
pub use convert::AsDisplay;
pub use convert::AsDisplayVec;
pub use convert::AsExternalPtr;
pub use convert::AsExternalPtrExt;
pub use convert::AsFromStr;
pub use convert::AsFromStrVec;
pub use convert::AsList;
pub use convert::AsListExt;
pub use convert::AsNamedList;
pub use convert::AsNamedListExt;
pub use convert::AsNamedVector;
pub use convert::AsNamedVectorExt;
pub use convert::AsNumeric;
pub use convert::AsNumericVec;
pub use convert::AsRNative;
pub use convert::AsRNativeExt;
pub use convert::Collect;
pub use convert::CollectNA;
pub use convert::CollectNAInt;
pub use convert::CollectStrings;
pub use convert::ColumnSource;
pub use into_r::Lazy;
pub use list::BuiltList;
pub use list::IntoList;
pub use list::List;
pub use list::ListAccumulator;
pub use list::ListBuilder;
pub use list::ListMut;
pub use list::NamedList;
pub use list::NamedListBuilder;
pub use list::TryFromList;
pub use list::collect_list;
pub use missing::Missing;
pub use missing::is_missing_arg;
pub use named_vector::AtomicElement;
pub use named_vector::NamedVector;
pub use rcow::RBorrow;
pub use rcow::RCow;
pub use strvec::ProtectedStrVec;
pub use strvec::ProtectedStrVecCowIter;
pub use strvec::ProtectedStrVecIter;
pub use strvec::StrVec;
pub use strvec::StrVecBuilder;
pub use strvec::StrVecCowIter;
pub use strvec::StrVecIter;
pub use typed_list::TypeSpec;
pub use typed_list::TypedEntry;
pub use typed_list::TypedList;
pub use typed_list::TypedListError;
pub use typed_list::TypedListSpec;
pub use typed_list::actual_type_string;
pub use typed_list::sexptype_name;
pub use typed_list::validate_list;
pub use externalptr::ErasedExternalPtr;
pub use externalptr::ExternalPtr;
pub use externalptr::ExternalPtrMut;
pub use externalptr::ExternalPtrRef;
pub use externalptr::ExternalSlice;
pub use externalptr::IntoExternalPtr;
pub use externalptr::TypedExternal;
pub use externalptr::altrep_data1_as;
pub use externalptr::altrep_data1_as_unchecked;
pub use externalptr::altrep_data1_mut;
pub use externalptr::altrep_data1_mut_unchecked;
pub use externalptr::altrep_data2_as;
pub use externalptr::altrep_data2_as_unchecked;
pub use gc_protect::OwnedProtect;
pub use gc_protect::ProtectIndex;
pub use gc_protect::ProtectScope;
pub use gc_protect::Protected;
pub use gc_protect::Protector;
pub use gc_protect::ReprotectSlot;
pub use gc_protect::Root;
pub use preserved::Preserved;
pub use protect_pool::ProtectKey;
pub use protect_pool::ProtectPool;
pub use refcount_protect::ArenaGuard;
pub use refcount_protect::RefCountedArena;
pub use refcount_protect::ThreadLocalArena;
pub use allocator::RAllocator;
pub use abi::mx_base_vtable;
pub use abi::mx_erased;
pub use abi::mx_meth;
pub use abi::mx_tag;
pub use trait_abi::TraitView;
pub use adapter_traits::RClone;
pub use adapter_traits::RClone;
pub use adapter_traits::RCopy;
pub use adapter_traits::RCopy;
pub use adapter_traits::RDebug;
pub use adapter_traits::RDebug;
pub use adapter_traits::RDefault;
pub use adapter_traits::RDefault;
pub use adapter_traits::RDisplay;
pub use adapter_traits::RDisplay;
pub use adapter_traits::RError;
pub use adapter_traits::RError;
pub use adapter_traits::RExtend;
pub use adapter_traits::RExtend;
pub use adapter_traits::RFromIter;
pub use adapter_traits::RFromIter;
pub use adapter_traits::RFromStr;
pub use adapter_traits::RFromStr;
pub use adapter_traits::RHash;
pub use adapter_traits::RHash;
pub use adapter_traits::RIterator;
pub use adapter_traits::RIterator;
pub use adapter_traits::RMakeIter;
pub use adapter_traits::RMakeIter;
pub use adapter_traits::ROrd;
pub use adapter_traits::ROrd;
pub use adapter_traits::RPartialOrd;
pub use adapter_traits::RPartialOrd;
pub use adapter_traits::RToVec;
pub use adapter_traits::RToVec;
pub use rarray::RArray;
pub use rarray::RArray3D;
pub use rarray::RMatrix;
pub use rarray::RVector;
pub use match_arg::MatchArg;
pub use match_arg::MatchArgAlias;
pub use match_arg::MatchArgError;
pub use match_arg::choices_sexp;
pub use match_arg::match_arg_from_sexp;
pub use match_arg::match_arg_missing_or;
pub use match_arg::match_arg_null_or;
pub use match_arg::match_arg_option_from_sexp;
pub use match_arg::match_arg_param;
pub use match_arg::match_arg_param_with_default;
pub use match_arg::match_arg_vec_from_sexp;
pub use match_arg::match_arg_vec_into_sexp;
pub use factor::Factor;
pub use factor::FactorMut;
pub use factor::FactorOptionVec;
pub use factor::FactorVec;
pub use factor::RFactor;
pub use factor::UnitEnumFactor;
pub use factor::build_factor;
pub use factor::build_levels_sexp;
pub use factor::build_levels_sexp_cached;
pub use factor::factor_from_sexp;

Modules§

abi
ABI types for cross-package trait dispatch.
adapter_traits
Built-in adapter traits for std library traits.
allocator
R-backed global allocator for Rust.
altrep
Core ALTREP types and registration traits.
altrep_bridge
Unsafe ALTREP trampolines and installers bridging safe traits to R’s C ABI.
altrep_data
High-level ALTREP data traits.
altrep_ext
Extension trait for SEXP providing ALTREP-specific accessors.
altrep_impl
ALTREP implementation utilities.
altrep_registration 👻
altrep_sexp
AltrepSexp — a !Send + !Sync wrapper for ALTREP vectors.
altrep_traits
Safe, idiomatic ALTREP trait hierarchy mirroring R’s method tables.
backtrace
Configurable panic hook for miniextendr-based R packages.
cached_class
Cached R class attribute SEXPs.
call_marker
Condition-call markers (Call / CallerCall) for #[miniextendr] parameters. Condition-call markers: Call and CallerCall.
coerce
Type coercion traits for converting Rust types to R native types.
condition
Condition macros and signal enum for the Rust→R condition pipeline.
convert
Wrapper helpers to force specific IntoR representations.
dataframe
R data.frame views, rooted Rust-built handles, and conversion traits.
dataframe_builder
Closure-per-column DataFrame builder.
deferred_condition
Deferred conditions: signal an R warning, message or condition and still return a value.
dots
R’s ... (variadic arguments) support.
encoding
Encoding / locale probing utilities.
env_flag 🔒
Shared truthiness parsing for boolean-ish environment-variable flags. Shared truthiness parsing for environment-variable flags.
error
Error handling helpers for R API calls.
error_value
Tagged condition value transport.
expression
Safe wrappers for R expression evaluation.
externalptr
ExternalPtr<T> — a Box-like owned pointer that wraps R’s EXTPTRSXP.
externalptr_std
TypedExternal implementations for standard library types.
factor
Factor support for enum ↔ R factor conversions.
ffi_guard
Unified FFI guard for catching panics at Rust-R boundaries.
from_r
Conversions from R SEXP to Rust types.
gc_protect
GC protection tools built on R’s PROTECT stack.
init
Package initialization for miniextendr R packages.
into_r
Conversions from Rust types to R SEXP.
into_r_as
Storage-directed conversion to R.
into_r_error
Error types for fallible IntoR conversions.
lazy_dots
The dots left unforced: LazyDots.
list
Thin wrapper around R list (VECSXP).
markers
Marker traits for proc-macro derived types. Marker traits for proc-macro derived types.
match_arg
match.arg-style string conversion for enums.
missing
Support for R’s missing arguments.
mx_abi
C-callable mx_abi functions (mx_wrap, mx_get, mx_query, mx_abi_register).
named_vector
Named atomic vector wrapper for HashMap/BTreeMap ↔ named R atomic vector conversions.
nargs
The argument-count marker (NArgs) for #[miniextendr] parameters. The argument-count marker: NArgs.
newtype
Container conversions for newtypes (#[derive(TryFromSexp)] / #[derive(IntoR)]) and string-parsed types (try_from_sexp_via_str_parse!). See the module docs, #844 and #1766. Container conversions for newtypes and string-parsed types.
nullable
The NULL-on-None return type (Nullable<T>). Nullable<T>: an optional return whose None is NULL in R.
optionals
Optional feature integrations with third-party crates.
panic_telemetry
Structured panic telemetry for debugging Rust panics that become R errors.
precondition_marker
Precondition markers (Checked<T> / Unchecked<T>) for #[miniextendr] parameters. Precondition markers: Checked<T> and Unchecked<T>.
prelude
Convenience re-exports for common miniextendr items.
preserved
Preserved: an owned GC root for one R object, on R’s precious list.
protect_pool
ProtectPool: an owned root set for R objects, held in one R list.
pump
WorkerPump<T> — safe main/worker thread coordination for FFI bodies.
quoted
Unevaluated-argument markers (Quoted / Quosure) for #[miniextendr] parameters. Unevaluated arguments: the Quoted and Quosure parameter markers.
r_coerce
Traits for R’s as.<class>() coercion functions.
rarray
N-dimensional R arrays with const generic dimension count. N-dimensional R arrays with const generic dimension count.
rcow
RCow — an R-aware copy-on-write slice.
refcount_protect
Reference-counted GC protection using a BTreeMap + VECSXP backing.
registry
Automatic registration for miniextendr.
rng
RNG (Random Number Generation) utilities for R interop.
rvalue
RValue — an owned, Send, R-native value tree.
s4_helpers
S4 slot access and class checking helpers.
sexp
The SEXP newtype and inherent methods. The SEXP newtype and its inherent methods.
sexp_ext
SexpExt and PairListExt — the ergonomic extension traits on SEXP. SexpExt — the ergonomic extension trait on SEXP — and PairListExt, its pairlist (call) counterpart.
sexp_types
Core type vocabulary for R values: SEXPTYPE, R_xlen_t, Rcomplex, RLogical, Rboolean, RNativeType, cetype_t. Core type vocabulary for R values: SEXPTYPE, R_xlen_t, Rbyte, Rcomplex, RLogical, Rboolean, cetype_t, R_CFinalizer_t, and the RNativeType and IsNA traits + impls.
strict
Strict conversion helpers for #[miniextendr(strict)].
strvec
Thin wrapper around R character vector (STRSXP).
sys
Raw R FFI bindings — extern "C-unwind" blocks for Rf_* / R_* / INTEGER / etc., plus the ALTREP method type aliases under sys::altrep. The escape hatch for code that genuinely needs the raw R C API.
thread
Advanced controls for R’s process-global C-stack bounds.
trait_abi
Runtime support for trait ABI operations.
tuple_macros 🔒
One arity table for the tuple trait families (unit keeps its NULL semantics).
typed_list
Typed list validation for structured R list arguments.
unwind_protect
Safe API for R’s R_UnwindProtect
visibility
Return-visibility markers (Invisible<T> / Visible<T>). Return-visibility markers: Invisible<T> and Visible<T>.
wasm_registry_writer
Host-time generator of wasm_registry.rs — the WASM-side replacement for linkme. See the module for full rationale.
worker
Worker thread infrastructure for safe Rust-R FFI.
wrap_as
Explicit R class-system return markers. Explicit R class-system return markers.

Macros§

__dataframe_row_when_rayon 👻
No-rayon build: the wrapped parallel methods vanish entirely. The trait’s *_par methods are themselves #[cfg(feature = "rayon")], so there is nothing to override.
__impl_alt_elt 👻
Shared elt implementation for ALTREP families with direct element access.
__impl_alt_family 👻
Internal macro: the per-family knob matrix.
__impl_alt_from_data 👻
Internal macro: canonical ALTREP emission.
__impl_alt_get_region 👻
Shared get_region implementation for ALTREP families.
__impl_alt_is_sorted 👻
Shared is_sorted implementation for ALTREP families.
__impl_alt_no_na 👻
Shared no_na implementation for ALTREP families.
__impl_altcomplex_methods 👻
Internal macro: impl AltComplex methods (elt, get_region)
__impl_altinteger_methods 👻
Internal macro for AltInteger method implementations.
__impl_altlogical_methods 👻
Internal macro: impl AltLogical methods from AltLogicalData
__impl_altraw_methods 👻
Internal macro for AltRaw method implementations.
__impl_altreal_methods 👻
Internal macro for AltReal method implementations.
__impl_altrep_base 👻
Internal macro: impl Altrep with just length, optionally plus serialization.
__impl_altstring_methods 👻
Internal macro for AltString method implementations.
__impl_altvec_complex_dataptr 👻
Internal macro: materializing dataptr for complex ALTREP.
__impl_altvec_dataptr 👻
Internal macro: impl AltVec with dataptr support
__impl_altvec_extract_subset 👻
Internal macro: impl AltVec with extract_subset support
__impl_altvec_flavor 👻
Internal macro: emit the impl AltVec for a given flavor.
__impl_altvec_integer_dataptr 👻
Internal macro: materializing dataptr for integer ALTREP.
__impl_altvec_logical_dataptr 👻
Internal macro: materializing dataptr for logical ALTREP.
__impl_altvec_materializing_dataptr 👻
Internal macro: impl AltVec with a materializing dataptr for a given element type.
__impl_altvec_raw_dataptr 👻
Internal macro: materializing dataptr for raw ALTREP.
__impl_altvec_real_dataptr 👻
Internal macro: materializing dataptr for real ALTREP.
__impl_altvec_string_dataptr 👻
Internal macro: impl AltVec with dataptr support for string ALTREP.
__impl_inferbase 👻
Parametric implementation of InferBase for any ALTREP family.
__mx_condition_data 👻
Internal: normalise a macro data = ... argument into Option<ConditionData>. Not part of the public API.
__mx_condition_field_name 👻
Internal: one condition-data field name, validated against the reserved slots. Not part of the public API.
__mx_condition_pair 👻
Internal: one (name, value) pair of a bracketed data = [...] list; the name goes through the reserved-slot check (compile time for literals).
__mx_condition_parts 👻
Internal: parse the shared option grid of error! / warning! / condition! and the defer_*! macros into (call, class, data, message). Not part of the public API.
__mx_conversion_arg_message 👻
Internal: the whole message of a failed argument conversion whose error words it itself (a match_arg choice error, see ConversionArgMessageBuiltin, or an error with an argument_message, see ConversionArgMessageClassed), for the argument $name; None otherwise. crate::error_value::conversion_condition_value then uses it in place of <prefix>: <reason>. Not public API.
__mx_conversion_err_parts 👻
Internal: the argument-conversion Err(e) probe used by generated wrappers. Not public API. Yields the error’s own ErrParts; crate::error_value::conversion_condition_value adds the parameter context.
__mx_conversion_expectation 👻
Internal: what a failed argument conversion’s error says the value should have been, for a parameter whose Rust type gives the macro no R-facing expectation (#1594). Some("one of \"fast\", \"slow\"") for a match_arg choice error, Some("a data frame") for a class error, the joined expectation of an Either whose arms both refused the kind of value, None otherwise. Not public API.
__mx_declared_err_parts 👻
Internal: the declared-shape stage of crate::__mx_result_err_parts!; nothing can be declared without the serde feature.
__mx_declared_serde_shape 👻
Internal: without the serde feature, a shape that sets nothing. serde_error(..) needs the feature anyway: its serde_err_parts call reports that, and $marker is never resolved.
__mx_result_err_parts 👻
Internal: the Err(e) probe used by generated wrappers. Not public API.
__mx_trait_metadata_RClone_7 👻
__mx_trait_metadata_RCopy_9 👻
__mx_trait_metadata_RDebug_0 👻
__mx_trait_metadata_RDefault_8 👻
__mx_trait_metadata_RDisplay_1 👻
__mx_trait_metadata_RError_5 👻
__mx_trait_metadata_RExtend_11 👻
__mx_trait_metadata_RFromIter_12 👻
__mx_trait_metadata_RFromStr_6 👻
__mx_trait_metadata_RHash_2 👻
__mx_trait_metadata_RIterator_10 👻
__mx_trait_metadata_RMakeIter_14 👻
__mx_trait_metadata_ROrd_3 👻
__mx_trait_metadata_RPartialOrd_4 👻
__mx_trait_metadata_RToVec_13 👻
_linkme_macro_MX_ALL_EQUAL 👻
_linkme_macro_MX_ALTREP_REGISTRATIONS 👻
_linkme_macro_MX_CALL_DEFS 👻
_linkme_macro_MX_CLASS_BLOCKS 👻
_linkme_macro_MX_CLASS_NAMES 👻
_linkme_macro_MX_CONVERSION_ERROR_CLASS 👻
_linkme_macro_MX_MATCH_ARG_CHOICES 👻
_linkme_macro_MX_MATCH_ARG_PARAM_DOCS 👻
_linkme_macro_MX_REEXPORTS 👻
_linkme_macro_MX_R_WRAPPERS 👻
_linkme_macro_MX_S7_SIDECAR_PROPS 👻
_linkme_macro_MX_SIDECAR_ACCESSORS 👻
_linkme_macro_MX_TRAIT_DISPATCH 👻
arg_error
Raise the argument error the generated R wrapper raises for a bad argument, from a #[miniextendr] function body.
condition
Signal a generic R condition from Rust with rust_condition class layering.
defer_condition
Queue a plain R condition (rust_condition layering, silent without a handler) and return normally; signalled when the surrounding guarded call or callback returns.
defer_message
Queue an R message (rust_message layering, muffled by suppressMessages()) and return normally; emitted when the surrounding guarded call or callback returns.
defer_warning
Queue an R warning with rust_warning class layering and return normally; the surrounding guarded call or callback signals it after its value is computed.
error
Raise an R error from Rust with rust_error class layering.
impl_altcomplex_from_data
Generate ALTREP trait implementations for a type that implements AltComplexData.
impl_altcomplex_from_data_generic
Generic form of impl_altcomplex_from_data! — see impl_altinteger_from_data_generic! for the calling convention.
impl_altinteger_from_data
Generate ALTREP trait implementations for a type that implements AltIntegerData.
impl_altinteger_from_data_generic
Generic form of impl_altinteger_from_data!: accepts an optional generic parameter list and where-clause ({T, U} Foo<T, U> {T: Bound, ..}) so it can target struct Foo<T> { .. } types, not just concrete/monomorphic ones. The non-generic macro above forwards here with empty {} brackets so there is exactly one emission body for both call shapes.
impl_altlist_from_data
Generate ALTREP trait implementations for a type that implements AltListData.
impl_altlist_from_data_generic
Generic form of impl_altlist_from_data!: accepts an optional generic parameter list and where-clause so it can target struct Foo<T> { .. } types, not just concrete ones. The non-generic macro above forwards here with empty {} brackets so there is exactly one emission body.
impl_altlogical_from_data
Generate ALTREP trait implementations for a type that implements AltLogicalData.
impl_altlogical_from_data_generic
Generic form of impl_altlogical_from_data! — see impl_altinteger_from_data_generic! for the calling convention.
impl_altraw_from_data
Generate ALTREP trait implementations for a type that implements AltRawData.
impl_altraw_from_data_generic
Generic form of impl_altraw_from_data! — see impl_altinteger_from_data_generic! for the calling convention.
impl_altreal_from_data
Generate ALTREP trait implementations for a type that implements AltRealData.
impl_altreal_from_data_generic
Generic form of impl_altreal_from_data! — see impl_altinteger_from_data_generic! for the calling convention.
impl_altstring_from_data
Generate ALTREP trait implementations for a type that implements AltStringData.
impl_altstring_from_data_generic
Generic form of impl_altstring_from_data! — see impl_altinteger_from_data_generic! for the calling convention.
impl_inferbase_complex
Implement InferBase for a complex ALTREP data type. See impl_inferbase_integer! for the generic calling convention.
impl_inferbase_integer
Implement InferBase for an integer ALTREP data type.
impl_inferbase_list
Implement InferBase for a list ALTREP data type. See impl_inferbase_integer! for the generic calling convention.
impl_inferbase_logical
Implement InferBase for a logical ALTREP data type. See impl_inferbase_integer! for the generic calling convention.
impl_inferbase_raw
Implement InferBase for a raw ALTREP data type. See impl_inferbase_integer! for the generic calling convention.
impl_inferbase_real
Implement InferBase for a real ALTREP data type. See impl_inferbase_integer! for the generic calling convention.
impl_inferbase_string
Implement InferBase for a string ALTREP data type. See impl_inferbase_integer! for the generic calling convention.
impl_typed_external
Generate TypedExternal and IntoExternalPtr impls for a concrete monomorphization of a generic type.
list
Construct an R list from Rust values.
message
Emit an R message from Rust with rust_message class layering.
miniextendr_init
Generate the R_init_* entry point for a miniextendr R package.
r
Evaluate R code written as Rust tokens, validated at compile time.
r_print
Print to R’s console (like print!).
r_println
Print to R’s console with a newline (like println!).
r_str
Parse and evaluate runtime R source from Rust.
reexport
Re-export other packages’ R functions from this package.
report_growth
Print and reset all growth counters.
rust_condition
Collision-free alias for crate::condition!.
rust_error
Collision-free alias for crate::error!.
serde_error_shape
Declare the SerdeErrorShape of an error type once, for every #[miniextendr] function and method of this crate that returns it. Needs the serde feature, without which a declaration is a compile error.
track_growth
Track a collection growth (reallocation) event.
try_from_sexp_via_str_parse
Give a type parsed from an R string its four TryFromSexp conversions: T, Option<T>, Vec<T> and Vec<Option<T>>.
typed_dataframe
Define a compile-time-validated wrapper for an R data.frame input.
typed_list
Create a TypedListSpec for validating ... arguments or lists.
warning
Raise an R warning from Rust with rust_warning class layering.

Structs§

AltrepPkgName 👻
Returns the current ALTREP package name as a C string pointer. This is set by the C entrypoint before ALTREP registration.

Statics§

ALTREP_DLL_INFO 🔒
ALTREP_PKG_NAME 👻
Opaque handle for ALTREP package name. Use ALTREP_PKG_NAME.as_ptr() to get the C string pointer.
ALTREP_PKG_NAME_PTR 🔒

Functions§

altrep_dll_info 👻
Get the stored DllInfo pointer for ALTREP class registration.
miniextendr_set_altrep_pkg_name 👻 ⚠
Set the ALTREP package name. Called from C entrypoint.
set_altrep_dll_info 👻
Store the DllInfo pointer during package init.

Attribute Macros§

miniextendr
Export Rust items to R.
r_ffi_checked
Generate thread-safe wrappers for R FFI functions.

Derive Macros§

AllEqual
Derive an all.equal() method for the R class of an ExternalPtr type, comparing the struct field by field (#2149).
Altrep
Derive ALTREP registration for a data struct.
AltrepComplex
Derive macro for ALTREP complex vector data types.
AltrepInteger
Derive macro for ALTREP integer vector data types.
AltrepList
Derive macro for ALTREP list vector data types.
AltrepLogical
Derive macro for ALTREP logical vector data types.
AltrepRaw
Derive macro for ALTREP raw vector data types.
AltrepReal
Derive macro for ALTREP real vector data types.
AltrepString
Derive macro for ALTREP string vector data types.
DataFrameRow
Derive DataFrameRow: generates a companion *DataFrame type with collection fields, plus IntoR / TryFromSexp / IntoDataFrame impls for seamless R data.frame conversion.
ExternalPtr
Derive macro for implementing TypedExternal on a type.
IntoList
Derive IntoList for a struct (Rust → R list).
IntoR
Derive IntoR for a single-field newtype: forward the Rust → R conversion to the inner type.
IsNA
Derive IsNA for a native newtype by forwarding to its single field.
MatchArg
Derive MatchArg: enables conversion between Rust enums and R character strings with match.arg semantics (partial matching, informative errors).
PreferExternalPtr
Derive PreferExternalPtr: return a type with a hand-written TypedExternal implementation as an R external pointer. #[derive(ExternalPtr)] already supplies IntoR; adding this derive to it creates conflicting implementations.
PreferList
Derive PreferList: emits an IntoR impl selecting list as the type’s default Rust→R conversion (via IntoList::into_list).
PreferRNativeType
Derive PreferRNativeType: when a newtype wraps an RNativeType and also implements other conversions, this selects the native R vector conversion as the default IntoR path.
RCondition
#[derive(RCondition)]: RConditionData generated from a type’s shape (#[condition(class = "…")], #[condition(message = "…")], the rename / skip / debug field options) and From<T> for RCondition with the declared kind (#[condition(kind = …)], default error). Derive an R condition type for a struct or enum: RConditionData (the R class vector, the message and the data fields handlers read as e$<name>) and From<Self> for miniextendr_api::RCondition.
RFactor
Derive RFactor: enables conversion between Rust enums and R factors.
RNativeType
Derive macro for implementing RNativeType on a newtype wrapper.
TryFromList
Derive TryFromList for a struct (R list → Rust).
TryFromSexp
Derive TryFromSexp for a single-field newtype: forward the R → Rust conversion to the inner type.