Skip to main content

miniextendr_api/
rvalue.rs

1//! `RValue` — an owned, `Send`, R-native value tree.
2//!
3//! The `serde_json::Value` analogue for R's base data types: an owned (no live
4//! `SEXP`), inspectable (`Debug + Clone`), `Send` (a `panic_any` payload can
5//! carry it) representation of "an arbitrary R native value". Use it wherever
6//! you need to carry a dynamic/heterogeneous R value through Rust — e.g.
7//! condition `data =` payloads, which travel through `panic_any` before any R
8//! object exists.
9//!
10//! Tuples with 1–12 fields convert into unnamed [`RValue::List`] entries,
11//! recursively using each field's `Into<RValue>` implementation. This lets
12//! condition data carry a tuple without allocating in R or requiring `Debug`.
13//!
14//! The variants enumerate R's (finite, closed) data type system — vectors only,
15//! since R has no true scalars. NA is modelled with `Option` where R carries it
16//! out of band (logical/integer/character); `Double` carries NA in the `NA_REAL`
17//! bit pattern inside `Vec<f64>` (no `Option`), matching R's in-band convention.
18//!
19//! Out of scope (existing homes): closures/environments/symbols/language objects
20//! (not data), S4 objects, `EXTPTRSXP` (use [`crate::externalptr::ExternalPtr`]),
21//! ALTREP internals. Attribute-carrying values (factor, `Date`, `POSIXct`) are
22//! modelled as their plain `Integer`/`Double` storage in v1 — richer handling is
23//! deferred until a consumer needs it.
24
25use crate::SexpExt;
26use crate::from_r::{SexpError, SexpLengthError, SexpNaError, SexpTypeError, TryFromSexp};
27use crate::into_r::IntoR;
28use crate::sexp_types::{Rcomplex, SEXPTYPE};
29use crate::{IsNA, SEXP};
30
31/// An owned, `Send`, R-native value tree. See the [module docs](self).
32#[derive(#[automatically_derived]impl ::core::fmt::Debug for RValue {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            Self::Null => ::core::fmt::Formatter::write_str(f, "Null"),
            Self::Logical(__self_0) =>
                ::core::fmt::Formatter::debug_struct_field1_finish(f,
                    "Logical", &__self_0),
            Self::Integer(__self_0) =>
                ::core::fmt::Formatter::debug_struct_field1_finish(f,
                    "Integer", &__self_0),
            Self::Double(__self_0) =>
                ::core::fmt::Formatter::debug_struct_field1_finish(f,
                    "Double", &__self_0),
            Self::Complex(__self_0) =>
                ::core::fmt::Formatter::debug_struct_field1_finish(f,
                    "Complex", &__self_0),
            Self::Character(__self_0) =>
                ::core::fmt::Formatter::debug_struct_field1_finish(f,
                    "Character", &__self_0),
            Self::Raw(__self_0) =>
                ::core::fmt::Formatter::debug_struct_field1_finish(f, "Raw",
                    &__self_0),
            Self::List(__self_0) =>
                ::core::fmt::Formatter::debug_struct_field1_finish(f, "List",
                    &__self_0),
        }
    }
}Debug, #[automatically_derived]impl ::core::clone::Clone for RValue {
    #[inline]
    fn clone(&self) -> Self {
        match self {
            Self::Null => RValue::Null,
            Self::Logical(__self_0) =>
                RValue::Logical(::core::clone::Clone::clone(__self_0)),
            Self::Integer(__self_0) =>
                RValue::Integer(::core::clone::Clone::clone(__self_0)),
            Self::Double(__self_0) =>
                RValue::Double(::core::clone::Clone::clone(__self_0)),
            Self::Complex(__self_0) =>
                RValue::Complex(::core::clone::Clone::clone(__self_0)),
            Self::Character(__self_0) =>
                RValue::Character(::core::clone::Clone::clone(__self_0)),
            Self::Raw(__self_0) =>
                RValue::Raw(::core::clone::Clone::clone(__self_0)),
            Self::List(__self_0) =>
                RValue::List(::core::clone::Clone::clone(__self_0)),
        }
    }
}Clone)]
33pub enum RValue {
34    /// `NULL` (`NILSXP`).
35    Null,
36    /// Logical vector (`LGLSXP`). `None` is `NA`.
37    Logical(Vec<Option<bool>>),
38    /// Integer vector (`INTSXP`). `None` is `NA`.
39    Integer(Vec<Option<i32>>),
40    /// Double vector (`REALSXP`). NA is carried in the `NA_REAL` bit pattern.
41    Double(Vec<f64>),
42    /// Complex vector (`CPLXSXP`).
43    Complex(Vec<Rcomplex>),
44    /// Character vector (`STRSXP`). `None` is `NA`.
45    Character(Vec<Option<String>>),
46    /// Raw byte vector (`RAWSXP`). No NA.
47    Raw(Vec<u8>),
48    /// Generic list (`VECSXP`). Recursive; a `None` name is an unnamed slot.
49    List(Vec<(Option<String>, RValue)>),
50}
51
52// region: IntoR
53
54impl IntoR for RValue {
55    type Error = std::convert::Infallible;
56
57    fn try_into_sexp(self) -> Result<SEXP, Self::Error> {
58        Ok(self.into_sexp())
59    }
60
61    unsafe fn try_into_sexp_unchecked(self) -> Result<SEXP, Self::Error> {
62        self.try_into_sexp()
63    }
64
65    fn into_sexp(self) -> SEXP {
66        match self {
67            RValue::Null => SEXP::nil(),
68            RValue::Logical(v) => v.into_sexp(),
69            RValue::Integer(v) => v.into_sexp(),
70            RValue::Double(v) => v.into_sexp(),
71            RValue::Complex(v) => v.into_sexp(),
72            RValue::Character(v) => v.into_sexp(),
73            RValue::Raw(v) => v.into_sexp(),
74            RValue::List(pairs) => list_into_sexp(pairs),
75        }
76    }
77}
78
79/// Build a `VECSXP` from list pairs, recursing into each child.
80///
81/// Each child `SEXP` is `protect_raw`-rooted before the next child allocates —
82/// the same GC discipline as `AsNamedList::into_sexp` (#1030/#1045), required
83/// under `gctorture`. The scope drops once the list is built.
84fn list_into_sexp(pairs: Vec<(Option<String>, RValue)>) -> SEXP {
85    use crate::list::List;
86    // SAFETY: `IntoR::into_sexp` for `#[miniextendr]` return values runs on the R
87    // main thread.
88    unsafe {
89        let scope = crate::gc_protect::ProtectScope::new();
90        if pairs.iter().any(|(name, _)| name.is_some()) {
91            // Named (R fills unnamed slots with ""). `from_raw_pairs` sets names.
92            let named: Vec<(String, SEXP)> = pairs
93                .into_iter()
94                .map(|(name, val)| (name.unwrap_or_default(), scope.protect_raw(val.into_sexp())))
95                .collect();
96            List::from_raw_pairs(named).into_sexp()
97        } else {
98            let values: Vec<SEXP> = pairs
99                .into_iter()
100                .map(|(_, val)| scope.protect_raw(val.into_sexp()))
101                .collect();
102            List::from_raw_values(values).into_sexp()
103        }
104    }
105}
106
107// endregion
108
109// region: TryFromSexp
110
111impl TryFromSexp for RValue {
112    type Error = SexpError;
113
114    fn try_from_sexp(sexp: SEXP) -> Result<Self, Self::Error> {
115        let n = sexp.len();
116        match sexp.type_of() {
117            SEXPTYPE::NILSXP => Ok(RValue::Null),
118            SEXPTYPE::LGLSXP => Ok(RValue::Logical(
119                (0..n as isize)
120                    .map(|i| {
121                        let x = sexp.logical_elt(i);
122                        (!x.is_na()).then_some(x != 0)
123                    })
124                    .collect(),
125            )),
126            SEXPTYPE::INTSXP => Ok(RValue::Integer(
127                (0..n as isize)
128                    .map(|i| {
129                        let x = sexp.integer_elt(i);
130                        (!x.is_na()).then_some(x)
131                    })
132                    .collect(),
133            )),
134            // NA stays in the bit pattern — no Option needed (decision 2).
135            SEXPTYPE::REALSXP => Ok(RValue::Double(
136                (0..n as isize).map(|i| sexp.real_elt(i)).collect(),
137            )),
138            SEXPTYPE::CPLXSXP => Ok(RValue::Complex(
139                (0..n as isize).map(|i| sexp.complex_elt(i)).collect(),
140            )),
141            // An element that is not text (marked as bytes) is refused; all
142            // of them in one error.
143            SEXPTYPE::STRSXP => crate::from_r::map_strsxp_with(sexp, |charsxp, _| {
144                if charsxp.is_na_string() {
145                    Ok(None)
146                } else {
147                    // SAFETY: a non-NA CHARSXP element of `sexp`.
148                    unsafe { crate::from_r::try_charsxp_to_str(charsxp) }
149                        .map(|s| Some(s.to_string()))
150                }
151            })
152            .map(RValue::Character),
153            // SAFETY: type checked to be RAWSXP; `as_slice` handles the empty (0x1) case.
154            SEXPTYPE::RAWSXP => Ok(RValue::Raw(unsafe { sexp.as_slice::<u8>() }.to_vec())),
155            SEXPTYPE::VECSXP => {
156                let names = sexp.get_names();
157                let mut pairs = Vec::with_capacity(n);
158                for i in 0..n as isize {
159                    // `||` short-circuits, so `string_elt` is only reached for a
160                    // character names vector. NA / empty names are unnamed slots.
161                    let name = if names.is_nil()
162                        || !names.is_character()
163                        || names.string_elt(i).is_na_string()
164                    {
165                        None
166                    } else {
167                        // SAFETY: a non-NA CHARSXP element of the names.
168                        let name =
169                            unsafe { crate::from_r::try_charsxp_to_str(names.string_elt(i)) }
170                                .map_err(|e| {
171                                    crate::from_r::name_refusal(
172                                        usize::try_from(i).expect("a list index is non-negative"),
173                                        &e,
174                                    )
175                                })?;
176                        (!name.is_empty()).then(|| name.to_string())
177                    };
178                    pairs.push((name, RValue::try_from_sexp(sexp.vector_elt(i))?));
179                }
180                Ok(RValue::List(pairs))
181            }
182            other => Err(SexpError::InvalidValue(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("RValue cannot represent SEXP of type {0:?} (only R data vectors are modelled)",
                other))
    })format!(
183                "RValue cannot represent SEXP of type {other:?} (only R data vectors are modelled)"
184            ))),
185        }
186    }
187}
188
189// endregion
190
191// region: ergonomic From impls (scalars wrap to length-1 vectors, per R semantics)
192
193impl From<i32> for RValue {
194    fn from(v: i32) -> Self {
195        RValue::Integer(::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [Some(v)]))vec![Some(v)])
196    }
197}
198impl From<f64> for RValue {
199    fn from(v: f64) -> Self {
200        RValue::Double(::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [v]))vec![v])
201    }
202}
203impl From<bool> for RValue {
204    fn from(v: bool) -> Self {
205        RValue::Logical(::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [Some(v)]))vec![Some(v)])
206    }
207}
208impl From<String> for RValue {
209    fn from(v: String) -> Self {
210        RValue::Character(::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [Some(v)]))vec![Some(v)])
211    }
212}
213impl From<&str> for RValue {
214    fn from(v: &str) -> Self {
215        RValue::Character(::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [Some(v.to_string())]))vec![Some(v.to_string())])
216    }
217}
218impl From<Vec<i32>> for RValue {
219    fn from(v: Vec<i32>) -> Self {
220        RValue::Integer(v.into_iter().map(Some).collect())
221    }
222}
223impl From<Vec<f64>> for RValue {
224    fn from(v: Vec<f64>) -> Self {
225        RValue::Double(v)
226    }
227}
228impl From<Vec<bool>> for RValue {
229    fn from(v: Vec<bool>) -> Self {
230        RValue::Logical(v.into_iter().map(Some).collect())
231    }
232}
233impl From<Vec<String>> for RValue {
234    fn from(v: Vec<String>) -> Self {
235        RValue::Character(v.into_iter().map(Some).collect())
236    }
237}
238impl From<Vec<&str>> for RValue {
239    fn from(v: Vec<&str>) -> Self {
240        RValue::Character(v.into_iter().map(|s| Some(s.to_string())).collect())
241    }
242}
243
244// endregion
245
246// region: Tuples (owned positional lists, no R allocation)
247
248macro_rules! impl_tuple_rvalue {
249    ($n:literal, $name:literal; $($T:ident $R:ident $idx:tt),+) => {
250        impl<$($T: Into<RValue>),+> From<($($T,)+)> for RValue {
251            fn from(value: ($($T,)+)) -> Self {
252                Self::List(vec![$((None, value.$idx.into()),)+])
253            }
254        }
255    };
256}
257
258impl<A: Into<RValue>, B: Into<RValue>, C: Into<RValue>, D: Into<RValue>,
    E: Into<RValue>, F: Into<RValue>, G: Into<RValue>, H: Into<RValue>,
    I: Into<RValue>, J: Into<RValue>, K: Into<RValue>, L: Into<RValue>>
    From<(A, B, C, D, E, F, G, H, I, J, K, L)> for RValue {
    fn from(value: (A, B, C, D, E, F, G, H, I, J, K, L)) -> Self {
        Self::List(::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
                    [(None, value.0.into()), (None, value.1.into()),
                            (None, value.2.into()), (None, value.3.into()),
                            (None, value.4.into()), (None, value.5.into()),
                            (None, value.6.into()), (None, value.7.into()),
                            (None, value.8.into()), (None, value.9.into()),
                            (None, value.10.into()), (None, value.11.into())])))
    }
}crate::tuple_macros::for_each_tuple!(impl_tuple_rvalue);
259
260// endregion
261
262// region: NA-aware Option / Vec<Option> + wide-integer ladder (ported from #1044/#995)
263
264// `Option<T>` → length-1 vector, `None` → `NA`. Integer/logical/character carry
265// NA out of band via the `None` slot; `Double` carries it in the `NA_REAL` bit
266// pattern (no `Option<f64>` variant — see the module docs).
267
268impl From<Option<i32>> for RValue {
269    fn from(v: Option<i32>) -> Self {
270        RValue::Integer(::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [v]))vec![v])
271    }
272}
273impl From<Option<f64>> for RValue {
274    fn from(v: Option<f64>) -> Self {
275        RValue::Double(::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [v.unwrap_or(crate::altrep_traits::NA_REAL)]))vec![v.unwrap_or(crate::altrep_traits::NA_REAL)])
276    }
277}
278impl From<Option<bool>> for RValue {
279    fn from(v: Option<bool>) -> Self {
280        RValue::Logical(::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [v]))vec![v])
281    }
282}
283impl From<Option<String>> for RValue {
284    fn from(v: Option<String>) -> Self {
285        RValue::Character(::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [v]))vec![v])
286    }
287}
288impl From<Option<&str>> for RValue {
289    fn from(v: Option<&str>) -> Self {
290        RValue::Character(::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [v.map(str::to_string)]))vec![v.map(str::to_string)])
291    }
292}
293impl From<Vec<Option<i32>>> for RValue {
294    fn from(v: Vec<Option<i32>>) -> Self {
295        RValue::Integer(v)
296    }
297}
298impl From<Vec<Option<f64>>> for RValue {
299    fn from(v: Vec<Option<f64>>) -> Self {
300        RValue::Double(
301            v.into_iter()
302                .map(|x| x.unwrap_or(crate::altrep_traits::NA_REAL))
303                .collect(),
304        )
305    }
306}
307impl From<Vec<Option<bool>>> for RValue {
308    fn from(v: Vec<Option<bool>>) -> Self {
309        RValue::Logical(v)
310    }
311}
312impl From<Vec<Option<String>>> for RValue {
313    fn from(v: Vec<Option<String>>) -> Self {
314        RValue::Character(v)
315    }
316}
317impl From<Vec<Option<&str>>> for RValue {
318    fn from(v: Vec<Option<&str>>) -> Self {
319        RValue::Character(v.into_iter().map(|s| s.map(str::to_string)).collect())
320    }
321}
322
323/// Wide-integer ladder: an `i64` (or `u32`) that fits in `i32` **and** is not
324/// `i32::MIN` (R's `NA_integer_`) becomes an `Integer`; anything else becomes a
325/// `Double`. Mirrors R's own integer→double promotion for out-of-range values.
326impl From<i64> for RValue {
327    fn from(v: i64) -> Self {
328        match i32::try_from(v) {
329            Ok(n) if !n.is_na() => RValue::Integer(::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [Some(n)]))vec![Some(n)]),
330            // Out of `i32` range (or exactly `NA_integer_`) — promote to double.
331            // `i64 → f64` is lossy past 2^53, matching R's own integer overflow.
332            _ => RValue::Double(::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [v as f64]))vec![v as f64]),
333        }
334    }
335}
336impl From<u32> for RValue {
337    /// Lossless widening to `i64`, then the shared ladder. A `u32` is never
338    /// `i32::MIN` as an `i32`, so only the `> i32::MAX` case falls to `Double`.
339    fn from(v: u32) -> Self {
340        RValue::from(i64::from(v))
341    }
342}
343
344// endregion
345
346// region: inspection accessors + owned extraction (#1050 decision 4, on demand)
347
348impl RValue {
349    /// The `SEXPTYPE` this value materialises to via [`IntoR`].
350    pub fn sexptype(&self) -> SEXPTYPE {
351        match self {
352            RValue::Null => SEXPTYPE::NILSXP,
353            RValue::Logical(_) => SEXPTYPE::LGLSXP,
354            RValue::Integer(_) => SEXPTYPE::INTSXP,
355            RValue::Double(_) => SEXPTYPE::REALSXP,
356            RValue::Complex(_) => SEXPTYPE::CPLXSXP,
357            RValue::Character(_) => SEXPTYPE::STRSXP,
358            RValue::Raw(_) => SEXPTYPE::RAWSXP,
359            RValue::List(_) => SEXPTYPE::VECSXP,
360        }
361    }
362
363    /// `true` if this is [`RValue::Null`].
364    pub fn is_null(&self) -> bool {
365        #[allow(non_exhaustive_omitted_patterns)] match self {
    RValue::Null => true,
    _ => false,
}matches!(self, RValue::Null)
366    }
367
368    /// Wrap any `T: Debug` as a length-1 `Character` carrying its `{:?}`
369    /// rendering — the escape hatch for a value with no R-native mapping
370    /// (e.g. a Rust range). The rendering happens eagerly here, so nothing
371    /// borrows across the `Send` boundary a condition payload crosses.
372    ///
373    /// ```ignore
374    /// # use miniextendr_api::RValue;
375    /// assert_eq!(RValue::debug(0..=100).as_str(), Some("0..=100"));
376    /// ```
377    pub fn debug<T: std::fmt::Debug>(value: T) -> Self {
378        RValue::Character(::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [Some(::alloc::__export::must_use({
                            ::alloc::fmt::format(format_args!("{0:?}", value))
                        }))]))vec![Some(format!("{value:?}"))])
379    }
380
381    /// The single non-NA `i32` of a length-1 `Integer`, else `None`.
382    ///
383    /// Returns `None` for the wrong variant, a length other than 1, or NA —
384    /// the borrow-friendly counterpart to `i32::try_from` when you don't need
385    /// to know *why* it failed.
386    pub fn as_i32(&self) -> Option<i32> {
387        match self {
388            RValue::Integer(v) if v.len() == 1 => v[0],
389            _ => None,
390        }
391    }
392
393    /// The single non-NA `f64` of a length-1 `Double`, else `None`.
394    ///
395    /// R's NA yields `None`, matching [`as_i32`](Self::as_i32). NA is decided by
396    /// R's `R_IsNA` rule, so a computed NA (`NA_real_ * 1`) counts; any other NaN
397    /// is returned as a value.
398    pub fn as_f64(&self) -> Option<f64> {
399        match self {
400            RValue::Double(v) if v.len() == 1 => {
401                let x = v[0];
402                (!x.is_na()).then_some(x)
403            }
404            _ => None,
405        }
406    }
407
408    /// The single non-NA `bool` of a length-1 `Logical`, else `None`.
409    pub fn as_bool(&self) -> Option<bool> {
410        match self {
411            RValue::Logical(v) if v.len() == 1 => v[0],
412            _ => None,
413        }
414    }
415
416    /// The single non-NA string of a length-1 `Character`, else `None`.
417    pub fn as_str(&self) -> Option<&str> {
418        match self {
419            RValue::Character(v) if v.len() == 1 => v[0].as_deref(),
420            _ => None,
421        }
422    }
423}
424
425/// `Type` error for a variant mismatch: the value's `SEXPTYPE` vs the expected one.
426fn wrong_type(expected: SEXPTYPE, actual: &RValue) -> SexpError {
427    SexpError::Type(SexpTypeError {
428        expected,
429        actual: actual.sexptype(),
430    })
431}
432
433/// `TryFrom<RValue>` for a scalar pulled from a length-1 Option-backed variant.
434///
435/// Fails with `Length` for a non-scalar, `Na` for NA, `Type` for the wrong
436/// variant — the failure modes a numeric `CoerceError` can't express, which is
437/// why this is `TryFrom`/`SexpError` rather than a `coerce.rs` impl.
438macro_rules! try_from_scalar_opt {
439    ($t:ty, $variant:ident, $ty:expr) => {
440        impl TryFrom<RValue> for $t {
441            type Error = SexpError;
442            fn try_from(value: RValue) -> Result<Self, SexpError> {
443                match value {
444                    RValue::$variant(xs) => {
445                        if xs.len() != 1 {
446                            return Err(SexpError::Length(SexpLengthError {
447                                expected: 1,
448                                actual: xs.len(),
449                            }));
450                        }
451                        xs.into_iter()
452                            .next()
453                            .unwrap()
454                            .ok_or(SexpError::Na(SexpNaError { sexp_type: $ty }))
455                    }
456                    other => Err(wrong_type($ty, &other)),
457                }
458            }
459        }
460    };
461}
462impl TryFrom<RValue> for i32 {
    type Error = SexpError;
    fn try_from(value: RValue) -> Result<Self, SexpError> {
        match value {
            RValue::Integer(xs) => {
                if xs.len() != 1 {
                    return Err(SexpError::Length(SexpLengthError {
                                    expected: 1,
                                    actual: xs.len(),
                                }));
                }
                xs.into_iter().next().unwrap().ok_or(SexpError::Na(SexpNaError {
                            sexp_type: SEXPTYPE::INTSXP,
                        }))
            }
            other => Err(wrong_type(SEXPTYPE::INTSXP, &other)),
        }
    }
}try_from_scalar_opt!(i32, Integer, SEXPTYPE::INTSXP);
463impl TryFrom<RValue> for bool {
    type Error = SexpError;
    fn try_from(value: RValue) -> Result<Self, SexpError> {
        match value {
            RValue::Logical(xs) => {
                if xs.len() != 1 {
                    return Err(SexpError::Length(SexpLengthError {
                                    expected: 1,
                                    actual: xs.len(),
                                }));
                }
                xs.into_iter().next().unwrap().ok_or(SexpError::Na(SexpNaError {
                            sexp_type: SEXPTYPE::LGLSXP,
                        }))
            }
            other => Err(wrong_type(SEXPTYPE::LGLSXP, &other)),
        }
    }
}try_from_scalar_opt!(bool, Logical, SEXPTYPE::LGLSXP);
464impl TryFrom<RValue> for String {
    type Error = SexpError;
    fn try_from(value: RValue) -> Result<Self, SexpError> {
        match value {
            RValue::Character(xs) => {
                if xs.len() != 1 {
                    return Err(SexpError::Length(SexpLengthError {
                                    expected: 1,
                                    actual: xs.len(),
                                }));
                }
                xs.into_iter().next().unwrap().ok_or(SexpError::Na(SexpNaError {
                            sexp_type: SEXPTYPE::STRSXP,
                        }))
            }
            other => Err(wrong_type(SEXPTYPE::STRSXP, &other)),
        }
    }
}try_from_scalar_opt!(String, Character, SEXPTYPE::STRSXP);
465
466// `Double` carries NA in the bit pattern, so it can't reuse the Option macro.
467impl TryFrom<RValue> for f64 {
468    type Error = SexpError;
469    fn try_from(value: RValue) -> Result<Self, SexpError> {
470        match value {
471            RValue::Double(xs) => {
472                if xs.len() != 1 {
473                    return Err(SexpError::Length(SexpLengthError {
474                        expected: 1,
475                        actual: xs.len(),
476                    }));
477                }
478                let x = xs[0];
479                // `R_IsNA`: a computed NA is an NA error too; other NaNs pass.
480                if x.is_na() {
481                    Err(SexpError::Na(SexpNaError {
482                        sexp_type: SEXPTYPE::REALSXP,
483                    }))
484                } else {
485                    Ok(x)
486                }
487            }
488            other => Err(wrong_type(SEXPTYPE::REALSXP, &other)),
489        }
490    }
491}
492
493/// `TryFrom<RValue>` for the whole vector of a single variant (NA preserved).
494macro_rules! try_from_vec {
495    ($t:ty, $variant:ident, $ty:expr) => {
496        impl TryFrom<RValue> for $t {
497            type Error = SexpError;
498            fn try_from(value: RValue) -> Result<Self, SexpError> {
499                match value {
500                    RValue::$variant(xs) => Ok(xs),
501                    other => Err(wrong_type($ty, &other)),
502                }
503            }
504        }
505    };
506}
507impl TryFrom<RValue> for Vec<Option<bool>> {
    type Error = SexpError;
    fn try_from(value: RValue) -> Result<Self, SexpError> {
        match value {
            RValue::Logical(xs) => Ok(xs),
            other => Err(wrong_type(SEXPTYPE::LGLSXP, &other)),
        }
    }
}try_from_vec!(Vec<Option<bool>>, Logical, SEXPTYPE::LGLSXP);
508impl TryFrom<RValue> for Vec<Option<i32>> {
    type Error = SexpError;
    fn try_from(value: RValue) -> Result<Self, SexpError> {
        match value {
            RValue::Integer(xs) => Ok(xs),
            other => Err(wrong_type(SEXPTYPE::INTSXP, &other)),
        }
    }
}try_from_vec!(Vec<Option<i32>>, Integer, SEXPTYPE::INTSXP);
509impl TryFrom<RValue> for Vec<f64> {
    type Error = SexpError;
    fn try_from(value: RValue) -> Result<Self, SexpError> {
        match value {
            RValue::Double(xs) => Ok(xs),
            other => Err(wrong_type(SEXPTYPE::REALSXP, &other)),
        }
    }
}try_from_vec!(Vec<f64>, Double, SEXPTYPE::REALSXP);
510impl TryFrom<RValue> for Vec<Rcomplex> {
    type Error = SexpError;
    fn try_from(value: RValue) -> Result<Self, SexpError> {
        match value {
            RValue::Complex(xs) => Ok(xs),
            other => Err(wrong_type(SEXPTYPE::CPLXSXP, &other)),
        }
    }
}try_from_vec!(Vec<Rcomplex>, Complex, SEXPTYPE::CPLXSXP);
511impl TryFrom<RValue> for Vec<Option<String>> {
    type Error = SexpError;
    fn try_from(value: RValue) -> Result<Self, SexpError> {
        match value {
            RValue::Character(xs) => Ok(xs),
            other => Err(wrong_type(SEXPTYPE::STRSXP, &other)),
        }
    }
}try_from_vec!(Vec<Option<String>>, Character, SEXPTYPE::STRSXP);
512impl TryFrom<RValue> for Vec<u8> {
    type Error = SexpError;
    fn try_from(value: RValue) -> Result<Self, SexpError> {
        match value {
            RValue::Raw(xs) => Ok(xs),
            other => Err(wrong_type(SEXPTYPE::RAWSXP, &other)),
        }
    }
}try_from_vec!(Vec<u8>, Raw, SEXPTYPE::RAWSXP);
513impl TryFrom<RValue> for Vec<(Option<String>, RValue)> {
    type Error = SexpError;
    fn try_from(value: RValue) -> Result<Self, SexpError> {
        match value {
            RValue::List(xs) => Ok(xs),
            other => Err(wrong_type(SEXPTYPE::VECSXP, &other)),
        }
    }
}try_from_vec!(Vec<(Option<String>, RValue)>, List, SEXPTYPE::VECSXP);
514
515// endregion
516
517#[cfg(test)]
518mod tests;