Skip to main content

Module coerce

Module coerce 

Source
Expand description

Type coercion traits for converting Rust types to R native types.

R has a fixed set of native scalar types:

  • i32 (INTSXP) - 32-bit signed integer
  • f64 (REALSXP) - 64-bit floating point
  • RLogical (LGLSXP) - logical (TRUE/FALSE/NA)
  • u8 (RAWSXP) - raw bytes
  • Rcomplex (CPLXSXP) - complex numbers

§Traits

  • Coerce<R> - infallible coercion (identity, widening)
  • TryCoerce<R> - fallible coercion (narrowing, overflow-possible)

§Where this fits

Coerce / TryCoerce is the looser inbound side — it’s the path crate::from_r::TryFromSexp impls take for multi-source scalars (i8/i16/u16/u32/f32/i64/u64/isize/usize). The strict inbound alternative is the bare TryFromSexp impl on the matching R native type (i32, f64, …), which rejects mismatched SEXPTYPEs outright. Failure mode of relying on coercion in a function that should be strict: a Rust i32 argument silently accepts 1.7 (REALSXP) and truncates.

The outbound strict-vs-lax pairing lives on crate::into_r::IntoR (lax, default) vs crate::strict (#[miniextendr(strict)] opt-in).

§Examples

use miniextendr_api::coerce::Coerce;

// Scalar coercion
let x: i32 = 42i8.coerce();

// Element-wise slice coercion
let slice: &[i8] = &[1, 2, 3];
let vec: Vec<i32> = slice.coerce();

Macros§

impl_identity 🔒
impl_nonzero_from_self 🔒
impl_try_narrow 🔒
Implement fallible narrowing TryCoerce<$target> for each $from via try_into (overflow → CoerceError::Overflow).
impl_tuple_coerce 🔒
Macro to implement element-wise Coerce for tuples.
impl_widen 🔒
Implement infallible widening Coerce<$to> for each $from => $to pair via Into.

Structs§

Coerced
Wrapper for values coerced from an R native type during conversion.

Enums§

CoerceError
Error type for coercion failures.
LogicalCoerceError
Error type for logical coercion failures.

Traits§

Coerce
Infallible coercion from Self to type R.
TryCoerce
Fallible coercion from Self to type R.