Skip to main content

miniextendr_api/
into_r.rs

1#![allow(rustdoc::private_intra_doc_links)]
2//! Conversions from Rust types to R SEXP.
3//!
4//! This module provides the [`IntoR`] trait for converting Rust values to R SEXPs.
5//!
6//! # Submodules
7//!
8//! | Module | Contents |
9//! |--------|----------|
10//! | [`large_integers`] | `i64`, `u64`, `isize`, `usize` → REALSXP, plus string/bool/Option scalars |
11//! | [`collections`] | `HashMap`, `BTreeMap`, `HashSet`, `BTreeSet` → named/unnamed lists |
12//! | [`result`] | `Result<T, E>` → list with `ok`/`err` fields |
13//! | [`altrep`] | `Altrep<T>` marker type, `Lazy<T>` alias, `IntoRAltrep` trait |
14//!
15//! # Choosing the right outbound conversion
16//!
17//! [`IntoR`] is the **lax** outbound path — it silently widens 64-bit integers
18//! to R's `REALSXP` when the value doesn't fit `INTSXP`. The strict alternative
19//! lives in [`crate::strict`] and is opted into via `#[miniextendr(strict)]`,
20//! which routes through [`crate::strict::checked_into_sexp_i64`] and friends.
21//! Failure mode of staying on the default lax path when you care about exact
22//! representation: an `i64` value just above `i32::MAX` lands in R as an
23//! inexact `f64` (and IDs/counters larger than `2^53` start colliding).
24//!
25//! For storage-directed conversions (e.g. force `Vec<i64>` into `INTSXP`
26//! when values fit), reach for [`crate::into_r_as::IntoRAs`] instead.
27//!
28//! The inbound counterpart is [`crate::from_r::TryFromSexp`] (strict by
29//! construction — returns `Result`); the inbound looser path is
30//! [`crate::coerce::Coerce`] / [`crate::coerce::TryCoerce`]. There is
31//! intentionally no `TryFromSexpStrict` trait.
32//!
33//! # Thread Safety
34//!
35//! The trait provides two methods:
36//! - [`IntoR::into_sexp`] - checked version with debug thread assertions
37//! - [`IntoR::into_sexp_unchecked`] - unchecked version for performance-critical paths
38//!
39//! Use `into_sexp_unchecked` when you're certain you're on the main thread:
40//! - Inside ALTREP callbacks
41//! - Inside standalone `#[miniextendr]` functions (they run on the main thread)
42//! - Inside `extern "C-unwind"` functions called directly by R
43//!
44//! # The absence contract: what `None` becomes in R
45//!
46//! `None` does **not** map to one universal R value — it depends on the
47//! shape of `T` in `Option<T>`:
48//!
49//! - Owned scalars (`Option<i32>`, `Option<f64>`, `Option<bool>`,
50//!   `Option<String>`, and friends in [`large_integers`]) → the matching
51//!   `NA_<type>_`. R has a native NA sentinel for each of these.
52//! - `Option<&T>` where `T: Copy` (e.g. `Option<&i32>`) → `NULL`. A
53//!   reference has nothing to copy on `None`, so there is no NA to
54//!   produce. See the impl doc on `Option<&T>` in [`large_integers`].
55//! - `Option<&str>` is the one exception to the previous rule: it returns
56//!   `NA_character_`, matching `Option<String>`, because `str` is unsized
57//!   and can't use the generic `Copy`-bounded blanket impl — it has its
58//!   own hand-written impl instead.
59//! - Containers (`Option<Vec<T>>`, `Option<HashMap<..>>`, `Option<HashSet<..>>`,
60//!   `Option<BTreeMap<..>>`, `Option<BTreeSet<..>>`) → `NULL`. No container
61//!   type has a native R NA sentinel either.
62//! - The reading markers' `Option` (`Option<AsNumeric>`,
63//!   `Option<AsNumericVec>`, `Option<AsCharacter>`, `Option<AsCharacterVec>`;
64//!   see [`AsNumeric`](crate::convert::AsNumeric) and
65//!   [`AsCharacter`](crate::convert::AsCharacter)) → `NULL`. `NA` already
66//!   means `Some(marker(None))`, so `NULL` is what the marker's `Option`
67//!   reads back as `None`.
68//! - [`Nullable<T>`](crate::Nullable) → `NULL`, whatever `T` is: the
69//!   optional whose `None` means "no value at all". It reads `NULL` and `NA`
70//!   back as `None`, as `Option<T>` does, so it can also be an `#[r_data]`
71//!   field type. An `Option<T>` `#[r_data]` field follows the rules above
72//!   (an `Option<String>` field reads `NA_character_`) unless it is marked
73//!   `#[r_data(null_if_none)]`, whose getter reads `NULL` for `None` (#2270).
74//!
75//! Changing a return type from `Option<i32>` to `Option<&i32>` or
76//! `Option<Vec<i32>>` therefore silently flips the R-visible absence value
77//! from `NA_integer_` to `NULL`, and switching a return from `Option<f64>`
78//! to `Option<AsNumeric>` changes `NA` to `NULL`, with no compiler warning. See
79//! [`result`] for the analogous (and differently-shaped) contract on
80//! `Result::Err`.
81
82use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
83use std::hash::Hash;
84
85use crate::SexpExt;
86use crate::altrep_traits::{NA_INTEGER, NA_LOGICAL, NA_REAL};
87use crate::gc_protect::ProtectScope;
88use crate::list::ListBuilder;
89use crate::strvec::StrVecBuilder;
90
91/// Trait for converting Rust types to R SEXP values.
92///
93/// Outbound counterpart of [`crate::from_r::TryFromSexp`]. This is the **lax**
94/// path for 64-bit integer types — values that overflow `i32` silently land
95/// as `REALSXP`. For the strict alternative, see [`crate::strict`] and the
96/// `#[miniextendr(strict)]` attribute.
97///
98/// # Required Method
99///
100/// Implementors must provide [`try_into_sexp`](IntoR::try_into_sexp) and
101/// specify [`Error`](IntoR::Error). The other three methods have sensible
102/// defaults.
103///
104/// # Examples
105///
106/// ```no_run
107/// use miniextendr_api::into_r::IntoR;
108///
109/// let sexp = 42i32.into_sexp();
110/// let sexp = "hello".to_string().into_sexp();
111///
112/// // Fallible path:
113/// let result = "hello".try_into_sexp();
114/// assert!(result.is_ok());
115/// ```
116#[diagnostic::on_unimplemented(
117    note = "an `Option<Class>` return converts when spelled `Option<ExternalPtr<Class>>`, or with an explicit class wrap: `Option<WrapAsR6<Class>>` or `#[miniextendr(wrap = \"r6\")]` (any class system)"
118)]
119pub trait IntoR {
120    /// The error type for fallible conversions.
121    ///
122    /// Use [`std::convert::Infallible`] for types that can never fail.
123    /// Use [`IntoRError`](crate::into_r_error::IntoRError) for types
124    /// that may fail (e.g. strings exceeding R's i32 length limit).
125    ///
126    /// It implements [`RConditionData`](crate::condition::RConditionData):
127    /// a returned value whose conversion fails raises the error's message,
128    /// classes and fields in R (`kind = "result_err"`), and so does a failed
129    /// element inside a tuple, as an entry of `e$errors`
130    /// ([`IntoRError::Elements`](crate::into_r_error::IntoRError::Elements)).
131    /// An error type with only a message implements `message()` alone; a
132    /// foreign error converts into [`RError`](crate::condition::RError).
133    type Error: crate::condition::RConditionData;
134
135    /// Try to convert this value to an R SEXP.
136    ///
137    /// This is the **required** method. All other methods delegate to it.
138    fn try_into_sexp(self) -> Result<crate::SEXP, Self::Error>;
139
140    /// Try to convert to SEXP without thread safety checks.
141    ///
142    /// # Safety
143    ///
144    /// Must be called from R's main thread.
145    unsafe fn try_into_sexp_unchecked(self) -> Result<crate::SEXP, Self::Error>
146    where
147        Self: Sized,
148    {
149        self.try_into_sexp()
150    }
151
152    /// Convert this value to an R SEXP, panicking on error.
153    ///
154    /// In debug builds, asserts that we're on R's main thread.
155    fn into_sexp(self) -> crate::SEXP
156    where
157        Self: Sized,
158    {
159        match self.try_into_sexp() {
160            Ok(sexp) => sexp,
161            Err(e) => {
    ::core::panicking::panic_fmt(format_args!("IntoR conversion failed: {0}",
            crate::condition::RConditionData::message(&e)));
}panic!(
162                "IntoR conversion failed: {}",
163                crate::condition::RConditionData::message(&e)
164            ),
165        }
166    }
167
168    /// Convert to SEXP without thread safety checks, panicking on error.
169    ///
170    /// # Safety
171    ///
172    /// Must be called from R's main thread. In debug builds, this still
173    /// calls the checked version by default, but implementations may
174    /// skip thread assertions for performance.
175    unsafe fn into_sexp_unchecked(self) -> crate::SEXP
176    where
177        Self: Sized,
178    {
179        // Default: just call the checked version
180        self.into_sexp()
181    }
182}
183
184impl IntoR for crate::SEXP {
185    type Error = std::convert::Infallible;
186    #[inline]
187    fn try_into_sexp(self) -> Result<crate::SEXP, Self::Error> {
188        Ok(self)
189    }
190    #[inline]
191    unsafe fn try_into_sexp_unchecked(self) -> Result<crate::SEXP, Self::Error> {
192        Ok(self)
193    }
194    #[inline]
195    fn into_sexp(self) -> crate::SEXP {
196        self
197    }
198}
199
200impl IntoR for () {
201    type Error = std::convert::Infallible;
202    #[inline]
203    fn try_into_sexp(self) -> Result<crate::SEXP, Self::Error> {
204        Ok(crate::SEXP::nil())
205    }
206    #[inline]
207    unsafe fn try_into_sexp_unchecked(self) -> Result<crate::SEXP, Self::Error> {
208        self.try_into_sexp()
209    }
210    #[inline]
211    fn into_sexp(self) -> crate::SEXP {
212        crate::SEXP::nil()
213    }
214}
215
216impl IntoR for std::convert::Infallible {
217    type Error = std::convert::Infallible;
218    #[inline]
219    fn try_into_sexp(self) -> Result<crate::SEXP, Self::Error> {
220        match self {}
221    }
222    #[inline]
223    unsafe fn try_into_sexp_unchecked(self) -> Result<crate::SEXP, Self::Error> {
224        match self {}
225    }
226    #[inline]
227    fn into_sexp(self) -> crate::SEXP {
228        match self {}
229    }
230}
231
232/// Macro for scalar IntoR via SEXP::scalar_* methods.
233macro_rules! impl_scalar_into_r {
234    ($ty:ty, $checked:ident, $unchecked:ident) => {
235        impl IntoR for $ty {
236            type Error = std::convert::Infallible;
237            #[inline]
238            fn try_into_sexp(self) -> Result<crate::SEXP, Self::Error> {
239                Ok(crate::SEXP::$checked(self))
240            }
241            #[inline]
242            unsafe fn try_into_sexp_unchecked(self) -> Result<crate::SEXP, Self::Error> {
243                Ok(unsafe { self.into_sexp_unchecked() })
244            }
245            #[inline]
246            fn into_sexp(self) -> crate::SEXP {
247                crate::SEXP::$checked(self)
248            }
249            #[inline]
250            unsafe fn into_sexp_unchecked(self) -> crate::SEXP {
251                unsafe { crate::SEXP::$unchecked(self) }
252            }
253        }
254    };
255}
256
257impl IntoR for i32 {
    type Error = std::convert::Infallible;
    #[inline]
    fn try_into_sexp(self) -> Result<crate::SEXP, Self::Error> {
        Ok(crate::SEXP::scalar_integer(self))
    }
    #[inline]
    unsafe fn try_into_sexp_unchecked(self)
        -> Result<crate::SEXP, Self::Error> {
        Ok(unsafe { self.into_sexp_unchecked() })
    }
    #[inline]
    fn into_sexp(self) -> crate::SEXP { crate::SEXP::scalar_integer(self) }
    #[inline]
    unsafe fn into_sexp_unchecked(self) -> crate::SEXP {
        unsafe { crate::SEXP::scalar_integer_unchecked(self) }
    }
}impl_scalar_into_r!(i32, scalar_integer, scalar_integer_unchecked);
258impl IntoR for f64 {
    type Error = std::convert::Infallible;
    #[inline]
    fn try_into_sexp(self) -> Result<crate::SEXP, Self::Error> {
        Ok(crate::SEXP::scalar_real(self))
    }
    #[inline]
    unsafe fn try_into_sexp_unchecked(self)
        -> Result<crate::SEXP, Self::Error> {
        Ok(unsafe { self.into_sexp_unchecked() })
    }
    #[inline]
    fn into_sexp(self) -> crate::SEXP { crate::SEXP::scalar_real(self) }
    #[inline]
    unsafe fn into_sexp_unchecked(self) -> crate::SEXP {
        unsafe { crate::SEXP::scalar_real_unchecked(self) }
    }
}impl_scalar_into_r!(f64, scalar_real, scalar_real_unchecked);
259impl IntoR for u8 {
    type Error = std::convert::Infallible;
    #[inline]
    fn try_into_sexp(self) -> Result<crate::SEXP, Self::Error> {
        Ok(crate::SEXP::scalar_raw(self))
    }
    #[inline]
    unsafe fn try_into_sexp_unchecked(self)
        -> Result<crate::SEXP, Self::Error> {
        Ok(unsafe { self.into_sexp_unchecked() })
    }
    #[inline]
    fn into_sexp(self) -> crate::SEXP { crate::SEXP::scalar_raw(self) }
    #[inline]
    unsafe fn into_sexp_unchecked(self) -> crate::SEXP {
        unsafe { crate::SEXP::scalar_raw_unchecked(self) }
    }
}impl_scalar_into_r!(u8, scalar_raw, scalar_raw_unchecked);
260impl IntoR for crate::Rcomplex {
    type Error = std::convert::Infallible;
    #[inline]
    fn try_into_sexp(self) -> Result<crate::SEXP, Self::Error> {
        Ok(crate::SEXP::scalar_complex(self))
    }
    #[inline]
    unsafe fn try_into_sexp_unchecked(self)
        -> Result<crate::SEXP, Self::Error> {
        Ok(unsafe { self.into_sexp_unchecked() })
    }
    #[inline]
    fn into_sexp(self) -> crate::SEXP { crate::SEXP::scalar_complex(self) }
    #[inline]
    unsafe fn into_sexp_unchecked(self) -> crate::SEXP {
        unsafe { crate::SEXP::scalar_complex_unchecked(self) }
    }
}impl_scalar_into_r!(crate::Rcomplex, scalar_complex, scalar_complex_unchecked);
261
262/// Generate an infallible [`IntoR`] impl whose only real method is `into_sexp`.
263///
264/// Collapses the four-line boilerplate shell shared by every `Infallible`
265/// `IntoR` impl in the optional-type modules: `try_into_sexp` delegates to
266/// `into_sexp`, `try_into_sexp_unchecked` delegates to `try_into_sexp`, and
267/// `into_sexp_unchecked` is left as the trait default. Only the `into_sexp`
268/// body is supplied, as a closure-style `|recv| expr` binding the receiver
269/// (a macro cannot reuse a `self` that arrives through a fragment, so the
270/// caller names it). The generated methods are byte-identical to the
271/// hand-written shell, so this is purely a dedup.
272///
273/// ```ignore
274/// into_r_infallible!(Uuid, |this| this.to_string().into_sexp());
275/// into_r_infallible!(Vec<Uuid>,
276///     |this| this.into_iter().map(|u| u.to_string()).collect::<Vec<_>>().into_sexp());
277/// ```
278macro_rules! into_r_infallible {
279    ($ty:ty, |$recv:ident| $body:expr) => {
280        impl $crate::into_r::IntoR for $ty {
281            type Error = ::std::convert::Infallible;
282            #[inline]
283            fn try_into_sexp(self) -> ::core::result::Result<$crate::SEXP, Self::Error> {
284                ::core::result::Result::Ok(self.into_sexp())
285            }
286            #[inline]
287            unsafe fn try_into_sexp_unchecked(
288                self,
289            ) -> ::core::result::Result<$crate::SEXP, Self::Error> {
290                self.try_into_sexp()
291            }
292            #[inline]
293            fn into_sexp(self) -> $crate::SEXP {
294                let $recv = self;
295                $body
296            }
297        }
298    };
299}
300#[allow(unused_imports)]
301pub(crate) use into_r_infallible;
302
303impl IntoR for Option<crate::Rcomplex> {
304    type Error = std::convert::Infallible;
305    #[inline]
306    fn try_into_sexp(self) -> Result<crate::SEXP, Self::Error> {
307        Ok(self.into_sexp())
308    }
309    #[inline]
310    unsafe fn try_into_sexp_unchecked(self) -> Result<crate::SEXP, Self::Error> {
311        Ok(unsafe { self.into_sexp_unchecked() })
312    }
313    #[inline]
314    fn into_sexp(self) -> crate::SEXP {
315        match self {
316            Some(v) => v.into_sexp(),
317            None => crate::SEXP::scalar_complex(crate::Rcomplex {
318                r: NA_REAL,
319                i: NA_REAL,
320            }),
321        }
322    }
323    #[inline]
324    unsafe fn into_sexp_unchecked(self) -> crate::SEXP {
325        match self {
326            Some(v) => unsafe { v.into_sexp_unchecked() },
327            None => unsafe {
328                crate::SEXP::scalar_complex_unchecked(crate::Rcomplex {
329                    r: NA_REAL,
330                    i: NA_REAL,
331                })
332            },
333        }
334    }
335}
336
337/// Macro for infallible widening IntoR via Coerce.
338macro_rules! impl_into_r_via_coerce {
339    ($from:ty => $to:ty) => {
340        impl IntoR for $from {
341            type Error = std::convert::Infallible;
342            #[inline]
343            fn try_into_sexp(self) -> Result<crate::SEXP, Self::Error> {
344                Ok(crate::coerce::Coerce::<$to>::coerce(self).into_sexp())
345            }
346            #[inline]
347            unsafe fn try_into_sexp_unchecked(self) -> Result<crate::SEXP, Self::Error> {
348                Ok(unsafe { self.into_sexp_unchecked() })
349            }
350            #[inline]
351            fn into_sexp(self) -> crate::SEXP {
352                crate::coerce::Coerce::<$to>::coerce(self).into_sexp()
353            }
354            #[inline]
355            unsafe fn into_sexp_unchecked(self) -> crate::SEXP {
356                unsafe { crate::coerce::Coerce::<$to>::coerce(self).into_sexp_unchecked() }
357            }
358        }
359    };
360}
361
362// Infallible widening to i32 (R's INTSXP)
363impl IntoR for i8 {
    type Error = std::convert::Infallible;
    #[inline]
    fn try_into_sexp(self) -> Result<crate::SEXP, Self::Error> {
        Ok(crate::coerce::Coerce::<i32>::coerce(self).into_sexp())
    }
    #[inline]
    unsafe fn try_into_sexp_unchecked(self)
        -> Result<crate::SEXP, Self::Error> {
        Ok(unsafe { self.into_sexp_unchecked() })
    }
    #[inline]
    fn into_sexp(self) -> crate::SEXP {
        crate::coerce::Coerce::<i32>::coerce(self).into_sexp()
    }
    #[inline]
    unsafe fn into_sexp_unchecked(self) -> crate::SEXP {
        unsafe {
            crate::coerce::Coerce::<i32>::coerce(self).into_sexp_unchecked()
        }
    }
}impl_into_r_via_coerce!(i8 => i32);
364impl IntoR for i16 {
    type Error = std::convert::Infallible;
    #[inline]
    fn try_into_sexp(self) -> Result<crate::SEXP, Self::Error> {
        Ok(crate::coerce::Coerce::<i32>::coerce(self).into_sexp())
    }
    #[inline]
    unsafe fn try_into_sexp_unchecked(self)
        -> Result<crate::SEXP, Self::Error> {
        Ok(unsafe { self.into_sexp_unchecked() })
    }
    #[inline]
    fn into_sexp(self) -> crate::SEXP {
        crate::coerce::Coerce::<i32>::coerce(self).into_sexp()
    }
    #[inline]
    unsafe fn into_sexp_unchecked(self) -> crate::SEXP {
        unsafe {
            crate::coerce::Coerce::<i32>::coerce(self).into_sexp_unchecked()
        }
    }
}impl_into_r_via_coerce!(i16 => i32);
365impl IntoR for u16 {
    type Error = std::convert::Infallible;
    #[inline]
    fn try_into_sexp(self) -> Result<crate::SEXP, Self::Error> {
        Ok(crate::coerce::Coerce::<i32>::coerce(self).into_sexp())
    }
    #[inline]
    unsafe fn try_into_sexp_unchecked(self)
        -> Result<crate::SEXP, Self::Error> {
        Ok(unsafe { self.into_sexp_unchecked() })
    }
    #[inline]
    fn into_sexp(self) -> crate::SEXP {
        crate::coerce::Coerce::<i32>::coerce(self).into_sexp()
    }
    #[inline]
    unsafe fn into_sexp_unchecked(self) -> crate::SEXP {
        unsafe {
            crate::coerce::Coerce::<i32>::coerce(self).into_sexp_unchecked()
        }
    }
}impl_into_r_via_coerce!(u16 => i32);
366
367// Infallible widening to f64 (R's REALSXP)
368impl IntoR for f32 {
    type Error = std::convert::Infallible;
    #[inline]
    fn try_into_sexp(self) -> Result<crate::SEXP, Self::Error> {
        Ok(crate::coerce::Coerce::<f64>::coerce(self).into_sexp())
    }
    #[inline]
    unsafe fn try_into_sexp_unchecked(self)
        -> Result<crate::SEXP, Self::Error> {
        Ok(unsafe { self.into_sexp_unchecked() })
    }
    #[inline]
    fn into_sexp(self) -> crate::SEXP {
        crate::coerce::Coerce::<f64>::coerce(self).into_sexp()
    }
    #[inline]
    unsafe fn into_sexp_unchecked(self) -> crate::SEXP {
        unsafe {
            crate::coerce::Coerce::<f64>::coerce(self).into_sexp_unchecked()
        }
    }
}impl_into_r_via_coerce!(f32 => f64);
369impl IntoR for u32 {
    type Error = std::convert::Infallible;
    #[inline]
    fn try_into_sexp(self) -> Result<crate::SEXP, Self::Error> {
        Ok(crate::coerce::Coerce::<f64>::coerce(self).into_sexp())
    }
    #[inline]
    unsafe fn try_into_sexp_unchecked(self)
        -> Result<crate::SEXP, Self::Error> {
        Ok(unsafe { self.into_sexp_unchecked() })
    }
    #[inline]
    fn into_sexp(self) -> crate::SEXP {
        crate::coerce::Coerce::<f64>::coerce(self).into_sexp()
    }
    #[inline]
    unsafe fn into_sexp_unchecked(self) -> crate::SEXP {
        unsafe {
            crate::coerce::Coerce::<f64>::coerce(self).into_sexp_unchecked()
        }
    }
}impl_into_r_via_coerce!(u32 => f64); // all u32 exactly representable in f64
370
371mod large_integers;
372pub(crate) use large_integers::{str_to_charsxp, str_to_charsxp_unchecked};
373
374// region: Vector conversions
375
376// Concrete IntoR impls for Vec<T> where T: RNativeType.
377//
378// These are written as concrete impls rather than a blanket
379// `impl<T: RNativeType> IntoR for Vec<T>` to avoid a coherence conflict with the
380// one `impl<T: IntoRVecElement> IntoR for Vec<T>` blanket (see `crate::newtype`):
381// `Vec<T>` admits exactly one open-bound `IntoR` blanket slot, and that slot is
382// the shared element-marker route used by `MatchArg` enums and `#[derive(IntoR)]`
383// newtypes. A second `RNativeType`-bounded blanket would be E0119 — negative
384// trait bounds are not stable, so coherence cannot prove the bounds disjoint.
385// Concrete per-type impls sidestep the slot entirely (concrete-vs-blanket is
386// allowed: the foreign R-native types provably do not implement the marker).
387macro_rules! impl_into_r_vec_native {
388    ($t:ty) => {
389        impl IntoR for Vec<$t> {
390            type Error = std::convert::Infallible;
391            #[inline]
392            fn try_into_sexp(self) -> Result<crate::SEXP, Self::Error> {
393                Ok(unsafe { vec_to_sexp(&self) })
394            }
395            #[inline]
396            unsafe fn try_into_sexp_unchecked(self) -> Result<crate::SEXP, Self::Error> {
397                Ok(unsafe { self.into_sexp_unchecked() })
398            }
399            #[inline]
400            fn into_sexp(self) -> crate::SEXP {
401                unsafe { vec_to_sexp(&self) }
402            }
403            #[inline]
404            unsafe fn into_sexp_unchecked(self) -> crate::SEXP {
405                unsafe { vec_to_sexp_unchecked(&self) }
406            }
407        }
408    };
409}
410
411impl IntoR for Vec<i32> {
    type Error = std::convert::Infallible;
    #[inline]
    fn try_into_sexp(self) -> Result<crate::SEXP, Self::Error> {
        Ok(unsafe { vec_to_sexp(&self) })
    }
    #[inline]
    unsafe fn try_into_sexp_unchecked(self)
        -> Result<crate::SEXP, Self::Error> {
        Ok(unsafe { self.into_sexp_unchecked() })
    }
    #[inline]
    fn into_sexp(self) -> crate::SEXP { unsafe { vec_to_sexp(&self) } }
    #[inline]
    unsafe fn into_sexp_unchecked(self) -> crate::SEXP {
        unsafe { vec_to_sexp_unchecked(&self) }
    }
}impl_into_r_vec_native!(i32);
412impl IntoR for Vec<f64> {
    type Error = std::convert::Infallible;
    #[inline]
    fn try_into_sexp(self) -> Result<crate::SEXP, Self::Error> {
        Ok(unsafe { vec_to_sexp(&self) })
    }
    #[inline]
    unsafe fn try_into_sexp_unchecked(self)
        -> Result<crate::SEXP, Self::Error> {
        Ok(unsafe { self.into_sexp_unchecked() })
    }
    #[inline]
    fn into_sexp(self) -> crate::SEXP { unsafe { vec_to_sexp(&self) } }
    #[inline]
    unsafe fn into_sexp_unchecked(self) -> crate::SEXP {
        unsafe { vec_to_sexp_unchecked(&self) }
    }
}impl_into_r_vec_native!(f64);
413impl IntoR for Vec<u8> {
    type Error = std::convert::Infallible;
    #[inline]
    fn try_into_sexp(self) -> Result<crate::SEXP, Self::Error> {
        Ok(unsafe { vec_to_sexp(&self) })
    }
    #[inline]
    unsafe fn try_into_sexp_unchecked(self)
        -> Result<crate::SEXP, Self::Error> {
        Ok(unsafe { self.into_sexp_unchecked() })
    }
    #[inline]
    fn into_sexp(self) -> crate::SEXP { unsafe { vec_to_sexp(&self) } }
    #[inline]
    unsafe fn into_sexp_unchecked(self) -> crate::SEXP {
        unsafe { vec_to_sexp_unchecked(&self) }
    }
}impl_into_r_vec_native!(u8);
414impl IntoR for Vec<crate::RLogical> {
    type Error = std::convert::Infallible;
    #[inline]
    fn try_into_sexp(self) -> Result<crate::SEXP, Self::Error> {
        Ok(unsafe { vec_to_sexp(&self) })
    }
    #[inline]
    unsafe fn try_into_sexp_unchecked(self)
        -> Result<crate::SEXP, Self::Error> {
        Ok(unsafe { self.into_sexp_unchecked() })
    }
    #[inline]
    fn into_sexp(self) -> crate::SEXP { unsafe { vec_to_sexp(&self) } }
    #[inline]
    unsafe fn into_sexp_unchecked(self) -> crate::SEXP {
        unsafe { vec_to_sexp_unchecked(&self) }
    }
}impl_into_r_vec_native!(crate::RLogical);
415impl IntoR for Vec<crate::Rcomplex> {
    type Error = std::convert::Infallible;
    #[inline]
    fn try_into_sexp(self) -> Result<crate::SEXP, Self::Error> {
        Ok(unsafe { vec_to_sexp(&self) })
    }
    #[inline]
    unsafe fn try_into_sexp_unchecked(self)
        -> Result<crate::SEXP, Self::Error> {
        Ok(unsafe { self.into_sexp_unchecked() })
    }
    #[inline]
    fn into_sexp(self) -> crate::SEXP { unsafe { vec_to_sexp(&self) } }
    #[inline]
    unsafe fn into_sexp_unchecked(self) -> crate::SEXP {
        unsafe { vec_to_sexp_unchecked(&self) }
    }
}impl_into_r_vec_native!(crate::Rcomplex);
416
417impl<T> IntoR for &[T]
418where
419    T: crate::RNativeType,
420{
421    type Error = std::convert::Infallible;
422    #[inline]
423    fn try_into_sexp(self) -> Result<crate::SEXP, Self::Error> {
424        Ok(unsafe { vec_to_sexp(self) })
425    }
426    #[inline]
427    unsafe fn try_into_sexp_unchecked(self) -> Result<crate::SEXP, Self::Error> {
428        Ok(unsafe { self.into_sexp_unchecked() })
429    }
430    #[inline]
431    fn into_sexp(self) -> crate::SEXP {
432        unsafe { vec_to_sexp(self) }
433    }
434    #[inline]
435    unsafe fn into_sexp_unchecked(self) -> crate::SEXP {
436        unsafe { vec_to_sexp_unchecked(self) }
437    }
438}
439
440// A boxed slice converts exactly like the owned vector. `into_vec()` is an
441// O(1), allocation-free widen, so this one blanket subsumes every per-element
442// `Box<[X]>` impl (native, String, Cow, bool, …): any `Vec<X>: IntoR` element
443// gets `Box<[X]>` for free, inheriting the vector impl's error type and path.
444// Coherence-equivalent to the prior `impl<T: RNativeType> IntoR for Box<[T]>`:
445// both occupy the whole `Box<[T]>` slot (where-clauses don't narrow overlap),
446// so concrete downstream `impl IntoR for Box<[Local]>` stays just as available.
447impl<T> IntoR for Box<[T]>
448where
449    Vec<T>: IntoR,
450{
451    type Error = <Vec<T> as IntoR>::Error;
452    #[inline]
453    fn try_into_sexp(self) -> Result<crate::SEXP, Self::Error> {
454        self.into_vec().try_into_sexp()
455    }
456    #[inline]
457    unsafe fn try_into_sexp_unchecked(self) -> Result<crate::SEXP, Self::Error> {
458        unsafe { self.into_vec().try_into_sexp_unchecked() }
459    }
460    #[inline]
461    fn into_sexp(self) -> crate::SEXP {
462        self.into_vec().into_sexp()
463    }
464    #[inline]
465    unsafe fn into_sexp_unchecked(self) -> crate::SEXP {
466        unsafe { self.into_vec().into_sexp_unchecked() }
467    }
468}
469
470// region: R vector allocation helpers
471//
472// These are the ONLY place in the codebase that should call Rf_allocVector
473// for typed vectors and obtain a mutable data slice. All conversion code
474// uses these helpers instead of raw FFI pointer arithmetic.
475
476/// Allocate an R vector of type `T` with `n` elements and return `(SEXP, &mut [T])`.
477///
478/// The returned SEXP is **unprotected** — caller must protect via `Rf_protect`,
479/// `OwnedProtect`, or `ProtectScope` before any further R allocation.
480///
481/// # Safety
482///
483/// Must be called from R's main thread.
484#[inline]
485pub(crate) unsafe fn alloc_r_vector<T: crate::RNativeType>(
486    n: usize,
487) -> (crate::SEXP, &'static mut [T]) {
488    unsafe {
489        let sexp = crate::sys::Rf_allocVector(T::SEXP_TYPE, n as crate::R_xlen_t);
490        let slice = crate::from_r::r_slice_mut(T::dataptr_mut(sexp), n);
491        (sexp, slice)
492    }
493}
494
495/// Allocate an R vector (unchecked FFI variant).
496///
497/// # Safety
498///
499/// Must be called from R's main thread.
500#[inline]
501pub(crate) unsafe fn alloc_r_vector_unchecked<T: crate::RNativeType>(
502    n: usize,
503) -> (crate::SEXP, &'static mut [T]) {
504    unsafe {
505        let sexp = crate::sys::Rf_allocVector_unchecked(T::SEXP_TYPE, n as crate::R_xlen_t);
506        let slice = crate::from_r::r_slice_mut(T::dataptr_mut(sexp), n);
507        (sexp, slice)
508    }
509}
510
511// endregion
512
513/// Convert a slice to an R vector (checked) using `copy_from_slice`.
514#[inline]
515unsafe fn vec_to_sexp<T: crate::RNativeType>(slice: &[T]) -> crate::SEXP {
516    unsafe {
517        let (sexp, dst) = alloc_r_vector::<T>(slice.len());
518        dst.copy_from_slice(slice);
519        sexp
520    }
521}
522
523/// Convert a slice to an R vector (unchecked) using `copy_from_slice`.
524#[inline]
525unsafe fn vec_to_sexp_unchecked<T: crate::RNativeType>(slice: &[T]) -> crate::SEXP {
526    unsafe {
527        let (sexp, dst) = alloc_r_vector_unchecked::<T>(slice.len());
528        dst.copy_from_slice(slice);
529        sexp
530    }
531}
532// endregion
533
534// region: Vec coercion for non-native types (i8, i16, u16 → i32; f32 → f64)
535
536/// Macro for `Vec<T>` where `T` coerces to a native R type.
537///
538/// Allocates the R vector directly and coerces in-place — no intermediate Vec.
539macro_rules! impl_vec_coerce_into_r {
540    ($from:ty => $to:ty) => {
541        impl IntoR for Vec<$from> {
542            type Error = std::convert::Infallible;
543            #[inline]
544            fn try_into_sexp(self) -> Result<crate::SEXP, Self::Error> {
545                Ok(self.into_sexp())
546            }
547            #[inline]
548            unsafe fn try_into_sexp_unchecked(self) -> Result<crate::SEXP, Self::Error> {
549                Ok(unsafe { self.into_sexp_unchecked() })
550            }
551            #[inline]
552            fn into_sexp(self) -> crate::SEXP {
553                unsafe {
554                    let (sexp, dst) = alloc_r_vector::<$to>(self.len());
555                    for (slot, val) in dst.iter_mut().zip(self.into_iter()) {
556                        *slot = <$to>::from(val);
557                    }
558                    sexp
559                }
560            }
561            #[inline]
562            unsafe fn into_sexp_unchecked(self) -> crate::SEXP {
563                unsafe {
564                    let (sexp, dst) = alloc_r_vector_unchecked::<$to>(self.len());
565                    for (slot, val) in dst.iter_mut().zip(self.into_iter()) {
566                        *slot = <$to>::from(val);
567                    }
568                    sexp
569                }
570            }
571        }
572
573        impl IntoR for &[$from] {
574            type Error = std::convert::Infallible;
575            #[inline]
576            fn try_into_sexp(self) -> Result<crate::SEXP, Self::Error> {
577                Ok(self.into_sexp())
578            }
579            #[inline]
580            unsafe fn try_into_sexp_unchecked(self) -> Result<crate::SEXP, Self::Error> {
581                Ok(unsafe { self.into_sexp_unchecked() })
582            }
583            #[inline]
584            fn into_sexp(self) -> crate::SEXP {
585                unsafe {
586                    let (sexp, dst) = alloc_r_vector::<$to>(self.len());
587                    for (slot, &val) in dst.iter_mut().zip(self.iter()) {
588                        *slot = <$to>::from(val);
589                    }
590                    sexp
591                }
592            }
593            #[inline]
594            unsafe fn into_sexp_unchecked(self) -> crate::SEXP {
595                unsafe {
596                    let (sexp, dst) = alloc_r_vector_unchecked::<$to>(self.len());
597                    for (slot, &val) in dst.iter_mut().zip(self.iter()) {
598                        *slot = <$to>::from(val);
599                    }
600                    sexp
601                }
602            }
603        }
604    };
605}
606
607// Sub-i32 integer types coerce to i32 (R's INTSXP)
608impl IntoR for Vec<i8> {
    type Error = std::convert::Infallible;
    #[inline]
    fn try_into_sexp(self) -> Result<crate::SEXP, Self::Error> {
        Ok(self.into_sexp())
    }
    #[inline]
    unsafe fn try_into_sexp_unchecked(self)
        -> Result<crate::SEXP, Self::Error> {
        Ok(unsafe { self.into_sexp_unchecked() })
    }
    #[inline]
    fn into_sexp(self) -> crate::SEXP {
        unsafe {
            let (sexp, dst) = alloc_r_vector::<i32>(self.len());
            for (slot, val) in dst.iter_mut().zip(self.into_iter()) {
                *slot = <i32>::from(val);
            }
            sexp
        }
    }
    #[inline]
    unsafe fn into_sexp_unchecked(self) -> crate::SEXP {
        unsafe {
            let (sexp, dst) = alloc_r_vector_unchecked::<i32>(self.len());
            for (slot, val) in dst.iter_mut().zip(self.into_iter()) {
                *slot = <i32>::from(val);
            }
            sexp
        }
    }
}
impl IntoR for &[i8] {
    type Error = std::convert::Infallible;
    #[inline]
    fn try_into_sexp(self) -> Result<crate::SEXP, Self::Error> {
        Ok(self.into_sexp())
    }
    #[inline]
    unsafe fn try_into_sexp_unchecked(self)
        -> Result<crate::SEXP, Self::Error> {
        Ok(unsafe { self.into_sexp_unchecked() })
    }
    #[inline]
    fn into_sexp(self) -> crate::SEXP {
        unsafe {
            let (sexp, dst) = alloc_r_vector::<i32>(self.len());
            for (slot, &val) in dst.iter_mut().zip(self.iter()) {
                *slot = <i32>::from(val);
            }
            sexp
        }
    }
    #[inline]
    unsafe fn into_sexp_unchecked(self) -> crate::SEXP {
        unsafe {
            let (sexp, dst) = alloc_r_vector_unchecked::<i32>(self.len());
            for (slot, &val) in dst.iter_mut().zip(self.iter()) {
                *slot = <i32>::from(val);
            }
            sexp
        }
    }
}impl_vec_coerce_into_r!(i8 => i32);
609impl IntoR for Vec<i16> {
    type Error = std::convert::Infallible;
    #[inline]
    fn try_into_sexp(self) -> Result<crate::SEXP, Self::Error> {
        Ok(self.into_sexp())
    }
    #[inline]
    unsafe fn try_into_sexp_unchecked(self)
        -> Result<crate::SEXP, Self::Error> {
        Ok(unsafe { self.into_sexp_unchecked() })
    }
    #[inline]
    fn into_sexp(self) -> crate::SEXP {
        unsafe {
            let (sexp, dst) = alloc_r_vector::<i32>(self.len());
            for (slot, val) in dst.iter_mut().zip(self.into_iter()) {
                *slot = <i32>::from(val);
            }
            sexp
        }
    }
    #[inline]
    unsafe fn into_sexp_unchecked(self) -> crate::SEXP {
        unsafe {
            let (sexp, dst) = alloc_r_vector_unchecked::<i32>(self.len());
            for (slot, val) in dst.iter_mut().zip(self.into_iter()) {
                *slot = <i32>::from(val);
            }
            sexp
        }
    }
}
impl IntoR for &[i16] {
    type Error = std::convert::Infallible;
    #[inline]
    fn try_into_sexp(self) -> Result<crate::SEXP, Self::Error> {
        Ok(self.into_sexp())
    }
    #[inline]
    unsafe fn try_into_sexp_unchecked(self)
        -> Result<crate::SEXP, Self::Error> {
        Ok(unsafe { self.into_sexp_unchecked() })
    }
    #[inline]
    fn into_sexp(self) -> crate::SEXP {
        unsafe {
            let (sexp, dst) = alloc_r_vector::<i32>(self.len());
            for (slot, &val) in dst.iter_mut().zip(self.iter()) {
                *slot = <i32>::from(val);
            }
            sexp
        }
    }
    #[inline]
    unsafe fn into_sexp_unchecked(self) -> crate::SEXP {
        unsafe {
            let (sexp, dst) = alloc_r_vector_unchecked::<i32>(self.len());
            for (slot, &val) in dst.iter_mut().zip(self.iter()) {
                *slot = <i32>::from(val);
            }
            sexp
        }
    }
}impl_vec_coerce_into_r!(i16 => i32);
610impl IntoR for Vec<u16> {
    type Error = std::convert::Infallible;
    #[inline]
    fn try_into_sexp(self) -> Result<crate::SEXP, Self::Error> {
        Ok(self.into_sexp())
    }
    #[inline]
    unsafe fn try_into_sexp_unchecked(self)
        -> Result<crate::SEXP, Self::Error> {
        Ok(unsafe { self.into_sexp_unchecked() })
    }
    #[inline]
    fn into_sexp(self) -> crate::SEXP {
        unsafe {
            let (sexp, dst) = alloc_r_vector::<i32>(self.len());
            for (slot, val) in dst.iter_mut().zip(self.into_iter()) {
                *slot = <i32>::from(val);
            }
            sexp
        }
    }
    #[inline]
    unsafe fn into_sexp_unchecked(self) -> crate::SEXP {
        unsafe {
            let (sexp, dst) = alloc_r_vector_unchecked::<i32>(self.len());
            for (slot, val) in dst.iter_mut().zip(self.into_iter()) {
                *slot = <i32>::from(val);
            }
            sexp
        }
    }
}
impl IntoR for &[u16] {
    type Error = std::convert::Infallible;
    #[inline]
    fn try_into_sexp(self) -> Result<crate::SEXP, Self::Error> {
        Ok(self.into_sexp())
    }
    #[inline]
    unsafe fn try_into_sexp_unchecked(self)
        -> Result<crate::SEXP, Self::Error> {
        Ok(unsafe { self.into_sexp_unchecked() })
    }
    #[inline]
    fn into_sexp(self) -> crate::SEXP {
        unsafe {
            let (sexp, dst) = alloc_r_vector::<i32>(self.len());
            for (slot, &val) in dst.iter_mut().zip(self.iter()) {
                *slot = <i32>::from(val);
            }
            sexp
        }
    }
    #[inline]
    unsafe fn into_sexp_unchecked(self) -> crate::SEXP {
        unsafe {
            let (sexp, dst) = alloc_r_vector_unchecked::<i32>(self.len());
            for (slot, &val) in dst.iter_mut().zip(self.iter()) {
                *slot = <i32>::from(val);
            }
            sexp
        }
    }
}impl_vec_coerce_into_r!(u16 => i32);
611
612// f32 coerces to f64 (R's REALSXP)
613impl IntoR for Vec<f32> {
    type Error = std::convert::Infallible;
    #[inline]
    fn try_into_sexp(self) -> Result<crate::SEXP, Self::Error> {
        Ok(self.into_sexp())
    }
    #[inline]
    unsafe fn try_into_sexp_unchecked(self)
        -> Result<crate::SEXP, Self::Error> {
        Ok(unsafe { self.into_sexp_unchecked() })
    }
    #[inline]
    fn into_sexp(self) -> crate::SEXP {
        unsafe {
            let (sexp, dst) = alloc_r_vector::<f64>(self.len());
            for (slot, val) in dst.iter_mut().zip(self.into_iter()) {
                *slot = <f64>::from(val);
            }
            sexp
        }
    }
    #[inline]
    unsafe fn into_sexp_unchecked(self) -> crate::SEXP {
        unsafe {
            let (sexp, dst) = alloc_r_vector_unchecked::<f64>(self.len());
            for (slot, val) in dst.iter_mut().zip(self.into_iter()) {
                *slot = <f64>::from(val);
            }
            sexp
        }
    }
}
impl IntoR for &[f32] {
    type Error = std::convert::Infallible;
    #[inline]
    fn try_into_sexp(self) -> Result<crate::SEXP, Self::Error> {
        Ok(self.into_sexp())
    }
    #[inline]
    unsafe fn try_into_sexp_unchecked(self)
        -> Result<crate::SEXP, Self::Error> {
        Ok(unsafe { self.into_sexp_unchecked() })
    }
    #[inline]
    fn into_sexp(self) -> crate::SEXP {
        unsafe {
            let (sexp, dst) = alloc_r_vector::<f64>(self.len());
            for (slot, &val) in dst.iter_mut().zip(self.iter()) {
                *slot = <f64>::from(val);
            }
            sexp
        }
    }
    #[inline]
    unsafe fn into_sexp_unchecked(self) -> crate::SEXP {
        unsafe {
            let (sexp, dst) = alloc_r_vector_unchecked::<f64>(self.len());
            for (slot, &val) in dst.iter_mut().zip(self.iter()) {
                *slot = <f64>::from(val);
            }
            sexp
        }
    }
}impl_vec_coerce_into_r!(f32 => f64);
614
615// i64/u64/isize/usize/u32: smart conversion (INTSXP when all fit, else REALSXP)
616//
617// Allocates the R vector directly and coerces in-place — no intermediate Vec.
618// The slice impl carries the conversion; the `Vec` impl borrows into it (the
619// elements are `Copy`), so `Vec<T>` and `&[T]` always agree.
620macro_rules! impl_vec_smart_i64_into_r {
621    ($t:ty, $fits_i32:expr) => {
622        impl IntoR for &[$t] {
623            type Error = std::convert::Infallible;
624            fn try_into_sexp(self) -> Result<crate::SEXP, Self::Error> {
625                Ok(self.into_sexp())
626            }
627            unsafe fn try_into_sexp_unchecked(self) -> Result<crate::SEXP, Self::Error> {
628                Ok(unsafe { self.into_sexp_unchecked() })
629            }
630            fn into_sexp(self) -> crate::SEXP {
631                unsafe {
632                    if self.iter().all(|&x| $fits_i32(x)) {
633                        let (sexp, dst) = alloc_r_vector::<i32>(self.len());
634                        for (slot, &val) in dst.iter_mut().zip(self.iter()) {
635                            // fits_i32 guard verified range
636                            *slot = val as i32;
637                        }
638                        sexp
639                    } else {
640                        let (sexp, dst) = alloc_r_vector::<f64>(self.len());
641                        for (slot, &val) in dst.iter_mut().zip(self.iter()) {
642                            // R has no 64-bit integer; f64 loses precision > 2^53
643                            *slot = val as f64;
644                        }
645                        sexp
646                    }
647                }
648            }
649            unsafe fn into_sexp_unchecked(self) -> crate::SEXP {
650                unsafe {
651                    if self.iter().all(|&x| $fits_i32(x)) {
652                        let (sexp, dst) = alloc_r_vector_unchecked::<i32>(self.len());
653                        for (slot, &val) in dst.iter_mut().zip(self.iter()) {
654                            // fits_i32 guard verified range
655                            *slot = val as i32;
656                        }
657                        sexp
658                    } else {
659                        let (sexp, dst) = alloc_r_vector_unchecked::<f64>(self.len());
660                        for (slot, &val) in dst.iter_mut().zip(self.iter()) {
661                            // R has no 64-bit integer; f64 loses precision > 2^53
662                            *slot = val as f64;
663                        }
664                        sexp
665                    }
666                }
667            }
668        }
669
670        impl IntoR for Vec<$t> {
671            type Error = std::convert::Infallible;
672            fn try_into_sexp(self) -> Result<crate::SEXP, Self::Error> {
673                Ok(self.into_sexp())
674            }
675            unsafe fn try_into_sexp_unchecked(self) -> Result<crate::SEXP, Self::Error> {
676                Ok(unsafe { self.into_sexp_unchecked() })
677            }
678            fn into_sexp(self) -> crate::SEXP {
679                self.as_slice().into_sexp()
680            }
681            unsafe fn into_sexp_unchecked(self) -> crate::SEXP {
682                unsafe { self.as_slice().into_sexp_unchecked() }
683            }
684        }
685    };
686}
687
688// i32::MIN is NA_integer_ in R, so exclude it
689impl IntoR for &[i64] {
    type Error = std::convert::Infallible;
    fn try_into_sexp(self) -> Result<crate::SEXP, Self::Error> {
        Ok(self.into_sexp())
    }
    unsafe fn try_into_sexp_unchecked(self)
        -> Result<crate::SEXP, Self::Error> {
        Ok(unsafe { self.into_sexp_unchecked() })
    }
    fn into_sexp(self) -> crate::SEXP {
        unsafe {
            if self.iter().all(|&x|
                        (|x: i64| x > i32::MIN as i64 && x <= i32::MAX as i64)(x)) {
                let (sexp, dst) = alloc_r_vector::<i32>(self.len());
                for (slot, &val) in dst.iter_mut().zip(self.iter()) {
                    *slot = val as i32;
                }
                sexp
            } else {
                let (sexp, dst) = alloc_r_vector::<f64>(self.len());
                for (slot, &val) in dst.iter_mut().zip(self.iter()) {
                    *slot = val as f64;
                }
                sexp
            }
        }
    }
    unsafe fn into_sexp_unchecked(self) -> crate::SEXP {
        unsafe {
            if self.iter().all(|&x|
                        (|x: i64| x > i32::MIN as i64 && x <= i32::MAX as i64)(x)) {
                let (sexp, dst) = alloc_r_vector_unchecked::<i32>(self.len());
                for (slot, &val) in dst.iter_mut().zip(self.iter()) {
                    *slot = val as i32;
                }
                sexp
            } else {
                let (sexp, dst) = alloc_r_vector_unchecked::<f64>(self.len());
                for (slot, &val) in dst.iter_mut().zip(self.iter()) {
                    *slot = val as f64;
                }
                sexp
            }
        }
    }
}
impl IntoR for Vec<i64> {
    type Error = std::convert::Infallible;
    fn try_into_sexp(self) -> Result<crate::SEXP, Self::Error> {
        Ok(self.into_sexp())
    }
    unsafe fn try_into_sexp_unchecked(self)
        -> Result<crate::SEXP, Self::Error> {
        Ok(unsafe { self.into_sexp_unchecked() })
    }
    fn into_sexp(self) -> crate::SEXP { self.as_slice().into_sexp() }
    unsafe fn into_sexp_unchecked(self) -> crate::SEXP {
        unsafe { self.as_slice().into_sexp_unchecked() }
    }
}impl_vec_smart_i64_into_r!(i64, |x: i64| x > i32::MIN as i64 && x <= i32::MAX as i64);
690impl IntoR for &[u64] {
    type Error = std::convert::Infallible;
    fn try_into_sexp(self) -> Result<crate::SEXP, Self::Error> {
        Ok(self.into_sexp())
    }
    unsafe fn try_into_sexp_unchecked(self)
        -> Result<crate::SEXP, Self::Error> {
        Ok(unsafe { self.into_sexp_unchecked() })
    }
    fn into_sexp(self) -> crate::SEXP {
        unsafe {
            if self.iter().all(|&x| (|x: u64| x <= i32::MAX as u64)(x)) {
                let (sexp, dst) = alloc_r_vector::<i32>(self.len());
                for (slot, &val) in dst.iter_mut().zip(self.iter()) {
                    *slot = val as i32;
                }
                sexp
            } else {
                let (sexp, dst) = alloc_r_vector::<f64>(self.len());
                for (slot, &val) in dst.iter_mut().zip(self.iter()) {
                    *slot = val as f64;
                }
                sexp
            }
        }
    }
    unsafe fn into_sexp_unchecked(self) -> crate::SEXP {
        unsafe {
            if self.iter().all(|&x| (|x: u64| x <= i32::MAX as u64)(x)) {
                let (sexp, dst) = alloc_r_vector_unchecked::<i32>(self.len());
                for (slot, &val) in dst.iter_mut().zip(self.iter()) {
                    *slot = val as i32;
                }
                sexp
            } else {
                let (sexp, dst) = alloc_r_vector_unchecked::<f64>(self.len());
                for (slot, &val) in dst.iter_mut().zip(self.iter()) {
                    *slot = val as f64;
                }
                sexp
            }
        }
    }
}
impl IntoR for Vec<u64> {
    type Error = std::convert::Infallible;
    fn try_into_sexp(self) -> Result<crate::SEXP, Self::Error> {
        Ok(self.into_sexp())
    }
    unsafe fn try_into_sexp_unchecked(self)
        -> Result<crate::SEXP, Self::Error> {
        Ok(unsafe { self.into_sexp_unchecked() })
    }
    fn into_sexp(self) -> crate::SEXP { self.as_slice().into_sexp() }
    unsafe fn into_sexp_unchecked(self) -> crate::SEXP {
        unsafe { self.as_slice().into_sexp_unchecked() }
    }
}impl_vec_smart_i64_into_r!(u64, |x: u64| x <= i32::MAX as u64);
691impl IntoR for &[isize] {
    type Error = std::convert::Infallible;
    fn try_into_sexp(self) -> Result<crate::SEXP, Self::Error> {
        Ok(self.into_sexp())
    }
    unsafe fn try_into_sexp_unchecked(self)
        -> Result<crate::SEXP, Self::Error> {
        Ok(unsafe { self.into_sexp_unchecked() })
    }
    fn into_sexp(self) -> crate::SEXP {
        unsafe {
            if self.iter().all(|&x|
                        (|x: isize|
                                x > i32::MIN as isize && x <= i32::MAX as isize)(x)) {
                let (sexp, dst) = alloc_r_vector::<i32>(self.len());
                for (slot, &val) in dst.iter_mut().zip(self.iter()) {
                    *slot = val as i32;
                }
                sexp
            } else {
                let (sexp, dst) = alloc_r_vector::<f64>(self.len());
                for (slot, &val) in dst.iter_mut().zip(self.iter()) {
                    *slot = val as f64;
                }
                sexp
            }
        }
    }
    unsafe fn into_sexp_unchecked(self) -> crate::SEXP {
        unsafe {
            if self.iter().all(|&x|
                        (|x: isize|
                                x > i32::MIN as isize && x <= i32::MAX as isize)(x)) {
                let (sexp, dst) = alloc_r_vector_unchecked::<i32>(self.len());
                for (slot, &val) in dst.iter_mut().zip(self.iter()) {
                    *slot = val as i32;
                }
                sexp
            } else {
                let (sexp, dst) = alloc_r_vector_unchecked::<f64>(self.len());
                for (slot, &val) in dst.iter_mut().zip(self.iter()) {
                    *slot = val as f64;
                }
                sexp
            }
        }
    }
}
impl IntoR for Vec<isize> {
    type Error = std::convert::Infallible;
    fn try_into_sexp(self) -> Result<crate::SEXP, Self::Error> {
        Ok(self.into_sexp())
    }
    unsafe fn try_into_sexp_unchecked(self)
        -> Result<crate::SEXP, Self::Error> {
        Ok(unsafe { self.into_sexp_unchecked() })
    }
    fn into_sexp(self) -> crate::SEXP { self.as_slice().into_sexp() }
    unsafe fn into_sexp_unchecked(self) -> crate::SEXP {
        unsafe { self.as_slice().into_sexp_unchecked() }
    }
}impl_vec_smart_i64_into_r!(isize, |x: isize| x > i32::MIN as isize
692    && x <= i32::MAX as isize);
693impl IntoR for &[usize] {
    type Error = std::convert::Infallible;
    fn try_into_sexp(self) -> Result<crate::SEXP, Self::Error> {
        Ok(self.into_sexp())
    }
    unsafe fn try_into_sexp_unchecked(self)
        -> Result<crate::SEXP, Self::Error> {
        Ok(unsafe { self.into_sexp_unchecked() })
    }
    fn into_sexp(self) -> crate::SEXP {
        unsafe {
            if self.iter().all(|&x| (|x: usize| x <= i32::MAX as usize)(x)) {
                let (sexp, dst) = alloc_r_vector::<i32>(self.len());
                for (slot, &val) in dst.iter_mut().zip(self.iter()) {
                    *slot = val as i32;
                }
                sexp
            } else {
                let (sexp, dst) = alloc_r_vector::<f64>(self.len());
                for (slot, &val) in dst.iter_mut().zip(self.iter()) {
                    *slot = val as f64;
                }
                sexp
            }
        }
    }
    unsafe fn into_sexp_unchecked(self) -> crate::SEXP {
        unsafe {
            if self.iter().all(|&x| (|x: usize| x <= i32::MAX as usize)(x)) {
                let (sexp, dst) = alloc_r_vector_unchecked::<i32>(self.len());
                for (slot, &val) in dst.iter_mut().zip(self.iter()) {
                    *slot = val as i32;
                }
                sexp
            } else {
                let (sexp, dst) = alloc_r_vector_unchecked::<f64>(self.len());
                for (slot, &val) in dst.iter_mut().zip(self.iter()) {
                    *slot = val as f64;
                }
                sexp
            }
        }
    }
}
impl IntoR for Vec<usize> {
    type Error = std::convert::Infallible;
    fn try_into_sexp(self) -> Result<crate::SEXP, Self::Error> {
        Ok(self.into_sexp())
    }
    unsafe fn try_into_sexp_unchecked(self)
        -> Result<crate::SEXP, Self::Error> {
        Ok(unsafe { self.into_sexp_unchecked() })
    }
    fn into_sexp(self) -> crate::SEXP { self.as_slice().into_sexp() }
    unsafe fn into_sexp_unchecked(self) -> crate::SEXP {
        unsafe { self.as_slice().into_sexp_unchecked() }
    }
}impl_vec_smart_i64_into_r!(usize, |x: usize| x <= i32::MAX as usize);
694// Matches Vec<Option<u32>> (impl_vec_option_coerce_into_r!(u32 => i64)):
695// INTSXP while everything fits, REALSXP otherwise.
696impl IntoR for &[u32] {
    type Error = std::convert::Infallible;
    fn try_into_sexp(self) -> Result<crate::SEXP, Self::Error> {
        Ok(self.into_sexp())
    }
    unsafe fn try_into_sexp_unchecked(self)
        -> Result<crate::SEXP, Self::Error> {
        Ok(unsafe { self.into_sexp_unchecked() })
    }
    fn into_sexp(self) -> crate::SEXP {
        unsafe {
            if self.iter().all(|&x| (|x: u32| x <= i32::MAX as u32)(x)) {
                let (sexp, dst) = alloc_r_vector::<i32>(self.len());
                for (slot, &val) in dst.iter_mut().zip(self.iter()) {
                    *slot = val as i32;
                }
                sexp
            } else {
                let (sexp, dst) = alloc_r_vector::<f64>(self.len());
                for (slot, &val) in dst.iter_mut().zip(self.iter()) {
                    *slot = val as f64;
                }
                sexp
            }
        }
    }
    unsafe fn into_sexp_unchecked(self) -> crate::SEXP {
        unsafe {
            if self.iter().all(|&x| (|x: u32| x <= i32::MAX as u32)(x)) {
                let (sexp, dst) = alloc_r_vector_unchecked::<i32>(self.len());
                for (slot, &val) in dst.iter_mut().zip(self.iter()) {
                    *slot = val as i32;
                }
                sexp
            } else {
                let (sexp, dst) = alloc_r_vector_unchecked::<f64>(self.len());
                for (slot, &val) in dst.iter_mut().zip(self.iter()) {
                    *slot = val as f64;
                }
                sexp
            }
        }
    }
}
impl IntoR for Vec<u32> {
    type Error = std::convert::Infallible;
    fn try_into_sexp(self) -> Result<crate::SEXP, Self::Error> {
        Ok(self.into_sexp())
    }
    unsafe fn try_into_sexp_unchecked(self)
        -> Result<crate::SEXP, Self::Error> {
        Ok(unsafe { self.into_sexp_unchecked() })
    }
    fn into_sexp(self) -> crate::SEXP { self.as_slice().into_sexp() }
    unsafe fn into_sexp_unchecked(self) -> crate::SEXP {
        unsafe { self.as_slice().into_sexp_unchecked() }
    }
}impl_vec_smart_i64_into_r!(u32, |x: u32| x <= i32::MAX as u32);
697// endregion
698
699mod altrep;
700mod collections;
701mod owned_str;
702mod result;
703
704pub use altrep::*;
705pub use result::*;
706
707// region: Fixed-size array conversions
708
709/// Convert a fixed-size array through its borrowed slice conversion.
710///
711/// Native values, smart integers, strings and logicals keep the slice's R
712/// representation and error type, without allocating an intermediate `Vec`.
713impl<T, E, const N: usize> IntoR for [T; N]
714where
715    for<'a> &'a [T]: IntoR<Error = E>,
716    E: crate::condition::RConditionData,
717{
718    type Error = E;
719    #[inline]
720    fn try_into_sexp(self) -> Result<crate::SEXP, Self::Error> {
721        self.as_slice().try_into_sexp()
722    }
723    #[inline]
724    unsafe fn try_into_sexp_unchecked(self) -> Result<crate::SEXP, Self::Error> {
725        unsafe { self.as_slice().try_into_sexp_unchecked() }
726    }
727    #[inline]
728    fn into_sexp(self) -> crate::SEXP {
729        self.as_slice().into_sexp()
730    }
731    #[inline]
732    unsafe fn into_sexp_unchecked(self) -> crate::SEXP {
733        unsafe { self.as_slice().into_sexp_unchecked() }
734    }
735}
736
737/// Convert an optional array: `Some` uses the array conversion, `None` is NULL.
738impl<T, const N: usize> IntoR for Option<[T; N]>
739where
740    [T; N]: IntoR,
741{
742    type Error = <[T; N] as IntoR>::Error;
743    #[inline]
744    fn try_into_sexp(self) -> Result<crate::SEXP, Self::Error> {
745        match self {
746            Some(array) => array.try_into_sexp(),
747            None => Ok(crate::SEXP::nil()),
748        }
749    }
750    #[inline]
751    unsafe fn try_into_sexp_unchecked(self) -> Result<crate::SEXP, Self::Error> {
752        match self {
753            Some(array) => unsafe { array.try_into_sexp_unchecked() },
754            None => Ok(crate::SEXP::nil()),
755        }
756    }
757    #[inline]
758    unsafe fn into_sexp_unchecked(self) -> crate::SEXP {
759        match self {
760            Some(array) => unsafe { array.into_sexp_unchecked() },
761            None => crate::SEXP::nil(),
762        }
763    }
764}
765
766#[cfg(test)]
767mod tests;
768// endregion
769
770// region: VecDeque conversions
771
772use std::collections::VecDeque;
773
774/// Convert `VecDeque<T>` to R vector where T: RNativeType.
775impl<T> IntoR for VecDeque<T>
776where
777    T: crate::RNativeType,
778{
779    type Error = std::convert::Infallible;
780    fn try_into_sexp(self) -> Result<crate::SEXP, Self::Error> {
781        Ok(self.into_sexp())
782    }
783    unsafe fn try_into_sexp_unchecked(self) -> Result<crate::SEXP, Self::Error> {
784        Ok(unsafe { self.into_sexp_unchecked() })
785    }
786    fn into_sexp(self) -> crate::SEXP {
787        let vec: Vec<T> = self.into_iter().collect();
788        vec.into_sexp()
789    }
790    unsafe fn into_sexp_unchecked(self) -> crate::SEXP {
791        let vec: Vec<T> = self.into_iter().collect();
792        unsafe { vec.into_sexp_unchecked() }
793    }
794}
795// endregion
796
797// region: BinaryHeap conversions
798
799use std::collections::BinaryHeap;
800
801/// Convert `BinaryHeap<T>` to R vector where T: RNativeType + Ord.
802///
803/// The heap is drained into a vector (destroying the heap property).
804/// Elements are returned in arbitrary order, not sorted.
805impl<T> IntoR for BinaryHeap<T>
806where
807    T: crate::RNativeType + Ord,
808{
809    type Error = std::convert::Infallible;
810    fn try_into_sexp(self) -> Result<crate::SEXP, Self::Error> {
811        Ok(self.into_vec().into_sexp())
812    }
813    unsafe fn try_into_sexp_unchecked(self) -> Result<crate::SEXP, Self::Error> {
814        Ok(unsafe { self.into_sexp_unchecked() })
815    }
816    fn into_sexp(self) -> crate::SEXP {
817        self.into_vec().into_sexp()
818    }
819    unsafe fn into_sexp_unchecked(self) -> crate::SEXP {
820        unsafe { self.into_vec().into_sexp_unchecked() }
821    }
822}
823// endregion
824
825// region: Cow conversions
826
827use std::borrow::Cow;
828
829/// Convert `Cow<'_, [T]>` to R vector where T: RNativeType.
830///
831/// Always copies into a fresh R vector via the `&[T]` path. We deliberately do
832/// *not* attempt speculative SEXP pointer recovery on the `Cow::Borrowed` arm:
833/// a bare `&[T]` carries no provenance metadata, so a borrowed *sub-slice* of
834/// an R vector (e.g. `&cow[2..5]`) is indistinguishable from a full borrow by
835/// pointer + length alone. Probing `data_ptr − header` for such a sub-slice
836/// reads provenance-free memory off the start of the R vector — the same hazard
837/// removed from the Arrow path in #867 (see #880). The Arrow `Buffer` can prove
838/// it is R-backed (`ptr_offset`/`capacity`); a `&[T]` cannot, so the only sound
839/// choice is the always-correct copy. `Cow` remains zero-copy on the *input*
840/// side through `TryFromRoot` and generated wrappers; raw `TryFromSexp`
841/// returns owned data. `IntoR` always copies.
842impl<T> IntoR for Cow<'_, [T]>
843where
844    T: crate::RNativeType + Clone,
845{
846    type Error = std::convert::Infallible;
847    fn try_into_sexp(self) -> Result<crate::SEXP, Self::Error> {
848        Ok(self.into_sexp())
849    }
850    unsafe fn try_into_sexp_unchecked(self) -> Result<crate::SEXP, Self::Error> {
851        Ok(unsafe { self.into_sexp_unchecked() })
852    }
853    fn into_sexp(self) -> crate::SEXP {
854        self.as_ref().into_sexp()
855    }
856    unsafe fn into_sexp_unchecked(self) -> crate::SEXP {
857        unsafe { self.as_ref().into_sexp_unchecked() }
858    }
859}
860
861/// Convert `Cow<'_, str>` to R character scalar.
862impl IntoR for Cow<'_, str> {
863    type Error = crate::into_r_error::IntoRError;
864    #[inline]
865    fn try_into_sexp(self) -> Result<crate::SEXP, Self::Error> {
866        self.as_ref().try_into_sexp()
867    }
868    #[inline]
869    unsafe fn try_into_sexp_unchecked(self) -> Result<crate::SEXP, Self::Error> {
870        Ok(unsafe { self.into_sexp_unchecked() })
871    }
872    #[inline]
873    fn into_sexp(self) -> crate::SEXP {
874        self.as_ref().into_sexp()
875    }
876    #[inline]
877    unsafe fn into_sexp_unchecked(self) -> crate::SEXP {
878        unsafe { self.as_ref().into_sexp_unchecked() }
879    }
880}
881// endregion
882
883// region: Box conversions (skipped - conflicts with IntoExternalPtr blanket impl)
884//
885// We can't add `impl<T: IntoR> IntoR for Box<T>` because it conflicts with
886// the blanket impl `impl<T: IntoExternalPtr> IntoR for T`. If downstream
887// crates implement `IntoExternalPtr for Box<SomeType>`, we'd have overlapping
888// impls. Users can manually unbox with `*boxed_value` before conversion.
889// endregion
890
891// region: PathBuf / OsString conversions
892
893use std::ffi::OsString;
894use std::path::PathBuf;
895
896/// Generate IntoR impls for types with `to_string_lossy()` (owned scalar, ref scalar,
897/// Option, Vec, `Vec<Option>`). Used for PathBuf/&Path and OsString/&OsStr.
898macro_rules! impl_lossy_string_into_r {
899    (
900        $(#[$owned_meta:meta])*
901        owned: $owned_ty:ty;
902        $(#[$ref_meta:meta])*
903        ref: $ref_ty:ty;
904        $(#[$option_meta:meta])*
905        option: $opt_ty:ty;
906        $(#[$vec_meta:meta])*
907        vec: $vec_ty:ty;
908        $(#[$vec_option_meta:meta])*
909        vec_option: $vec_opt_ty:ty;
910    ) => {
911        $(#[$owned_meta])*
912        impl IntoR for $owned_ty {
913            type Error = crate::into_r_error::IntoRError;
914            #[inline]
915            fn try_into_sexp(self) -> Result<crate::SEXP, Self::Error> {
916                self.to_string_lossy().into_owned().try_into_sexp()
917            }
918            #[inline]
919            unsafe fn try_into_sexp_unchecked(self) -> Result<crate::SEXP, Self::Error> {
920                Ok(unsafe { self.into_sexp_unchecked() })
921            }
922            #[inline]
923            fn into_sexp(self) -> crate::SEXP {
924                self.to_string_lossy().into_owned().into_sexp()
925            }
926            #[inline]
927            unsafe fn into_sexp_unchecked(self) -> crate::SEXP {
928                unsafe { self.to_string_lossy().into_owned().into_sexp_unchecked() }
929            }
930        }
931
932        $(#[$ref_meta])*
933        impl IntoR for $ref_ty {
934            type Error = crate::into_r_error::IntoRError;
935            #[inline]
936            fn try_into_sexp(self) -> Result<crate::SEXP, Self::Error> {
937                self.to_string_lossy().into_owned().try_into_sexp()
938            }
939            #[inline]
940            unsafe fn try_into_sexp_unchecked(self) -> Result<crate::SEXP, Self::Error> {
941                Ok(unsafe { self.into_sexp_unchecked() })
942            }
943            #[inline]
944            fn into_sexp(self) -> crate::SEXP {
945                self.to_string_lossy().into_owned().into_sexp()
946            }
947            #[inline]
948            unsafe fn into_sexp_unchecked(self) -> crate::SEXP {
949                unsafe { self.to_string_lossy().into_owned().into_sexp_unchecked() }
950            }
951        }
952
953        $(#[$option_meta])*
954        impl IntoR for Option<$owned_ty> {
955            type Error = crate::into_r_error::IntoRError;
956            #[inline]
957            fn try_into_sexp(self) -> Result<crate::SEXP, Self::Error> {
958                self.map(|v| v.to_string_lossy().into_owned()).try_into_sexp()
959            }
960            #[inline]
961            unsafe fn try_into_sexp_unchecked(self) -> Result<crate::SEXP, Self::Error> {
962                Ok(unsafe { self.into_sexp_unchecked() })
963            }
964            #[inline]
965            fn into_sexp(self) -> crate::SEXP {
966                self.map(|v| v.to_string_lossy().into_owned()).into_sexp()
967            }
968            #[inline]
969            unsafe fn into_sexp_unchecked(self) -> crate::SEXP {
970                unsafe {
971                    self.map(|v| v.to_string_lossy().into_owned())
972                        .into_sexp_unchecked()
973                }
974            }
975        }
976
977        $(#[$vec_meta])*
978        impl IntoR for Vec<$owned_ty> {
979            type Error = crate::into_r_error::IntoRError;
980            fn try_into_sexp(self) -> Result<crate::SEXP, Self::Error> {
981                Ok(self.into_sexp())
982            }
983            unsafe fn try_into_sexp_unchecked(self) -> Result<crate::SEXP, Self::Error> {
984                Ok(unsafe { self.into_sexp_unchecked() })
985            }
986            fn into_sexp(self) -> crate::SEXP {
987                let strings: Vec<String> = self
988                    .into_iter()
989                    .map(|v| v.to_string_lossy().into_owned())
990                    .collect();
991                strings.into_sexp()
992            }
993            unsafe fn into_sexp_unchecked(self) -> crate::SEXP {
994                let strings: Vec<String> = self
995                    .into_iter()
996                    .map(|v| v.to_string_lossy().into_owned())
997                    .collect();
998                unsafe { strings.into_sexp_unchecked() }
999            }
1000        }
1001
1002        $(#[$vec_option_meta])*
1003        impl IntoR for Vec<Option<$owned_ty>> {
1004            type Error = crate::into_r_error::IntoRError;
1005            fn try_into_sexp(self) -> Result<crate::SEXP, Self::Error> {
1006                Ok(self.into_sexp())
1007            }
1008            unsafe fn try_into_sexp_unchecked(self) -> Result<crate::SEXP, Self::Error> {
1009                Ok(unsafe { self.into_sexp_unchecked() })
1010            }
1011            fn into_sexp(self) -> crate::SEXP {
1012                let strings: Vec<Option<String>> = self
1013                    .into_iter()
1014                    .map(|opt| opt.map(|v| v.to_string_lossy().into_owned()))
1015                    .collect();
1016                strings.into_sexp()
1017            }
1018            unsafe fn into_sexp_unchecked(self) -> crate::SEXP {
1019                let strings: Vec<Option<String>> = self
1020                    .into_iter()
1021                    .map(|opt| opt.map(|v| v.to_string_lossy().into_owned()))
1022                    .collect();
1023                unsafe { strings.into_sexp_unchecked() }
1024            }
1025        }
1026    };
1027}
1028
1029#[doc = r" Convert `PathBuf` to R character scalar."]
#[doc = r""]
#[doc = r" On Unix, paths that are not valid UTF-8 will produce lossy output"]
#[doc = r" (invalid sequences replaced with U+FFFD)."]
impl IntoR for PathBuf {
    type Error = crate::into_r_error::IntoRError;
    #[inline]
    fn try_into_sexp(self) -> Result<crate::SEXP, Self::Error> {
        self.to_string_lossy().into_owned().try_into_sexp()
    }
    #[inline]
    unsafe fn try_into_sexp_unchecked(self)
        -> Result<crate::SEXP, Self::Error> {
        Ok(unsafe { self.into_sexp_unchecked() })
    }
    #[inline]
    fn into_sexp(self) -> crate::SEXP {
        self.to_string_lossy().into_owned().into_sexp()
    }
    #[inline]
    unsafe fn into_sexp_unchecked(self) -> crate::SEXP {
        unsafe { self.to_string_lossy().into_owned().into_sexp_unchecked() }
    }
}
#[doc = r" Convert `&Path` to R character scalar."]
impl IntoR for &std::path::Path {
    type Error = crate::into_r_error::IntoRError;
    #[inline]
    fn try_into_sexp(self) -> Result<crate::SEXP, Self::Error> {
        self.to_string_lossy().into_owned().try_into_sexp()
    }
    #[inline]
    unsafe fn try_into_sexp_unchecked(self)
        -> Result<crate::SEXP, Self::Error> {
        Ok(unsafe { self.into_sexp_unchecked() })
    }
    #[inline]
    fn into_sexp(self) -> crate::SEXP {
        self.to_string_lossy().into_owned().into_sexp()
    }
    #[inline]
    unsafe fn into_sexp_unchecked(self) -> crate::SEXP {
        unsafe { self.to_string_lossy().into_owned().into_sexp_unchecked() }
    }
}
#[doc =
r" Convert `Option<PathBuf>` to R: Some(path) -> character, None -> NA_character_."]
impl IntoR for Option<PathBuf> {
    type Error = crate::into_r_error::IntoRError;
    #[inline]
    fn try_into_sexp(self) -> Result<crate::SEXP, Self::Error> {
        self.map(|v| v.to_string_lossy().into_owned()).try_into_sexp()
    }
    #[inline]
    unsafe fn try_into_sexp_unchecked(self)
        -> Result<crate::SEXP, Self::Error> {
        Ok(unsafe { self.into_sexp_unchecked() })
    }
    #[inline]
    fn into_sexp(self) -> crate::SEXP {
        self.map(|v| v.to_string_lossy().into_owned()).into_sexp()
    }
    #[inline]
    unsafe fn into_sexp_unchecked(self) -> crate::SEXP {
        unsafe {
            self.map(|v|
                        v.to_string_lossy().into_owned()).into_sexp_unchecked()
        }
    }
}
#[doc = r" Convert `Vec<PathBuf>` to R character vector."]
impl IntoR for Vec<PathBuf> {
    type Error = crate::into_r_error::IntoRError;
    fn try_into_sexp(self) -> Result<crate::SEXP, Self::Error> {
        Ok(self.into_sexp())
    }
    unsafe fn try_into_sexp_unchecked(self)
        -> Result<crate::SEXP, Self::Error> {
        Ok(unsafe { self.into_sexp_unchecked() })
    }
    fn into_sexp(self) -> crate::SEXP {
        let strings: Vec<String> =
            self.into_iter().map(|v|
                        v.to_string_lossy().into_owned()).collect();
        strings.into_sexp()
    }
    unsafe fn into_sexp_unchecked(self) -> crate::SEXP {
        let strings: Vec<String> =
            self.into_iter().map(|v|
                        v.to_string_lossy().into_owned()).collect();
        unsafe { strings.into_sexp_unchecked() }
    }
}
#[doc =
r" Convert `Vec<Option<PathBuf>>` to R character vector with NA support."]
impl IntoR for Vec<Option<PathBuf>> {
    type Error = crate::into_r_error::IntoRError;
    fn try_into_sexp(self) -> Result<crate::SEXP, Self::Error> {
        Ok(self.into_sexp())
    }
    unsafe fn try_into_sexp_unchecked(self)
        -> Result<crate::SEXP, Self::Error> {
        Ok(unsafe { self.into_sexp_unchecked() })
    }
    fn into_sexp(self) -> crate::SEXP {
        let strings: Vec<Option<String>> =
            self.into_iter().map(|opt|
                        opt.map(|v| v.to_string_lossy().into_owned())).collect();
        strings.into_sexp()
    }
    unsafe fn into_sexp_unchecked(self) -> crate::SEXP {
        let strings: Vec<Option<String>> =
            self.into_iter().map(|opt|
                        opt.map(|v| v.to_string_lossy().into_owned())).collect();
        unsafe { strings.into_sexp_unchecked() }
    }
}impl_lossy_string_into_r!(
1030    /// Convert `PathBuf` to R character scalar.
1031    ///
1032    /// On Unix, paths that are not valid UTF-8 will produce lossy output
1033    /// (invalid sequences replaced with U+FFFD).
1034    owned: PathBuf;
1035    /// Convert `&Path` to R character scalar.
1036    ref: &std::path::Path;
1037    /// Convert `Option<PathBuf>` to R: Some(path) -> character, None -> NA_character_.
1038    option: PathBuf;
1039    /// Convert `Vec<PathBuf>` to R character vector.
1040    vec: PathBuf;
1041    /// Convert `Vec<Option<PathBuf>>` to R character vector with NA support.
1042    vec_option: PathBuf;
1043);
1044
1045#[doc = r" Convert `OsString` to R character scalar."]
#[doc = r""]
#[doc =
r" On Unix, strings that are not valid UTF-8 will produce lossy output"]
#[doc = r" (invalid sequences replaced with U+FFFD)."]
impl IntoR for OsString {
    type Error = crate::into_r_error::IntoRError;
    #[inline]
    fn try_into_sexp(self) -> Result<crate::SEXP, Self::Error> {
        self.to_string_lossy().into_owned().try_into_sexp()
    }
    #[inline]
    unsafe fn try_into_sexp_unchecked(self)
        -> Result<crate::SEXP, Self::Error> {
        Ok(unsafe { self.into_sexp_unchecked() })
    }
    #[inline]
    fn into_sexp(self) -> crate::SEXP {
        self.to_string_lossy().into_owned().into_sexp()
    }
    #[inline]
    unsafe fn into_sexp_unchecked(self) -> crate::SEXP {
        unsafe { self.to_string_lossy().into_owned().into_sexp_unchecked() }
    }
}
#[doc = r" Convert `&OsStr` to R character scalar."]
impl IntoR for &std::ffi::OsStr {
    type Error = crate::into_r_error::IntoRError;
    #[inline]
    fn try_into_sexp(self) -> Result<crate::SEXP, Self::Error> {
        self.to_string_lossy().into_owned().try_into_sexp()
    }
    #[inline]
    unsafe fn try_into_sexp_unchecked(self)
        -> Result<crate::SEXP, Self::Error> {
        Ok(unsafe { self.into_sexp_unchecked() })
    }
    #[inline]
    fn into_sexp(self) -> crate::SEXP {
        self.to_string_lossy().into_owned().into_sexp()
    }
    #[inline]
    unsafe fn into_sexp_unchecked(self) -> crate::SEXP {
        unsafe { self.to_string_lossy().into_owned().into_sexp_unchecked() }
    }
}
#[doc =
r" Convert `Option<OsString>` to R: Some(s) -> character, None -> NA_character_."]
impl IntoR for Option<OsString> {
    type Error = crate::into_r_error::IntoRError;
    #[inline]
    fn try_into_sexp(self) -> Result<crate::SEXP, Self::Error> {
        self.map(|v| v.to_string_lossy().into_owned()).try_into_sexp()
    }
    #[inline]
    unsafe fn try_into_sexp_unchecked(self)
        -> Result<crate::SEXP, Self::Error> {
        Ok(unsafe { self.into_sexp_unchecked() })
    }
    #[inline]
    fn into_sexp(self) -> crate::SEXP {
        self.map(|v| v.to_string_lossy().into_owned()).into_sexp()
    }
    #[inline]
    unsafe fn into_sexp_unchecked(self) -> crate::SEXP {
        unsafe {
            self.map(|v|
                        v.to_string_lossy().into_owned()).into_sexp_unchecked()
        }
    }
}
#[doc = r" Convert `Vec<OsString>` to R character vector."]
impl IntoR for Vec<OsString> {
    type Error = crate::into_r_error::IntoRError;
    fn try_into_sexp(self) -> Result<crate::SEXP, Self::Error> {
        Ok(self.into_sexp())
    }
    unsafe fn try_into_sexp_unchecked(self)
        -> Result<crate::SEXP, Self::Error> {
        Ok(unsafe { self.into_sexp_unchecked() })
    }
    fn into_sexp(self) -> crate::SEXP {
        let strings: Vec<String> =
            self.into_iter().map(|v|
                        v.to_string_lossy().into_owned()).collect();
        strings.into_sexp()
    }
    unsafe fn into_sexp_unchecked(self) -> crate::SEXP {
        let strings: Vec<String> =
            self.into_iter().map(|v|
                        v.to_string_lossy().into_owned()).collect();
        unsafe { strings.into_sexp_unchecked() }
    }
}
#[doc =
r" Convert `Vec<Option<OsString>>` to R character vector with NA support."]
impl IntoR for Vec<Option<OsString>> {
    type Error = crate::into_r_error::IntoRError;
    fn try_into_sexp(self) -> Result<crate::SEXP, Self::Error> {
        Ok(self.into_sexp())
    }
    unsafe fn try_into_sexp_unchecked(self)
        -> Result<crate::SEXP, Self::Error> {
        Ok(unsafe { self.into_sexp_unchecked() })
    }
    fn into_sexp(self) -> crate::SEXP {
        let strings: Vec<Option<String>> =
            self.into_iter().map(|opt|
                        opt.map(|v| v.to_string_lossy().into_owned())).collect();
        strings.into_sexp()
    }
    unsafe fn into_sexp_unchecked(self) -> crate::SEXP {
        let strings: Vec<Option<String>> =
            self.into_iter().map(|opt|
                        opt.map(|v| v.to_string_lossy().into_owned())).collect();
        unsafe { strings.into_sexp_unchecked() }
    }
}impl_lossy_string_into_r!(
1046    /// Convert `OsString` to R character scalar.
1047    ///
1048    /// On Unix, strings that are not valid UTF-8 will produce lossy output
1049    /// (invalid sequences replaced with U+FFFD).
1050    owned: OsString;
1051    /// Convert `&OsStr` to R character scalar.
1052    ref: &std::ffi::OsStr;
1053    /// Convert `Option<OsString>` to R: Some(s) -> character, None -> NA_character_.
1054    option: OsString;
1055    /// Convert `Vec<OsString>` to R character vector.
1056    vec: OsString;
1057    /// Convert `Vec<Option<OsString>>` to R character vector with NA support.
1058    vec_option: OsString;
1059);
1060// endregion
1061
1062// region: Set coercion for non-native types (i8, i16, u16 → i32)
1063
1064/// Macro for `HashSet<T>`/`BTreeSet<T>` where `T` coerces to i32 (R's native integer type).
1065macro_rules! impl_set_coerce_into_r {
1066    ($from:ty) => {
1067        impl IntoR for HashSet<$from> {
1068            type Error = std::convert::Infallible;
1069            fn try_into_sexp(self) -> Result<crate::SEXP, Self::Error> {
1070                Ok(self.into_sexp())
1071            }
1072            unsafe fn try_into_sexp_unchecked(self) -> Result<crate::SEXP, Self::Error> {
1073                self.try_into_sexp()
1074            }
1075            fn into_sexp(self) -> crate::SEXP {
1076                let vec: Vec<i32> = self.into_iter().map(|x| i32::from(x)).collect();
1077                vec.into_sexp()
1078            }
1079        }
1080
1081        impl IntoR for BTreeSet<$from> {
1082            type Error = std::convert::Infallible;
1083            fn try_into_sexp(self) -> Result<crate::SEXP, Self::Error> {
1084                Ok(self.into_sexp())
1085            }
1086            unsafe fn try_into_sexp_unchecked(self) -> Result<crate::SEXP, Self::Error> {
1087                self.try_into_sexp()
1088            }
1089            fn into_sexp(self) -> crate::SEXP {
1090                let vec: Vec<i32> = self.into_iter().map(|x| i32::from(x)).collect();
1091                vec.into_sexp()
1092            }
1093        }
1094    };
1095}
1096
1097// Sub-i32 integer types in sets coerce to i32 (R's INTSXP)
1098impl IntoR for HashSet<i8> {
    type Error = std::convert::Infallible;
    fn try_into_sexp(self) -> Result<crate::SEXP, Self::Error> {
        Ok(self.into_sexp())
    }
    unsafe fn try_into_sexp_unchecked(self)
        -> Result<crate::SEXP, Self::Error> {
        self.try_into_sexp()
    }
    fn into_sexp(self) -> crate::SEXP {
        let vec: Vec<i32> = self.into_iter().map(|x| i32::from(x)).collect();
        vec.into_sexp()
    }
}
impl IntoR for BTreeSet<i8> {
    type Error = std::convert::Infallible;
    fn try_into_sexp(self) -> Result<crate::SEXP, Self::Error> {
        Ok(self.into_sexp())
    }
    unsafe fn try_into_sexp_unchecked(self)
        -> Result<crate::SEXP, Self::Error> {
        self.try_into_sexp()
    }
    fn into_sexp(self) -> crate::SEXP {
        let vec: Vec<i32> = self.into_iter().map(|x| i32::from(x)).collect();
        vec.into_sexp()
    }
}impl_set_coerce_into_r!(i8);
1099impl IntoR for HashSet<i16> {
    type Error = std::convert::Infallible;
    fn try_into_sexp(self) -> Result<crate::SEXP, Self::Error> {
        Ok(self.into_sexp())
    }
    unsafe fn try_into_sexp_unchecked(self)
        -> Result<crate::SEXP, Self::Error> {
        self.try_into_sexp()
    }
    fn into_sexp(self) -> crate::SEXP {
        let vec: Vec<i32> = self.into_iter().map(|x| i32::from(x)).collect();
        vec.into_sexp()
    }
}
impl IntoR for BTreeSet<i16> {
    type Error = std::convert::Infallible;
    fn try_into_sexp(self) -> Result<crate::SEXP, Self::Error> {
        Ok(self.into_sexp())
    }
    unsafe fn try_into_sexp_unchecked(self)
        -> Result<crate::SEXP, Self::Error> {
        self.try_into_sexp()
    }
    fn into_sexp(self) -> crate::SEXP {
        let vec: Vec<i32> = self.into_iter().map(|x| i32::from(x)).collect();
        vec.into_sexp()
    }
}impl_set_coerce_into_r!(i16);
1100impl IntoR for HashSet<u16> {
    type Error = std::convert::Infallible;
    fn try_into_sexp(self) -> Result<crate::SEXP, Self::Error> {
        Ok(self.into_sexp())
    }
    unsafe fn try_into_sexp_unchecked(self)
        -> Result<crate::SEXP, Self::Error> {
        self.try_into_sexp()
    }
    fn into_sexp(self) -> crate::SEXP {
        let vec: Vec<i32> = self.into_iter().map(|x| i32::from(x)).collect();
        vec.into_sexp()
    }
}
impl IntoR for BTreeSet<u16> {
    type Error = std::convert::Infallible;
    fn try_into_sexp(self) -> Result<crate::SEXP, Self::Error> {
        Ok(self.into_sexp())
    }
    unsafe fn try_into_sexp_unchecked(self)
        -> Result<crate::SEXP, Self::Error> {
        self.try_into_sexp()
    }
    fn into_sexp(self) -> crate::SEXP {
        let vec: Vec<i32> = self.into_iter().map(|x| i32::from(x)).collect();
        vec.into_sexp()
    }
}impl_set_coerce_into_r!(u16);
1101// endregion
1102
1103// region: Option<Collection> conversions
1104//
1105// These return NULL (R_NilValue) for None, and the converted collection for Some.
1106// This differs from Option<scalar> which returns NA for None.
1107
1108/// Convert `Option<Vec<T>>` to R: `Some(vec)` → the R vector `Vec<T>`
1109/// produces, `None` → NULL, for every `T` with a `Vec<T>: IntoR` conversion.
1110impl<T> IntoR for Option<Vec<T>>
1111where
1112    Vec<T>: IntoR,
1113{
1114    type Error = <Vec<T> as IntoR>::Error;
1115    #[inline]
1116    fn try_into_sexp(self) -> Result<crate::SEXP, Self::Error> {
1117        match self {
1118            Some(v) => v.try_into_sexp(),
1119            None => Ok(crate::SEXP::nil()),
1120        }
1121    }
1122    #[inline]
1123    unsafe fn try_into_sexp_unchecked(self) -> Result<crate::SEXP, Self::Error> {
1124        match self {
1125            Some(v) => unsafe { v.try_into_sexp_unchecked() },
1126            None => Ok(crate::SEXP::nil()),
1127        }
1128    }
1129    #[inline]
1130    fn into_sexp(self) -> crate::SEXP {
1131        match self {
1132            Some(v) => v.into_sexp(),
1133            None => crate::SEXP::nil(),
1134        }
1135    }
1136    #[inline]
1137    unsafe fn into_sexp_unchecked(self) -> crate::SEXP {
1138        match self {
1139            Some(v) => unsafe { v.into_sexp_unchecked() },
1140            None => crate::SEXP::nil(),
1141        }
1142    }
1143}
1144
1145/// Convert `Option<Box<[T]>>` to R exactly as `Option<Vec<T>>` (`into_vec()`
1146/// is an O(1) widen): `Some` → the R vector `Vec<T>` produces, `None` → NULL.
1147impl<T> IntoR for Option<Box<[T]>>
1148where
1149    Vec<T>: IntoR,
1150{
1151    type Error = <Vec<T> as IntoR>::Error;
1152    #[inline]
1153    fn try_into_sexp(self) -> Result<crate::SEXP, Self::Error> {
1154        self.map(<[T]>::into_vec).try_into_sexp()
1155    }
1156    #[inline]
1157    unsafe fn try_into_sexp_unchecked(self) -> Result<crate::SEXP, Self::Error> {
1158        unsafe { self.map(<[T]>::into_vec).try_into_sexp_unchecked() }
1159    }
1160    #[inline]
1161    fn into_sexp(self) -> crate::SEXP {
1162        self.map(<[T]>::into_vec).into_sexp()
1163    }
1164    #[inline]
1165    unsafe fn into_sexp_unchecked(self) -> crate::SEXP {
1166        unsafe { self.map(<[T]>::into_vec).into_sexp_unchecked() }
1167    }
1168}
1169
1170/// Convert `Option<&[T]>` to R as the slice converts: `Some` → the R vector
1171/// `&[T]` produces, `None` → NULL.
1172impl<'a, T> IntoR for Option<&'a [T]>
1173where
1174    &'a [T]: IntoR,
1175{
1176    type Error = <&'a [T] as IntoR>::Error;
1177    #[inline]
1178    fn try_into_sexp(self) -> Result<crate::SEXP, Self::Error> {
1179        match self {
1180            Some(v) => v.try_into_sexp(),
1181            None => Ok(crate::SEXP::nil()),
1182        }
1183    }
1184    #[inline]
1185    unsafe fn try_into_sexp_unchecked(self) -> Result<crate::SEXP, Self::Error> {
1186        match self {
1187            Some(v) => unsafe { v.try_into_sexp_unchecked() },
1188            None => Ok(crate::SEXP::nil()),
1189        }
1190    }
1191    #[inline]
1192    fn into_sexp(self) -> crate::SEXP {
1193        match self {
1194            Some(v) => v.into_sexp(),
1195            None => crate::SEXP::nil(),
1196        }
1197    }
1198    #[inline]
1199    unsafe fn into_sexp_unchecked(self) -> crate::SEXP {
1200        match self {
1201            Some(v) => unsafe { v.into_sexp_unchecked() },
1202            None => crate::SEXP::nil(),
1203        }
1204    }
1205}
1206
1207/// Convert `Option<HashMap<String, V>>` to R: Some(map) -> named list, None -> NULL.
1208impl<V: IntoR> IntoR for Option<HashMap<String, V>> {
1209    type Error = crate::into_r_error::IntoRError;
1210    #[inline]
1211    fn try_into_sexp(self) -> Result<crate::SEXP, Self::Error> {
1212        Ok(self.into_sexp())
1213    }
1214    #[inline]
1215    unsafe fn try_into_sexp_unchecked(self) -> Result<crate::SEXP, Self::Error> {
1216        Ok(unsafe { self.into_sexp_unchecked() })
1217    }
1218    #[inline]
1219    fn into_sexp(self) -> crate::SEXP {
1220        match self {
1221            Some(v) => v.into_sexp(),
1222            None => crate::SEXP::nil(),
1223        }
1224    }
1225    #[inline]
1226    unsafe fn into_sexp_unchecked(self) -> crate::SEXP {
1227        match self {
1228            Some(v) => unsafe { v.into_sexp_unchecked() },
1229            None => crate::SEXP::nil(),
1230        }
1231    }
1232}
1233
1234/// Convert `Option<BTreeMap<String, V>>` to R: Some(map) -> named list, None -> NULL.
1235impl<V: IntoR> IntoR for Option<BTreeMap<String, V>> {
1236    type Error = crate::into_r_error::IntoRError;
1237    #[inline]
1238    fn try_into_sexp(self) -> Result<crate::SEXP, Self::Error> {
1239        Ok(self.into_sexp())
1240    }
1241    #[inline]
1242    unsafe fn try_into_sexp_unchecked(self) -> Result<crate::SEXP, Self::Error> {
1243        Ok(unsafe { self.into_sexp_unchecked() })
1244    }
1245    #[inline]
1246    fn into_sexp(self) -> crate::SEXP {
1247        match self {
1248            Some(v) => v.into_sexp(),
1249            None => crate::SEXP::nil(),
1250        }
1251    }
1252    #[inline]
1253    unsafe fn into_sexp_unchecked(self) -> crate::SEXP {
1254        match self {
1255            Some(v) => unsafe { v.into_sexp_unchecked() },
1256            None => crate::SEXP::nil(),
1257        }
1258    }
1259}
1260
1261/// Convert `Option<HashSet<T>>` to R: Some(set) -> vector, None -> NULL.
1262impl<T: crate::RNativeType + Eq + Hash> IntoR for Option<HashSet<T>> {
1263    type Error = std::convert::Infallible;
1264    #[inline]
1265    fn try_into_sexp(self) -> Result<crate::SEXP, Self::Error> {
1266        Ok(self.into_sexp())
1267    }
1268    #[inline]
1269    unsafe fn try_into_sexp_unchecked(self) -> Result<crate::SEXP, Self::Error> {
1270        Ok(unsafe { self.into_sexp_unchecked() })
1271    }
1272    #[inline]
1273    fn into_sexp(self) -> crate::SEXP {
1274        match self {
1275            Some(v) => v.into_sexp(),
1276            None => crate::SEXP::nil(),
1277        }
1278    }
1279    #[inline]
1280    unsafe fn into_sexp_unchecked(self) -> crate::SEXP {
1281        match self {
1282            Some(v) => unsafe { v.into_sexp_unchecked() },
1283            None => crate::SEXP::nil(),
1284        }
1285    }
1286}
1287
1288/// Convert `Option<BTreeSet<T>>` to R: Some(set) -> vector, None -> NULL.
1289impl<T: crate::RNativeType + Ord> IntoR for Option<BTreeSet<T>> {
1290    type Error = std::convert::Infallible;
1291    #[inline]
1292    fn try_into_sexp(self) -> Result<crate::SEXP, Self::Error> {
1293        Ok(self.into_sexp())
1294    }
1295    #[inline]
1296    unsafe fn try_into_sexp_unchecked(self) -> Result<crate::SEXP, Self::Error> {
1297        Ok(unsafe { self.into_sexp_unchecked() })
1298    }
1299    #[inline]
1300    fn into_sexp(self) -> crate::SEXP {
1301        match self {
1302            Some(v) => v.into_sexp(),
1303            None => crate::SEXP::nil(),
1304        }
1305    }
1306    #[inline]
1307    unsafe fn into_sexp_unchecked(self) -> crate::SEXP {
1308        match self {
1309            Some(v) => unsafe { v.into_sexp_unchecked() },
1310            None => crate::SEXP::nil(),
1311        }
1312    }
1313}
1314
1315macro_rules! impl_option_collection_into_r {
1316    ($(#[$meta:meta])* $ty:ty) => {
1317        $(#[$meta])*
1318        impl IntoR for Option<$ty> {
1319            type Error = crate::into_r_error::IntoRError;
1320            #[inline]
1321            fn try_into_sexp(self) -> Result<crate::SEXP, Self::Error> {
1322                Ok(self.into_sexp())
1323            }
1324            #[inline]
1325            unsafe fn try_into_sexp_unchecked(self) -> Result<crate::SEXP, Self::Error> {
1326                Ok(unsafe { self.into_sexp_unchecked() })
1327            }
1328            #[inline]
1329            fn into_sexp(self) -> crate::SEXP {
1330                match self {
1331                    Some(v) => v.into_sexp(),
1332                    None => crate::SEXP::nil(),
1333                }
1334            }
1335            #[inline]
1336            unsafe fn into_sexp_unchecked(self) -> crate::SEXP {
1337                match self {
1338                    Some(v) => unsafe { v.into_sexp_unchecked() },
1339                    None => crate::SEXP::nil(),
1340                }
1341            }
1342        }
1343    };
1344}
1345
1346#[doc =
r" Convert `Option<HashSet<String>>` to R: Some(set) -> character vector, None -> NULL."]
impl IntoR for Option<HashSet<String>> {
    type Error = crate::into_r_error::IntoRError;
    #[inline]
    fn try_into_sexp(self) -> Result<crate::SEXP, Self::Error> {
        Ok(self.into_sexp())
    }
    #[inline]
    unsafe fn try_into_sexp_unchecked(self)
        -> Result<crate::SEXP, Self::Error> {
        Ok(unsafe { self.into_sexp_unchecked() })
    }
    #[inline]
    fn into_sexp(self) -> crate::SEXP {
        match self { Some(v) => v.into_sexp(), None => crate::SEXP::nil(), }
    }
    #[inline]
    unsafe fn into_sexp_unchecked(self) -> crate::SEXP {
        match self {
            Some(v) => unsafe { v.into_sexp_unchecked() },
            None => crate::SEXP::nil(),
        }
    }
}impl_option_collection_into_r!(
1347    /// Convert `Option<HashSet<String>>` to R: Some(set) -> character vector, None -> NULL.
1348    HashSet<String>
1349);
1350#[doc =
r" Convert `Option<BTreeSet<String>>` to R: Some(set) -> character vector, None -> NULL."]
impl IntoR for Option<BTreeSet<String>> {
    type Error = crate::into_r_error::IntoRError;
    #[inline]
    fn try_into_sexp(self) -> Result<crate::SEXP, Self::Error> {
        Ok(self.into_sexp())
    }
    #[inline]
    unsafe fn try_into_sexp_unchecked(self)
        -> Result<crate::SEXP, Self::Error> {
        Ok(unsafe { self.into_sexp_unchecked() })
    }
    #[inline]
    fn into_sexp(self) -> crate::SEXP {
        match self { Some(v) => v.into_sexp(), None => crate::SEXP::nil(), }
    }
    #[inline]
    unsafe fn into_sexp_unchecked(self) -> crate::SEXP {
        match self {
            Some(v) => unsafe { v.into_sexp_unchecked() },
            None => crate::SEXP::nil(),
        }
    }
}impl_option_collection_into_r!(
1351    /// Convert `Option<BTreeSet<String>>` to R: Some(set) -> character vector, None -> NULL.
1352    BTreeSet<String>
1353);
1354
1355/// Helper: allocate STRSXP and fill from a string iterator (checked).
1356///
1357/// Routes the alloc + protect through [`StrVecBuilder`] over a local
1358/// [`ProtectScope`]; the CHARSXP policy (empty-string → `R_BlankString`) stays
1359/// here via [`str_to_charsxp`].
1360pub(crate) fn str_iter_to_strsxp<'a>(iter: impl ExactSizeIterator<Item = &'a str>) -> crate::SEXP {
1361    unsafe {
1362        let scope = ProtectScope::new();
1363        let builder = StrVecBuilder::new(&scope, iter.len());
1364        let vec = builder.as_sexp();
1365        for (i, s) in iter.enumerate() {
1366            vec.set_string_elt(i as isize, str_to_charsxp(s));
1367        }
1368        builder.into_sexp()
1369    }
1370}
1371
1372/// Helper: allocate STRSXP and fill from a string iterator (unchecked).
1373pub(crate) unsafe fn str_iter_to_strsxp_unchecked<'a>(
1374    iter: impl ExactSizeIterator<Item = &'a str>,
1375) -> crate::SEXP {
1376    unsafe {
1377        let scope = ProtectScope::new();
1378        let builder = StrVecBuilder::new_unchecked(&scope, iter.len());
1379        let vec = builder.as_sexp();
1380        for (i, s) in iter.enumerate() {
1381            vec.set_string_elt_unchecked(i as isize, str_to_charsxp_unchecked(s));
1382        }
1383        builder.into_sexp()
1384    }
1385}
1386
1387/// Helper: allocate STRSXP and fill from an optional-string iterator (checked).
1388///
1389/// `None` becomes `NA_character_`. Shared by the `Vec<Option<…str>>` impls.
1390pub(crate) fn opt_str_iter_to_strsxp<'a>(
1391    iter: impl ExactSizeIterator<Item = Option<&'a str>>,
1392) -> crate::SEXP {
1393    unsafe {
1394        let scope = ProtectScope::new();
1395        let builder = StrVecBuilder::new(&scope, iter.len());
1396        let vec = builder.as_sexp();
1397        for (i, opt_s) in iter.enumerate() {
1398            let charsxp = match opt_s {
1399                Some(s) => str_to_charsxp(s),
1400                None => crate::SEXP::na_string(),
1401            };
1402            vec.set_string_elt(i as isize, charsxp);
1403        }
1404        builder.into_sexp()
1405    }
1406}
1407
1408/// Helper: allocate STRSXP and fill from an optional-string iterator (unchecked).
1409pub(crate) unsafe fn opt_str_iter_to_strsxp_unchecked<'a>(
1410    iter: impl ExactSizeIterator<Item = Option<&'a str>>,
1411) -> crate::SEXP {
1412    unsafe {
1413        let scope = ProtectScope::new();
1414        let builder = StrVecBuilder::new_unchecked(&scope, iter.len());
1415        let vec = builder.as_sexp();
1416        for (i, opt_s) in iter.enumerate() {
1417            let charsxp = match opt_s {
1418                Some(s) => str_to_charsxp_unchecked(s),
1419                None => crate::SEXP::na_string(),
1420            };
1421            vec.set_string_elt_unchecked(i as isize, charsxp);
1422        }
1423        builder.into_sexp()
1424    }
1425}
1426
1427/// Convert `Vec<String>` to R character vector (STRSXP).
1428impl IntoR for Vec<String> {
1429    type Error = std::convert::Infallible;
1430    fn try_into_sexp(self) -> Result<crate::SEXP, Self::Error> {
1431        Ok(self.into_sexp())
1432    }
1433    unsafe fn try_into_sexp_unchecked(self) -> Result<crate::SEXP, Self::Error> {
1434        Ok(unsafe { self.into_sexp_unchecked() })
1435    }
1436    fn into_sexp(self) -> crate::SEXP {
1437        str_iter_to_strsxp(self.iter().map(|s| s.as_str()))
1438    }
1439
1440    unsafe fn into_sexp_unchecked(self) -> crate::SEXP {
1441        unsafe { str_iter_to_strsxp_unchecked(self.iter().map(|s| s.as_str())) }
1442    }
1443}
1444
1445/// Convert `&[String]` to R character vector (STRSXP).
1446impl IntoR for &[String] {
1447    type Error = std::convert::Infallible;
1448    fn try_into_sexp(self) -> Result<crate::SEXP, Self::Error> {
1449        Ok(self.into_sexp())
1450    }
1451    unsafe fn try_into_sexp_unchecked(self) -> Result<crate::SEXP, Self::Error> {
1452        Ok(unsafe { self.into_sexp_unchecked() })
1453    }
1454    fn into_sexp(self) -> crate::SEXP {
1455        str_iter_to_strsxp(self.iter().map(|s| s.as_str()))
1456    }
1457
1458    unsafe fn into_sexp_unchecked(self) -> crate::SEXP {
1459        unsafe { str_iter_to_strsxp_unchecked(self.iter().map(|s| s.as_str())) }
1460    }
1461}
1462
1463/// Convert &[&str] to R character vector (STRSXP).
1464impl IntoR for &[&str] {
1465    type Error = std::convert::Infallible;
1466    fn try_into_sexp(self) -> Result<crate::SEXP, Self::Error> {
1467        Ok(self.into_sexp())
1468    }
1469    unsafe fn try_into_sexp_unchecked(self) -> Result<crate::SEXP, Self::Error> {
1470        Ok(unsafe { self.into_sexp_unchecked() })
1471    }
1472    fn into_sexp(self) -> crate::SEXP {
1473        str_iter_to_strsxp(self.iter().copied())
1474    }
1475
1476    unsafe fn into_sexp_unchecked(self) -> crate::SEXP {
1477        unsafe { str_iter_to_strsxp_unchecked(self.iter().copied()) }
1478    }
1479}
1480
1481/// Convert `Vec<Cow<'_, str>>` to R character vector (STRSXP).
1482impl IntoR for Vec<std::borrow::Cow<'_, str>> {
1483    type Error = std::convert::Infallible;
1484    fn try_into_sexp(self) -> Result<crate::SEXP, Self::Error> {
1485        Ok(self.into_sexp())
1486    }
1487    unsafe fn try_into_sexp_unchecked(self) -> Result<crate::SEXP, Self::Error> {
1488        Ok(unsafe { self.into_sexp_unchecked() })
1489    }
1490    fn into_sexp(self) -> crate::SEXP {
1491        str_iter_to_strsxp(self.iter().map(|s| s.as_ref()))
1492    }
1493    unsafe fn into_sexp_unchecked(self) -> crate::SEXP {
1494        unsafe { str_iter_to_strsxp_unchecked(self.iter().map(|s| s.as_ref())) }
1495    }
1496}
1497
1498/// Convert `Vec<Option<Cow<'_, str>>>` to R character vector with NA support.
1499///
1500/// `None` values become `NA_character_` in R.
1501impl IntoR for Vec<Option<std::borrow::Cow<'_, str>>> {
1502    type Error = std::convert::Infallible;
1503    fn try_into_sexp(self) -> Result<crate::SEXP, Self::Error> {
1504        Ok(self.into_sexp())
1505    }
1506    unsafe fn try_into_sexp_unchecked(self) -> Result<crate::SEXP, Self::Error> {
1507        Ok(unsafe { self.into_sexp_unchecked() })
1508    }
1509    fn into_sexp(self) -> crate::SEXP {
1510        opt_str_iter_to_strsxp(self.iter().map(|o| o.as_ref().map(|c| c.as_ref())))
1511    }
1512    unsafe fn into_sexp_unchecked(self) -> crate::SEXP {
1513        unsafe {
1514            opt_str_iter_to_strsxp_unchecked(self.iter().map(|o| o.as_ref().map(|c| c.as_ref())))
1515        }
1516    }
1517}
1518
1519// region: Vec<Option<borrowed string>>
1520/// Convert `Vec<Option<&str>>` to R character vector with NA support.
1521///
1522/// `None` values become `NA_character_` in R. Borrowed analogue of `Vec<Option<String>>`.
1523impl IntoR for Vec<Option<&str>> {
1524    type Error = std::convert::Infallible;
1525    fn try_into_sexp(self) -> Result<crate::SEXP, Self::Error> {
1526        Ok(self.into_sexp())
1527    }
1528    unsafe fn try_into_sexp_unchecked(self) -> Result<crate::SEXP, Self::Error> {
1529        Ok(unsafe { self.into_sexp_unchecked() })
1530    }
1531    fn into_sexp(self) -> crate::SEXP {
1532        opt_str_iter_to_strsxp(self.iter().copied())
1533    }
1534    unsafe fn into_sexp_unchecked(self) -> crate::SEXP {
1535        unsafe { opt_str_iter_to_strsxp_unchecked(self.iter().copied()) }
1536    }
1537}
1538// endregion
1539
1540/// Convert `Vec<&str>` to R character vector (STRSXP).
1541impl IntoR for Vec<&str> {
1542    type Error = std::convert::Infallible;
1543    fn try_into_sexp(self) -> Result<crate::SEXP, Self::Error> {
1544        Ok(self.into_sexp())
1545    }
1546    unsafe fn try_into_sexp_unchecked(self) -> Result<crate::SEXP, Self::Error> {
1547        Ok(unsafe { self.into_sexp_unchecked() })
1548    }
1549    fn into_sexp(self) -> crate::SEXP {
1550        self.as_slice().into_sexp()
1551    }
1552
1553    unsafe fn into_sexp_unchecked(self) -> crate::SEXP {
1554        unsafe { self.as_slice().into_sexp_unchecked() }
1555    }
1556}
1557// endregion
1558
1559// region: VECSXP-from-iterator helpers
1560
1561/// Build a VECSXP from an exact-size iterator of child `SEXP`s (checked).
1562///
1563/// Routes through [`ListBuilder`]: the list is allocated and protected by a
1564/// local [`ProtectScope`] before iteration begins, then the iterator is consumed
1565/// inside the protected window so each child produced lazily (typically via a
1566/// `.map(|c| c.into_sexp())` adaptor at the callsite) is inserted immediately
1567/// via [`ListBuilder::set`], closing the GC gap.
1568///
1569/// The element type is `SEXP` (not a generic `IntoR`) deliberately: the caller
1570/// performs the conversion lazily in the iterator adaptor, which keeps the
1571/// trait solver from chasing the recursive `Vec<Option<Vec<T>>>` impl.
1572///
1573/// # Safety
1574///
1575/// Must be called from the R main thread.
1576#[inline]
1577unsafe fn vecsxp_from_iter<I>(iter: I) -> crate::SEXP
1578where
1579    I: ExactSizeIterator<Item = crate::SEXP>,
1580{
1581    unsafe {
1582        let scope = ProtectScope::new();
1583        let builder = ListBuilder::new(&scope, iter.len());
1584        for (i, child) in iter.enumerate() {
1585            builder.set(i as isize, child);
1586        }
1587        builder.into_sexp()
1588    }
1589}
1590
1591/// `_unchecked` twin of [`vecsxp_from_iter`] — uses [`ListBuilder::set_unchecked`].
1592/// For ALTREP / `with_r_thread` / unwind contexts. The caller's adaptor must
1593/// produce children via `into_sexp_unchecked()`.
1594///
1595/// # Safety
1596///
1597/// Must be called from the R main thread, in a context where the checked-FFI
1598/// assertion is intentionally bypassed.
1599#[inline]
1600unsafe fn vecsxp_from_iter_unchecked<I>(iter: I) -> crate::SEXP
1601where
1602    I: ExactSizeIterator<Item = crate::SEXP>,
1603{
1604    unsafe {
1605        let scope = ProtectScope::new();
1606        let builder = ListBuilder::new_unchecked(&scope, iter.len());
1607        for (i, child) in iter.enumerate() {
1608            builder.set_unchecked(i as isize, child);
1609        }
1610        builder.into_sexp()
1611    }
1612}
1613
1614// endregion
1615
1616// region: Nested vector conversions (list of vectors)
1617//
1618// One generic impl per list-of-vectors shape, each bounded on the element
1619// vector's own conversion (`Vec<T>: IntoR`, or `&[T]: IntoR` for borrowed
1620// rows). Every row therefore lands exactly as the matching flat vector would:
1621// `Vec<Vec<usize>>` gives each row the smart INTSXP-or-REALSXP choice of
1622// `Vec<usize>`, `Vec<Vec<String>>` gives character vectors, and so on. The
1623// fallible paths propagate the row conversion's error type.
1624
1625/// Fallible twin of [`vecsxp_from_iter`]: stops at the first row whose
1626/// conversion fails. The list stays protected by the local scope until it
1627/// returns, so the partially filled list is released on the error path.
1628///
1629/// # Safety
1630///
1631/// Must be called from the R main thread.
1632#[inline]
1633unsafe fn try_vecsxp_from_iter<I, E>(iter: I) -> Result<crate::SEXP, E>
1634where
1635    I: ExactSizeIterator<Item = Result<crate::SEXP, E>>,
1636{
1637    unsafe {
1638        let scope = ProtectScope::new();
1639        let builder = ListBuilder::new(&scope, iter.len());
1640        for (i, child) in iter.enumerate() {
1641            builder.set(i as isize, child?);
1642        }
1643        Ok(builder.into_sexp())
1644    }
1645}
1646
1647/// `_unchecked` twin of [`try_vecsxp_from_iter`] — uses
1648/// [`ListBuilder::set_unchecked`]. The caller's adaptor must produce children
1649/// via `try_into_sexp_unchecked()`.
1650///
1651/// # Safety
1652///
1653/// Must be called from the R main thread, in a context where the checked-FFI
1654/// assertion is intentionally bypassed.
1655#[inline]
1656unsafe fn try_vecsxp_from_iter_unchecked<I, E>(iter: I) -> Result<crate::SEXP, E>
1657where
1658    I: ExactSizeIterator<Item = Result<crate::SEXP, E>>,
1659{
1660    unsafe {
1661        let scope = ProtectScope::new();
1662        let builder = ListBuilder::new_unchecked(&scope, iter.len());
1663        for (i, child) in iter.enumerate() {
1664            builder.set_unchecked(i as isize, child?);
1665        }
1666        Ok(builder.into_sexp())
1667    }
1668}
1669
1670/// Convert `Vec<Vec<T>>` to an R list of vectors (VECSXP), for every `T` with
1671/// a `Vec<T>: IntoR` conversion. Each row is converted by that impl, so it has
1672/// the R type `Vec<T>` produces (for `usize` / `u64` / `i64` / `isize` / `u32`:
1673/// integer when every value fits, else double, decided per row).
1674impl<T> IntoR for Vec<Vec<T>>
1675where
1676    Vec<T>: IntoR,
1677{
1678    type Error = <Vec<T> as IntoR>::Error;
1679    fn try_into_sexp(self) -> Result<crate::SEXP, Self::Error> {
1680        unsafe { try_vecsxp_from_iter(self.into_iter().map(IntoR::try_into_sexp)) }
1681    }
1682    unsafe fn try_into_sexp_unchecked(self) -> Result<crate::SEXP, Self::Error> {
1683        unsafe {
1684            try_vecsxp_from_iter_unchecked(self.into_iter().map(|c| c.try_into_sexp_unchecked()))
1685        }
1686    }
1687    fn into_sexp(self) -> crate::SEXP {
1688        unsafe { vecsxp_from_iter(self.into_iter().map(IntoR::into_sexp)) }
1689    }
1690    unsafe fn into_sexp_unchecked(self) -> crate::SEXP {
1691        unsafe { vecsxp_from_iter_unchecked(self.into_iter().map(|c| c.into_sexp_unchecked())) }
1692    }
1693}
1694
1695/// Convert `Vec<&[T]>` to an R list of vectors (VECSXP), for every `T` with a
1696/// `&[T]: IntoR` conversion.
1697///
1698/// Borrowed analogue of `Vec<Vec<T>>` — each slice is copied into a fresh R
1699/// vector of the type `&[T]` (and `Vec<T>`) produces.
1700impl<'a, T> IntoR for Vec<&'a [T]>
1701where
1702    &'a [T]: IntoR,
1703{
1704    type Error = <&'a [T] as IntoR>::Error;
1705    fn try_into_sexp(self) -> Result<crate::SEXP, Self::Error> {
1706        unsafe { try_vecsxp_from_iter(self.into_iter().map(IntoR::try_into_sexp)) }
1707    }
1708    unsafe fn try_into_sexp_unchecked(self) -> Result<crate::SEXP, Self::Error> {
1709        unsafe {
1710            try_vecsxp_from_iter_unchecked(self.into_iter().map(|c| c.try_into_sexp_unchecked()))
1711        }
1712    }
1713    fn into_sexp(self) -> crate::SEXP {
1714        unsafe { vecsxp_from_iter(self.into_iter().map(IntoR::into_sexp)) }
1715    }
1716    unsafe fn into_sexp_unchecked(self) -> crate::SEXP {
1717        unsafe { vecsxp_from_iter_unchecked(self.into_iter().map(|c| c.into_sexp_unchecked())) }
1718    }
1719}
1720// endregion
1721
1722// region: NA-aware vector conversions
1723
1724/// Macro for NA-aware `Vec<Option<T>> → R` vector conversions.
1725///
1726/// Uses `alloc_r_vector` to get a mutable slice, then fills it.
1727///
1728/// Unlike the sibling `Vec<Option<T>>` macros (`impl_vec_option_smart_i64_into_r!`
1729/// / `impl_vec_option_coerce_into_r!`, which route through `into_r_infallible!`
1730/// and inherit the default-unchecked policy), this one is written out by hand
1731/// because it carries a *real* `into_sexp_unchecked` path (`alloc_r_vector_unchecked`)
1732/// that the others have no analogue for. The divergence is deliberate.
1733macro_rules! impl_vec_option_into_r {
1734    ($t:ty, $na_value:expr) => {
1735        impl IntoR for Vec<Option<$t>> {
1736            type Error = std::convert::Infallible;
1737            fn try_into_sexp(self) -> Result<crate::SEXP, Self::Error> {
1738                Ok(self.into_sexp())
1739            }
1740            unsafe fn try_into_sexp_unchecked(self) -> Result<crate::SEXP, Self::Error> {
1741                Ok(unsafe { self.into_sexp_unchecked() })
1742            }
1743            fn into_sexp(self) -> crate::SEXP {
1744                unsafe {
1745                    let (sexp, dst) = alloc_r_vector::<$t>(self.len());
1746                    for (slot, val) in dst.iter_mut().zip(self.into_iter()) {
1747                        *slot = val.unwrap_or($na_value);
1748                    }
1749                    sexp
1750                }
1751            }
1752
1753            unsafe fn into_sexp_unchecked(self) -> crate::SEXP {
1754                unsafe {
1755                    let (sexp, dst) = alloc_r_vector_unchecked::<$t>(self.len());
1756                    for (slot, val) in dst.iter_mut().zip(self.into_iter()) {
1757                        *slot = val.unwrap_or($na_value);
1758                    }
1759                    sexp
1760                }
1761            }
1762        }
1763    };
1764}
1765
1766impl IntoR for Vec<Option<f64>> {
    type Error = std::convert::Infallible;
    fn try_into_sexp(self) -> Result<crate::SEXP, Self::Error> {
        Ok(self.into_sexp())
    }
    unsafe fn try_into_sexp_unchecked(self)
        -> Result<crate::SEXP, Self::Error> {
        Ok(unsafe { self.into_sexp_unchecked() })
    }
    fn into_sexp(self) -> crate::SEXP {
        unsafe {
            let (sexp, dst) = alloc_r_vector::<f64>(self.len());
            for (slot, val) in dst.iter_mut().zip(self.into_iter()) {
                *slot = val.unwrap_or(NA_REAL);
            }
            sexp
        }
    }
    unsafe fn into_sexp_unchecked(self) -> crate::SEXP {
        unsafe {
            let (sexp, dst) = alloc_r_vector_unchecked::<f64>(self.len());
            for (slot, val) in dst.iter_mut().zip(self.into_iter()) {
                *slot = val.unwrap_or(NA_REAL);
            }
            sexp
        }
    }
}impl_vec_option_into_r!(f64, NA_REAL); // NA_real_
1767impl IntoR for Vec<Option<i32>> {
    type Error = std::convert::Infallible;
    fn try_into_sexp(self) -> Result<crate::SEXP, Self::Error> {
        Ok(self.into_sexp())
    }
    unsafe fn try_into_sexp_unchecked(self)
        -> Result<crate::SEXP, Self::Error> {
        Ok(unsafe { self.into_sexp_unchecked() })
    }
    fn into_sexp(self) -> crate::SEXP {
        unsafe {
            let (sexp, dst) = alloc_r_vector::<i32>(self.len());
            for (slot, val) in dst.iter_mut().zip(self.into_iter()) {
                *slot = val.unwrap_or(NA_INTEGER);
            }
            sexp
        }
    }
    unsafe fn into_sexp_unchecked(self) -> crate::SEXP {
        unsafe {
            let (sexp, dst) = alloc_r_vector_unchecked::<i32>(self.len());
            for (slot, val) in dst.iter_mut().zip(self.into_iter()) {
                *slot = val.unwrap_or(NA_INTEGER);
            }
            sexp
        }
    }
}impl_vec_option_into_r!(i32, NA_INTEGER); // NA_integer_
1768
1769/// Macro for NA-aware `Vec<Option<T>> → R` smart vector conversion.
1770/// Checks if all non-None values fit i32 → INTSXP, otherwise REALSXP.
1771///
1772/// Allocates the R vector directly and coerces in-place — no intermediate Vec.
1773macro_rules! impl_vec_option_smart_i64_into_r {
1774    ($t:ty, $fits_i32:expr) => {
1775        // Default-unchecked policy, single-sourced through `into_r_infallible!`
1776        // (no bespoke unchecked path — the checked allocation is the only one).
1777        into_r_infallible!(Vec<Option<$t>>, |this| unsafe {
1778            if this.iter().all(|opt| match opt {
1779                Some(x) => $fits_i32(*x),
1780                None => true,
1781            }) {
1782                let (sexp, dst) = alloc_r_vector::<i32>(this.len());
1783                for (slot, val) in dst.iter_mut().zip(this.into_iter()) {
1784                    *slot = match val {
1785                        Some(x) => x as i32,
1786                        None => NA_INTEGER,
1787                    };
1788                }
1789                sexp
1790            } else {
1791                let (sexp, dst) = alloc_r_vector::<f64>(this.len());
1792                for (slot, val) in dst.iter_mut().zip(this.into_iter()) {
1793                    *slot = match val {
1794                        Some(x) => x as f64,
1795                        None => NA_REAL,
1796                    };
1797                }
1798                sexp
1799            }
1800        });
1801    };
1802}
1803
1804// i32::MIN is NA_integer_ in R, so exclude it
1805impl crate::into_r::IntoR for Vec<Option<i64>> {
    type Error = ::std::convert::Infallible;
    #[inline]
    fn try_into_sexp(self)
        -> ::core::result::Result<crate::SEXP, Self::Error> {
        ::core::result::Result::Ok(self.into_sexp())
    }
    #[inline]
    unsafe fn try_into_sexp_unchecked(self)
        -> ::core::result::Result<crate::SEXP, Self::Error> {
        self.try_into_sexp()
    }
    #[inline]
    fn into_sexp(self) -> crate::SEXP {
        let this = self;
        unsafe {
            if this.iter().all(|opt|
                        match opt {
                            Some(x) =>
                                (|x: i64| x > i32::MIN as i64 && x <= i32::MAX as i64)(*x),
                            None => true,
                        }) {
                let (sexp, dst) = alloc_r_vector::<i32>(this.len());
                for (slot, val) in dst.iter_mut().zip(this.into_iter()) {
                    *slot =
                        match val { Some(x) => x as i32, None => NA_INTEGER, };
                }
                sexp
            } else {
                let (sexp, dst) = alloc_r_vector::<f64>(this.len());
                for (slot, val) in dst.iter_mut().zip(this.into_iter()) {
                    *slot = match val { Some(x) => x as f64, None => NA_REAL, };
                }
                sexp
            }
        }
    }
}impl_vec_option_smart_i64_into_r!(i64, |x: i64| x > i32::MIN as i64 && x <= i32::MAX as i64);
1806impl crate::into_r::IntoR for Vec<Option<u64>> {
    type Error = ::std::convert::Infallible;
    #[inline]
    fn try_into_sexp(self)
        -> ::core::result::Result<crate::SEXP, Self::Error> {
        ::core::result::Result::Ok(self.into_sexp())
    }
    #[inline]
    unsafe fn try_into_sexp_unchecked(self)
        -> ::core::result::Result<crate::SEXP, Self::Error> {
        self.try_into_sexp()
    }
    #[inline]
    fn into_sexp(self) -> crate::SEXP {
        let this = self;
        unsafe {
            if this.iter().all(|opt|
                        match opt {
                            Some(x) => (|x: u64| x <= i32::MAX as u64)(*x),
                            None => true,
                        }) {
                let (sexp, dst) = alloc_r_vector::<i32>(this.len());
                for (slot, val) in dst.iter_mut().zip(this.into_iter()) {
                    *slot =
                        match val { Some(x) => x as i32, None => NA_INTEGER, };
                }
                sexp
            } else {
                let (sexp, dst) = alloc_r_vector::<f64>(this.len());
                for (slot, val) in dst.iter_mut().zip(this.into_iter()) {
                    *slot = match val { Some(x) => x as f64, None => NA_REAL, };
                }
                sexp
            }
        }
    }
}impl_vec_option_smart_i64_into_r!(u64, |x: u64| x <= i32::MAX as u64);
1807impl crate::into_r::IntoR for Vec<Option<isize>> {
    type Error = ::std::convert::Infallible;
    #[inline]
    fn try_into_sexp(self)
        -> ::core::result::Result<crate::SEXP, Self::Error> {
        ::core::result::Result::Ok(self.into_sexp())
    }
    #[inline]
    unsafe fn try_into_sexp_unchecked(self)
        -> ::core::result::Result<crate::SEXP, Self::Error> {
        self.try_into_sexp()
    }
    #[inline]
    fn into_sexp(self) -> crate::SEXP {
        let this = self;
        unsafe {
            if this.iter().all(|opt|
                        match opt {
                            Some(x) =>
                                (|x: isize|
                                        x > i32::MIN as isize && x <= i32::MAX as isize)(*x),
                            None => true,
                        }) {
                let (sexp, dst) = alloc_r_vector::<i32>(this.len());
                for (slot, val) in dst.iter_mut().zip(this.into_iter()) {
                    *slot =
                        match val { Some(x) => x as i32, None => NA_INTEGER, };
                }
                sexp
            } else {
                let (sexp, dst) = alloc_r_vector::<f64>(this.len());
                for (slot, val) in dst.iter_mut().zip(this.into_iter()) {
                    *slot = match val { Some(x) => x as f64, None => NA_REAL, };
                }
                sexp
            }
        }
    }
}impl_vec_option_smart_i64_into_r!(isize, |x: isize| x > i32::MIN as isize
1808    && x <= i32::MAX as isize);
1809impl crate::into_r::IntoR for Vec<Option<usize>> {
    type Error = ::std::convert::Infallible;
    #[inline]
    fn try_into_sexp(self)
        -> ::core::result::Result<crate::SEXP, Self::Error> {
        ::core::result::Result::Ok(self.into_sexp())
    }
    #[inline]
    unsafe fn try_into_sexp_unchecked(self)
        -> ::core::result::Result<crate::SEXP, Self::Error> {
        self.try_into_sexp()
    }
    #[inline]
    fn into_sexp(self) -> crate::SEXP {
        let this = self;
        unsafe {
            if this.iter().all(|opt|
                        match opt {
                            Some(x) => (|x: usize| x <= i32::MAX as usize)(*x),
                            None => true,
                        }) {
                let (sexp, dst) = alloc_r_vector::<i32>(this.len());
                for (slot, val) in dst.iter_mut().zip(this.into_iter()) {
                    *slot =
                        match val { Some(x) => x as i32, None => NA_INTEGER, };
                }
                sexp
            } else {
                let (sexp, dst) = alloc_r_vector::<f64>(this.len());
                for (slot, val) in dst.iter_mut().zip(this.into_iter()) {
                    *slot = match val { Some(x) => x as f64, None => NA_REAL, };
                }
                sexp
            }
        }
    }
}impl_vec_option_smart_i64_into_r!(usize, |x: usize| x <= i32::MAX as usize);
1810
1811/// Macro for `Vec<Option<T>>` where `T` coerces to a type with existing Option impl.
1812///
1813/// Delegates to the target type's `Vec<Option<$to>>` impl (which itself uses alloc_r_vector).
1814macro_rules! impl_vec_option_coerce_into_r {
1815    ($from:ty => $to:ty) => {
1816        // Default-unchecked policy, single-sourced through `into_r_infallible!`;
1817        // `into_sexp` delegates to the target `Vec<Option<$to>>` impl.
1818        into_r_infallible!(Vec<Option<$from>>, |this| {
1819            let coerced: Vec<Option<$to>> = this
1820                .into_iter()
1821                .map(|opt| opt.map(|x| <$to>::from(x)))
1822                .collect();
1823            coerced.into_sexp()
1824        });
1825    };
1826}
1827
1828impl crate::into_r::IntoR for Vec<Option<i8>> {
    type Error = ::std::convert::Infallible;
    #[inline]
    fn try_into_sexp(self)
        -> ::core::result::Result<crate::SEXP, Self::Error> {
        ::core::result::Result::Ok(self.into_sexp())
    }
    #[inline]
    unsafe fn try_into_sexp_unchecked(self)
        -> ::core::result::Result<crate::SEXP, Self::Error> {
        self.try_into_sexp()
    }
    #[inline]
    fn into_sexp(self) -> crate::SEXP {
        let this = self;
        {
            let coerced: Vec<Option<i32>> =
                this.into_iter().map(|opt|
                            opt.map(|x| <i32>::from(x))).collect();
            coerced.into_sexp()
        }
    }
}impl_vec_option_coerce_into_r!(i8 => i32);
1829impl crate::into_r::IntoR for Vec<Option<i16>> {
    type Error = ::std::convert::Infallible;
    #[inline]
    fn try_into_sexp(self)
        -> ::core::result::Result<crate::SEXP, Self::Error> {
        ::core::result::Result::Ok(self.into_sexp())
    }
    #[inline]
    unsafe fn try_into_sexp_unchecked(self)
        -> ::core::result::Result<crate::SEXP, Self::Error> {
        self.try_into_sexp()
    }
    #[inline]
    fn into_sexp(self) -> crate::SEXP {
        let this = self;
        {
            let coerced: Vec<Option<i32>> =
                this.into_iter().map(|opt|
                            opt.map(|x| <i32>::from(x))).collect();
            coerced.into_sexp()
        }
    }
}impl_vec_option_coerce_into_r!(i16 => i32);
1830impl crate::into_r::IntoR for Vec<Option<u16>> {
    type Error = ::std::convert::Infallible;
    #[inline]
    fn try_into_sexp(self)
        -> ::core::result::Result<crate::SEXP, Self::Error> {
        ::core::result::Result::Ok(self.into_sexp())
    }
    #[inline]
    unsafe fn try_into_sexp_unchecked(self)
        -> ::core::result::Result<crate::SEXP, Self::Error> {
        self.try_into_sexp()
    }
    #[inline]
    fn into_sexp(self) -> crate::SEXP {
        let this = self;
        {
            let coerced: Vec<Option<i32>> =
                this.into_iter().map(|opt|
                            opt.map(|x| <i32>::from(x))).collect();
            coerced.into_sexp()
        }
    }
}impl_vec_option_coerce_into_r!(u16 => i32);
1831impl crate::into_r::IntoR for Vec<Option<u32>> {
    type Error = ::std::convert::Infallible;
    #[inline]
    fn try_into_sexp(self)
        -> ::core::result::Result<crate::SEXP, Self::Error> {
        ::core::result::Result::Ok(self.into_sexp())
    }
    #[inline]
    unsafe fn try_into_sexp_unchecked(self)
        -> ::core::result::Result<crate::SEXP, Self::Error> {
        self.try_into_sexp()
    }
    #[inline]
    fn into_sexp(self) -> crate::SEXP {
        let this = self;
        {
            let coerced: Vec<Option<i64>> =
                this.into_iter().map(|opt|
                            opt.map(|x| <i64>::from(x))).collect();
            coerced.into_sexp()
        }
    }
}impl_vec_option_coerce_into_r!(u32 => i64); // delegates to smart i64 path
1832impl crate::into_r::IntoR for Vec<Option<f32>> {
    type Error = ::std::convert::Infallible;
    #[inline]
    fn try_into_sexp(self)
        -> ::core::result::Result<crate::SEXP, Self::Error> {
        ::core::result::Result::Ok(self.into_sexp())
    }
    #[inline]
    unsafe fn try_into_sexp_unchecked(self)
        -> ::core::result::Result<crate::SEXP, Self::Error> {
        self.try_into_sexp()
    }
    #[inline]
    fn into_sexp(self) -> crate::SEXP {
        let this = self;
        {
            let coerced: Vec<Option<f64>> =
                this.into_iter().map(|opt|
                            opt.map(|x| <f64>::from(x))).collect();
            coerced.into_sexp()
        }
    }
}impl_vec_option_coerce_into_r!(f32 => f64);
1833
1834/// Helper: allocate LGLSXP and fill from an i32 iterator (checked).
1835///
1836/// Uses `alloc_r_vector` — logical vectors are `RLogical` (repr(transparent) i32).
1837fn logical_iter_to_lglsxp(n: usize, iter: impl Iterator<Item = i32>) -> crate::SEXP {
1838    unsafe {
1839        let (sexp, dst) = alloc_r_vector::<crate::RLogical>(n);
1840        // RLogical is repr(transparent) over i32, safe to write i32 values.
1841        let dst_i32: &mut [i32] = std::slice::from_raw_parts_mut(dst.as_mut_ptr().cast::<i32>(), n);
1842        for (slot, val) in dst_i32.iter_mut().zip(iter) {
1843            *slot = val;
1844        }
1845        sexp
1846    }
1847}
1848
1849/// Helper: allocate LGLSXP and fill from an i32 iterator (unchecked).
1850unsafe fn logical_iter_to_lglsxp_unchecked(
1851    n: usize,
1852    iter: impl Iterator<Item = i32>,
1853) -> crate::SEXP {
1854    unsafe {
1855        let (sexp, dst) = alloc_r_vector_unchecked::<crate::RLogical>(n);
1856        let dst_i32: &mut [i32] = std::slice::from_raw_parts_mut(dst.as_mut_ptr().cast::<i32>(), n);
1857        for (slot, val) in dst_i32.iter_mut().zip(iter) {
1858            *slot = val;
1859        }
1860        sexp
1861    }
1862}
1863
1864/// Convert `Vec<bool>` to R logical vector.
1865impl IntoR for Vec<bool> {
1866    type Error = std::convert::Infallible;
1867    fn try_into_sexp(self) -> Result<crate::SEXP, Self::Error> {
1868        Ok(self.into_sexp())
1869    }
1870    unsafe fn try_into_sexp_unchecked(self) -> Result<crate::SEXP, Self::Error> {
1871        Ok(unsafe { self.into_sexp_unchecked() })
1872    }
1873    fn into_sexp(self) -> crate::SEXP {
1874        let n = self.len();
1875        logical_iter_to_lglsxp(n, self.into_iter().map(i32::from))
1876    }
1877
1878    unsafe fn into_sexp_unchecked(self) -> crate::SEXP {
1879        let n = self.len();
1880        unsafe { logical_iter_to_lglsxp_unchecked(n, self.into_iter().map(i32::from)) }
1881    }
1882}
1883
1884/// Convert `&[bool]` to R logical vector.
1885impl IntoR for &[bool] {
1886    type Error = std::convert::Infallible;
1887    fn try_into_sexp(self) -> Result<crate::SEXP, Self::Error> {
1888        Ok(self.into_sexp())
1889    }
1890    unsafe fn try_into_sexp_unchecked(self) -> Result<crate::SEXP, Self::Error> {
1891        Ok(unsafe { self.into_sexp_unchecked() })
1892    }
1893    fn into_sexp(self) -> crate::SEXP {
1894        let n = self.len();
1895        logical_iter_to_lglsxp(n, self.iter().map(|&v| i32::from(v)))
1896    }
1897
1898    unsafe fn into_sexp_unchecked(self) -> crate::SEXP {
1899        let n = self.len();
1900        unsafe { logical_iter_to_lglsxp_unchecked(n, self.iter().map(|&v| i32::from(v))) }
1901    }
1902}
1903
1904/// Convert `Vec<Rboolean>` to R logical vector (no NA: Rboolean is TRUE/FALSE only).
1905impl IntoR for Vec<crate::Rboolean> {
1906    type Error = std::convert::Infallible;
1907    fn try_into_sexp(self) -> Result<crate::SEXP, Self::Error> {
1908        Ok(self.into_sexp())
1909    }
1910    unsafe fn try_into_sexp_unchecked(self) -> Result<crate::SEXP, Self::Error> {
1911        Ok(unsafe { self.into_sexp_unchecked() })
1912    }
1913    fn into_sexp(self) -> crate::SEXP {
1914        let n = self.len();
1915        logical_iter_to_lglsxp(n, self.into_iter().map(|b| b as i32))
1916    }
1917
1918    unsafe fn into_sexp_unchecked(self) -> crate::SEXP {
1919        let n = self.len();
1920        unsafe { logical_iter_to_lglsxp_unchecked(n, self.into_iter().map(|b| b as i32)) }
1921    }
1922}
1923
1924/// Convert `&[Rboolean]` to R logical vector (no NA: Rboolean is TRUE/FALSE only).
1925impl IntoR for &[crate::Rboolean] {
1926    type Error = std::convert::Infallible;
1927    fn try_into_sexp(self) -> Result<crate::SEXP, Self::Error> {
1928        Ok(self.into_sexp())
1929    }
1930    unsafe fn try_into_sexp_unchecked(self) -> Result<crate::SEXP, Self::Error> {
1931        Ok(unsafe { self.into_sexp_unchecked() })
1932    }
1933    fn into_sexp(self) -> crate::SEXP {
1934        let n = self.len();
1935        logical_iter_to_lglsxp(n, self.iter().map(|&b| b as i32))
1936    }
1937
1938    unsafe fn into_sexp_unchecked(self) -> crate::SEXP {
1939        let n = self.len();
1940        unsafe { logical_iter_to_lglsxp_unchecked(n, self.iter().map(|&b| b as i32)) }
1941    }
1942}
1943
1944macro_rules! impl_vec_option_logical_into_r {
1945    ($(#[$meta:meta])* $t:ty, $convert:expr) => {
1946        $(#[$meta])*
1947        impl IntoR for Vec<Option<$t>> {
1948            type Error = std::convert::Infallible;
1949            fn try_into_sexp(self) -> Result<crate::SEXP, Self::Error> {
1950                Ok(self.into_sexp())
1951            }
1952            unsafe fn try_into_sexp_unchecked(self) -> Result<crate::SEXP, Self::Error> {
1953                Ok(unsafe { self.into_sexp_unchecked() })
1954            }
1955            fn into_sexp(self) -> crate::SEXP {
1956                let n = self.len();
1957                logical_iter_to_lglsxp(n, self.into_iter().map($convert))
1958            }
1959
1960            unsafe fn into_sexp_unchecked(self) -> crate::SEXP {
1961                let n = self.len();
1962                unsafe { logical_iter_to_lglsxp_unchecked(n, self.into_iter().map($convert)) }
1963            }
1964        }
1965    };
1966}
1967
1968#[doc = r" Convert `Vec<Option<bool>>` to R logical vector with NA support."]
impl IntoR for Vec<Option<bool>> {
    type Error = std::convert::Infallible;
    fn try_into_sexp(self) -> Result<crate::SEXP, Self::Error> {
        Ok(self.into_sexp())
    }
    unsafe fn try_into_sexp_unchecked(self)
        -> Result<crate::SEXP, Self::Error> {
        Ok(unsafe { self.into_sexp_unchecked() })
    }
    fn into_sexp(self) -> crate::SEXP {
        let n = self.len();
        logical_iter_to_lglsxp(n,
            self.into_iter().map(|v: Option<bool>|
                    match v {
                        Some(true) => 1,
                        Some(false) => 0,
                        None => NA_LOGICAL,
                    }))
    }
    unsafe fn into_sexp_unchecked(self) -> crate::SEXP {
        let n = self.len();
        unsafe {
            logical_iter_to_lglsxp_unchecked(n,
                self.into_iter().map(|v: Option<bool>|
                        match v {
                            Some(true) => 1,
                            Some(false) => 0,
                            None => NA_LOGICAL,
                        }))
        }
    }
}impl_vec_option_logical_into_r!(
1969    /// Convert `Vec<Option<bool>>` to R logical vector with NA support.
1970    bool,
1971    |v: Option<bool>| match v {
1972        Some(true) => 1,
1973        Some(false) => 0,
1974        None => NA_LOGICAL,
1975    }
1976);
1977#[doc =
r" Convert `Vec<Option<Rboolean>>` to R logical vector with NA support."]
impl IntoR for Vec<Option<crate::Rboolean>> {
    type Error = std::convert::Infallible;
    fn try_into_sexp(self) -> Result<crate::SEXP, Self::Error> {
        Ok(self.into_sexp())
    }
    unsafe fn try_into_sexp_unchecked(self)
        -> Result<crate::SEXP, Self::Error> {
        Ok(unsafe { self.into_sexp_unchecked() })
    }
    fn into_sexp(self) -> crate::SEXP {
        let n = self.len();
        logical_iter_to_lglsxp(n,
            self.into_iter().map(|v: Option<crate::Rboolean>|
                    match v { Some(b) => b as i32, None => NA_LOGICAL, }))
    }
    unsafe fn into_sexp_unchecked(self) -> crate::SEXP {
        let n = self.len();
        unsafe {
            logical_iter_to_lglsxp_unchecked(n,
                self.into_iter().map(|v: Option<crate::Rboolean>|
                        match v { Some(b) => b as i32, None => NA_LOGICAL, }))
        }
    }
}impl_vec_option_logical_into_r!(
1978    /// Convert `Vec<Option<Rboolean>>` to R logical vector with NA support.
1979    crate::Rboolean,
1980    |v: Option<crate::Rboolean>| match v {
1981        Some(b) => b as i32,
1982        None => NA_LOGICAL,
1983    }
1984);
1985#[doc =
r" Convert `Vec<Option<RLogical>>` to R logical vector with NA support."]
impl IntoR for Vec<Option<crate::RLogical>> {
    type Error = std::convert::Infallible;
    fn try_into_sexp(self) -> Result<crate::SEXP, Self::Error> {
        Ok(self.into_sexp())
    }
    unsafe fn try_into_sexp_unchecked(self)
        -> Result<crate::SEXP, Self::Error> {
        Ok(unsafe { self.into_sexp_unchecked() })
    }
    fn into_sexp(self) -> crate::SEXP {
        let n = self.len();
        logical_iter_to_lglsxp(n,
            self.into_iter().map(|v: Option<crate::RLogical>|
                    match v { Some(b) => b.to_i32(), None => NA_LOGICAL, }))
    }
    unsafe fn into_sexp_unchecked(self) -> crate::SEXP {
        let n = self.len();
        unsafe {
            logical_iter_to_lglsxp_unchecked(n,
                self.into_iter().map(|v: Option<crate::RLogical>|
                        match v { Some(b) => b.to_i32(), None => NA_LOGICAL, }))
        }
    }
}impl_vec_option_logical_into_r!(
1986    /// Convert `Vec<Option<RLogical>>` to R logical vector with NA support.
1987    crate::RLogical,
1988    |v: Option<crate::RLogical>| match v {
1989        Some(b) => b.to_i32(),
1990        None => NA_LOGICAL,
1991    }
1992);
1993
1994/// Convert `Vec<Option<String>>` to R character vector with NA support.
1995///
1996/// `None` values become `NA_character_` in R.
1997impl IntoR for Vec<Option<String>> {
1998    type Error = std::convert::Infallible;
1999    fn try_into_sexp(self) -> Result<crate::SEXP, Self::Error> {
2000        Ok(self.into_sexp())
2001    }
2002    unsafe fn try_into_sexp_unchecked(self) -> Result<crate::SEXP, Self::Error> {
2003        Ok(unsafe { self.into_sexp_unchecked() })
2004    }
2005    fn into_sexp(self) -> crate::SEXP {
2006        opt_str_iter_to_strsxp(self.iter().map(|o| o.as_deref()))
2007    }
2008
2009    unsafe fn into_sexp_unchecked(self) -> crate::SEXP {
2010        unsafe { opt_str_iter_to_strsxp_unchecked(self.iter().map(|o| o.as_deref())) }
2011    }
2012}
2013// endregion
2014
2015// region: Tuple to list conversions
2016
2017// Reuse the protected streaming list builder for both tuple-row shapes.
2018// Failed rows leave NULL slots while later rows are checked; the partial list
2019// never escapes on failure. Each successful row is rooted before the next runs.
2020macro_rules! impl_tuple_vec_into_r {
2021    (($($T:ident),+), $row:ty) => {
2022        impl<$($T: IntoR),+> IntoR for Vec<$row> {
2023            type Error = crate::into_r_error::IntoRError;
2024
2025            fn try_into_sexp(self) -> Result<crate::SEXP, Self::Error> {
2026                let mut errors = crate::into_r_error::ElementFailures::default();
2027                let result = unsafe {
2028                    vecsxp_from_iter(self.into_iter().enumerate().map(|(index, row)| {
2029                        match row.try_into_sexp() {
2030                            Ok(child) => child,
2031                            Err(error) => {
2032                                errors.push_row(index, error);
2033                                crate::SEXP::nil()
2034                            }
2035                        }
2036                    }))
2037                };
2038                if errors.is_empty() {
2039                    Ok(result)
2040                } else {
2041                    Err(errors.into_error())
2042                }
2043            }
2044
2045            unsafe fn try_into_sexp_unchecked(self) -> Result<crate::SEXP, Self::Error> {
2046                let mut errors = crate::into_r_error::ElementFailures::default();
2047                let result = unsafe {
2048                    vecsxp_from_iter_unchecked(self.into_iter().enumerate().map(|(index, row)| {
2049                        match row.try_into_sexp_unchecked() {
2050                            Ok(child) => child,
2051                            Err(error) => {
2052                                errors.push_row(index, error);
2053                                crate::SEXP::nil()
2054                            }
2055                        }
2056                    }))
2057                };
2058                if errors.is_empty() {
2059                    Ok(result)
2060                } else {
2061                    Err(errors.into_error())
2062                }
2063            }
2064        }
2065    };
2066}
2067
2068/// Convert Rust tuples to unnamed R lists, collecting every failing field.
2069/// Field error types may differ; their messages share the existing batched
2070/// conversion format with 1-based positions, and each field's condition is
2071/// kept with its position, in `IntoRError::Elements`.
2072macro_rules! impl_tuple_into_r {
2073    ($n:literal, $name:literal; $($T:ident $R:ident $idx:tt),+) => {
2074        impl<$($T: IntoR),+> IntoR for ($($T,)+) {
2075            type Error = crate::into_r_error::IntoRError;
2076
2077            fn try_into_sexp(self) -> Result<crate::SEXP, Self::Error> {
2078                unsafe {
2079                    let scope = ProtectScope::new();
2080                    let builder = ListBuilder::new(&scope, $n);
2081                    let mut errors = crate::into_r_error::ElementFailures::default();
2082                    $(
2083                        match self.$idx.try_into_sexp() {
2084                            Ok(child) => builder.set($idx as isize, child),
2085                            Err(error) => errors.push($idx, &error),
2086                        }
2087                    )+
2088                    if errors.is_empty() {
2089                        Ok(builder.into_sexp())
2090                    } else {
2091                        Err(errors.into_error())
2092                    }
2093                }
2094            }
2095
2096            unsafe fn try_into_sexp_unchecked(self) -> Result<crate::SEXP, Self::Error> {
2097                unsafe {
2098                    let scope = ProtectScope::new();
2099                    let builder = ListBuilder::new_unchecked(&scope, $n);
2100                    let mut errors = crate::into_r_error::ElementFailures::default();
2101                    $(
2102                        match self.$idx.try_into_sexp_unchecked() {
2103                            Ok(child) => builder.set_unchecked($idx as isize, child),
2104                            Err(error) => errors.push($idx, &error),
2105                        }
2106                    )+
2107                    if errors.is_empty() {
2108                        Ok(builder.into_sexp())
2109                    } else {
2110                        Err(errors.into_error())
2111                    }
2112                }
2113            }
2114        }
2115
2116        impl<$($T: IntoR),+> IntoR for Option<($($T,)+)> {
2117            type Error = <($($T,)+) as IntoR>::Error;
2118
2119            fn try_into_sexp(self) -> Result<crate::SEXP, Self::Error> {
2120                self.map_or_else(|| Ok(crate::SEXP::nil()), IntoR::try_into_sexp)
2121            }
2122
2123            unsafe fn try_into_sexp_unchecked(self) -> Result<crate::SEXP, Self::Error> {
2124                self.map_or_else(|| Ok(crate::SEXP::nil()), |value| unsafe { value.try_into_sexp_unchecked() })
2125            }
2126        }
2127
2128        impl_tuple_vec_into_r!(($($T),+), ($($T,)+));
2129        impl_tuple_vec_into_r!(($($T),+), Option<($($T,)+)>);
2130    };
2131}
2132
2133impl<A: IntoR> IntoR for (A,) {
    type Error = crate::into_r_error::IntoRError;
    fn try_into_sexp(self) -> Result<crate::SEXP, Self::Error> {
        unsafe {
            let scope = ProtectScope::new();
            let builder = ListBuilder::new(&scope, 1);
            let mut errors = crate::into_r_error::ElementFailures::default();
            match self.0.try_into_sexp() {
                Ok(child) => builder.set(0 as isize, child),
                Err(error) => errors.push(0, &error),
            }
            if errors.is_empty() {
                Ok(builder.into_sexp())
            } else { Err(errors.into_error()) }
        }
    }
    unsafe fn try_into_sexp_unchecked(self)
        -> Result<crate::SEXP, Self::Error> {
        unsafe {
            let scope = ProtectScope::new();
            let builder = ListBuilder::new_unchecked(&scope, 1);
            let mut errors = crate::into_r_error::ElementFailures::default();
            match self.0.try_into_sexp_unchecked() {
                Ok(child) => builder.set_unchecked(0 as isize, child),
                Err(error) => errors.push(0, &error),
            }
            if errors.is_empty() {
                Ok(builder.into_sexp())
            } else { Err(errors.into_error()) }
        }
    }
}
impl<A: IntoR> IntoR for Option<(A,)> {
    type Error = <(A,) as IntoR>::Error;
    fn try_into_sexp(self) -> Result<crate::SEXP, Self::Error> {
        self.map_or_else(|| Ok(crate::SEXP::nil()), IntoR::try_into_sexp)
    }
    unsafe fn try_into_sexp_unchecked(self)
        -> Result<crate::SEXP, Self::Error> {
        self.map_or_else(|| Ok(crate::SEXP::nil()),
            |value| unsafe { value.try_into_sexp_unchecked() })
    }
}
impl<A: IntoR> IntoR for Vec<(A,)> {
    type Error = crate::into_r_error::IntoRError;
    fn try_into_sexp(self) -> Result<crate::SEXP, Self::Error> {
        let mut errors = crate::into_r_error::ElementFailures::default();
        let result =
            unsafe {
                vecsxp_from_iter(self.into_iter().enumerate().map(|(index,
                                row)|
                            {
                                match row.try_into_sexp() {
                                    Ok(child) => child,
                                    Err(error) => {
                                        errors.push_row(index, error);
                                        crate::SEXP::nil()
                                    }
                                }
                            }))
            };
        if errors.is_empty() { Ok(result) } else { Err(errors.into_error()) }
    }
    unsafe fn try_into_sexp_unchecked(self)
        -> Result<crate::SEXP, Self::Error> {
        let mut errors = crate::into_r_error::ElementFailures::default();
        let result =
            unsafe {
                vecsxp_from_iter_unchecked(self.into_iter().enumerate().map(|(index,
                                row)|
                            {
                                match row.try_into_sexp_unchecked() {
                                    Ok(child) => child,
                                    Err(error) => {
                                        errors.push_row(index, error);
                                        crate::SEXP::nil()
                                    }
                                }
                            }))
            };
        if errors.is_empty() { Ok(result) } else { Err(errors.into_error()) }
    }
}
impl<A: IntoR> IntoR for Vec<Option<(A,)>> {
    type Error = crate::into_r_error::IntoRError;
    fn try_into_sexp(self) -> Result<crate::SEXP, Self::Error> {
        let mut errors = crate::into_r_error::ElementFailures::default();
        let result =
            unsafe {
                vecsxp_from_iter(self.into_iter().enumerate().map(|(index,
                                row)|
                            {
                                match row.try_into_sexp() {
                                    Ok(child) => child,
                                    Err(error) => {
                                        errors.push_row(index, error);
                                        crate::SEXP::nil()
                                    }
                                }
                            }))
            };
        if errors.is_empty() { Ok(result) } else { Err(errors.into_error()) }
    }
    unsafe fn try_into_sexp_unchecked(self)
        -> Result<crate::SEXP, Self::Error> {
        let mut errors = crate::into_r_error::ElementFailures::default();
        let result =
            unsafe {
                vecsxp_from_iter_unchecked(self.into_iter().enumerate().map(|(index,
                                row)|
                            {
                                match row.try_into_sexp_unchecked() {
                                    Ok(child) => child,
                                    Err(error) => {
                                        errors.push_row(index, error);
                                        crate::SEXP::nil()
                                    }
                                }
                            }))
            };
        if errors.is_empty() { Ok(result) } else { Err(errors.into_error()) }
    }
}
impl<A: IntoR, B: IntoR> IntoR for (A, B) {
    type Error = crate::into_r_error::IntoRError;
    fn try_into_sexp(self) -> Result<crate::SEXP, Self::Error> {
        unsafe {
            let scope = ProtectScope::new();
            let builder = ListBuilder::new(&scope, 2);
            let mut errors = crate::into_r_error::ElementFailures::default();
            match self.0.try_into_sexp() {
                Ok(child) => builder.set(0 as isize, child),
                Err(error) => errors.push(0, &error),
            }
            match self.1.try_into_sexp() {
                Ok(child) => builder.set(1 as isize, child),
                Err(error) => errors.push(1, &error),
            }
            if errors.is_empty() {
                Ok(builder.into_sexp())
            } else { Err(errors.into_error()) }
        }
    }
    unsafe fn try_into_sexp_unchecked(self)
        -> Result<crate::SEXP, Self::Error> {
        unsafe {
            let scope = ProtectScope::new();
            let builder = ListBuilder::new_unchecked(&scope, 2);
            let mut errors = crate::into_r_error::ElementFailures::default();
            match self.0.try_into_sexp_unchecked() {
                Ok(child) => builder.set_unchecked(0 as isize, child),
                Err(error) => errors.push(0, &error),
            }
            match self.1.try_into_sexp_unchecked() {
                Ok(child) => builder.set_unchecked(1 as isize, child),
                Err(error) => errors.push(1, &error),
            }
            if errors.is_empty() {
                Ok(builder.into_sexp())
            } else { Err(errors.into_error()) }
        }
    }
}
impl<A: IntoR, B: IntoR> IntoR for Option<(A, B)> {
    type Error = <(A, B) as IntoR>::Error;
    fn try_into_sexp(self) -> Result<crate::SEXP, Self::Error> {
        self.map_or_else(|| Ok(crate::SEXP::nil()), IntoR::try_into_sexp)
    }
    unsafe fn try_into_sexp_unchecked(self)
        -> Result<crate::SEXP, Self::Error> {
        self.map_or_else(|| Ok(crate::SEXP::nil()),
            |value| unsafe { value.try_into_sexp_unchecked() })
    }
}
impl<A: IntoR, B: IntoR> IntoR for Vec<(A, B)> {
    type Error = crate::into_r_error::IntoRError;
    fn try_into_sexp(self) -> Result<crate::SEXP, Self::Error> {
        let mut errors = crate::into_r_error::ElementFailures::default();
        let result =
            unsafe {
                vecsxp_from_iter(self.into_iter().enumerate().map(|(index,
                                row)|
                            {
                                match row.try_into_sexp() {
                                    Ok(child) => child,
                                    Err(error) => {
                                        errors.push_row(index, error);
                                        crate::SEXP::nil()
                                    }
                                }
                            }))
            };
        if errors.is_empty() { Ok(result) } else { Err(errors.into_error()) }
    }
    unsafe fn try_into_sexp_unchecked(self)
        -> Result<crate::SEXP, Self::Error> {
        let mut errors = crate::into_r_error::ElementFailures::default();
        let result =
            unsafe {
                vecsxp_from_iter_unchecked(self.into_iter().enumerate().map(|(index,
                                row)|
                            {
                                match row.try_into_sexp_unchecked() {
                                    Ok(child) => child,
                                    Err(error) => {
                                        errors.push_row(index, error);
                                        crate::SEXP::nil()
                                    }
                                }
                            }))
            };
        if errors.is_empty() { Ok(result) } else { Err(errors.into_error()) }
    }
}
impl<A: IntoR, B: IntoR> IntoR for Vec<Option<(A, B)>> {
    type Error = crate::into_r_error::IntoRError;
    fn try_into_sexp(self) -> Result<crate::SEXP, Self::Error> {
        let mut errors = crate::into_r_error::ElementFailures::default();
        let result =
            unsafe {
                vecsxp_from_iter(self.into_iter().enumerate().map(|(index,
                                row)|
                            {
                                match row.try_into_sexp() {
                                    Ok(child) => child,
                                    Err(error) => {
                                        errors.push_row(index, error);
                                        crate::SEXP::nil()
                                    }
                                }
                            }))
            };
        if errors.is_empty() { Ok(result) } else { Err(errors.into_error()) }
    }
    unsafe fn try_into_sexp_unchecked(self)
        -> Result<crate::SEXP, Self::Error> {
        let mut errors = crate::into_r_error::ElementFailures::default();
        let result =
            unsafe {
                vecsxp_from_iter_unchecked(self.into_iter().enumerate().map(|(index,
                                row)|
                            {
                                match row.try_into_sexp_unchecked() {
                                    Ok(child) => child,
                                    Err(error) => {
                                        errors.push_row(index, error);
                                        crate::SEXP::nil()
                                    }
                                }
                            }))
            };
        if errors.is_empty() { Ok(result) } else { Err(errors.into_error()) }
    }
}
impl<A: IntoR, B: IntoR, C: IntoR> IntoR for (A, B, C) {
    type Error = crate::into_r_error::IntoRError;
    fn try_into_sexp(self) -> Result<crate::SEXP, Self::Error> {
        unsafe {
            let scope = ProtectScope::new();
            let builder = ListBuilder::new(&scope, 3);
            let mut errors = crate::into_r_error::ElementFailures::default();
            match self.0.try_into_sexp() {
                Ok(child) => builder.set(0 as isize, child),
                Err(error) => errors.push(0, &error),
            }
            match self.1.try_into_sexp() {
                Ok(child) => builder.set(1 as isize, child),
                Err(error) => errors.push(1, &error),
            }
            match self.2.try_into_sexp() {
                Ok(child) => builder.set(2 as isize, child),
                Err(error) => errors.push(2, &error),
            }
            if errors.is_empty() {
                Ok(builder.into_sexp())
            } else { Err(errors.into_error()) }
        }
    }
    unsafe fn try_into_sexp_unchecked(self)
        -> Result<crate::SEXP, Self::Error> {
        unsafe {
            let scope = ProtectScope::new();
            let builder = ListBuilder::new_unchecked(&scope, 3);
            let mut errors = crate::into_r_error::ElementFailures::default();
            match self.0.try_into_sexp_unchecked() {
                Ok(child) => builder.set_unchecked(0 as isize, child),
                Err(error) => errors.push(0, &error),
            }
            match self.1.try_into_sexp_unchecked() {
                Ok(child) => builder.set_unchecked(1 as isize, child),
                Err(error) => errors.push(1, &error),
            }
            match self.2.try_into_sexp_unchecked() {
                Ok(child) => builder.set_unchecked(2 as isize, child),
                Err(error) => errors.push(2, &error),
            }
            if errors.is_empty() {
                Ok(builder.into_sexp())
            } else { Err(errors.into_error()) }
        }
    }
}
impl<A: IntoR, B: IntoR, C: IntoR> IntoR for Option<(A, B, C)> {
    type Error = <(A, B, C) as IntoR>::Error;
    fn try_into_sexp(self) -> Result<crate::SEXP, Self::Error> {
        self.map_or_else(|| Ok(crate::SEXP::nil()), IntoR::try_into_sexp)
    }
    unsafe fn try_into_sexp_unchecked(self)
        -> Result<crate::SEXP, Self::Error> {
        self.map_or_else(|| Ok(crate::SEXP::nil()),
            |value| unsafe { value.try_into_sexp_unchecked() })
    }
}
impl<A: IntoR, B: IntoR, C: IntoR> IntoR for Vec<(A, B, C)> {
    type Error = crate::into_r_error::IntoRError;
    fn try_into_sexp(self) -> Result<crate::SEXP, Self::Error> {
        let mut errors = crate::into_r_error::ElementFailures::default();
        let result =
            unsafe {
                vecsxp_from_iter(self.into_iter().enumerate().map(|(index,
                                row)|
                            {
                                match row.try_into_sexp() {
                                    Ok(child) => child,
                                    Err(error) => {
                                        errors.push_row(index, error);
                                        crate::SEXP::nil()
                                    }
                                }
                            }))
            };
        if errors.is_empty() { Ok(result) } else { Err(errors.into_error()) }
    }
    unsafe fn try_into_sexp_unchecked(self)
        -> Result<crate::SEXP, Self::Error> {
        let mut errors = crate::into_r_error::ElementFailures::default();
        let result =
            unsafe {
                vecsxp_from_iter_unchecked(self.into_iter().enumerate().map(|(index,
                                row)|
                            {
                                match row.try_into_sexp_unchecked() {
                                    Ok(child) => child,
                                    Err(error) => {
                                        errors.push_row(index, error);
                                        crate::SEXP::nil()
                                    }
                                }
                            }))
            };
        if errors.is_empty() { Ok(result) } else { Err(errors.into_error()) }
    }
}
impl<A: IntoR, B: IntoR, C: IntoR> IntoR for Vec<Option<(A, B, C)>> {
    type Error = crate::into_r_error::IntoRError;
    fn try_into_sexp(self) -> Result<crate::SEXP, Self::Error> {
        let mut errors = crate::into_r_error::ElementFailures::default();
        let result =
            unsafe {
                vecsxp_from_iter(self.into_iter().enumerate().map(|(index,
                                row)|
                            {
                                match row.try_into_sexp() {
                                    Ok(child) => child,
                                    Err(error) => {
                                        errors.push_row(index, error);
                                        crate::SEXP::nil()
                                    }
                                }
                            }))
            };
        if errors.is_empty() { Ok(result) } else { Err(errors.into_error()) }
    }
    unsafe fn try_into_sexp_unchecked(self)
        -> Result<crate::SEXP, Self::Error> {
        let mut errors = crate::into_r_error::ElementFailures::default();
        let result =
            unsafe {
                vecsxp_from_iter_unchecked(self.into_iter().enumerate().map(|(index,
                                row)|
                            {
                                match row.try_into_sexp_unchecked() {
                                    Ok(child) => child,
                                    Err(error) => {
                                        errors.push_row(index, error);
                                        crate::SEXP::nil()
                                    }
                                }
                            }))
            };
        if errors.is_empty() { Ok(result) } else { Err(errors.into_error()) }
    }
}
impl<A: IntoR, B: IntoR, C: IntoR, D: IntoR> IntoR for (A, B, C, D) {
    type Error = crate::into_r_error::IntoRError;
    fn try_into_sexp(self) -> Result<crate::SEXP, Self::Error> {
        unsafe {
            let scope = ProtectScope::new();
            let builder = ListBuilder::new(&scope, 4);
            let mut errors = crate::into_r_error::ElementFailures::default();
            match self.0.try_into_sexp() {
                Ok(child) => builder.set(0 as isize, child),
                Err(error) => errors.push(0, &error),
            }
            match self.1.try_into_sexp() {
                Ok(child) => builder.set(1 as isize, child),
                Err(error) => errors.push(1, &error),
            }
            match self.2.try_into_sexp() {
                Ok(child) => builder.set(2 as isize, child),
                Err(error) => errors.push(2, &error),
            }
            match self.3.try_into_sexp() {
                Ok(child) => builder.set(3 as isize, child),
                Err(error) => errors.push(3, &error),
            }
            if errors.is_empty() {
                Ok(builder.into_sexp())
            } else { Err(errors.into_error()) }
        }
    }
    unsafe fn try_into_sexp_unchecked(self)
        -> Result<crate::SEXP, Self::Error> {
        unsafe {
            let scope = ProtectScope::new();
            let builder = ListBuilder::new_unchecked(&scope, 4);
            let mut errors = crate::into_r_error::ElementFailures::default();
            match self.0.try_into_sexp_unchecked() {
                Ok(child) => builder.set_unchecked(0 as isize, child),
                Err(error) => errors.push(0, &error),
            }
            match self.1.try_into_sexp_unchecked() {
                Ok(child) => builder.set_unchecked(1 as isize, child),
                Err(error) => errors.push(1, &error),
            }
            match self.2.try_into_sexp_unchecked() {
                Ok(child) => builder.set_unchecked(2 as isize, child),
                Err(error) => errors.push(2, &error),
            }
            match self.3.try_into_sexp_unchecked() {
                Ok(child) => builder.set_unchecked(3 as isize, child),
                Err(error) => errors.push(3, &error),
            }
            if errors.is_empty() {
                Ok(builder.into_sexp())
            } else { Err(errors.into_error()) }
        }
    }
}
impl<A: IntoR, B: IntoR, C: IntoR, D: IntoR> IntoR for Option<(A, B, C, D)> {
    type Error = <(A, B, C, D) as IntoR>::Error;
    fn try_into_sexp(self) -> Result<crate::SEXP, Self::Error> {
        self.map_or_else(|| Ok(crate::SEXP::nil()), IntoR::try_into_sexp)
    }
    unsafe fn try_into_sexp_unchecked(self)
        -> Result<crate::SEXP, Self::Error> {
        self.map_or_else(|| Ok(crate::SEXP::nil()),
            |value| unsafe { value.try_into_sexp_unchecked() })
    }
}
impl<A: IntoR, B: IntoR, C: IntoR, D: IntoR> IntoR for Vec<(A, B, C, D)> {
    type Error = crate::into_r_error::IntoRError;
    fn try_into_sexp(self) -> Result<crate::SEXP, Self::Error> {
        let mut errors = crate::into_r_error::ElementFailures::default();
        let result =
            unsafe {
                vecsxp_from_iter(self.into_iter().enumerate().map(|(index,
                                row)|
                            {
                                match row.try_into_sexp() {
                                    Ok(child) => child,
                                    Err(error) => {
                                        errors.push_row(index, error);
                                        crate::SEXP::nil()
                                    }
                                }
                            }))
            };
        if errors.is_empty() { Ok(result) } else { Err(errors.into_error()) }
    }
    unsafe fn try_into_sexp_unchecked(self)
        -> Result<crate::SEXP, Self::Error> {
        let mut errors = crate::into_r_error::ElementFailures::default();
        let result =
            unsafe {
                vecsxp_from_iter_unchecked(self.into_iter().enumerate().map(|(index,
                                row)|
                            {
                                match row.try_into_sexp_unchecked() {
                                    Ok(child) => child,
                                    Err(error) => {
                                        errors.push_row(index, error);
                                        crate::SEXP::nil()
                                    }
                                }
                            }))
            };
        if errors.is_empty() { Ok(result) } else { Err(errors.into_error()) }
    }
}
impl<A: IntoR, B: IntoR, C: IntoR, D: IntoR> IntoR for
    Vec<Option<(A, B, C, D)>> {
    type Error = crate::into_r_error::IntoRError;
    fn try_into_sexp(self) -> Result<crate::SEXP, Self::Error> {
        let mut errors = crate::into_r_error::ElementFailures::default();
        let result =
            unsafe {
                vecsxp_from_iter(self.into_iter().enumerate().map(|(index,
                                row)|
                            {
                                match row.try_into_sexp() {
                                    Ok(child) => child,
                                    Err(error) => {
                                        errors.push_row(index, error);
                                        crate::SEXP::nil()
                                    }
                                }
                            }))
            };
        if errors.is_empty() { Ok(result) } else { Err(errors.into_error()) }
    }
    unsafe fn try_into_sexp_unchecked(self)
        -> Result<crate::SEXP, Self::Error> {
        let mut errors = crate::into_r_error::ElementFailures::default();
        let result =
            unsafe {
                vecsxp_from_iter_unchecked(self.into_iter().enumerate().map(|(index,
                                row)|
                            {
                                match row.try_into_sexp_unchecked() {
                                    Ok(child) => child,
                                    Err(error) => {
                                        errors.push_row(index, error);
                                        crate::SEXP::nil()
                                    }
                                }
                            }))
            };
        if errors.is_empty() { Ok(result) } else { Err(errors.into_error()) }
    }
}
impl<A: IntoR, B: IntoR, C: IntoR, D: IntoR, E: IntoR> IntoR for
    (A, B, C, D, E) {
    type Error = crate::into_r_error::IntoRError;
    fn try_into_sexp(self) -> Result<crate::SEXP, Self::Error> {
        unsafe {
            let scope = ProtectScope::new();
            let builder = ListBuilder::new(&scope, 5);
            let mut errors = crate::into_r_error::ElementFailures::default();
            match self.0.try_into_sexp() {
                Ok(child) => builder.set(0 as isize, child),
                Err(error) => errors.push(0, &error),
            }
            match self.1.try_into_sexp() {
                Ok(child) => builder.set(1 as isize, child),
                Err(error) => errors.push(1, &error),
            }
            match self.2.try_into_sexp() {
                Ok(child) => builder.set(2 as isize, child),
                Err(error) => errors.push(2, &error),
            }
            match self.3.try_into_sexp() {
                Ok(child) => builder.set(3 as isize, child),
                Err(error) => errors.push(3, &error),
            }
            match self.4.try_into_sexp() {
                Ok(child) => builder.set(4 as isize, child),
                Err(error) => errors.push(4, &error),
            }
            if errors.is_empty() {
                Ok(builder.into_sexp())
            } else { Err(errors.into_error()) }
        }
    }
    unsafe fn try_into_sexp_unchecked(self)
        -> Result<crate::SEXP, Self::Error> {
        unsafe {
            let scope = ProtectScope::new();
            let builder = ListBuilder::new_unchecked(&scope, 5);
            let mut errors = crate::into_r_error::ElementFailures::default();
            match self.0.try_into_sexp_unchecked() {
                Ok(child) => builder.set_unchecked(0 as isize, child),
                Err(error) => errors.push(0, &error),
            }
            match self.1.try_into_sexp_unchecked() {
                Ok(child) => builder.set_unchecked(1 as isize, child),
                Err(error) => errors.push(1, &error),
            }
            match self.2.try_into_sexp_unchecked() {
                Ok(child) => builder.set_unchecked(2 as isize, child),
                Err(error) => errors.push(2, &error),
            }
            match self.3.try_into_sexp_unchecked() {
                Ok(child) => builder.set_unchecked(3 as isize, child),
                Err(error) => errors.push(3, &error),
            }
            match self.4.try_into_sexp_unchecked() {
                Ok(child) => builder.set_unchecked(4 as isize, child),
                Err(error) => errors.push(4, &error),
            }
            if errors.is_empty() {
                Ok(builder.into_sexp())
            } else { Err(errors.into_error()) }
        }
    }
}
impl<A: IntoR, B: IntoR, C: IntoR, D: IntoR, E: IntoR> IntoR for
    Option<(A, B, C, D, E)> {
    type Error = <(A, B, C, D, E) as IntoR>::Error;
    fn try_into_sexp(self) -> Result<crate::SEXP, Self::Error> {
        self.map_or_else(|| Ok(crate::SEXP::nil()), IntoR::try_into_sexp)
    }
    unsafe fn try_into_sexp_unchecked(self)
        -> Result<crate::SEXP, Self::Error> {
        self.map_or_else(|| Ok(crate::SEXP::nil()),
            |value| unsafe { value.try_into_sexp_unchecked() })
    }
}
impl<A: IntoR, B: IntoR, C: IntoR, D: IntoR, E: IntoR> IntoR for
    Vec<(A, B, C, D, E)> {
    type Error = crate::into_r_error::IntoRError;
    fn try_into_sexp(self) -> Result<crate::SEXP, Self::Error> {
        let mut errors = crate::into_r_error::ElementFailures::default();
        let result =
            unsafe {
                vecsxp_from_iter(self.into_iter().enumerate().map(|(index,
                                row)|
                            {
                                match row.try_into_sexp() {
                                    Ok(child) => child,
                                    Err(error) => {
                                        errors.push_row(index, error);
                                        crate::SEXP::nil()
                                    }
                                }
                            }))
            };
        if errors.is_empty() { Ok(result) } else { Err(errors.into_error()) }
    }
    unsafe fn try_into_sexp_unchecked(self)
        -> Result<crate::SEXP, Self::Error> {
        let mut errors = crate::into_r_error::ElementFailures::default();
        let result =
            unsafe {
                vecsxp_from_iter_unchecked(self.into_iter().enumerate().map(|(index,
                                row)|
                            {
                                match row.try_into_sexp_unchecked() {
                                    Ok(child) => child,
                                    Err(error) => {
                                        errors.push_row(index, error);
                                        crate::SEXP::nil()
                                    }
                                }
                            }))
            };
        if errors.is_empty() { Ok(result) } else { Err(errors.into_error()) }
    }
}
impl<A: IntoR, B: IntoR, C: IntoR, D: IntoR, E: IntoR> IntoR for
    Vec<Option<(A, B, C, D, E)>> {
    type Error = crate::into_r_error::IntoRError;
    fn try_into_sexp(self) -> Result<crate::SEXP, Self::Error> {
        let mut errors = crate::into_r_error::ElementFailures::default();
        let result =
            unsafe {
                vecsxp_from_iter(self.into_iter().enumerate().map(|(index,
                                row)|
                            {
                                match row.try_into_sexp() {
                                    Ok(child) => child,
                                    Err(error) => {
                                        errors.push_row(index, error);
                                        crate::SEXP::nil()
                                    }
                                }
                            }))
            };
        if errors.is_empty() { Ok(result) } else { Err(errors.into_error()) }
    }
    unsafe fn try_into_sexp_unchecked(self)
        -> Result<crate::SEXP, Self::Error> {
        let mut errors = crate::into_r_error::ElementFailures::default();
        let result =
            unsafe {
                vecsxp_from_iter_unchecked(self.into_iter().enumerate().map(|(index,
                                row)|
                            {
                                match row.try_into_sexp_unchecked() {
                                    Ok(child) => child,
                                    Err(error) => {
                                        errors.push_row(index, error);
                                        crate::SEXP::nil()
                                    }
                                }
                            }))
            };
        if errors.is_empty() { Ok(result) } else { Err(errors.into_error()) }
    }
}
impl<A: IntoR, B: IntoR, C: IntoR, D: IntoR, E: IntoR, F: IntoR> IntoR for
    (A, B, C, D, E, F) {
    type Error = crate::into_r_error::IntoRError;
    fn try_into_sexp(self) -> Result<crate::SEXP, Self::Error> {
        unsafe {
            let scope = ProtectScope::new();
            let builder = ListBuilder::new(&scope, 6);
            let mut errors = crate::into_r_error::ElementFailures::default();
            match self.0.try_into_sexp() {
                Ok(child) => builder.set(0 as isize, child),
                Err(error) => errors.push(0, &error),
            }
            match self.1.try_into_sexp() {
                Ok(child) => builder.set(1 as isize, child),
                Err(error) => errors.push(1, &error),
            }
            match self.2.try_into_sexp() {
                Ok(child) => builder.set(2 as isize, child),
                Err(error) => errors.push(2, &error),
            }
            match self.3.try_into_sexp() {
                Ok(child) => builder.set(3 as isize, child),
                Err(error) => errors.push(3, &error),
            }
            match self.4.try_into_sexp() {
                Ok(child) => builder.set(4 as isize, child),
                Err(error) => errors.push(4, &error),
            }
            match self.5.try_into_sexp() {
                Ok(child) => builder.set(5 as isize, child),
                Err(error) => errors.push(5, &error),
            }
            if errors.is_empty() {
                Ok(builder.into_sexp())
            } else { Err(errors.into_error()) }
        }
    }
    unsafe fn try_into_sexp_unchecked(self)
        -> Result<crate::SEXP, Self::Error> {
        unsafe {
            let scope = ProtectScope::new();
            let builder = ListBuilder::new_unchecked(&scope, 6);
            let mut errors = crate::into_r_error::ElementFailures::default();
            match self.0.try_into_sexp_unchecked() {
                Ok(child) => builder.set_unchecked(0 as isize, child),
                Err(error) => errors.push(0, &error),
            }
            match self.1.try_into_sexp_unchecked() {
                Ok(child) => builder.set_unchecked(1 as isize, child),
                Err(error) => errors.push(1, &error),
            }
            match self.2.try_into_sexp_unchecked() {
                Ok(child) => builder.set_unchecked(2 as isize, child),
                Err(error) => errors.push(2, &error),
            }
            match self.3.try_into_sexp_unchecked() {
                Ok(child) => builder.set_unchecked(3 as isize, child),
                Err(error) => errors.push(3, &error),
            }
            match self.4.try_into_sexp_unchecked() {
                Ok(child) => builder.set_unchecked(4 as isize, child),
                Err(error) => errors.push(4, &error),
            }
            match self.5.try_into_sexp_unchecked() {
                Ok(child) => builder.set_unchecked(5 as isize, child),
                Err(error) => errors.push(5, &error),
            }
            if errors.is_empty() {
                Ok(builder.into_sexp())
            } else { Err(errors.into_error()) }
        }
    }
}
impl<A: IntoR, B: IntoR, C: IntoR, D: IntoR, E: IntoR, F: IntoR> IntoR for
    Option<(A, B, C, D, E, F)> {
    type Error = <(A, B, C, D, E, F) as IntoR>::Error;
    fn try_into_sexp(self) -> Result<crate::SEXP, Self::Error> {
        self.map_or_else(|| Ok(crate::SEXP::nil()), IntoR::try_into_sexp)
    }
    unsafe fn try_into_sexp_unchecked(self)
        -> Result<crate::SEXP, Self::Error> {
        self.map_or_else(|| Ok(crate::SEXP::nil()),
            |value| unsafe { value.try_into_sexp_unchecked() })
    }
}
impl<A: IntoR, B: IntoR, C: IntoR, D: IntoR, E: IntoR, F: IntoR> IntoR for
    Vec<(A, B, C, D, E, F)> {
    type Error = crate::into_r_error::IntoRError;
    fn try_into_sexp(self) -> Result<crate::SEXP, Self::Error> {
        let mut errors = crate::into_r_error::ElementFailures::default();
        let result =
            unsafe {
                vecsxp_from_iter(self.into_iter().enumerate().map(|(index,
                                row)|
                            {
                                match row.try_into_sexp() {
                                    Ok(child) => child,
                                    Err(error) => {
                                        errors.push_row(index, error);
                                        crate::SEXP::nil()
                                    }
                                }
                            }))
            };
        if errors.is_empty() { Ok(result) } else { Err(errors.into_error()) }
    }
    unsafe fn try_into_sexp_unchecked(self)
        -> Result<crate::SEXP, Self::Error> {
        let mut errors = crate::into_r_error::ElementFailures::default();
        let result =
            unsafe {
                vecsxp_from_iter_unchecked(self.into_iter().enumerate().map(|(index,
                                row)|
                            {
                                match row.try_into_sexp_unchecked() {
                                    Ok(child) => child,
                                    Err(error) => {
                                        errors.push_row(index, error);
                                        crate::SEXP::nil()
                                    }
                                }
                            }))
            };
        if errors.is_empty() { Ok(result) } else { Err(errors.into_error()) }
    }
}
impl<A: IntoR, B: IntoR, C: IntoR, D: IntoR, E: IntoR, F: IntoR> IntoR for
    Vec<Option<(A, B, C, D, E, F)>> {
    type Error = crate::into_r_error::IntoRError;
    fn try_into_sexp(self) -> Result<crate::SEXP, Self::Error> {
        let mut errors = crate::into_r_error::ElementFailures::default();
        let result =
            unsafe {
                vecsxp_from_iter(self.into_iter().enumerate().map(|(index,
                                row)|
                            {
                                match row.try_into_sexp() {
                                    Ok(child) => child,
                                    Err(error) => {
                                        errors.push_row(index, error);
                                        crate::SEXP::nil()
                                    }
                                }
                            }))
            };
        if errors.is_empty() { Ok(result) } else { Err(errors.into_error()) }
    }
    unsafe fn try_into_sexp_unchecked(self)
        -> Result<crate::SEXP, Self::Error> {
        let mut errors = crate::into_r_error::ElementFailures::default();
        let result =
            unsafe {
                vecsxp_from_iter_unchecked(self.into_iter().enumerate().map(|(index,
                                row)|
                            {
                                match row.try_into_sexp_unchecked() {
                                    Ok(child) => child,
                                    Err(error) => {
                                        errors.push_row(index, error);
                                        crate::SEXP::nil()
                                    }
                                }
                            }))
            };
        if errors.is_empty() { Ok(result) } else { Err(errors.into_error()) }
    }
}
impl<A: IntoR, B: IntoR, C: IntoR, D: IntoR, E: IntoR, F: IntoR, G: IntoR>
    IntoR for (A, B, C, D, E, F, G) {
    type Error = crate::into_r_error::IntoRError;
    fn try_into_sexp(self) -> Result<crate::SEXP, Self::Error> {
        unsafe {
            let scope = ProtectScope::new();
            let builder = ListBuilder::new(&scope, 7);
            let mut errors = crate::into_r_error::ElementFailures::default();
            match self.0.try_into_sexp() {
                Ok(child) => builder.set(0 as isize, child),
                Err(error) => errors.push(0, &error),
            }
            match self.1.try_into_sexp() {
                Ok(child) => builder.set(1 as isize, child),
                Err(error) => errors.push(1, &error),
            }
            match self.2.try_into_sexp() {
                Ok(child) => builder.set(2 as isize, child),
                Err(error) => errors.push(2, &error),
            }
            match self.3.try_into_sexp() {
                Ok(child) => builder.set(3 as isize, child),
                Err(error) => errors.push(3, &error),
            }
            match self.4.try_into_sexp() {
                Ok(child) => builder.set(4 as isize, child),
                Err(error) => errors.push(4, &error),
            }
            match self.5.try_into_sexp() {
                Ok(child) => builder.set(5 as isize, child),
                Err(error) => errors.push(5, &error),
            }
            match self.6.try_into_sexp() {
                Ok(child) => builder.set(6 as isize, child),
                Err(error) => errors.push(6, &error),
            }
            if errors.is_empty() {
                Ok(builder.into_sexp())
            } else { Err(errors.into_error()) }
        }
    }
    unsafe fn try_into_sexp_unchecked(self)
        -> Result<crate::SEXP, Self::Error> {
        unsafe {
            let scope = ProtectScope::new();
            let builder = ListBuilder::new_unchecked(&scope, 7);
            let mut errors = crate::into_r_error::ElementFailures::default();
            match self.0.try_into_sexp_unchecked() {
                Ok(child) => builder.set_unchecked(0 as isize, child),
                Err(error) => errors.push(0, &error),
            }
            match self.1.try_into_sexp_unchecked() {
                Ok(child) => builder.set_unchecked(1 as isize, child),
                Err(error) => errors.push(1, &error),
            }
            match self.2.try_into_sexp_unchecked() {
                Ok(child) => builder.set_unchecked(2 as isize, child),
                Err(error) => errors.push(2, &error),
            }
            match self.3.try_into_sexp_unchecked() {
                Ok(child) => builder.set_unchecked(3 as isize, child),
                Err(error) => errors.push(3, &error),
            }
            match self.4.try_into_sexp_unchecked() {
                Ok(child) => builder.set_unchecked(4 as isize, child),
                Err(error) => errors.push(4, &error),
            }
            match self.5.try_into_sexp_unchecked() {
                Ok(child) => builder.set_unchecked(5 as isize, child),
                Err(error) => errors.push(5, &error),
            }
            match self.6.try_into_sexp_unchecked() {
                Ok(child) => builder.set_unchecked(6 as isize, child),
                Err(error) => errors.push(6, &error),
            }
            if errors.is_empty() {
                Ok(builder.into_sexp())
            } else { Err(errors.into_error()) }
        }
    }
}
impl<A: IntoR, B: IntoR, C: IntoR, D: IntoR, E: IntoR, F: IntoR, G: IntoR>
    IntoR for Option<(A, B, C, D, E, F, G)> {
    type Error = <(A, B, C, D, E, F, G) as IntoR>::Error;
    fn try_into_sexp(self) -> Result<crate::SEXP, Self::Error> {
        self.map_or_else(|| Ok(crate::SEXP::nil()), IntoR::try_into_sexp)
    }
    unsafe fn try_into_sexp_unchecked(self)
        -> Result<crate::SEXP, Self::Error> {
        self.map_or_else(|| Ok(crate::SEXP::nil()),
            |value| unsafe { value.try_into_sexp_unchecked() })
    }
}
impl<A: IntoR, B: IntoR, C: IntoR, D: IntoR, E: IntoR, F: IntoR, G: IntoR>
    IntoR for Vec<(A, B, C, D, E, F, G)> {
    type Error = crate::into_r_error::IntoRError;
    fn try_into_sexp(self) -> Result<crate::SEXP, Self::Error> {
        let mut errors = crate::into_r_error::ElementFailures::default();
        let result =
            unsafe {
                vecsxp_from_iter(self.into_iter().enumerate().map(|(index,
                                row)|
                            {
                                match row.try_into_sexp() {
                                    Ok(child) => child,
                                    Err(error) => {
                                        errors.push_row(index, error);
                                        crate::SEXP::nil()
                                    }
                                }
                            }))
            };
        if errors.is_empty() { Ok(result) } else { Err(errors.into_error()) }
    }
    unsafe fn try_into_sexp_unchecked(self)
        -> Result<crate::SEXP, Self::Error> {
        let mut errors = crate::into_r_error::ElementFailures::default();
        let result =
            unsafe {
                vecsxp_from_iter_unchecked(self.into_iter().enumerate().map(|(index,
                                row)|
                            {
                                match row.try_into_sexp_unchecked() {
                                    Ok(child) => child,
                                    Err(error) => {
                                        errors.push_row(index, error);
                                        crate::SEXP::nil()
                                    }
                                }
                            }))
            };
        if errors.is_empty() { Ok(result) } else { Err(errors.into_error()) }
    }
}
impl<A: IntoR, B: IntoR, C: IntoR, D: IntoR, E: IntoR, F: IntoR, G: IntoR>
    IntoR for Vec<Option<(A, B, C, D, E, F, G)>> {
    type Error = crate::into_r_error::IntoRError;
    fn try_into_sexp(self) -> Result<crate::SEXP, Self::Error> {
        let mut errors = crate::into_r_error::ElementFailures::default();
        let result =
            unsafe {
                vecsxp_from_iter(self.into_iter().enumerate().map(|(index,
                                row)|
                            {
                                match row.try_into_sexp() {
                                    Ok(child) => child,
                                    Err(error) => {
                                        errors.push_row(index, error);
                                        crate::SEXP::nil()
                                    }
                                }
                            }))
            };
        if errors.is_empty() { Ok(result) } else { Err(errors.into_error()) }
    }
    unsafe fn try_into_sexp_unchecked(self)
        -> Result<crate::SEXP, Self::Error> {
        let mut errors = crate::into_r_error::ElementFailures::default();
        let result =
            unsafe {
                vecsxp_from_iter_unchecked(self.into_iter().enumerate().map(|(index,
                                row)|
                            {
                                match row.try_into_sexp_unchecked() {
                                    Ok(child) => child,
                                    Err(error) => {
                                        errors.push_row(index, error);
                                        crate::SEXP::nil()
                                    }
                                }
                            }))
            };
        if errors.is_empty() { Ok(result) } else { Err(errors.into_error()) }
    }
}
impl<A: IntoR, B: IntoR, C: IntoR, D: IntoR, E: IntoR, F: IntoR, G: IntoR,
    H: IntoR> IntoR for (A, B, C, D, E, F, G, H) {
    type Error = crate::into_r_error::IntoRError;
    fn try_into_sexp(self) -> Result<crate::SEXP, Self::Error> {
        unsafe {
            let scope = ProtectScope::new();
            let builder = ListBuilder::new(&scope, 8);
            let mut errors = crate::into_r_error::ElementFailures::default();
            match self.0.try_into_sexp() {
                Ok(child) => builder.set(0 as isize, child),
                Err(error) => errors.push(0, &error),
            }
            match self.1.try_into_sexp() {
                Ok(child) => builder.set(1 as isize, child),
                Err(error) => errors.push(1, &error),
            }
            match self.2.try_into_sexp() {
                Ok(child) => builder.set(2 as isize, child),
                Err(error) => errors.push(2, &error),
            }
            match self.3.try_into_sexp() {
                Ok(child) => builder.set(3 as isize, child),
                Err(error) => errors.push(3, &error),
            }
            match self.4.try_into_sexp() {
                Ok(child) => builder.set(4 as isize, child),
                Err(error) => errors.push(4, &error),
            }
            match self.5.try_into_sexp() {
                Ok(child) => builder.set(5 as isize, child),
                Err(error) => errors.push(5, &error),
            }
            match self.6.try_into_sexp() {
                Ok(child) => builder.set(6 as isize, child),
                Err(error) => errors.push(6, &error),
            }
            match self.7.try_into_sexp() {
                Ok(child) => builder.set(7 as isize, child),
                Err(error) => errors.push(7, &error),
            }
            if errors.is_empty() {
                Ok(builder.into_sexp())
            } else { Err(errors.into_error()) }
        }
    }
    unsafe fn try_into_sexp_unchecked(self)
        -> Result<crate::SEXP, Self::Error> {
        unsafe {
            let scope = ProtectScope::new();
            let builder = ListBuilder::new_unchecked(&scope, 8);
            let mut errors = crate::into_r_error::ElementFailures::default();
            match self.0.try_into_sexp_unchecked() {
                Ok(child) => builder.set_unchecked(0 as isize, child),
                Err(error) => errors.push(0, &error),
            }
            match self.1.try_into_sexp_unchecked() {
                Ok(child) => builder.set_unchecked(1 as isize, child),
                Err(error) => errors.push(1, &error),
            }
            match self.2.try_into_sexp_unchecked() {
                Ok(child) => builder.set_unchecked(2 as isize, child),
                Err(error) => errors.push(2, &error),
            }
            match self.3.try_into_sexp_unchecked() {
                Ok(child) => builder.set_unchecked(3 as isize, child),
                Err(error) => errors.push(3, &error),
            }
            match self.4.try_into_sexp_unchecked() {
                Ok(child) => builder.set_unchecked(4 as isize, child),
                Err(error) => errors.push(4, &error),
            }
            match self.5.try_into_sexp_unchecked() {
                Ok(child) => builder.set_unchecked(5 as isize, child),
                Err(error) => errors.push(5, &error),
            }
            match self.6.try_into_sexp_unchecked() {
                Ok(child) => builder.set_unchecked(6 as isize, child),
                Err(error) => errors.push(6, &error),
            }
            match self.7.try_into_sexp_unchecked() {
                Ok(child) => builder.set_unchecked(7 as isize, child),
                Err(error) => errors.push(7, &error),
            }
            if errors.is_empty() {
                Ok(builder.into_sexp())
            } else { Err(errors.into_error()) }
        }
    }
}
impl<A: IntoR, B: IntoR, C: IntoR, D: IntoR, E: IntoR, F: IntoR, G: IntoR,
    H: IntoR> IntoR for Option<(A, B, C, D, E, F, G, H)> {
    type Error = <(A, B, C, D, E, F, G, H) as IntoR>::Error;
    fn try_into_sexp(self) -> Result<crate::SEXP, Self::Error> {
        self.map_or_else(|| Ok(crate::SEXP::nil()), IntoR::try_into_sexp)
    }
    unsafe fn try_into_sexp_unchecked(self)
        -> Result<crate::SEXP, Self::Error> {
        self.map_or_else(|| Ok(crate::SEXP::nil()),
            |value| unsafe { value.try_into_sexp_unchecked() })
    }
}
impl<A: IntoR, B: IntoR, C: IntoR, D: IntoR, E: IntoR, F: IntoR, G: IntoR,
    H: IntoR> IntoR for Vec<(A, B, C, D, E, F, G, H)> {
    type Error = crate::into_r_error::IntoRError;
    fn try_into_sexp(self) -> Result<crate::SEXP, Self::Error> {
        let mut errors = crate::into_r_error::ElementFailures::default();
        let result =
            unsafe {
                vecsxp_from_iter(self.into_iter().enumerate().map(|(index,
                                row)|
                            {
                                match row.try_into_sexp() {
                                    Ok(child) => child,
                                    Err(error) => {
                                        errors.push_row(index, error);
                                        crate::SEXP::nil()
                                    }
                                }
                            }))
            };
        if errors.is_empty() { Ok(result) } else { Err(errors.into_error()) }
    }
    unsafe fn try_into_sexp_unchecked(self)
        -> Result<crate::SEXP, Self::Error> {
        let mut errors = crate::into_r_error::ElementFailures::default();
        let result =
            unsafe {
                vecsxp_from_iter_unchecked(self.into_iter().enumerate().map(|(index,
                                row)|
                            {
                                match row.try_into_sexp_unchecked() {
                                    Ok(child) => child,
                                    Err(error) => {
                                        errors.push_row(index, error);
                                        crate::SEXP::nil()
                                    }
                                }
                            }))
            };
        if errors.is_empty() { Ok(result) } else { Err(errors.into_error()) }
    }
}
impl<A: IntoR, B: IntoR, C: IntoR, D: IntoR, E: IntoR, F: IntoR, G: IntoR,
    H: IntoR> IntoR for Vec<Option<(A, B, C, D, E, F, G, H)>> {
    type Error = crate::into_r_error::IntoRError;
    fn try_into_sexp(self) -> Result<crate::SEXP, Self::Error> {
        let mut errors = crate::into_r_error::ElementFailures::default();
        let result =
            unsafe {
                vecsxp_from_iter(self.into_iter().enumerate().map(|(index,
                                row)|
                            {
                                match row.try_into_sexp() {
                                    Ok(child) => child,
                                    Err(error) => {
                                        errors.push_row(index, error);
                                        crate::SEXP::nil()
                                    }
                                }
                            }))
            };
        if errors.is_empty() { Ok(result) } else { Err(errors.into_error()) }
    }
    unsafe fn try_into_sexp_unchecked(self)
        -> Result<crate::SEXP, Self::Error> {
        let mut errors = crate::into_r_error::ElementFailures::default();
        let result =
            unsafe {
                vecsxp_from_iter_unchecked(self.into_iter().enumerate().map(|(index,
                                row)|
                            {
                                match row.try_into_sexp_unchecked() {
                                    Ok(child) => child,
                                    Err(error) => {
                                        errors.push_row(index, error);
                                        crate::SEXP::nil()
                                    }
                                }
                            }))
            };
        if errors.is_empty() { Ok(result) } else { Err(errors.into_error()) }
    }
}
impl<A: IntoR, B: IntoR, C: IntoR, D: IntoR, E: IntoR, F: IntoR, G: IntoR,
    H: IntoR, I: IntoR> IntoR for (A, B, C, D, E, F, G, H, I) {
    type Error = crate::into_r_error::IntoRError;
    fn try_into_sexp(self) -> Result<crate::SEXP, Self::Error> {
        unsafe {
            let scope = ProtectScope::new();
            let builder = ListBuilder::new(&scope, 9);
            let mut errors = crate::into_r_error::ElementFailures::default();
            match self.0.try_into_sexp() {
                Ok(child) => builder.set(0 as isize, child),
                Err(error) => errors.push(0, &error),
            }
            match self.1.try_into_sexp() {
                Ok(child) => builder.set(1 as isize, child),
                Err(error) => errors.push(1, &error),
            }
            match self.2.try_into_sexp() {
                Ok(child) => builder.set(2 as isize, child),
                Err(error) => errors.push(2, &error),
            }
            match self.3.try_into_sexp() {
                Ok(child) => builder.set(3 as isize, child),
                Err(error) => errors.push(3, &error),
            }
            match self.4.try_into_sexp() {
                Ok(child) => builder.set(4 as isize, child),
                Err(error) => errors.push(4, &error),
            }
            match self.5.try_into_sexp() {
                Ok(child) => builder.set(5 as isize, child),
                Err(error) => errors.push(5, &error),
            }
            match self.6.try_into_sexp() {
                Ok(child) => builder.set(6 as isize, child),
                Err(error) => errors.push(6, &error),
            }
            match self.7.try_into_sexp() {
                Ok(child) => builder.set(7 as isize, child),
                Err(error) => errors.push(7, &error),
            }
            match self.8.try_into_sexp() {
                Ok(child) => builder.set(8 as isize, child),
                Err(error) => errors.push(8, &error),
            }
            if errors.is_empty() {
                Ok(builder.into_sexp())
            } else { Err(errors.into_error()) }
        }
    }
    unsafe fn try_into_sexp_unchecked(self)
        -> Result<crate::SEXP, Self::Error> {
        unsafe {
            let scope = ProtectScope::new();
            let builder = ListBuilder::new_unchecked(&scope, 9);
            let mut errors = crate::into_r_error::ElementFailures::default();
            match self.0.try_into_sexp_unchecked() {
                Ok(child) => builder.set_unchecked(0 as isize, child),
                Err(error) => errors.push(0, &error),
            }
            match self.1.try_into_sexp_unchecked() {
                Ok(child) => builder.set_unchecked(1 as isize, child),
                Err(error) => errors.push(1, &error),
            }
            match self.2.try_into_sexp_unchecked() {
                Ok(child) => builder.set_unchecked(2 as isize, child),
                Err(error) => errors.push(2, &error),
            }
            match self.3.try_into_sexp_unchecked() {
                Ok(child) => builder.set_unchecked(3 as isize, child),
                Err(error) => errors.push(3, &error),
            }
            match self.4.try_into_sexp_unchecked() {
                Ok(child) => builder.set_unchecked(4 as isize, child),
                Err(error) => errors.push(4, &error),
            }
            match self.5.try_into_sexp_unchecked() {
                Ok(child) => builder.set_unchecked(5 as isize, child),
                Err(error) => errors.push(5, &error),
            }
            match self.6.try_into_sexp_unchecked() {
                Ok(child) => builder.set_unchecked(6 as isize, child),
                Err(error) => errors.push(6, &error),
            }
            match self.7.try_into_sexp_unchecked() {
                Ok(child) => builder.set_unchecked(7 as isize, child),
                Err(error) => errors.push(7, &error),
            }
            match self.8.try_into_sexp_unchecked() {
                Ok(child) => builder.set_unchecked(8 as isize, child),
                Err(error) => errors.push(8, &error),
            }
            if errors.is_empty() {
                Ok(builder.into_sexp())
            } else { Err(errors.into_error()) }
        }
    }
}
impl<A: IntoR, B: IntoR, C: IntoR, D: IntoR, E: IntoR, F: IntoR, G: IntoR,
    H: IntoR, I: IntoR> IntoR for Option<(A, B, C, D, E, F, G, H, I)> {
    type Error = <(A, B, C, D, E, F, G, H, I) as IntoR>::Error;
    fn try_into_sexp(self) -> Result<crate::SEXP, Self::Error> {
        self.map_or_else(|| Ok(crate::SEXP::nil()), IntoR::try_into_sexp)
    }
    unsafe fn try_into_sexp_unchecked(self)
        -> Result<crate::SEXP, Self::Error> {
        self.map_or_else(|| Ok(crate::SEXP::nil()),
            |value| unsafe { value.try_into_sexp_unchecked() })
    }
}
impl<A: IntoR, B: IntoR, C: IntoR, D: IntoR, E: IntoR, F: IntoR, G: IntoR,
    H: IntoR, I: IntoR> IntoR for Vec<(A, B, C, D, E, F, G, H, I)> {
    type Error = crate::into_r_error::IntoRError;
    fn try_into_sexp(self) -> Result<crate::SEXP, Self::Error> {
        let mut errors = crate::into_r_error::ElementFailures::default();
        let result =
            unsafe {
                vecsxp_from_iter(self.into_iter().enumerate().map(|(index,
                                row)|
                            {
                                match row.try_into_sexp() {
                                    Ok(child) => child,
                                    Err(error) => {
                                        errors.push_row(index, error);
                                        crate::SEXP::nil()
                                    }
                                }
                            }))
            };
        if errors.is_empty() { Ok(result) } else { Err(errors.into_error()) }
    }
    unsafe fn try_into_sexp_unchecked(self)
        -> Result<crate::SEXP, Self::Error> {
        let mut errors = crate::into_r_error::ElementFailures::default();
        let result =
            unsafe {
                vecsxp_from_iter_unchecked(self.into_iter().enumerate().map(|(index,
                                row)|
                            {
                                match row.try_into_sexp_unchecked() {
                                    Ok(child) => child,
                                    Err(error) => {
                                        errors.push_row(index, error);
                                        crate::SEXP::nil()
                                    }
                                }
                            }))
            };
        if errors.is_empty() { Ok(result) } else { Err(errors.into_error()) }
    }
}
impl<A: IntoR, B: IntoR, C: IntoR, D: IntoR, E: IntoR, F: IntoR, G: IntoR,
    H: IntoR, I: IntoR> IntoR for Vec<Option<(A, B, C, D, E, F, G, H, I)>> {
    type Error = crate::into_r_error::IntoRError;
    fn try_into_sexp(self) -> Result<crate::SEXP, Self::Error> {
        let mut errors = crate::into_r_error::ElementFailures::default();
        let result =
            unsafe {
                vecsxp_from_iter(self.into_iter().enumerate().map(|(index,
                                row)|
                            {
                                match row.try_into_sexp() {
                                    Ok(child) => child,
                                    Err(error) => {
                                        errors.push_row(index, error);
                                        crate::SEXP::nil()
                                    }
                                }
                            }))
            };
        if errors.is_empty() { Ok(result) } else { Err(errors.into_error()) }
    }
    unsafe fn try_into_sexp_unchecked(self)
        -> Result<crate::SEXP, Self::Error> {
        let mut errors = crate::into_r_error::ElementFailures::default();
        let result =
            unsafe {
                vecsxp_from_iter_unchecked(self.into_iter().enumerate().map(|(index,
                                row)|
                            {
                                match row.try_into_sexp_unchecked() {
                                    Ok(child) => child,
                                    Err(error) => {
                                        errors.push_row(index, error);
                                        crate::SEXP::nil()
                                    }
                                }
                            }))
            };
        if errors.is_empty() { Ok(result) } else { Err(errors.into_error()) }
    }
}
impl<A: IntoR, B: IntoR, C: IntoR, D: IntoR, E: IntoR, F: IntoR, G: IntoR,
    H: IntoR, I: IntoR, J: IntoR> IntoR for (A, B, C, D, E, F, G, H, I, J) {
    type Error = crate::into_r_error::IntoRError;
    fn try_into_sexp(self) -> Result<crate::SEXP, Self::Error> {
        unsafe {
            let scope = ProtectScope::new();
            let builder = ListBuilder::new(&scope, 10);
            let mut errors = crate::into_r_error::ElementFailures::default();
            match self.0.try_into_sexp() {
                Ok(child) => builder.set(0 as isize, child),
                Err(error) => errors.push(0, &error),
            }
            match self.1.try_into_sexp() {
                Ok(child) => builder.set(1 as isize, child),
                Err(error) => errors.push(1, &error),
            }
            match self.2.try_into_sexp() {
                Ok(child) => builder.set(2 as isize, child),
                Err(error) => errors.push(2, &error),
            }
            match self.3.try_into_sexp() {
                Ok(child) => builder.set(3 as isize, child),
                Err(error) => errors.push(3, &error),
            }
            match self.4.try_into_sexp() {
                Ok(child) => builder.set(4 as isize, child),
                Err(error) => errors.push(4, &error),
            }
            match self.5.try_into_sexp() {
                Ok(child) => builder.set(5 as isize, child),
                Err(error) => errors.push(5, &error),
            }
            match self.6.try_into_sexp() {
                Ok(child) => builder.set(6 as isize, child),
                Err(error) => errors.push(6, &error),
            }
            match self.7.try_into_sexp() {
                Ok(child) => builder.set(7 as isize, child),
                Err(error) => errors.push(7, &error),
            }
            match self.8.try_into_sexp() {
                Ok(child) => builder.set(8 as isize, child),
                Err(error) => errors.push(8, &error),
            }
            match self.9.try_into_sexp() {
                Ok(child) => builder.set(9 as isize, child),
                Err(error) => errors.push(9, &error),
            }
            if errors.is_empty() {
                Ok(builder.into_sexp())
            } else { Err(errors.into_error()) }
        }
    }
    unsafe fn try_into_sexp_unchecked(self)
        -> Result<crate::SEXP, Self::Error> {
        unsafe {
            let scope = ProtectScope::new();
            let builder = ListBuilder::new_unchecked(&scope, 10);
            let mut errors = crate::into_r_error::ElementFailures::default();
            match self.0.try_into_sexp_unchecked() {
                Ok(child) => builder.set_unchecked(0 as isize, child),
                Err(error) => errors.push(0, &error),
            }
            match self.1.try_into_sexp_unchecked() {
                Ok(child) => builder.set_unchecked(1 as isize, child),
                Err(error) => errors.push(1, &error),
            }
            match self.2.try_into_sexp_unchecked() {
                Ok(child) => builder.set_unchecked(2 as isize, child),
                Err(error) => errors.push(2, &error),
            }
            match self.3.try_into_sexp_unchecked() {
                Ok(child) => builder.set_unchecked(3 as isize, child),
                Err(error) => errors.push(3, &error),
            }
            match self.4.try_into_sexp_unchecked() {
                Ok(child) => builder.set_unchecked(4 as isize, child),
                Err(error) => errors.push(4, &error),
            }
            match self.5.try_into_sexp_unchecked() {
                Ok(child) => builder.set_unchecked(5 as isize, child),
                Err(error) => errors.push(5, &error),
            }
            match self.6.try_into_sexp_unchecked() {
                Ok(child) => builder.set_unchecked(6 as isize, child),
                Err(error) => errors.push(6, &error),
            }
            match self.7.try_into_sexp_unchecked() {
                Ok(child) => builder.set_unchecked(7 as isize, child),
                Err(error) => errors.push(7, &error),
            }
            match self.8.try_into_sexp_unchecked() {
                Ok(child) => builder.set_unchecked(8 as isize, child),
                Err(error) => errors.push(8, &error),
            }
            match self.9.try_into_sexp_unchecked() {
                Ok(child) => builder.set_unchecked(9 as isize, child),
                Err(error) => errors.push(9, &error),
            }
            if errors.is_empty() {
                Ok(builder.into_sexp())
            } else { Err(errors.into_error()) }
        }
    }
}
impl<A: IntoR, B: IntoR, C: IntoR, D: IntoR, E: IntoR, F: IntoR, G: IntoR,
    H: IntoR, I: IntoR, J: IntoR> IntoR for
    Option<(A, B, C, D, E, F, G, H, I, J)> {
    type Error = <(A, B, C, D, E, F, G, H, I, J) as IntoR>::Error;
    fn try_into_sexp(self) -> Result<crate::SEXP, Self::Error> {
        self.map_or_else(|| Ok(crate::SEXP::nil()), IntoR::try_into_sexp)
    }
    unsafe fn try_into_sexp_unchecked(self)
        -> Result<crate::SEXP, Self::Error> {
        self.map_or_else(|| Ok(crate::SEXP::nil()),
            |value| unsafe { value.try_into_sexp_unchecked() })
    }
}
impl<A: IntoR, B: IntoR, C: IntoR, D: IntoR, E: IntoR, F: IntoR, G: IntoR,
    H: IntoR, I: IntoR, J: IntoR> IntoR for
    Vec<(A, B, C, D, E, F, G, H, I, J)> {
    type Error = crate::into_r_error::IntoRError;
    fn try_into_sexp(self) -> Result<crate::SEXP, Self::Error> {
        let mut errors = crate::into_r_error::ElementFailures::default();
        let result =
            unsafe {
                vecsxp_from_iter(self.into_iter().enumerate().map(|(index,
                                row)|
                            {
                                match row.try_into_sexp() {
                                    Ok(child) => child,
                                    Err(error) => {
                                        errors.push_row(index, error);
                                        crate::SEXP::nil()
                                    }
                                }
                            }))
            };
        if errors.is_empty() { Ok(result) } else { Err(errors.into_error()) }
    }
    unsafe fn try_into_sexp_unchecked(self)
        -> Result<crate::SEXP, Self::Error> {
        let mut errors = crate::into_r_error::ElementFailures::default();
        let result =
            unsafe {
                vecsxp_from_iter_unchecked(self.into_iter().enumerate().map(|(index,
                                row)|
                            {
                                match row.try_into_sexp_unchecked() {
                                    Ok(child) => child,
                                    Err(error) => {
                                        errors.push_row(index, error);
                                        crate::SEXP::nil()
                                    }
                                }
                            }))
            };
        if errors.is_empty() { Ok(result) } else { Err(errors.into_error()) }
    }
}
impl<A: IntoR, B: IntoR, C: IntoR, D: IntoR, E: IntoR, F: IntoR, G: IntoR,
    H: IntoR, I: IntoR, J: IntoR> IntoR for
    Vec<Option<(A, B, C, D, E, F, G, H, I, J)>> {
    type Error = crate::into_r_error::IntoRError;
    fn try_into_sexp(self) -> Result<crate::SEXP, Self::Error> {
        let mut errors = crate::into_r_error::ElementFailures::default();
        let result =
            unsafe {
                vecsxp_from_iter(self.into_iter().enumerate().map(|(index,
                                row)|
                            {
                                match row.try_into_sexp() {
                                    Ok(child) => child,
                                    Err(error) => {
                                        errors.push_row(index, error);
                                        crate::SEXP::nil()
                                    }
                                }
                            }))
            };
        if errors.is_empty() { Ok(result) } else { Err(errors.into_error()) }
    }
    unsafe fn try_into_sexp_unchecked(self)
        -> Result<crate::SEXP, Self::Error> {
        let mut errors = crate::into_r_error::ElementFailures::default();
        let result =
            unsafe {
                vecsxp_from_iter_unchecked(self.into_iter().enumerate().map(|(index,
                                row)|
                            {
                                match row.try_into_sexp_unchecked() {
                                    Ok(child) => child,
                                    Err(error) => {
                                        errors.push_row(index, error);
                                        crate::SEXP::nil()
                                    }
                                }
                            }))
            };
        if errors.is_empty() { Ok(result) } else { Err(errors.into_error()) }
    }
}
impl<A: IntoR, B: IntoR, C: IntoR, D: IntoR, E: IntoR, F: IntoR, G: IntoR,
    H: IntoR, I: IntoR, J: IntoR, K: IntoR> IntoR for
    (A, B, C, D, E, F, G, H, I, J, K) {
    type Error = crate::into_r_error::IntoRError;
    fn try_into_sexp(self) -> Result<crate::SEXP, Self::Error> {
        unsafe {
            let scope = ProtectScope::new();
            let builder = ListBuilder::new(&scope, 11);
            let mut errors = crate::into_r_error::ElementFailures::default();
            match self.0.try_into_sexp() {
                Ok(child) => builder.set(0 as isize, child),
                Err(error) => errors.push(0, &error),
            }
            match self.1.try_into_sexp() {
                Ok(child) => builder.set(1 as isize, child),
                Err(error) => errors.push(1, &error),
            }
            match self.2.try_into_sexp() {
                Ok(child) => builder.set(2 as isize, child),
                Err(error) => errors.push(2, &error),
            }
            match self.3.try_into_sexp() {
                Ok(child) => builder.set(3 as isize, child),
                Err(error) => errors.push(3, &error),
            }
            match self.4.try_into_sexp() {
                Ok(child) => builder.set(4 as isize, child),
                Err(error) => errors.push(4, &error),
            }
            match self.5.try_into_sexp() {
                Ok(child) => builder.set(5 as isize, child),
                Err(error) => errors.push(5, &error),
            }
            match self.6.try_into_sexp() {
                Ok(child) => builder.set(6 as isize, child),
                Err(error) => errors.push(6, &error),
            }
            match self.7.try_into_sexp() {
                Ok(child) => builder.set(7 as isize, child),
                Err(error) => errors.push(7, &error),
            }
            match self.8.try_into_sexp() {
                Ok(child) => builder.set(8 as isize, child),
                Err(error) => errors.push(8, &error),
            }
            match self.9.try_into_sexp() {
                Ok(child) => builder.set(9 as isize, child),
                Err(error) => errors.push(9, &error),
            }
            match self.10.try_into_sexp() {
                Ok(child) => builder.set(10 as isize, child),
                Err(error) => errors.push(10, &error),
            }
            if errors.is_empty() {
                Ok(builder.into_sexp())
            } else { Err(errors.into_error()) }
        }
    }
    unsafe fn try_into_sexp_unchecked(self)
        -> Result<crate::SEXP, Self::Error> {
        unsafe {
            let scope = ProtectScope::new();
            let builder = ListBuilder::new_unchecked(&scope, 11);
            let mut errors = crate::into_r_error::ElementFailures::default();
            match self.0.try_into_sexp_unchecked() {
                Ok(child) => builder.set_unchecked(0 as isize, child),
                Err(error) => errors.push(0, &error),
            }
            match self.1.try_into_sexp_unchecked() {
                Ok(child) => builder.set_unchecked(1 as isize, child),
                Err(error) => errors.push(1, &error),
            }
            match self.2.try_into_sexp_unchecked() {
                Ok(child) => builder.set_unchecked(2 as isize, child),
                Err(error) => errors.push(2, &error),
            }
            match self.3.try_into_sexp_unchecked() {
                Ok(child) => builder.set_unchecked(3 as isize, child),
                Err(error) => errors.push(3, &error),
            }
            match self.4.try_into_sexp_unchecked() {
                Ok(child) => builder.set_unchecked(4 as isize, child),
                Err(error) => errors.push(4, &error),
            }
            match self.5.try_into_sexp_unchecked() {
                Ok(child) => builder.set_unchecked(5 as isize, child),
                Err(error) => errors.push(5, &error),
            }
            match self.6.try_into_sexp_unchecked() {
                Ok(child) => builder.set_unchecked(6 as isize, child),
                Err(error) => errors.push(6, &error),
            }
            match self.7.try_into_sexp_unchecked() {
                Ok(child) => builder.set_unchecked(7 as isize, child),
                Err(error) => errors.push(7, &error),
            }
            match self.8.try_into_sexp_unchecked() {
                Ok(child) => builder.set_unchecked(8 as isize, child),
                Err(error) => errors.push(8, &error),
            }
            match self.9.try_into_sexp_unchecked() {
                Ok(child) => builder.set_unchecked(9 as isize, child),
                Err(error) => errors.push(9, &error),
            }
            match self.10.try_into_sexp_unchecked() {
                Ok(child) => builder.set_unchecked(10 as isize, child),
                Err(error) => errors.push(10, &error),
            }
            if errors.is_empty() {
                Ok(builder.into_sexp())
            } else { Err(errors.into_error()) }
        }
    }
}
impl<A: IntoR, B: IntoR, C: IntoR, D: IntoR, E: IntoR, F: IntoR, G: IntoR,
    H: IntoR, I: IntoR, J: IntoR, K: IntoR> IntoR for
    Option<(A, B, C, D, E, F, G, H, I, J, K)> {
    type Error = <(A, B, C, D, E, F, G, H, I, J, K) as IntoR>::Error;
    fn try_into_sexp(self) -> Result<crate::SEXP, Self::Error> {
        self.map_or_else(|| Ok(crate::SEXP::nil()), IntoR::try_into_sexp)
    }
    unsafe fn try_into_sexp_unchecked(self)
        -> Result<crate::SEXP, Self::Error> {
        self.map_or_else(|| Ok(crate::SEXP::nil()),
            |value| unsafe { value.try_into_sexp_unchecked() })
    }
}
impl<A: IntoR, B: IntoR, C: IntoR, D: IntoR, E: IntoR, F: IntoR, G: IntoR,
    H: IntoR, I: IntoR, J: IntoR, K: IntoR> IntoR for
    Vec<(A, B, C, D, E, F, G, H, I, J, K)> {
    type Error = crate::into_r_error::IntoRError;
    fn try_into_sexp(self) -> Result<crate::SEXP, Self::Error> {
        let mut errors = crate::into_r_error::ElementFailures::default();
        let result =
            unsafe {
                vecsxp_from_iter(self.into_iter().enumerate().map(|(index,
                                row)|
                            {
                                match row.try_into_sexp() {
                                    Ok(child) => child,
                                    Err(error) => {
                                        errors.push_row(index, error);
                                        crate::SEXP::nil()
                                    }
                                }
                            }))
            };
        if errors.is_empty() { Ok(result) } else { Err(errors.into_error()) }
    }
    unsafe fn try_into_sexp_unchecked(self)
        -> Result<crate::SEXP, Self::Error> {
        let mut errors = crate::into_r_error::ElementFailures::default();
        let result =
            unsafe {
                vecsxp_from_iter_unchecked(self.into_iter().enumerate().map(|(index,
                                row)|
                            {
                                match row.try_into_sexp_unchecked() {
                                    Ok(child) => child,
                                    Err(error) => {
                                        errors.push_row(index, error);
                                        crate::SEXP::nil()
                                    }
                                }
                            }))
            };
        if errors.is_empty() { Ok(result) } else { Err(errors.into_error()) }
    }
}
impl<A: IntoR, B: IntoR, C: IntoR, D: IntoR, E: IntoR, F: IntoR, G: IntoR,
    H: IntoR, I: IntoR, J: IntoR, K: IntoR> IntoR for
    Vec<Option<(A, B, C, D, E, F, G, H, I, J, K)>> {
    type Error = crate::into_r_error::IntoRError;
    fn try_into_sexp(self) -> Result<crate::SEXP, Self::Error> {
        let mut errors = crate::into_r_error::ElementFailures::default();
        let result =
            unsafe {
                vecsxp_from_iter(self.into_iter().enumerate().map(|(index,
                                row)|
                            {
                                match row.try_into_sexp() {
                                    Ok(child) => child,
                                    Err(error) => {
                                        errors.push_row(index, error);
                                        crate::SEXP::nil()
                                    }
                                }
                            }))
            };
        if errors.is_empty() { Ok(result) } else { Err(errors.into_error()) }
    }
    unsafe fn try_into_sexp_unchecked(self)
        -> Result<crate::SEXP, Self::Error> {
        let mut errors = crate::into_r_error::ElementFailures::default();
        let result =
            unsafe {
                vecsxp_from_iter_unchecked(self.into_iter().enumerate().map(|(index,
                                row)|
                            {
                                match row.try_into_sexp_unchecked() {
                                    Ok(child) => child,
                                    Err(error) => {
                                        errors.push_row(index, error);
                                        crate::SEXP::nil()
                                    }
                                }
                            }))
            };
        if errors.is_empty() { Ok(result) } else { Err(errors.into_error()) }
    }
}
impl<A: IntoR, B: IntoR, C: IntoR, D: IntoR, E: IntoR, F: IntoR, G: IntoR,
    H: IntoR, I: IntoR, J: IntoR, K: IntoR, L: IntoR> IntoR for
    (A, B, C, D, E, F, G, H, I, J, K, L) {
    type Error = crate::into_r_error::IntoRError;
    fn try_into_sexp(self) -> Result<crate::SEXP, Self::Error> {
        unsafe {
            let scope = ProtectScope::new();
            let builder = ListBuilder::new(&scope, 12);
            let mut errors = crate::into_r_error::ElementFailures::default();
            match self.0.try_into_sexp() {
                Ok(child) => builder.set(0 as isize, child),
                Err(error) => errors.push(0, &error),
            }
            match self.1.try_into_sexp() {
                Ok(child) => builder.set(1 as isize, child),
                Err(error) => errors.push(1, &error),
            }
            match self.2.try_into_sexp() {
                Ok(child) => builder.set(2 as isize, child),
                Err(error) => errors.push(2, &error),
            }
            match self.3.try_into_sexp() {
                Ok(child) => builder.set(3 as isize, child),
                Err(error) => errors.push(3, &error),
            }
            match self.4.try_into_sexp() {
                Ok(child) => builder.set(4 as isize, child),
                Err(error) => errors.push(4, &error),
            }
            match self.5.try_into_sexp() {
                Ok(child) => builder.set(5 as isize, child),
                Err(error) => errors.push(5, &error),
            }
            match self.6.try_into_sexp() {
                Ok(child) => builder.set(6 as isize, child),
                Err(error) => errors.push(6, &error),
            }
            match self.7.try_into_sexp() {
                Ok(child) => builder.set(7 as isize, child),
                Err(error) => errors.push(7, &error),
            }
            match self.8.try_into_sexp() {
                Ok(child) => builder.set(8 as isize, child),
                Err(error) => errors.push(8, &error),
            }
            match self.9.try_into_sexp() {
                Ok(child) => builder.set(9 as isize, child),
                Err(error) => errors.push(9, &error),
            }
            match self.10.try_into_sexp() {
                Ok(child) => builder.set(10 as isize, child),
                Err(error) => errors.push(10, &error),
            }
            match self.11.try_into_sexp() {
                Ok(child) => builder.set(11 as isize, child),
                Err(error) => errors.push(11, &error),
            }
            if errors.is_empty() {
                Ok(builder.into_sexp())
            } else { Err(errors.into_error()) }
        }
    }
    unsafe fn try_into_sexp_unchecked(self)
        -> Result<crate::SEXP, Self::Error> {
        unsafe {
            let scope = ProtectScope::new();
            let builder = ListBuilder::new_unchecked(&scope, 12);
            let mut errors = crate::into_r_error::ElementFailures::default();
            match self.0.try_into_sexp_unchecked() {
                Ok(child) => builder.set_unchecked(0 as isize, child),
                Err(error) => errors.push(0, &error),
            }
            match self.1.try_into_sexp_unchecked() {
                Ok(child) => builder.set_unchecked(1 as isize, child),
                Err(error) => errors.push(1, &error),
            }
            match self.2.try_into_sexp_unchecked() {
                Ok(child) => builder.set_unchecked(2 as isize, child),
                Err(error) => errors.push(2, &error),
            }
            match self.3.try_into_sexp_unchecked() {
                Ok(child) => builder.set_unchecked(3 as isize, child),
                Err(error) => errors.push(3, &error),
            }
            match self.4.try_into_sexp_unchecked() {
                Ok(child) => builder.set_unchecked(4 as isize, child),
                Err(error) => errors.push(4, &error),
            }
            match self.5.try_into_sexp_unchecked() {
                Ok(child) => builder.set_unchecked(5 as isize, child),
                Err(error) => errors.push(5, &error),
            }
            match self.6.try_into_sexp_unchecked() {
                Ok(child) => builder.set_unchecked(6 as isize, child),
                Err(error) => errors.push(6, &error),
            }
            match self.7.try_into_sexp_unchecked() {
                Ok(child) => builder.set_unchecked(7 as isize, child),
                Err(error) => errors.push(7, &error),
            }
            match self.8.try_into_sexp_unchecked() {
                Ok(child) => builder.set_unchecked(8 as isize, child),
                Err(error) => errors.push(8, &error),
            }
            match self.9.try_into_sexp_unchecked() {
                Ok(child) => builder.set_unchecked(9 as isize, child),
                Err(error) => errors.push(9, &error),
            }
            match self.10.try_into_sexp_unchecked() {
                Ok(child) => builder.set_unchecked(10 as isize, child),
                Err(error) => errors.push(10, &error),
            }
            match self.11.try_into_sexp_unchecked() {
                Ok(child) => builder.set_unchecked(11 as isize, child),
                Err(error) => errors.push(11, &error),
            }
            if errors.is_empty() {
                Ok(builder.into_sexp())
            } else { Err(errors.into_error()) }
        }
    }
}
impl<A: IntoR, B: IntoR, C: IntoR, D: IntoR, E: IntoR, F: IntoR, G: IntoR,
    H: IntoR, I: IntoR, J: IntoR, K: IntoR, L: IntoR> IntoR for
    Option<(A, B, C, D, E, F, G, H, I, J, K, L)> {
    type Error = <(A, B, C, D, E, F, G, H, I, J, K, L) as IntoR>::Error;
    fn try_into_sexp(self) -> Result<crate::SEXP, Self::Error> {
        self.map_or_else(|| Ok(crate::SEXP::nil()), IntoR::try_into_sexp)
    }
    unsafe fn try_into_sexp_unchecked(self)
        -> Result<crate::SEXP, Self::Error> {
        self.map_or_else(|| Ok(crate::SEXP::nil()),
            |value| unsafe { value.try_into_sexp_unchecked() })
    }
}
impl<A: IntoR, B: IntoR, C: IntoR, D: IntoR, E: IntoR, F: IntoR, G: IntoR,
    H: IntoR, I: IntoR, J: IntoR, K: IntoR, L: IntoR> IntoR for
    Vec<(A, B, C, D, E, F, G, H, I, J, K, L)> {
    type Error = crate::into_r_error::IntoRError;
    fn try_into_sexp(self) -> Result<crate::SEXP, Self::Error> {
        let mut errors = crate::into_r_error::ElementFailures::default();
        let result =
            unsafe {
                vecsxp_from_iter(self.into_iter().enumerate().map(|(index,
                                row)|
                            {
                                match row.try_into_sexp() {
                                    Ok(child) => child,
                                    Err(error) => {
                                        errors.push_row(index, error);
                                        crate::SEXP::nil()
                                    }
                                }
                            }))
            };
        if errors.is_empty() { Ok(result) } else { Err(errors.into_error()) }
    }
    unsafe fn try_into_sexp_unchecked(self)
        -> Result<crate::SEXP, Self::Error> {
        let mut errors = crate::into_r_error::ElementFailures::default();
        let result =
            unsafe {
                vecsxp_from_iter_unchecked(self.into_iter().enumerate().map(|(index,
                                row)|
                            {
                                match row.try_into_sexp_unchecked() {
                                    Ok(child) => child,
                                    Err(error) => {
                                        errors.push_row(index, error);
                                        crate::SEXP::nil()
                                    }
                                }
                            }))
            };
        if errors.is_empty() { Ok(result) } else { Err(errors.into_error()) }
    }
}
impl<A: IntoR, B: IntoR, C: IntoR, D: IntoR, E: IntoR, F: IntoR, G: IntoR,
    H: IntoR, I: IntoR, J: IntoR, K: IntoR, L: IntoR> IntoR for
    Vec<Option<(A, B, C, D, E, F, G, H, I, J, K, L)>> {
    type Error = crate::into_r_error::IntoRError;
    fn try_into_sexp(self) -> Result<crate::SEXP, Self::Error> {
        let mut errors = crate::into_r_error::ElementFailures::default();
        let result =
            unsafe {
                vecsxp_from_iter(self.into_iter().enumerate().map(|(index,
                                row)|
                            {
                                match row.try_into_sexp() {
                                    Ok(child) => child,
                                    Err(error) => {
                                        errors.push_row(index, error);
                                        crate::SEXP::nil()
                                    }
                                }
                            }))
            };
        if errors.is_empty() { Ok(result) } else { Err(errors.into_error()) }
    }
    unsafe fn try_into_sexp_unchecked(self)
        -> Result<crate::SEXP, Self::Error> {
        let mut errors = crate::into_r_error::ElementFailures::default();
        let result =
            unsafe {
                vecsxp_from_iter_unchecked(self.into_iter().enumerate().map(|(index,
                                row)|
                            {
                                match row.try_into_sexp_unchecked() {
                                    Ok(child) => child,
                                    Err(error) => {
                                        errors.push_row(index, error);
                                        crate::SEXP::nil()
                                    }
                                }
                            }))
            };
        if errors.is_empty() { Ok(result) } else { Err(errors.into_error()) }
    }
}crate::tuple_macros::for_each_tuple!(impl_tuple_into_r);
2134// endregion
2135
2136// region: ALTREP zero-copy extension trait
2137
2138/// Extension trait for ALTREP conversions.
2139///
2140/// This trait provides ergonomic methods for converting Rust types to R ALTREP
2141/// vectors without copying data. The data stays in Rust memory (wrapped in an
2142/// ExternalPtr) and R accesses it via ALTREP callbacks.
2143///
2144/// # Performance Characteristics
2145///
2146/// | Operation | Regular (IntoR) | ALTREP (IntoRAltrep) |
2147/// |-----------|-----------------|------------------------|
2148/// | Creation | O(n) copy | O(1) wrap |
2149/// | Memory | Duplicated in R | Single copy in Rust |
2150/// | Element access | Direct pointer | Callback (~10ns overhead) |
2151/// | DATAPTR ops | O(1) | O(1) if Vec/Box, N/A if lazy |
2152///
2153/// # When to Use ALTREP
2154///
2155/// **Good candidates**:
2156/// - ✅ Large vectors (>1000 elements)
2157/// - ✅ Lazy/computed data (avoid eager materialization)
2158/// - ✅ External data sources (files, databases, APIs)
2159/// - ✅ Data that might not be fully accessed by R
2160///
2161/// **Not recommended**:
2162/// - ❌ Small vectors (<100 elements) - copy overhead is negligible
2163/// - ❌ Data R will immediately modify (triggers copy anyway)
2164/// - ❌ Temporary results (extra indirection not worth it)
2165///
2166/// # Example
2167///
2168/// ```rust,ignore
2169/// use miniextendr_api::{miniextendr, IntoRAltrep, IntoR, SEXP};
2170///
2171/// #[miniextendr]
2172/// fn large_dataset() -> SEXP {
2173///     let data: Vec<f64> = (0..1_000_000).map(|i| i as f64).collect();
2174///
2175///     // Zero-copy: wraps pointer instead of copying 1M elements
2176///     data.into_sexp_altrep()
2177/// }
2178///
2179/// #[miniextendr]
2180/// fn small_result() -> SEXP {
2181///     let data = vec![1, 2, 3, 4, 5];
2182///
2183///     // Regular copy is fine for small data
2184///     data.into_sexp()
2185/// }
2186/// ```
2187pub trait IntoRAltrep {
2188    /// Convert to R SEXP using ALTREP zero-copy representation.
2189    ///
2190    /// This is equivalent to `Altrep(self).into_sexp()` but more discoverable
2191    /// and explicit about the zero-copy intent.
2192    fn into_sexp_altrep(self) -> crate::SEXP;
2193
2194    /// Convert to R SEXP using ALTREP, skipping debug thread assertions.
2195    ///
2196    /// # Safety
2197    ///
2198    /// Caller must ensure they are on R's main thread.
2199    unsafe fn into_sexp_altrep_unchecked(self) -> crate::SEXP
2200    where
2201        Self: Sized,
2202    {
2203        self.into_sexp_altrep()
2204    }
2205
2206    /// Create an `Altrep<Self>` wrapper.
2207    ///
2208    /// This returns the wrapper explicitly, allowing you to store it or
2209    /// further process it before conversion.
2210    fn into_altrep(self) -> Altrep<Self>
2211    where
2212        Self: Sized,
2213    {
2214        Altrep(self)
2215    }
2216}
2217
2218impl<T> IntoRAltrep for T
2219where
2220    T: crate::altrep::RegisterAltrep + crate::externalptr::TypedExternal,
2221{
2222    fn into_sexp_altrep(self) -> crate::SEXP {
2223        Altrep(self).into_sexp()
2224    }
2225
2226    unsafe fn into_sexp_altrep_unchecked(self) -> crate::SEXP {
2227        unsafe { Altrep(self).into_sexp_unchecked() }
2228    }
2229}
2230// endregion
2231
2232// region: Additional collection type conversions for DataFrameRow support
2233
2234/// Convert `Vec<Box<[T]>>` to an R list of vectors, for every `T` with a
2235/// `Vec<T>: IntoR` conversion. Each boxed slice becomes the R vector its
2236/// `Vec<T>` would (`into_vec()` is an O(1) widen).
2237impl<T> IntoR for Vec<Box<[T]>>
2238where
2239    Vec<T>: IntoR,
2240{
2241    type Error = <Vec<T> as IntoR>::Error;
2242    fn try_into_sexp(self) -> Result<crate::SEXP, Self::Error> {
2243        unsafe { try_vecsxp_from_iter(self.into_iter().map(|b| b.into_vec().try_into_sexp())) }
2244    }
2245    unsafe fn try_into_sexp_unchecked(self) -> Result<crate::SEXP, Self::Error> {
2246        unsafe {
2247            try_vecsxp_from_iter_unchecked(
2248                self.into_iter()
2249                    .map(|b| b.into_vec().try_into_sexp_unchecked()),
2250            )
2251        }
2252    }
2253    fn into_sexp(self) -> crate::SEXP {
2254        unsafe { vecsxp_from_iter(self.into_iter().map(|b| b.into_vec().into_sexp())) }
2255    }
2256    unsafe fn into_sexp_unchecked(self) -> crate::SEXP {
2257        unsafe {
2258            vecsxp_from_iter_unchecked(self.into_iter().map(|b| b.into_vec().into_sexp_unchecked()))
2259        }
2260    }
2261}
2262
2263/// Convert `Vec<[T; N]>` to an R list of vectors, for every `T` with a
2264/// `Vec<T>: IntoR` conversion. Each array becomes the R vector its `Vec<T>`
2265/// would.
2266impl<T, const N: usize> IntoR for Vec<[T; N]>
2267where
2268    Vec<T>: IntoR,
2269{
2270    type Error = <Vec<T> as IntoR>::Error;
2271    fn try_into_sexp(self) -> Result<crate::SEXP, Self::Error> {
2272        unsafe { try_vecsxp_from_iter(self.into_iter().map(|a| Vec::from(a).try_into_sexp())) }
2273    }
2274    unsafe fn try_into_sexp_unchecked(self) -> Result<crate::SEXP, Self::Error> {
2275        unsafe {
2276            try_vecsxp_from_iter_unchecked(
2277                self.into_iter()
2278                    .map(|a| Vec::from(a).try_into_sexp_unchecked()),
2279            )
2280        }
2281    }
2282    fn into_sexp(self) -> crate::SEXP {
2283        unsafe { vecsxp_from_iter(self.into_iter().map(|a| Vec::from(a).into_sexp())) }
2284    }
2285    unsafe fn into_sexp_unchecked(self) -> crate::SEXP {
2286        unsafe {
2287            vecsxp_from_iter_unchecked(self.into_iter().map(|a| Vec::from(a).into_sexp_unchecked()))
2288        }
2289    }
2290}
2291
2292/// Helper: convert a Vec of IntoR items to an R list (VECSXP).
2293fn vec_of_into_r_to_list<T: IntoR>(items: Vec<T>) -> crate::SEXP {
2294    unsafe { vecsxp_from_iter(items.into_iter().map(|item| item.into_sexp())) }
2295}
2296
2297// region: Vec<Option<Collection>> conversions
2298
2299/// Helper: convert `Vec<Option<C: IntoR>>` to a VECSXP, with `None` mapping to
2300/// `R_NilValue` (NULL) and `Some(v)` mapping to whatever `v.into_sexp()` produces.
2301fn vec_option_of_into_r_to_list<T: IntoR>(items: Vec<Option<T>>) -> crate::SEXP {
2302    unsafe {
2303        vecsxp_from_iter(items.into_iter().map(|item| match item {
2304            Some(v) => v.into_sexp(),
2305            None => crate::SEXP::nil(),
2306        }))
2307    }
2308}
2309
2310/// Convert `Vec<Option<Vec<T>>>` to an R list where `None` → NULL and
2311/// `Some(v)` → the R vector `Vec<T>` produces, for every `T` with a
2312/// `Vec<T>: IntoR` conversion.
2313impl<T> IntoR for Vec<Option<Vec<T>>>
2314where
2315    Vec<T>: IntoR,
2316{
2317    type Error = <Vec<T> as IntoR>::Error;
2318    fn try_into_sexp(self) -> Result<crate::SEXP, Self::Error> {
2319        unsafe {
2320            try_vecsxp_from_iter(self.into_iter().map(|item| match item {
2321                Some(v) => v.try_into_sexp(),
2322                None => Ok(crate::SEXP::nil()),
2323            }))
2324        }
2325    }
2326    unsafe fn try_into_sexp_unchecked(self) -> Result<crate::SEXP, Self::Error> {
2327        unsafe {
2328            try_vecsxp_from_iter_unchecked(self.into_iter().map(|item| match item {
2329                Some(v) => v.try_into_sexp_unchecked(),
2330                None => Ok(crate::SEXP::nil()),
2331            }))
2332        }
2333    }
2334    fn into_sexp(self) -> crate::SEXP {
2335        vec_option_of_into_r_to_list(self)
2336    }
2337}
2338
2339/// Convert `Vec<Option<Box<[T]>>>` exactly as `Vec<Option<Vec<T>>>` (each
2340/// `into_vec()` is an O(1) widen). The enum `DataFrameRow` companion stores an
2341/// opaque `Box<[T]>` variant field in this shape.
2342impl<T> IntoR for Vec<Option<Box<[T]>>>
2343where
2344    Vec<T>: IntoR,
2345{
2346    type Error = <Vec<T> as IntoR>::Error;
2347    fn try_into_sexp(self) -> Result<crate::SEXP, Self::Error> {
2348        unsafe {
2349            try_vecsxp_from_iter(self.into_iter().map(|item| match item {
2350                Some(b) => b.into_vec().try_into_sexp(),
2351                None => Ok(crate::SEXP::nil()),
2352            }))
2353        }
2354    }
2355    unsafe fn try_into_sexp_unchecked(self) -> Result<crate::SEXP, Self::Error> {
2356        unsafe {
2357            try_vecsxp_from_iter_unchecked(self.into_iter().map(|item| match item {
2358                Some(b) => b.into_vec().try_into_sexp_unchecked(),
2359                None => Ok(crate::SEXP::nil()),
2360            }))
2361        }
2362    }
2363    fn into_sexp(self) -> crate::SEXP {
2364        vec_option_of_into_r_to_list::<Vec<T>>(
2365            self.into_iter().map(|b| b.map(<[T]>::into_vec)).collect(),
2366        )
2367    }
2368}
2369
2370/// Convert `Vec<Option<HashSet<T>>>` to R list where `None` → NULL, `Some(s)` → unordered vector.
2371impl<T: crate::RNativeType + Eq + Hash> IntoR for Vec<Option<HashSet<T>>>
2372where
2373    HashSet<T>: IntoR,
2374{
2375    type Error = std::convert::Infallible;
2376    fn try_into_sexp(self) -> Result<crate::SEXP, Self::Error> {
2377        Ok(self.into_sexp())
2378    }
2379    unsafe fn try_into_sexp_unchecked(self) -> Result<crate::SEXP, Self::Error> {
2380        self.try_into_sexp()
2381    }
2382    fn into_sexp(self) -> crate::SEXP {
2383        vec_option_of_into_r_to_list(self)
2384    }
2385}
2386
2387// Convert `Vec<Option<HashSet<String>>>` to R list where `None` → NULL, `Some(s)` → character vector.
2388impl crate::into_r::IntoR for Vec<Option<HashSet<String>>> {
    type Error = ::std::convert::Infallible;
    #[inline]
    fn try_into_sexp(self)
        -> ::core::result::Result<crate::SEXP, Self::Error> {
        ::core::result::Result::Ok(self.into_sexp())
    }
    #[inline]
    unsafe fn try_into_sexp_unchecked(self)
        -> ::core::result::Result<crate::SEXP, Self::Error> {
        self.try_into_sexp()
    }
    #[inline]
    fn into_sexp(self) -> crate::SEXP {
        let this = self;
        { vec_option_of_into_r_to_list(this) }
    }
}into_r_infallible!(Vec<Option<HashSet<String>>>, |this| {
2389    vec_option_of_into_r_to_list(this)
2390});
2391
2392/// Convert `Vec<Option<BTreeSet<T>>>` to R list where `None` → NULL, `Some(s)` → sorted vector.
2393impl<T: crate::RNativeType + Ord> IntoR for Vec<Option<BTreeSet<T>>>
2394where
2395    BTreeSet<T>: IntoR,
2396{
2397    type Error = std::convert::Infallible;
2398    fn try_into_sexp(self) -> Result<crate::SEXP, Self::Error> {
2399        Ok(self.into_sexp())
2400    }
2401    unsafe fn try_into_sexp_unchecked(self) -> Result<crate::SEXP, Self::Error> {
2402        self.try_into_sexp()
2403    }
2404    fn into_sexp(self) -> crate::SEXP {
2405        vec_option_of_into_r_to_list(self)
2406    }
2407}
2408
2409// Convert `Vec<Option<BTreeSet<String>>>` to R list where `None` → NULL, `Some(s)` → sorted character vector.
2410impl crate::into_r::IntoR for Vec<Option<BTreeSet<String>>> {
    type Error = ::std::convert::Infallible;
    #[inline]
    fn try_into_sexp(self)
        -> ::core::result::Result<crate::SEXP, Self::Error> {
        ::core::result::Result::Ok(self.into_sexp())
    }
    #[inline]
    unsafe fn try_into_sexp_unchecked(self)
        -> ::core::result::Result<crate::SEXP, Self::Error> {
        self.try_into_sexp()
    }
    #[inline]
    fn into_sexp(self) -> crate::SEXP {
        let this = self;
        { vec_option_of_into_r_to_list(this) }
    }
}into_r_infallible!(Vec<Option<BTreeSet<String>>>, |this| {
2411    vec_option_of_into_r_to_list(this)
2412});
2413
2414/// Convert `Vec<Option<HashMap<String, V>>>` to R list where `None` → NULL, `Some(m)` → named list.
2415impl<V: IntoR> IntoR for Vec<Option<HashMap<String, V>>> {
2416    type Error = std::convert::Infallible;
2417    fn try_into_sexp(self) -> Result<crate::SEXP, Self::Error> {
2418        Ok(self.into_sexp())
2419    }
2420    unsafe fn try_into_sexp_unchecked(self) -> Result<crate::SEXP, Self::Error> {
2421        self.try_into_sexp()
2422    }
2423    fn into_sexp(self) -> crate::SEXP {
2424        vec_option_of_into_r_to_list(self)
2425    }
2426}
2427
2428/// Convert `Vec<Option<BTreeMap<String, V>>>` to R list where `None` → NULL, `Some(m)` → named list.
2429impl<V: IntoR> IntoR for Vec<Option<BTreeMap<String, V>>> {
2430    type Error = std::convert::Infallible;
2431    fn try_into_sexp(self) -> Result<crate::SEXP, Self::Error> {
2432        Ok(self.into_sexp())
2433    }
2434    unsafe fn try_into_sexp_unchecked(self) -> Result<crate::SEXP, Self::Error> {
2435        self.try_into_sexp()
2436    }
2437    fn into_sexp(self) -> crate::SEXP {
2438        vec_option_of_into_r_to_list(self)
2439    }
2440}
2441
2442/// Convert `Vec<Option<&[T]>>` to an R list where `None` → NULL and
2443/// `Some(s)` → the R vector `&[T]` produces, for every `T` with a
2444/// `&[T]: IntoR` conversion.
2445///
2446/// Borrowed analogue of `Vec<Option<Vec<T>>>` — each slice is copied into a fresh R vector.
2447impl<'a, T> IntoR for Vec<Option<&'a [T]>>
2448where
2449    &'a [T]: IntoR,
2450{
2451    type Error = <&'a [T] as IntoR>::Error;
2452    fn try_into_sexp(self) -> Result<crate::SEXP, Self::Error> {
2453        unsafe {
2454            try_vecsxp_from_iter(self.into_iter().map(|item| match item {
2455                Some(v) => v.try_into_sexp(),
2456                None => Ok(crate::SEXP::nil()),
2457            }))
2458        }
2459    }
2460    unsafe fn try_into_sexp_unchecked(self) -> Result<crate::SEXP, Self::Error> {
2461        unsafe {
2462            try_vecsxp_from_iter_unchecked(self.into_iter().map(|item| match item {
2463                Some(v) => v.try_into_sexp_unchecked(),
2464                None => Ok(crate::SEXP::nil()),
2465            }))
2466        }
2467    }
2468    fn into_sexp(self) -> crate::SEXP {
2469        vec_option_of_into_r_to_list(self)
2470    }
2471}
2472
2473// endregion
2474
2475/// Convert `Vec<HashSet<T>>` to R list of vectors (for RNativeType elements).
2476/// Each HashSet becomes an R vector (unordered).
2477impl<T: crate::RNativeType> IntoR for Vec<std::collections::HashSet<T>>
2478where
2479    Vec<T>: IntoR,
2480{
2481    type Error = std::convert::Infallible;
2482    fn try_into_sexp(self) -> Result<crate::SEXP, Self::Error> {
2483        Ok(self.into_sexp())
2484    }
2485    unsafe fn try_into_sexp_unchecked(self) -> Result<crate::SEXP, Self::Error> {
2486        self.try_into_sexp()
2487    }
2488    fn into_sexp(self) -> crate::SEXP {
2489        let converted: Vec<Vec<T>> = self.into_iter().map(|s| s.into_iter().collect()).collect();
2490        vec_of_into_r_to_list(converted)
2491    }
2492}
2493
2494/// Convert `Vec<BTreeSet<T>>` to R list of vectors (for RNativeType elements).
2495/// Each BTreeSet becomes an R vector (sorted).
2496impl<T: crate::RNativeType> IntoR for Vec<std::collections::BTreeSet<T>>
2497where
2498    Vec<T>: IntoR,
2499{
2500    type Error = std::convert::Infallible;
2501    fn try_into_sexp(self) -> Result<crate::SEXP, Self::Error> {
2502        Ok(self.into_sexp())
2503    }
2504    unsafe fn try_into_sexp_unchecked(self) -> Result<crate::SEXP, Self::Error> {
2505        self.try_into_sexp()
2506    }
2507    fn into_sexp(self) -> crate::SEXP {
2508        let converted: Vec<Vec<T>> = self.into_iter().map(|s| s.into_iter().collect()).collect();
2509        vec_of_into_r_to_list(converted)
2510    }
2511}
2512
2513// Convert `Vec<HashSet<String>>` to R list of character vectors.
2514impl crate::into_r::IntoR for Vec<std::collections::HashSet<String>> {
    type Error = ::std::convert::Infallible;
    #[inline]
    fn try_into_sexp(self)
        -> ::core::result::Result<crate::SEXP, Self::Error> {
        ::core::result::Result::Ok(self.into_sexp())
    }
    #[inline]
    unsafe fn try_into_sexp_unchecked(self)
        -> ::core::result::Result<crate::SEXP, Self::Error> {
        self.try_into_sexp()
    }
    #[inline]
    fn into_sexp(self) -> crate::SEXP {
        let this = self;
        {
            let converted: Vec<Vec<String>> =
                this.into_iter().map(|s| s.into_iter().collect()).collect();
            vec_of_into_r_to_list(converted)
        }
    }
}into_r_infallible!(Vec<std::collections::HashSet<String>>, |this| {
2515    let converted: Vec<Vec<String>> = this.into_iter().map(|s| s.into_iter().collect()).collect();
2516    vec_of_into_r_to_list(converted)
2517});
2518
2519// Convert `Vec<BTreeSet<String>>` to R list of character vectors.
2520impl crate::into_r::IntoR for Vec<std::collections::BTreeSet<String>> {
    type Error = ::std::convert::Infallible;
    #[inline]
    fn try_into_sexp(self)
        -> ::core::result::Result<crate::SEXP, Self::Error> {
        ::core::result::Result::Ok(self.into_sexp())
    }
    #[inline]
    unsafe fn try_into_sexp_unchecked(self)
        -> ::core::result::Result<crate::SEXP, Self::Error> {
        self.try_into_sexp()
    }
    #[inline]
    fn into_sexp(self) -> crate::SEXP {
        let this = self;
        {
            let converted: Vec<Vec<String>> =
                this.into_iter().map(|s| s.into_iter().collect()).collect();
            vec_of_into_r_to_list(converted)
        }
    }
}into_r_infallible!(Vec<std::collections::BTreeSet<String>>, |this| {
2521    let converted: Vec<Vec<String>> = this.into_iter().map(|s| s.into_iter().collect()).collect();
2522    vec_of_into_r_to_list(converted)
2523});
2524
2525macro_rules! impl_vec_map_into_r {
2526    ($(#[$meta:meta])* $map_ty:ident) => {
2527        $(#[$meta])*
2528        impl<V: IntoR> IntoR for Vec<$map_ty<String, V>> {
2529            type Error = std::convert::Infallible;
2530            fn try_into_sexp(self) -> Result<crate::SEXP, Self::Error> {
2531                Ok(self.into_sexp())
2532            }
2533            unsafe fn try_into_sexp_unchecked(self) -> Result<crate::SEXP, Self::Error> {
2534                self.try_into_sexp()
2535            }
2536            fn into_sexp(self) -> crate::SEXP {
2537                vec_of_maps_to_list(self)
2538            }
2539        }
2540    };
2541}
2542
2543#[doc = r" Convert `Vec<HashMap<String, V>>` to R list of named lists."]
impl<V: IntoR> IntoR for Vec<HashMap<String, V>> {
    type Error = std::convert::Infallible;
    fn try_into_sexp(self) -> Result<crate::SEXP, Self::Error> {
        Ok(self.into_sexp())
    }
    unsafe fn try_into_sexp_unchecked(self)
        -> Result<crate::SEXP, Self::Error> {
        self.try_into_sexp()
    }
    fn into_sexp(self) -> crate::SEXP { vec_of_maps_to_list(self) }
}impl_vec_map_into_r!(
2544    /// Convert `Vec<HashMap<String, V>>` to R list of named lists.
2545    HashMap
2546);
2547#[doc = r" Convert `Vec<BTreeMap<String, V>>` to R list of named lists."]
impl<V: IntoR> IntoR for Vec<BTreeMap<String, V>> {
    type Error = std::convert::Infallible;
    fn try_into_sexp(self) -> Result<crate::SEXP, Self::Error> {
        Ok(self.into_sexp())
    }
    unsafe fn try_into_sexp_unchecked(self)
        -> Result<crate::SEXP, Self::Error> {
        self.try_into_sexp()
    }
    fn into_sexp(self) -> crate::SEXP { vec_of_maps_to_list(self) }
}impl_vec_map_into_r!(
2548    /// Convert `Vec<BTreeMap<String, V>>` to R list of named lists.
2549    BTreeMap
2550);
2551
2552/// Helper to convert a Vec of map-like types to an R list of named lists.
2553fn vec_of_maps_to_list<T: IntoR>(vec: Vec<T>) -> crate::SEXP {
2554    unsafe { vecsxp_from_iter(vec.into_iter().map(|c| c.into_sexp())) }
2555}
2556// endregion
2557
2558// region: R connections — IntoR impls (issue #175, #176)
2559
2560#[cfg(feature = "connections")]
2561mod connections_into_r {
2562    use crate::SEXP;
2563    use crate::connection::{RNullConnection, RStderr, RStdin, RStdout};
2564    use crate::into_r::IntoR;
2565
2566    // Evaluate a no-arg base function and return the resulting SEXP
2567    // (unprotected). An R error panics with R's message.
2568    //
2569    // # Safety
2570    // Must be called from the R main thread.
2571    unsafe fn eval_base_noarg(name: &str) -> SEXP {
2572        unsafe { crate::expression::RCall::new(name).eval_base() }
2573            .unwrap_or_else(|e| panic!("failed to evaluate {name}(): {e}"))
2574    }
2575
2576    impl IntoR for RStdin {
2577        type Error = std::convert::Infallible;
2578
2579        fn try_into_sexp(self) -> Result<SEXP, Self::Error> {
2580            Ok(self.into_sexp())
2581        }
2582
2583        fn into_sexp(self) -> SEXP {
2584            unsafe { eval_base_noarg("stdin") }
2585        }
2586    }
2587
2588    impl IntoR for RStdout {
2589        type Error = std::convert::Infallible;
2590
2591        fn try_into_sexp(self) -> Result<SEXP, Self::Error> {
2592            Ok(self.into_sexp())
2593        }
2594
2595        fn into_sexp(self) -> SEXP {
2596            unsafe { eval_base_noarg("stdout") }
2597        }
2598    }
2599
2600    impl IntoR for RStderr {
2601        type Error = std::convert::Infallible;
2602
2603        fn try_into_sexp(self) -> Result<SEXP, Self::Error> {
2604            Ok(self.into_sexp())
2605        }
2606
2607        fn into_sexp(self) -> SEXP {
2608            unsafe { eval_base_noarg("stderr") }
2609        }
2610    }
2611
2612    /// Returns the held SEXP and disarms the `Drop` guard (no double-close).
2613    impl IntoR for RNullConnection {
2614        type Error = std::convert::Infallible;
2615
2616        fn try_into_sexp(self) -> Result<SEXP, Self::Error> {
2617            Ok(self.into_sexp())
2618        }
2619
2620        fn into_sexp(self) -> SEXP {
2621            let sexp = self.sexp();
2622            // Transfer ownership to R: release from precious list (R's connection
2623            // table keeps the connection alive), then forget self to skip Drop.
2624            unsafe { crate::sys::R_ReleaseObject(sexp) };
2625            std::mem::forget(self);
2626            sexp
2627        }
2628    }
2629}
2630
2631// endregion
2632
2633// region: txtProgressBar — IntoR (issue #177)
2634
2635#[cfg(feature = "connections")]
2636mod txt_progress_bar_into_r {
2637    use crate::SEXP;
2638    use crate::into_r::IntoR;
2639    use crate::txt_progress_bar::RTxtProgressBar;
2640
2641    /// Transfer ownership of the `RTxtProgressBar` back to R.
2642    ///
2643    /// Releases the SEXP from the precious list and forgets `self` (so `Drop`
2644    /// is a no-op). R's environment keeps the bar alive after this call.
2645    impl IntoR for RTxtProgressBar {
2646        type Error = std::convert::Infallible;
2647
2648        fn try_into_sexp(self) -> Result<SEXP, Self::Error> {
2649            Ok(self.into_sexp())
2650        }
2651
2652        fn into_sexp(self) -> SEXP {
2653            let sexp = self.sexp();
2654            // Release from precious list; R manages lifetime from here on.
2655            unsafe { crate::sys::R_ReleaseObject(sexp) };
2656            std::mem::forget(self); // Disarm Drop guard — no double-release.
2657            sexp
2658        }
2659    }
2660}
2661
2662// endregion