Skip to main content

Module from_r

Module from_r 

Source
Expand description

Conversions from R SEXP to Rust types.

This module provides TryFromSexp implementations for converting R values to Rust types:

R TypeRust TypeAccess Method
INTSXPi32, &[i32]INTEGER() / DATAPTR_RO
REALSXPf64, &[f64]REAL() / DATAPTR_RO
LGLSXPRLogical, &[RLogical]LOGICAL() / DATAPTR_RO
RAWSXPu8, &[u8]RAW() / DATAPTR_RO
CPLXSXPRcomplexCOMPLEX() / DATAPTR_RO
STRSXP&str, StringSTRING_ELT() + encoding-aware UTF-8 extraction

§Submodules

ModuleContents
logicalRboolean.string_elt(bool, Option<bool>
coerced_scalarsMulti-source numeric scalars (i8..usize) + large integers (i64, u64)
referencesBorrowed views: &T, &mut T, &[T], Vec<&T>
strings&str, String, char from STRSXP
na_vectorsVec<Option<T>>, Box<[Option<T>]> with NA awareness
collectionsHashMap, BTreeMap, HashSet, BTreeSet
cow_and_pathsCow<[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:

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, ParsedRStr and try_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§

BatchedErrors 🔒
Bounded accumulator that folds per-element conversion failures into one batched SexpError::InvalidValue, with the elements numbered as R counts them (1-based).
ElementErrors 🔒
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.
SexpClassError
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).
SexpLengthError
Error describing an unexpected R object length.
SexpNaError
Error for NA values in conversions that require non-missing values.
SexpTypeError
Error describing an unexpected R SEXPTYPE.

Enums§

SexpError
Unified conversion error when decoding an R SEXP.
Utf8Text 🔒
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 bytes encoding is refused: its bytes are not text in any encoding, so it has no Rust str. 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§

TryFromSexp
TryFrom-style trait for converting SEXP to Rust types.

Functions§

__mx_any_na 👻
any_na for generated code: the C wrapper’s check of a NonNa<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 / ExternalPtrMut argument: converted like an ExternalPtr<T> argument. A free function, so the generated ::<T> is spanned on T and a T that isn’t TypedExternal gets one error.
__mx_optional_external_arg 👻
__mx_external_arg for an Option argument: NULL is None.
any_na 🔒
Whether R’s anyNA(sexp) is TRUE: the check no_na’s R guard makes, done in Rust on an argument that the guard does not cover (see TryFromSexp::__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 Result to 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+FFFD for each invalid sequence) instead of refused.
charsxp_to_cow_or_panic 🔒 ⚠
try_charsxp_to_cow for a caller that has no Result to return. Panics as charsxp_to_str_or_panic does.
charsxp_to_str_or_panic 🔒 ⚠
try_charsxp_to_str for a caller that has no Result to return: an accessor that returns Option<&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 a Result uses try_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 Option form of a coerce scalar: NULL reads None, any other input goes through read, the type’s coerced scalar helper, and an NA that helper refuses reads None, as it does for the bare Option<i32>.
collect_coerced 🔒
Drive a per-element coercion, batching every failure into one diagnostic.
element_position 🔒
(element <k>) for one 0-based index: the position suffix of a single per-element failure, as BatchedErrors writes it.
external_ptr_from_sexp 🔒
An ExternalPtr<T> from a bare EXTPTRSXP, or from a class handle carrying one (R6 private$.ptr, S4 ptr slot, S7 .ptr attribute, a list or environment with .ptr; generated Env/S3 handles are already bare EXTPTRSXPs). 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 sexp is NULL or a plain NA, R’s untyped missing value: a logical vector of length one holding NA. Its attributes are not looked at, as the R-side check is.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_na through the unchecked FFI variants, for the try_from_sexp_unchecked bodies.
map_strsxp_with 🔒
Shared SEXP-dispatch shell for the STRSXP (character vector) walk.
map_vecsxp_batched 🔒
Read a list (VECSXP) element by element with read, which gets each element’s SEXP, and report every element that fails in one error (ElementErrors), its position numbered as R counts it. Anything but a VECSXP is 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 — uses len_unchecked / vector_elt_unchecked for the type-check and walk.
name_refusal 🔒
The error of a name that try_charsxp_to_str refused, for the element at 0-based index: the name of element 3 is marked as bytes, not text.
native_slice_type 🔒
The one check of a native slice conversion: sexp has T’s R type. Shared with its preparation, which defers the slice (#1504).
no_element_check 👻
The ElementCheck that 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 bare EXTPTRSXP nor a class handle wrapping one (audit A9 — class-wrapped handles like Foo$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_slice for from_raw_parts_mut.
refuse_text 🔒
The panic of a *_or_panic read, 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 — uses len_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-NA scalar was refused, in R terms: got NULL, got length 0, got "abc" (a string that does not parse), NA is not allowed, or got <type> for a value of another kind.
translated_charsxp_to_str 🔒 ⚠
try_charsxp_to_cow 🔒 ⚠
try_charsxp_to_str as a Cow.
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 coerce boolean parameter from a logical or integer zero/one. Numeric parameters already have multi-source TryFromSexp implementations; bool needs this extension while its ordinary conversion stays logical-only.
try_from_sexp_coerced_bool_vec 👻
Convert a coerce boolean vector, retaining indexed, batched diagnostics.
try_from_sexp_coerced_f64 👻
Convert a coerce native f64 parameter.
try_from_sexp_coerced_f64_vec 👻
Convert a coerce Vec<f64> parameter.
try_from_sexp_coerced_i32 👻
Convert a coerce native i32 parameter.
try_from_sexp_coerced_i32_vec 👻
Convert a coerce Vec<i32> parameter.
try_from_sexp_coerced_option_bool 👻
Convert a coerce Option<bool> parameter.
try_from_sexp_coerced_option_bool_vec 👻
Convert a coerce Vec<Option<bool>> parameter.
try_from_sexp_coerced_option_f64 👻
Convert a coerce Option<f64> parameter.
try_from_sexp_coerced_option_f64_vec 👻
Convert a coerce Vec<Option<f64>> parameter.
try_from_sexp_coerced_option_i32 👻
Convert a coerce Option<i32> parameter.
try_from_sexp_coerced_option_i32_vec 👻
Convert a coerce Vec<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 TypeMismatchError to the SexpError surfaced from ExternalPtr<T> argument conversion. Shared by the checked and unchecked TryFromSexp paths below.
utf8_text 🔒 ⚠
A CHARSXP’s text as UTF-8, given its encoding mark, its bytes and R’s translateCharUTF8.

Type Aliases§

ElementCheck 👻
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.