Expand description
Conversions from R SEXP to Rust types.
This module provides TryFromSexp implementations for converting R values to Rust types:
| R Type | Rust Type | Access Method |
|---|---|---|
| INTSXP | i32, &[i32] | INTEGER() / DATAPTR_RO |
| REALSXP | f64, &[f64] | REAL() / DATAPTR_RO |
| LGLSXP | RLogical, &[RLogical] | LOGICAL() / DATAPTR_RO |
| RAWSXP | u8, &[u8] | RAW() / DATAPTR_RO |
| CPLXSXP | Rcomplex | COMPLEX() / DATAPTR_RO |
| STRSXP | &str, String | STRING_ELT() + encoding-aware UTF-8 extraction |
§Submodules
| Module | Contents |
|---|---|
logical | Rboolean.string_elt(bool, Option<bool> |
coerced_scalars | Multi-source numeric scalars (i8..usize) + large integers (i64, u64) |
references | Borrowed views: &T, &mut T, &[T], Vec<&T> |
strings | &str, String, char from STRSXP |
na_vectors | Vec<Option<T>>, Box<[Option<T>]> with NA awareness |
collections | HashMap, BTreeMap, HashSet, BTreeSet |
cow_and_paths | Cow<[T]>, PathBuf, OsString, string sets |
§Choosing the right inbound conversion
TryFromSexp is the strict inbound path: it returns Result<T, SexpError>
and rejects mismatched SEXPTYPEs outright (no silent coercion). When you
need to accept arguments coming from multiple R native types, reach for
the crate::coerce::Coerce / crate::coerce::TryCoerce traits instead
— those are the looser inbound path and the entry point for the multi-source
scalars handled in coerced_scalars.
The strict-vs-lax pairing for outbound conversion lives on
crate::into_r::IntoR (lax, default) vs crate::strict (#[miniextendr(strict)]).
There is intentionally no TryFromSexpStrict trait — inbound is already
strict-by-default because it returns Result.
§Thread Safety
The trait provides two methods:
TryFromSexp::try_from_sexp- checked version with debug thread assertionsTryFromSexp::try_from_sexp_unchecked- unchecked version for performance-critical paths
Use try_from_sexp_unchecked when you’re certain you’re on the main thread:
- Inside ALTREP callbacks
- Inside standalone
#[miniextendr]functions (they run on the main thread) - Inside
extern "C-unwind"functions called directly by R
Re-exports§
use std::collections::BTreeMap;🔒use std::collections::BTreeSet;🔒use std::collections::HashMap;🔒use std::collections::HashSet;🔒use crate::altrep_traits::NA_REAL;🔒use crate::coerce::TryCoerce;🔒use crate::IsNA;🔒use crate::IsNA;🔒use crate::RLogical;🔒use crate::SEXP;🔒use crate::SEXPTYPE;🔒use crate::SexpExt;🔒pub use borrow::NativeBorrow;pub(crate) use coerced_scalars::coerce_real_value;🔒pub(crate) use coerced_scalars::coerce_value;🔒pub use str_parse::ParseRStr;pub use str_parse::ParsedRStr;use std::collections::VecDeque;🔒use std::collections::BinaryHeap;🔒pub use rooted::TryFromRoot;use crate::coerce::Coerced;🔒use crate::externalptr::ExternalPtr;🔒use crate::externalptr::TypeMismatchError;🔒use crate::externalptr::TypedExternal;🔒pub(crate) use impl_option_try_from_sexp;🔒pub(crate) use impl_vec_try_from_sexp_list;🔒pub(crate) use impl_vec_option_try_from_sexp_list;🔒
Modules§
- borrow
- Native vector borrow metadata and pre-conversion alias checks.
- coerced_
scalars 🔒 - Coerced scalar conversions (multi-source numeric) and large integer scalars.
- collections 🔒
- Collection conversions (HashMap, BTreeMap, HashSet, BTreeSet).
- cow_
and_ 🔒paths - Cow, PathBuf, OsString, and string collection conversions.
- logical 🔒
- Logical type conversions (Rboolean, bool, Option variants).
- na_
vectors 🔒 - NA-aware vector conversions (
Vec<Option<T>>,Box<[Option<T>]>). - prepared 👻
- Preparing an argument whose native borrow depends on the arm its conversion takes (#1504).
- references 🔒
- Reference conversions (borrowed views into R vectors).
- rooted 🔒
- Conversions whose borrowed result cannot outlive an R root.
- str_
parse 🔒 - Conversions for types parsed from an R string:
ParseRStr,ParsedRStrandtry_from_sexp_via_str_parse!. - strings 🔒
- String conversions — STRSXP requires special handling via
STRING_ELT. - tuples 🔒
- Tuple conversions: read an R list (VECSXP) positionally into
(A, B, ...).
Macros§
- impl_
option_ 🔒map_ try_ from_ sexp - impl_
option_ 🔒set_ try_ from_ sexp - impl_
option_ 🔒try_ from_ sexp - Implement
TryFromSexp for Option<T>where T already implements TryFromSexp. - impl_
set_ 🔒try_ from_ sexp_ bool - impl_
set_ 🔒try_ from_ sexp_ numeric - impl_
try_ 🔒from_ sexp_ scalar_ native - impl_
vec_ 🔒option_ try_ from_ sexp_ list - Implement
TryFromSexp for Vec<Option<T>>from R list (VECSXP). - impl_
vec_ 🔒try_ from_ sexp_ list - Implement
TryFromSexp for Vec<T>from R list (VECSXP). - impl_
vec_ 🔒try_ from_ sexp_ numeric - Implement
TryFromSexp for Vec<$target>by coercing from integer/real/logical/raw.
Structs§
- Batched
Errors 🔒 - Bounded accumulator that folds per-element conversion failures into one
batched
SexpError::InvalidValue, with the elements numbered as R counts them (1-based). - Element
Errors 🔒 - The failures of a list read element by element (
map_vecsxp_batched), folded into one error that keeps the classes and fields of the check refusals among them. - Sexp
Class Error - Error describing a value that is not the kind of R object a conversion
reads, where that kind is a class rather than a
SEXPTYPE(a data frame is a list with a class). - Sexp
Length Error - Error describing an unexpected R object length.
- Sexp
NaError - Error for NA values in conversions that require non-missing values.
- Sexp
Type Error - Error describing an unexpected R
SEXPTYPE.
Enums§
- Sexp
Error - Unified conversion error when decoding an R
SEXP. - Utf8
Text 🔒 - Where a CHARSXP’s UTF-8 text lives.
Constants§
- BATCHED_
ERROR_ 🔒CAP - Cap on the number of per-element failures listed in a batched vector
conversion error; the remainder is summarized as
"and N more". - BYTES_
REASON 🔒 - Why a string marked with R’s
bytesencoding is refused: its bytes are not text in any encoding, so it has no Ruststr. Worded as the reason of an argument error ('x' must be a single string: marked as bytes, not text), and of each element of a batched one (marked as bytes, not text (elements 2, 4)). - INVALID_
UTF8_ 🔒REASON - Why a string whose own bytes are not valid UTF-8 is refused: a UTF-8 string, or a native one R reads without translation (any native string in a UTF-8 session).
Traits§
- TryFrom
Sexp - TryFrom-style trait for converting SEXP to Rust types.
Functions§
- __
mx_ 👻any_ na any_nafor generated code: the C wrapper’s check of aNonNa<T>argument before its conversion, which also covers a.Call()that skips the R wrapper’s!anyNA()guard.- __
mx_ 👻external_ arg - The handle a generated wrapper borrows for a
&T/&mut T/ExternalPtrRef/ExternalPtrMutargument: converted like anExternalPtr<T>argument. A free function, so the generated::<T>is spanned onTand aTthat isn’tTypedExternalgets one error. - __
mx_ 👻optional_ external_ arg __mx_external_argfor anOptionargument:NULLisNone.- any_na 🔒
- Whether R’s
anyNA(sexp)isTRUE: the checkno_na’s R guard makes, done in Rust on an argument that the guard does not cover (seeTryFromSexp::__mx_input_has_na). - bytes_
refusal 🔒 - The error for a string marked as bytes (
BYTES_REASON). - charsxp_
to_ 🔒 ⚠borrowed_ str_ or_ panic - Borrow directly from a CHARSXP whose bytes are its UTF-8 text, for a caller
that has no
Resultto return. - charsxp_
to_ 🔒 ⚠cow_ lossy - Read a CHARSXP as text whatever it holds, for a read that must not fail
(a name in a message, a class attribute): as
try_charsxp_to_str, except that a string marked as bytes, or one whose bytes are not valid UTF-8, is decoded lossily (U+FFFDfor each invalid sequence) instead of refused. - charsxp_
to_ 🔒 ⚠cow_ or_ panic try_charsxp_to_cowfor a caller that has noResultto return. Panics ascharsxp_to_str_or_panicdoes.- charsxp_
to_ 🔒 ⚠str_ or_ panic try_charsxp_to_strfor a caller that has noResultto return: an accessor that returnsOption<&str>, a symbol’s print name. Panics with the refusal’s reason on a string marked as bytes or one that is not valid UTF-8; a caller that returns aResultusestry_charsxp_to_str.- charsxp_
to_ 🔒 ⚠string_ lossy - Convert CHARSXP to an owned, lossy
String. - charsxp_
utf8_ 🔒 ⚠bytes - coerce_
slice_ 🔒to_ vec - Helper to coerce a slice element-wise into a Vec.
- coerced_
option 🔒 - The
Optionform of acoercescalar:NULLreadsNone, any other input goes throughread, the type’s coerced scalar helper, and anNAthat helper refuses readsNone, as it does for the bareOption<i32>. - collect_
coerced 🔒 - Drive a per-element coercion, batching every failure into one diagnostic.
- element_
position 🔒 (element <k>)for one 0-basedindex: the position suffix of a single per-element failure, asBatchedErrorswrites it.- external_
ptr_ 🔒from_ sexp - An
ExternalPtr<T>from a bareEXTPTRSXP, or from a class handle carrying one (R6private$.ptr, S4ptrslot, S7.ptrattribute, a list or environment with.ptr; generated Env/S3 handles are already bareEXTPTRSXPs). A pointer unwrapped from a class handle is rooted for the handle’s lifetime: R code can drop the class handle’s reference while Rust holds the pointer, and the finalizer would then free the value. - from_
numeric_ 🔒vec_ with - Shared SEXP-dispatch shell for coerced numeric/logical/raw vectors.
- is_
null_ 🔒or_ plain_ na - Whether
sexpisNULLor a plainNA, R’s untyped missing value: a logical vector of length one holdingNA. Its attributes are not looked at, as the R-side checkis.null(x) || (is.logical(x) && length(x) == 1L && is.na(x))does not look at them. - is_
null_ 🔒 ⚠or_ plain_ na_ unchecked is_null_or_plain_nathrough the unchecked FFI variants, for thetry_from_sexp_uncheckedbodies.- map_
strsxp_ 🔒with - Shared SEXP-dispatch shell for the STRSXP (character vector) walk.
- map_
vecsxp_ 🔒batched - Read a list (
VECSXP) element by element withread, which gets each element’sSEXP, and report every element that fails in one error (ElementErrors), its position numbered as R counts it. Anything but aVECSXPis a type error, and no element is read. - map_
vecsxp_ 🔒with - Shared SEXP-dispatch shell for the VECSXP (list) walk.
- map_
vecsxp_ 🔒 ⚠with_ unchecked - Unchecked-FFI variant of
map_vecsxp_with— useslen_unchecked/vector_elt_uncheckedfor the type-check and walk. - name_
refusal 🔒 - The error of a name that
try_charsxp_to_strrefused, for the element at 0-basedindex:the name of element 3 is marked as bytes, not text. - native_
slice_ 🔒type - The one check of a native slice conversion:
sexphasT’s R type. Shared with its preparation, which defers the slice (#1504). - no_
element_ 👻check - The
ElementCheckthat accepts every value: what a container starts from when nothing encloses it. Not public API. - not_
a_ 🔒handle_ error - Error for an
ExternalPtr<T>argument that is neither a bareEXTPTRSXPnor a class handle wrapping one (audit A9 — class-wrapped handles likeFoo$new(...)are unwrapped automatically; this fires only when no.ptr/slot/attribute could be recovered at all). - push_
element_ 🔒positions - Append
(element 2)/(elements 2, 5)for the given 0-based indices, numbered as R counts them. The one spelling of an element position in a conversion message. - r_slice 🔒 ⚠
- Create a slice from an R data pointer, handling the zero-length case.
- r_
slice_ 🔒 ⚠mut - Mutable version of
r_sliceforfrom_raw_parts_mut. - refuse_
text 🔒 - The panic of a
*_or_panicread, with the refusal’s reason. - scalar_
charsxp 🔒 - Shared scalar-STRSXP prologue: type-check +
len == 1+string_elt(0). - scalar_
charsxp_ 🔒 ⚠unchecked - Unchecked-FFI variant of
scalar_charsxp— useslen_unchecked/string_elt_unchecked. - scalar_
rejection_ 👻reason - Why a value that
Rf_asInteger/Rf_asReal/Rf_asLogical(or a raw coercion) could not reduce to one non-NAscalar was refused, in R terms:got NULL,got length 0,got "abc"(a string that does not parse),NA is not allowed, orgot <type>for a value of another kind. - translated_
charsxp_ 🔒 ⚠to_ str - try_
charsxp_ 🔒 ⚠to_ cow try_charsxp_to_stras aCow.- try_
charsxp_ 🔒 ⚠to_ str - Read a CHARSXP as Rust text, translating it to UTF-8 when its encoding requires.
- try_
charsxp_ 🔒 ⚠to_ str_ unchecked - Unchecked version of
try_charsxp_to_str(skips R thread checks on R API calls). - try_
from_ 👻sexp_ coerced_ bool - Convert a
coerceboolean parameter from a logical or integer zero/one. Numeric parameters already have multi-sourceTryFromSexpimplementations; bool needs this extension while its ordinary conversion stays logical-only. - try_
from_ 👻sexp_ coerced_ bool_ vec - Convert a
coerceboolean vector, retaining indexed, batched diagnostics. - try_
from_ 👻sexp_ coerced_ f64 - Convert a
coercenativef64parameter. - try_
from_ 👻sexp_ coerced_ f64_ vec - Convert a
coerceVec<f64>parameter. - try_
from_ 👻sexp_ coerced_ i32 - Convert a
coercenativei32parameter. - try_
from_ 👻sexp_ coerced_ i32_ vec - Convert a
coerceVec<i32>parameter. - try_
from_ 👻sexp_ coerced_ option_ bool - Convert a
coerceOption<bool>parameter. - try_
from_ 👻sexp_ coerced_ option_ bool_ vec - Convert a
coerceVec<Option<bool>>parameter. - try_
from_ 👻sexp_ coerced_ option_ f64 - Convert a
coerceOption<f64>parameter. - try_
from_ 👻sexp_ coerced_ option_ f64_ vec - Convert a
coerceVec<Option<f64>>parameter. - try_
from_ 👻sexp_ coerced_ option_ i32 - Convert a
coerceOption<i32>parameter. - try_
from_ 👻sexp_ coerced_ option_ i32_ vec - Convert a
coerceVec<Option<i32>>parameter. - try_
from_ 🔒sexp_ numeric_ set - Convert numeric/logical/raw vectors to a set type with element-wise coercion.
- try_
from_ 🔒sexp_ numeric_ vec - Convert numeric/logical/raw vectors to
Vec<T>with element-wise coercion. - type_
mismatch_ 🔒to_ sexp_ error - Map a downcast
TypeMismatchErrorto theSexpErrorsurfaced fromExternalPtr<T>argument conversion. Shared by the checked and uncheckedTryFromSexppaths below. - utf8_
text 🔒 ⚠ - A CHARSXP’s text as UTF-8, given its encoding mark, its bytes and R’s
translateCharUTF8.
Type Aliases§
- Element
Check 👻 - An element type’s check on an R value, as the newtype containers pass it
to
TryFromSexp::__mx_try_from_sexp_with_check:T::check_sexp, with the checks of any enclosing newtypes before it. Not public API.