Skip to main content

miniextendr_api/
rarray.rs

1//! N-dimensional R arrays with const generic dimension count.
2//!
3//! This module provides [`RArray<T, NDIM>`], a wrapper around R arrays that
4//! tracks the number of dimensions at compile time.
5//!
6//! # Type Aliases
7//!
8//! | Alias | Type | R Equivalent |
9//! |-------|------|--------------|
10//! | [`RVector<T>`] | `RArray<T, 1>` | `vector` (with dim) |
11//! | [`RMatrix<T>`] | `RArray<T, 2>` | `matrix` |
12//! | [`RArray3D<T>`] | `RArray<T, 3>` | `array(..., dim=c(a,b,c))` |
13//!
14//! # Memory Layout
15//!
16//! R arrays are stored in **column-major** (Fortran) order. For a 2×3 matrix:
17//!
18//! ```text
19//! Logical layout:     Memory layout:
20//! [0,0] [0,1] [0,2]   [0,0] [1,0] [0,1] [1,1] [0,2] [1,2]
21//! [1,0] [1,1] [1,2]
22//! ```
23//!
24//! The [`get`][RArray::get] method handles index translation automatically.
25//!
26//! # Thread Safety
27//!
28//! **`RArray` is `!Send` and `!Sync`** - it cannot be transferred to or accessed
29//! from other threads. This is because the underlying R APIs (`DATAPTR_RO`, etc.)
30//! must be called on the R main thread.
31//!
32//! Every `#[miniextendr]` function runs on R's main thread, so `RArray` /
33//! `RMatrix` parameters are read there. No attribute is required.
34//!
35//! To use the data on other threads (Rayon, `std::thread::spawn`), copy it with
36//! [`to_vec()`][RArray::to_vec] on the main thread and pass the owned `Vec` on.
37//!
38//! # Performance
39//!
40//! For best performance, prefer slice-based and column-based access over per-element
41//! indexing:
42//!
43//! | Method | Speed | Use Case |
44//! |--------|-------|----------|
45//! | [`as_slice()`][RArray::as_slice] | Fastest | Full-buffer iteration, SIMD |
46//! | [`column()`][RMatrix::column] | Fast | Per-column operations (matrices) |
47//! | [`column_mut()`][RMatrix::column_mut] | Fast | Per-column mutation |
48//! | [`get()`][RArray::get] / [`get_rc()`][RMatrix::get_rc] | Slower | Single-element access |
49//!
50//! **Why?** Per-element methods like `get()` perform index translation and bounds
51//! checks on every call. For tight loops, this overhead dominates.
52//!
53//! ```ignore
54//! // Slow: per-element access
55//! for row in 0..nrow {
56//!     for col in 0..ncol {
57//!         let val = unsafe { matrix.get_rc(row, col) };
58//!     }
59//! }
60//!
61//! // Fast: slice-based iteration
62//! for val in unsafe { matrix.as_slice() } {
63//!     // ...
64//! }
65//!
66//! // Fast: column-wise iteration (columns are contiguous in R)
67//! for col in 0..ncol {
68//!     for val in unsafe { matrix.column(col) } {
69//!         // ...
70//!     }
71//! }
72//! ```
73//!
74//! # Example
75//!
76//! ```ignore
77//! use miniextendr_api::rarray::{RMatrix, RArray};
78//!
79//! // Runs on the main thread due to the RMatrix parameter (RArray is !Send)
80//! #[miniextendr]
81//! fn matrix_sum(m: RMatrix<f64>) -> f64 {
82//!     unsafe { m.as_slice().iter().sum() }
83//! }
84//! ```
85
86use crate::from_r::{SexpError, SexpLengthError, SexpTypeError, TryFromSexp};
87use crate::into_r::IntoR;
88use crate::{R_xlen_t, RNativeType, SEXP, SEXPTYPE, SexpExt};
89use core::marker::PhantomData;
90
91// region: Type aliases
92
93/// A 1-dimensional R vector with explicit dim attribute.
94pub type RVector<T> = RArray<T, 1>;
95
96/// A 2-dimensional R matrix.
97pub type RMatrix<T> = RArray<T, 2>;
98
99/// A 3-dimensional R array.
100pub type RArray3D<T> = RArray<T, 3>;
101// endregion
102
103// region: RArray
104
105/// An N-dimensional R array.
106///
107/// This type wraps an R array SEXP. The dimension count `NDIM` is tracked
108/// at compile time, but dimension sizes are read from the R object.
109///
110/// # Type Parameters
111///
112/// - `T`: The element type, must implement [`RNativeType`]
113/// - `NDIM`: The number of dimensions (compile-time constant)
114///
115/// # Thread Safety
116///
117/// This type is `!Send` and `!Sync` because its methods require access to
118/// R APIs that must run on the R main thread.
119#[derive(#[automatically_derived]impl<T: ::core::clone::Clone, const NDIM : usize>
    ::core::clone::Clone for RArray<T, NDIM> {
    #[inline]
    fn clone(&self) -> Self {
        RArray {
            sexp: ::core::clone::Clone::clone(&self.sexp),
            _marker: ::core::clone::Clone::clone(&self._marker),
        }
    }
}Clone, #[automatically_derived]impl<T: ::core::marker::Copy, const NDIM : usize>
    ::core::marker::Copy for RArray<T, NDIM> {
}Copy)]
120#[repr(transparent)]
121pub struct RArray<T, const NDIM: usize> {
122    sexp: SEXP,
123    // PhantomData<*const T> keeps T in the type AND makes this !Send + !Sync
124    _marker: PhantomData<*const T>,
125}
126// endregion
127
128// region: Basic methods (no T bounds - available for all RArray types)
129
130impl<T, const NDIM: usize> RArray<T, NDIM> {
131    /// Create an RArray from a SEXP without validation.
132    ///
133    /// # Safety
134    ///
135    /// - The SEXP must be protected from GC
136    /// - The SEXP must have the correct type for `T`
137    /// - The SEXP must have exactly `NDIM` dimensions
138    #[inline]
139    pub const unsafe fn from_sexp_unchecked(sexp: SEXP) -> Self {
140        Self {
141            sexp,
142            _marker: PhantomData,
143        }
144    }
145
146    /// Get the underlying SEXP.
147    #[inline]
148    pub const fn as_sexp(&self) -> SEXP {
149        self.sexp
150    }
151
152    /// Consume and return the underlying SEXP.
153    #[inline]
154    pub fn into_inner(self) -> SEXP {
155        self.sexp
156    }
157
158    /// Get the dimensions as an array.
159    ///
160    /// # Safety
161    ///
162    /// The SEXP must be valid.
163    #[inline]
164    pub unsafe fn dims(&self) -> [usize; NDIM] {
165        unsafe { get_dims::<NDIM>(self.sexp) }
166    }
167
168    /// Get a specific dimension size.
169    ///
170    /// # Safety
171    ///
172    /// The SEXP must be valid.
173    ///
174    /// # Panics
175    ///
176    /// Panics if `dim >= NDIM`.
177    #[inline]
178    pub unsafe fn dim(&self, dim: usize) -> usize {
179        if !(dim < NDIM) {
    {
        ::core::panicking::panic_fmt(format_args!("dimension index out of bounds"));
    }
};assert!(dim < NDIM, "dimension index out of bounds");
180        unsafe { self.dims()[dim] }
181    }
182
183    /// Get the total number of elements.
184    #[inline]
185    pub fn len(&self) -> usize {
186        self.sexp.len()
187    }
188
189    /// Check if the array is empty.
190    #[inline]
191    pub fn is_empty(&self) -> bool {
192        self.len() == 0
193    }
194
195    /// Convert N-dimensional indices to linear index (column-major).
196    ///
197    /// # Safety
198    ///
199    /// The SEXP must be valid (needed to read dims).
200    ///
201    /// # Panics
202    ///
203    /// Panics if any index is out of bounds.
204    #[inline]
205    pub unsafe fn linear_index(&self, indices: [usize; NDIM]) -> usize {
206        let dims = unsafe { self.dims() };
207        let mut linear = 0;
208        let mut stride = 1;
209        for i in 0..NDIM {
210            if !(indices[i] < dims[i]) {
    {
        ::core::panicking::panic_fmt(format_args!("index {0} out of bounds for dimension {1} (size {2})",
                indices[i], i, dims[i]));
    }
};assert!(
211                indices[i] < dims[i],
212                "index {} out of bounds for dimension {} (size {})",
213                indices[i],
214                i,
215                dims[i]
216            );
217            linear += indices[i] * stride;
218            stride *= dims[i];
219        }
220        linear
221    }
222}
223// endregion
224
225// region: Native type methods (T: RNativeType - slice access, mutation, etc.)
226
227impl<T: RNativeType, const NDIM: usize> RArray<T, NDIM> {
228    /// Create an RArray from a SEXP, validating type and dimensions.
229    ///
230    /// # Safety
231    ///
232    /// The SEXP must be protected from GC for the lifetime of the returned RArray.
233    ///
234    /// # Errors
235    ///
236    /// Returns an error if:
237    /// - The SEXP type doesn't match `T::SEXP_TYPE`
238    /// - The dim attribute has wrong number of dimensions
239    #[inline]
240    pub unsafe fn from_sexp(sexp: SEXP) -> Result<Self, SexpError> {
241        // Type check
242        let actual = sexp.type_of();
243        if actual != T::SEXP_TYPE {
244            return Err(SexpTypeError {
245                expected: T::SEXP_TYPE,
246                actual,
247            }
248            .into());
249        }
250
251        // Validate dimensions count
252        let ndim = get_ndim(sexp);
253        if ndim != NDIM {
254            return Err(SexpLengthError {
255                expected: NDIM,
256                actual: ndim,
257            }
258            .into());
259        }
260
261        Ok(Self {
262            sexp,
263            _marker: PhantomData,
264        })
265    }
266
267    /// Get the data as a slice (column-major order).
268    ///
269    /// # Safety
270    ///
271    /// The SEXP must be protected and valid.
272    #[inline]
273    pub unsafe fn as_slice(&self) -> &[T] {
274        unsafe { self.sexp.as_slice() }
275    }
276
277    /// Get the data as a mutable slice (column-major order).
278    ///
279    /// # Safety
280    ///
281    /// - The SEXP must be protected and valid
282    /// - No other references to the data may exist
283    #[inline]
284    pub unsafe fn as_slice_mut(&mut self) -> &mut [T] {
285        unsafe {
286            let ptr = T::dataptr_mut(self.sexp);
287            crate::from_r::r_slice_mut(ptr, self.len())
288        }
289    }
290
291    /// Copy array data to an owned `Vec<T>`.
292    ///
293    /// This method copies the data, making it safe to move to other threads
294    /// or pass to parallel computation. The copy is performed on the current
295    /// thread (which must be the R main thread).
296    ///
297    /// # Safety
298    ///
299    /// The SEXP must be protected and valid.
300    ///
301    /// # Example
302    ///
303    /// ```ignore
304    /// use miniextendr_api::rarray::RMatrix;
305    ///
306    /// #[miniextendr]
307    /// fn process_matrix(m: RMatrix<f64>) -> f64 {
308    ///     // Copy data - Vec<f64> is Send and can move to other threads
309    ///     let data: Vec<f64> = unsafe { m.to_vec() };
310    ///     // Now data can be passed to parallel computation
311    ///     data.iter().sum()
312    /// }
313    /// ```
314    #[inline]
315    pub unsafe fn to_vec(&self) -> Vec<T>
316    where
317        T: Copy,
318    {
319        unsafe { self.as_slice().to_vec() }
320    }
321
322    /// Get an element by N-dimensional indices.
323    ///
324    /// # Safety
325    ///
326    /// The SEXP must be protected and valid.
327    ///
328    /// # Panics
329    ///
330    /// Panics if any index is out of bounds.
331    #[inline]
332    pub unsafe fn get(&self, indices: [usize; NDIM]) -> T
333    where
334        T: Copy,
335    {
336        let idx = unsafe { self.linear_index(indices) };
337        unsafe { *self.as_slice().get_unchecked(idx) }
338    }
339
340    /// Set an element by N-dimensional indices.
341    ///
342    /// # Safety
343    ///
344    /// - The SEXP must be protected and valid
345    /// - No other references to the data may exist
346    ///
347    /// # Panics
348    ///
349    /// Panics if any index is out of bounds.
350    #[inline]
351    pub unsafe fn set(&mut self, indices: [usize; NDIM], value: T)
352    where
353        T: Copy,
354    {
355        let idx = unsafe { self.linear_index(indices) };
356        unsafe {
357            *self.as_slice_mut().get_unchecked_mut(idx) = value;
358        }
359    }
360}
361// endregion
362
363// region: Matrix-specific methods (NDIM = 2)
364
365impl<T: RNativeType> RMatrix<T> {
366    /// Get the number of rows.
367    ///
368    /// # Safety
369    ///
370    /// The SEXP must be valid.
371    #[inline]
372    pub unsafe fn nrow(&self) -> usize {
373        unsafe { self.dim(0) }
374    }
375
376    /// Get the number of columns.
377    ///
378    /// # Safety
379    ///
380    /// The SEXP must be valid.
381    #[inline]
382    pub unsafe fn ncol(&self) -> usize {
383        unsafe { self.dim(1) }
384    }
385
386    /// Get an element by row and column.
387    ///
388    /// # Safety
389    ///
390    /// The SEXP must be protected and valid.
391    #[inline]
392    pub unsafe fn get_rc(&self, row: usize, col: usize) -> T
393    where
394        T: Copy,
395    {
396        unsafe { self.get([row, col]) }
397    }
398
399    /// Set an element by row and column.
400    ///
401    /// # Safety
402    ///
403    /// - The SEXP must be protected and valid
404    /// - No other references to the data may exist
405    #[inline]
406    pub unsafe fn set_rc(&mut self, row: usize, col: usize, value: T)
407    where
408        T: Copy,
409    {
410        unsafe { self.set([row, col], value) }
411    }
412
413    /// Get a column as a slice.
414    ///
415    /// # Safety
416    ///
417    /// The SEXP must be protected and valid.
418    #[inline]
419    pub unsafe fn column(&self, col: usize) -> &[T] {
420        let nrow = unsafe { self.nrow() };
421        let ncol = unsafe { self.ncol() };
422        if !(col < ncol) {
    {
        ::core::panicking::panic_fmt(format_args!("column index out of bounds"));
    }
};assert!(col < ncol, "column index out of bounds");
423        let start = col * nrow;
424        unsafe { &self.as_slice()[start..start + nrow] }
425    }
426
427    /// Get a mutable column as a slice.
428    ///
429    /// Columns are contiguous in R's column-major layout, so this returns
430    /// a proper `&mut [T]` without any striding.
431    ///
432    /// # Safety
433    ///
434    /// The SEXP must be protected and valid.
435    ///
436    /// # Panics
437    ///
438    /// Panics if `col >= ncol`.
439    #[inline]
440    pub unsafe fn column_mut(&mut self, col: usize) -> &mut [T] {
441        let nrow = unsafe { self.nrow() };
442        let ncol = unsafe { self.ncol() };
443        if !(col < ncol) {
    {
        ::core::panicking::panic_fmt(format_args!("column index out of bounds"));
    }
};assert!(col < ncol, "column index out of bounds");
444        let start = col * nrow;
445        unsafe { &mut self.as_slice_mut()[start..start + nrow] }
446    }
447}
448// endregion
449
450// region: Attribute access (equivalent to R's GET_*/SET_* macros)
451
452impl<T: RNativeType, const NDIM: usize> RArray<T, NDIM> {
453    // region: Attribute getters
454
455    /// Get an arbitrary attribute by symbol (unchecked internal helper).
456    ///
457    /// # Safety
458    ///
459    /// - The SEXP must be valid.
460    /// - `what` must be a valid symbol SEXP.
461    #[inline]
462    fn get_attr_opt(&self, name: SEXP) -> Option<SEXP> {
463        let attr = self.sexp.get_attr(name);
464        if attr.is_nil() { None } else { Some(attr) }
465    }
466
467    /// Get the `names` attribute if present.
468    ///
469    /// Equivalent to R's `GET_NAMES(x)`.
470    ///
471    /// # Safety
472    ///
473    /// The SEXP must be valid.
474    #[inline]
475    pub unsafe fn get_names(&self) -> Option<SEXP> {
476        // Safety: R_NamesSymbol is a known symbol
477        self.get_attr_opt(SEXP::names_symbol())
478    }
479
480    /// Get the `class` attribute if present.
481    ///
482    /// Equivalent to R's `GET_CLASS(x)`.
483    ///
484    /// # Safety
485    ///
486    /// The SEXP must be valid.
487    #[inline]
488    pub unsafe fn get_class(&self) -> Option<SEXP> {
489        // Safety: R_ClassSymbol is a known symbol
490        self.get_attr_opt(SEXP::class_symbol())
491    }
492
493    /// Get the `dimnames` attribute if present.
494    ///
495    /// Equivalent to R's `GET_DIMNAMES(x)`.
496    ///
497    /// # Safety
498    ///
499    /// The SEXP must be valid.
500    #[inline]
501    pub unsafe fn get_dimnames(&self) -> Option<SEXP> {
502        // Safety: R_DimNamesSymbol is a known symbol
503        self.get_attr_opt(SEXP::dimnames_symbol())
504    }
505
506    /// Get row names from the `dimnames` attribute.
507    ///
508    /// Equivalent to R's `GET_ROWNAMES(x)` / `Rf_GetRowNames(x)`.
509    ///
510    /// # Safety
511    ///
512    /// The SEXP must be valid.
513    #[inline]
514    pub unsafe fn get_rownames(&self) -> Option<SEXP> {
515        unsafe {
516            let dimnames = self.sexp.get_dimnames();
517            if dimnames.is_nil() {
518                return None;
519            }
520            let rownames = sys::Rf_GetRowNames(dimnames);
521            if rownames.is_nil() {
522                None
523            } else {
524                Some(rownames)
525            }
526        }
527    }
528
529    /// Get column names from the `dimnames` attribute.
530    ///
531    /// Equivalent to R's `GET_COLNAMES(x)` / `Rf_GetColNames(x)`.
532    ///
533    /// # Safety
534    ///
535    /// The SEXP must be valid.
536    #[inline]
537    pub unsafe fn get_colnames(&self) -> Option<SEXP> {
538        unsafe {
539            let dimnames = self.sexp.get_dimnames();
540            if dimnames.is_nil() {
541                return None;
542            }
543            let colnames = sys::Rf_GetColNames(dimnames);
544            if colnames.is_nil() {
545                None
546            } else {
547                Some(colnames)
548            }
549        }
550    }
551    // endregion
552
553    // region: Attribute setters
554
555    /// Set an arbitrary attribute by symbol (unchecked internal helper).
556    ///
557    /// # Safety
558    ///
559    /// Set the `names` attribute.
560    ///
561    /// Equivalent to R's `SET_NAMES(x, n)`.
562    ///
563    /// # Safety
564    ///
565    /// The SEXP must be valid and not shared.
566    #[inline]
567    pub unsafe fn set_names(&mut self, names: SEXP) {
568        self.sexp.set_names(names);
569    }
570
571    /// Set the `class` attribute.
572    ///
573    /// Equivalent to R's `SET_CLASS(x, n)`.
574    ///
575    /// # Safety
576    ///
577    /// The SEXP must be valid and not shared.
578    #[inline]
579    pub unsafe fn set_class(&mut self, class: SEXP) {
580        self.sexp.set_class(class);
581    }
582
583    /// Set the `dimnames` attribute.
584    ///
585    /// Equivalent to R's `SET_DIMNAMES(x, n)`.
586    ///
587    /// # Safety
588    ///
589    /// The SEXP must be valid and not shared.
590    #[inline]
591    pub unsafe fn set_dimnames(&mut self, dimnames: SEXP) {
592        self.sexp.set_dimnames(dimnames);
593    }
594    // endregion
595}
596// endregion
597
598// region: Construction helpers
599
600impl<T: RNativeType, const NDIM: usize> RArray<T, NDIM> {
601    /// Allocate a new R array with the given dimensions.
602    ///
603    /// The array is allocated. The closure receives a mutable slice to
604    /// initialize the data.
605    ///
606    /// # Safety
607    ///
608    /// Must be called from the R main thread (or via routed FFI).
609    /// The returned RArray holds an unprotected SEXP - caller must protect.
610    ///
611    /// # Example
612    ///
613    /// ```ignore
614    /// let matrix = unsafe {
615    ///     RMatrix::<f64>::new([3, 4], |slice| {
616    ///         for (i, v) in slice.iter_mut().enumerate() {
617    ///             *v = i as f64;
618    ///         }
619    ///     })
620    /// };
621    /// ```
622    pub unsafe fn new<F>(dims: [usize; NDIM], init: F) -> Self
623    where
624        F: FnOnce(&mut [T]),
625    {
626        let total_len: usize = dims
627            .iter()
628            .try_fold(1usize, |acc, &d| acc.checked_mul(d))
629            .expect("array total length overflows usize");
630
631        if !(total_len <= R_xlen_t::MAX as usize) {
    {
        ::core::panicking::panic_fmt(format_args!("array total length {0} exceeds R_xlen_t::MAX",
                total_len));
    }
};assert!(
632            total_len <= R_xlen_t::MAX as usize,
633            "array total length {total_len} exceeds R_xlen_t::MAX"
634        );
635
636        // Allocate the vector
637        let sexp = unsafe { sys::Rf_allocVector(T::SEXP_TYPE, total_len as R_xlen_t) };
638
639        // Set dimensions
640        unsafe { set_dims::<NDIM>(sexp, &dims) };
641
642        // Initialize data
643        let ptr = unsafe { T::dataptr_mut(sexp) };
644        let slice = unsafe { crate::from_r::r_slice_mut(ptr, total_len) };
645        init(slice);
646
647        Self {
648            sexp,
649            _marker: PhantomData,
650        }
651    }
652
653    /// Allocate a new R array filled with zeros.
654    ///
655    /// # Safety
656    ///
657    /// Must be called from the R main thread (or via routed FFI).
658    /// The returned RArray holds an unprotected SEXP - caller must protect.
659    pub unsafe fn zeros(dims: [usize; NDIM]) -> Self
660    where
661        T: Default + Copy,
662    {
663        unsafe {
664            Self::new(dims, |slice| {
665                slice.fill(T::default());
666            })
667        }
668    }
669}
670// endregion
671
672// region: TryFromSexp implementation
673
674impl<T: RNativeType, const NDIM: usize> TryFromSexp for RArray<T, NDIM> {
675    type Error = SexpError;
676
677    fn try_from_sexp(sexp: SEXP) -> Result<Self, Self::Error> {
678        unsafe { Self::from_sexp(sexp) }
679    }
680
681    unsafe fn try_from_sexp_unchecked(sexp: SEXP) -> Result<Self, Self::Error> {
682        unsafe { Self::from_sexp(sexp) }
683    }
684}
685// endregion
686
687// region: Direct coercion TryFromSexp implementations
688//
689// These implement TryFromSexp for RArray<T, NDIM> where T is not an R native type
690// but can be coerced from one. The RArray wraps the source SEXP directly (zero-copy).
691// Note: as_slice() is not available for coerced types - use to_vec_coerced() instead.
692
693use crate::RLogical;
694use crate::coerce::TryCoerce;
695use crate::sys::{self};
696
697/// Helper to validate all elements can be coerced.
698fn validate_coercion<S, T>(slice: &[S]) -> Result<(), SexpError>
699where
700    S: Copy + TryCoerce<T>,
701    <S as TryCoerce<T>>::Error: std::fmt::Debug,
702{
703    for &val in slice {
704        val.try_coerce()
705            .map_err(|e| SexpError::InvalidValue(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0:?}", e))
    })format!("{e:?}")))?;
706    }
707    Ok(())
708}
709
710/// Implement `TryFromSexp for RArray<$target, NDIM>` by reading R's native `$source` type.
711///
712/// The RArray wraps the source SEXP directly. Use `to_vec_coerced()` to get coerced data.
713macro_rules! impl_rarray_try_from_sexp_coerce {
714    ($source:ty => $target:ty) => {
715        impl<const NDIM: usize> TryFromSexp for RArray<$target, NDIM> {
716            type Error = SexpError;
717
718            fn try_from_sexp(sexp: SEXP) -> Result<Self, Self::Error> {
719                // Check source type
720                let actual = sexp.type_of();
721                if actual != <$source as RNativeType>::SEXP_TYPE {
722                    return Err(SexpTypeError {
723                        expected: <$source as RNativeType>::SEXP_TYPE,
724                        actual,
725                    }
726                    .into());
727                }
728
729                // Validate dimensions count
730                let ndim = get_ndim(sexp);
731                if ndim != NDIM {
732                    return Err(SexpLengthError {
733                        expected: NDIM,
734                        actual: ndim,
735                    }
736                    .into());
737                }
738
739                // Validate all elements can be coerced
740                let slice: &[$source] = unsafe { sexp.as_slice() };
741                validate_coercion::<$source, $target>(slice)?;
742
743                Ok(Self {
744                    sexp,
745                    _marker: PhantomData,
746                })
747            }
748
749            unsafe fn try_from_sexp_unchecked(sexp: SEXP) -> Result<Self, Self::Error> {
750                Self::try_from_sexp(sexp)
751            }
752        }
753
754        impl<const NDIM: usize> RArray<$target, NDIM> {
755            /// Copy array data to an owned `Vec`, coercing from the R native type.
756            ///
757            /// # Safety
758            ///
759            /// The SEXP must be protected and valid.
760            ///
761            /// # Panics
762            ///
763            /// Panics if any element fails to coerce (shouldn't happen if constructed via TryFromSexp).
764            #[inline]
765            pub unsafe fn to_vec_coerced(&self) -> Vec<$target> {
766                let slice: &[$source] = unsafe { self.sexp.as_slice() };
767                slice
768                    .iter()
769                    .copied()
770                    .map(|v| {
771                        <$source as TryCoerce<$target>>::try_coerce(v)
772                            .expect("coercion should succeed")
773                    })
774                    .collect()
775            }
776        }
777    };
778}
779
780// Integer coercions: R integer (i32) -> various Rust integer types
781impl<const NDIM : usize> TryFromSexp for RArray<i8, NDIM> {
    type Error = SexpError;
    fn try_from_sexp(sexp: SEXP) -> Result<Self, Self::Error> {
        let actual = sexp.type_of();
        if actual != <i32 as RNativeType>::SEXP_TYPE {
            return Err(SexpTypeError {
                            expected: <i32 as RNativeType>::SEXP_TYPE,
                            actual,
                        }.into());
        }
        let ndim = get_ndim(sexp);
        if ndim != NDIM {
            return Err(SexpLengthError {
                            expected: NDIM,
                            actual: ndim,
                        }.into());
        }
        let slice: &[i32] = unsafe { sexp.as_slice() };
        validate_coercion::<i32, i8>(slice)?;
        Ok(Self { sexp, _marker: PhantomData })
    }
    unsafe fn try_from_sexp_unchecked(sexp: SEXP)
        -> Result<Self, Self::Error> {
        Self::try_from_sexp(sexp)
    }
}
impl<const NDIM : usize> RArray<i8, NDIM> {
    /// Copy array data to an owned `Vec`, coercing from the R native type.
    ///
    /// # Safety
    ///
    /// The SEXP must be protected and valid.
    ///
    /// # Panics
    ///
    /// Panics if any element fails to coerce (shouldn't happen if constructed via TryFromSexp).
    #[inline]
    pub unsafe fn to_vec_coerced(&self) -> Vec<i8> {
        let slice: &[i32] = unsafe { self.sexp.as_slice() };
        slice.iter().copied().map(|v|
                    {
                        <i32 as
                                    TryCoerce<i8>>::try_coerce(v).expect("coercion should succeed")
                    }).collect()
    }
}impl_rarray_try_from_sexp_coerce!(i32 => i8);
782impl<const NDIM : usize> TryFromSexp for RArray<i16, NDIM> {
    type Error = SexpError;
    fn try_from_sexp(sexp: SEXP) -> Result<Self, Self::Error> {
        let actual = sexp.type_of();
        if actual != <i32 as RNativeType>::SEXP_TYPE {
            return Err(SexpTypeError {
                            expected: <i32 as RNativeType>::SEXP_TYPE,
                            actual,
                        }.into());
        }
        let ndim = get_ndim(sexp);
        if ndim != NDIM {
            return Err(SexpLengthError {
                            expected: NDIM,
                            actual: ndim,
                        }.into());
        }
        let slice: &[i32] = unsafe { sexp.as_slice() };
        validate_coercion::<i32, i16>(slice)?;
        Ok(Self { sexp, _marker: PhantomData })
    }
    unsafe fn try_from_sexp_unchecked(sexp: SEXP)
        -> Result<Self, Self::Error> {
        Self::try_from_sexp(sexp)
    }
}
impl<const NDIM : usize> RArray<i16, NDIM> {
    /// Copy array data to an owned `Vec`, coercing from the R native type.
    ///
    /// # Safety
    ///
    /// The SEXP must be protected and valid.
    ///
    /// # Panics
    ///
    /// Panics if any element fails to coerce (shouldn't happen if constructed via TryFromSexp).
    #[inline]
    pub unsafe fn to_vec_coerced(&self) -> Vec<i16> {
        let slice: &[i32] = unsafe { self.sexp.as_slice() };
        slice.iter().copied().map(|v|
                    {
                        <i32 as
                                    TryCoerce<i16>>::try_coerce(v).expect("coercion should succeed")
                    }).collect()
    }
}impl_rarray_try_from_sexp_coerce!(i32 => i16);
783impl<const NDIM : usize> TryFromSexp for RArray<i64, NDIM> {
    type Error = SexpError;
    fn try_from_sexp(sexp: SEXP) -> Result<Self, Self::Error> {
        let actual = sexp.type_of();
        if actual != <i32 as RNativeType>::SEXP_TYPE {
            return Err(SexpTypeError {
                            expected: <i32 as RNativeType>::SEXP_TYPE,
                            actual,
                        }.into());
        }
        let ndim = get_ndim(sexp);
        if ndim != NDIM {
            return Err(SexpLengthError {
                            expected: NDIM,
                            actual: ndim,
                        }.into());
        }
        let slice: &[i32] = unsafe { sexp.as_slice() };
        validate_coercion::<i32, i64>(slice)?;
        Ok(Self { sexp, _marker: PhantomData })
    }
    unsafe fn try_from_sexp_unchecked(sexp: SEXP)
        -> Result<Self, Self::Error> {
        Self::try_from_sexp(sexp)
    }
}
impl<const NDIM : usize> RArray<i64, NDIM> {
    /// Copy array data to an owned `Vec`, coercing from the R native type.
    ///
    /// # Safety
    ///
    /// The SEXP must be protected and valid.
    ///
    /// # Panics
    ///
    /// Panics if any element fails to coerce (shouldn't happen if constructed via TryFromSexp).
    #[inline]
    pub unsafe fn to_vec_coerced(&self) -> Vec<i64> {
        let slice: &[i32] = unsafe { self.sexp.as_slice() };
        slice.iter().copied().map(|v|
                    {
                        <i32 as
                                    TryCoerce<i64>>::try_coerce(v).expect("coercion should succeed")
                    }).collect()
    }
}impl_rarray_try_from_sexp_coerce!(i32 => i64);
784impl<const NDIM : usize> TryFromSexp for RArray<isize, NDIM> {
    type Error = SexpError;
    fn try_from_sexp(sexp: SEXP) -> Result<Self, Self::Error> {
        let actual = sexp.type_of();
        if actual != <i32 as RNativeType>::SEXP_TYPE {
            return Err(SexpTypeError {
                            expected: <i32 as RNativeType>::SEXP_TYPE,
                            actual,
                        }.into());
        }
        let ndim = get_ndim(sexp);
        if ndim != NDIM {
            return Err(SexpLengthError {
                            expected: NDIM,
                            actual: ndim,
                        }.into());
        }
        let slice: &[i32] = unsafe { sexp.as_slice() };
        validate_coercion::<i32, isize>(slice)?;
        Ok(Self { sexp, _marker: PhantomData })
    }
    unsafe fn try_from_sexp_unchecked(sexp: SEXP)
        -> Result<Self, Self::Error> {
        Self::try_from_sexp(sexp)
    }
}
impl<const NDIM : usize> RArray<isize, NDIM> {
    /// Copy array data to an owned `Vec`, coercing from the R native type.
    ///
    /// # Safety
    ///
    /// The SEXP must be protected and valid.
    ///
    /// # Panics
    ///
    /// Panics if any element fails to coerce (shouldn't happen if constructed via TryFromSexp).
    #[inline]
    pub unsafe fn to_vec_coerced(&self) -> Vec<isize> {
        let slice: &[i32] = unsafe { self.sexp.as_slice() };
        slice.iter().copied().map(|v|
                    {
                        <i32 as
                                    TryCoerce<isize>>::try_coerce(v).expect("coercion should succeed")
                    }).collect()
    }
}impl_rarray_try_from_sexp_coerce!(i32 => isize);
785impl<const NDIM : usize> TryFromSexp for RArray<u16, NDIM> {
    type Error = SexpError;
    fn try_from_sexp(sexp: SEXP) -> Result<Self, Self::Error> {
        let actual = sexp.type_of();
        if actual != <i32 as RNativeType>::SEXP_TYPE {
            return Err(SexpTypeError {
                            expected: <i32 as RNativeType>::SEXP_TYPE,
                            actual,
                        }.into());
        }
        let ndim = get_ndim(sexp);
        if ndim != NDIM {
            return Err(SexpLengthError {
                            expected: NDIM,
                            actual: ndim,
                        }.into());
        }
        let slice: &[i32] = unsafe { sexp.as_slice() };
        validate_coercion::<i32, u16>(slice)?;
        Ok(Self { sexp, _marker: PhantomData })
    }
    unsafe fn try_from_sexp_unchecked(sexp: SEXP)
        -> Result<Self, Self::Error> {
        Self::try_from_sexp(sexp)
    }
}
impl<const NDIM : usize> RArray<u16, NDIM> {
    /// Copy array data to an owned `Vec`, coercing from the R native type.
    ///
    /// # Safety
    ///
    /// The SEXP must be protected and valid.
    ///
    /// # Panics
    ///
    /// Panics if any element fails to coerce (shouldn't happen if constructed via TryFromSexp).
    #[inline]
    pub unsafe fn to_vec_coerced(&self) -> Vec<u16> {
        let slice: &[i32] = unsafe { self.sexp.as_slice() };
        slice.iter().copied().map(|v|
                    {
                        <i32 as
                                    TryCoerce<u16>>::try_coerce(v).expect("coercion should succeed")
                    }).collect()
    }
}impl_rarray_try_from_sexp_coerce!(i32 => u16);
786impl<const NDIM : usize> TryFromSexp for RArray<u32, NDIM> {
    type Error = SexpError;
    fn try_from_sexp(sexp: SEXP) -> Result<Self, Self::Error> {
        let actual = sexp.type_of();
        if actual != <i32 as RNativeType>::SEXP_TYPE {
            return Err(SexpTypeError {
                            expected: <i32 as RNativeType>::SEXP_TYPE,
                            actual,
                        }.into());
        }
        let ndim = get_ndim(sexp);
        if ndim != NDIM {
            return Err(SexpLengthError {
                            expected: NDIM,
                            actual: ndim,
                        }.into());
        }
        let slice: &[i32] = unsafe { sexp.as_slice() };
        validate_coercion::<i32, u32>(slice)?;
        Ok(Self { sexp, _marker: PhantomData })
    }
    unsafe fn try_from_sexp_unchecked(sexp: SEXP)
        -> Result<Self, Self::Error> {
        Self::try_from_sexp(sexp)
    }
}
impl<const NDIM : usize> RArray<u32, NDIM> {
    /// Copy array data to an owned `Vec`, coercing from the R native type.
    ///
    /// # Safety
    ///
    /// The SEXP must be protected and valid.
    ///
    /// # Panics
    ///
    /// Panics if any element fails to coerce (shouldn't happen if constructed via TryFromSexp).
    #[inline]
    pub unsafe fn to_vec_coerced(&self) -> Vec<u32> {
        let slice: &[i32] = unsafe { self.sexp.as_slice() };
        slice.iter().copied().map(|v|
                    {
                        <i32 as
                                    TryCoerce<u32>>::try_coerce(v).expect("coercion should succeed")
                    }).collect()
    }
}impl_rarray_try_from_sexp_coerce!(i32 => u32);
787impl<const NDIM : usize> TryFromSexp for RArray<u64, NDIM> {
    type Error = SexpError;
    fn try_from_sexp(sexp: SEXP) -> Result<Self, Self::Error> {
        let actual = sexp.type_of();
        if actual != <i32 as RNativeType>::SEXP_TYPE {
            return Err(SexpTypeError {
                            expected: <i32 as RNativeType>::SEXP_TYPE,
                            actual,
                        }.into());
        }
        let ndim = get_ndim(sexp);
        if ndim != NDIM {
            return Err(SexpLengthError {
                            expected: NDIM,
                            actual: ndim,
                        }.into());
        }
        let slice: &[i32] = unsafe { sexp.as_slice() };
        validate_coercion::<i32, u64>(slice)?;
        Ok(Self { sexp, _marker: PhantomData })
    }
    unsafe fn try_from_sexp_unchecked(sexp: SEXP)
        -> Result<Self, Self::Error> {
        Self::try_from_sexp(sexp)
    }
}
impl<const NDIM : usize> RArray<u64, NDIM> {
    /// Copy array data to an owned `Vec`, coercing from the R native type.
    ///
    /// # Safety
    ///
    /// The SEXP must be protected and valid.
    ///
    /// # Panics
    ///
    /// Panics if any element fails to coerce (shouldn't happen if constructed via TryFromSexp).
    #[inline]
    pub unsafe fn to_vec_coerced(&self) -> Vec<u64> {
        let slice: &[i32] = unsafe { self.sexp.as_slice() };
        slice.iter().copied().map(|v|
                    {
                        <i32 as
                                    TryCoerce<u64>>::try_coerce(v).expect("coercion should succeed")
                    }).collect()
    }
}impl_rarray_try_from_sexp_coerce!(i32 => u64);
788impl<const NDIM : usize> TryFromSexp for RArray<usize, NDIM> {
    type Error = SexpError;
    fn try_from_sexp(sexp: SEXP) -> Result<Self, Self::Error> {
        let actual = sexp.type_of();
        if actual != <i32 as RNativeType>::SEXP_TYPE {
            return Err(SexpTypeError {
                            expected: <i32 as RNativeType>::SEXP_TYPE,
                            actual,
                        }.into());
        }
        let ndim = get_ndim(sexp);
        if ndim != NDIM {
            return Err(SexpLengthError {
                            expected: NDIM,
                            actual: ndim,
                        }.into());
        }
        let slice: &[i32] = unsafe { sexp.as_slice() };
        validate_coercion::<i32, usize>(slice)?;
        Ok(Self { sexp, _marker: PhantomData })
    }
    unsafe fn try_from_sexp_unchecked(sexp: SEXP)
        -> Result<Self, Self::Error> {
        Self::try_from_sexp(sexp)
    }
}
impl<const NDIM : usize> RArray<usize, NDIM> {
    /// Copy array data to an owned `Vec`, coercing from the R native type.
    ///
    /// # Safety
    ///
    /// The SEXP must be protected and valid.
    ///
    /// # Panics
    ///
    /// Panics if any element fails to coerce (shouldn't happen if constructed via TryFromSexp).
    #[inline]
    pub unsafe fn to_vec_coerced(&self) -> Vec<usize> {
        let slice: &[i32] = unsafe { self.sexp.as_slice() };
        slice.iter().copied().map(|v|
                    {
                        <i32 as
                                    TryCoerce<usize>>::try_coerce(v).expect("coercion should succeed")
                    }).collect()
    }
}impl_rarray_try_from_sexp_coerce!(i32 => usize);
789
790// Float coercions: R numeric (f64) -> f32
791impl<const NDIM : usize> TryFromSexp for RArray<f32, NDIM> {
    type Error = SexpError;
    fn try_from_sexp(sexp: SEXP) -> Result<Self, Self::Error> {
        let actual = sexp.type_of();
        if actual != <f64 as RNativeType>::SEXP_TYPE {
            return Err(SexpTypeError {
                            expected: <f64 as RNativeType>::SEXP_TYPE,
                            actual,
                        }.into());
        }
        let ndim = get_ndim(sexp);
        if ndim != NDIM {
            return Err(SexpLengthError {
                            expected: NDIM,
                            actual: ndim,
                        }.into());
        }
        let slice: &[f64] = unsafe { sexp.as_slice() };
        validate_coercion::<f64, f32>(slice)?;
        Ok(Self { sexp, _marker: PhantomData })
    }
    unsafe fn try_from_sexp_unchecked(sexp: SEXP)
        -> Result<Self, Self::Error> {
        Self::try_from_sexp(sexp)
    }
}
impl<const NDIM : usize> RArray<f32, NDIM> {
    /// Copy array data to an owned `Vec`, coercing from the R native type.
    ///
    /// # Safety
    ///
    /// The SEXP must be protected and valid.
    ///
    /// # Panics
    ///
    /// Panics if any element fails to coerce (shouldn't happen if constructed via TryFromSexp).
    #[inline]
    pub unsafe fn to_vec_coerced(&self) -> Vec<f32> {
        let slice: &[f64] = unsafe { self.sexp.as_slice() };
        slice.iter().copied().map(|v|
                    {
                        <f64 as
                                    TryCoerce<f32>>::try_coerce(v).expect("coercion should succeed")
                    }).collect()
    }
}impl_rarray_try_from_sexp_coerce!(f64 => f32);
792
793// Logical coercions: R logical (RLogical) -> bool
794impl<const NDIM : usize> TryFromSexp for RArray<bool, NDIM> {
    type Error = SexpError;
    fn try_from_sexp(sexp: SEXP) -> Result<Self, Self::Error> {
        let actual = sexp.type_of();
        if actual != <RLogical as RNativeType>::SEXP_TYPE {
            return Err(SexpTypeError {
                            expected: <RLogical as RNativeType>::SEXP_TYPE,
                            actual,
                        }.into());
        }
        let ndim = get_ndim(sexp);
        if ndim != NDIM {
            return Err(SexpLengthError {
                            expected: NDIM,
                            actual: ndim,
                        }.into());
        }
        let slice: &[RLogical] = unsafe { sexp.as_slice() };
        validate_coercion::<RLogical, bool>(slice)?;
        Ok(Self { sexp, _marker: PhantomData })
    }
    unsafe fn try_from_sexp_unchecked(sexp: SEXP)
        -> Result<Self, Self::Error> {
        Self::try_from_sexp(sexp)
    }
}
impl<const NDIM : usize> RArray<bool, NDIM> {
    /// Copy array data to an owned `Vec`, coercing from the R native type.
    ///
    /// # Safety
    ///
    /// The SEXP must be protected and valid.
    ///
    /// # Panics
    ///
    /// Panics if any element fails to coerce (shouldn't happen if constructed via TryFromSexp).
    #[inline]
    pub unsafe fn to_vec_coerced(&self) -> Vec<bool> {
        let slice: &[RLogical] = unsafe { self.sexp.as_slice() };
        slice.iter().copied().map(|v|
                    {
                        <RLogical as
                                    TryCoerce<bool>>::try_coerce(v).expect("coercion should succeed")
                    }).collect()
    }
}impl_rarray_try_from_sexp_coerce!(RLogical => bool);
795// endregion
796
797// region: IntoR implementation
798
799impl<T: RNativeType, const NDIM: usize> IntoR for RArray<T, NDIM> {
800    type Error = std::convert::Infallible;
801    fn try_into_sexp(self) -> Result<crate::SEXP, Self::Error> {
802        Ok(self.into_sexp())
803    }
804    unsafe fn try_into_sexp_unchecked(self) -> Result<crate::SEXP, Self::Error> {
805        Ok(unsafe { self.into_sexp_unchecked() })
806    }
807    fn into_sexp(self) -> SEXP {
808        self.sexp
809    }
810
811    unsafe fn into_sexp_unchecked(self) -> SEXP {
812        self.sexp
813    }
814}
815// endregion
816
817// region: Helper functions
818
819/// Get number of dimensions from SEXP.
820fn get_ndim(sexp: SEXP) -> usize {
821    {
822        let dim_sexp = sexp.get_dim();
823        if dim_sexp.type_of() != SEXPTYPE::INTSXP {
824            // No dim attribute - treat as 1D
825            1
826        } else {
827            dim_sexp.len()
828        }
829    }
830}
831
832/// Get dimensions from SEXP as array.
833///
834/// # Safety
835///
836/// Caller must ensure SEXP has NDIM dimensions.
837unsafe fn get_dims<const NDIM: usize>(sexp: SEXP) -> [usize; NDIM] {
838    let mut dims = [0usize; NDIM];
839
840    unsafe {
841        let dim_sexp = sexp.get_dim();
842
843        if dim_sexp.type_of() != SEXPTYPE::INTSXP {
844            // No dim attribute - treat as 1D with length
845            if NDIM == 1 {
846                dims[0] = sexp.len();
847            }
848        } else {
849            let dim_slice: &[i32] = dim_sexp.as_slice();
850            for (i, &d) in dim_slice.iter().take(NDIM).enumerate() {
851                dims[i] = d as usize;
852            }
853        }
854    }
855
856    dims
857}
858
859/// Set dimensions on a SEXP.
860///
861/// # Safety
862///
863/// Must be called from R main thread.
864unsafe fn set_dims<const NDIM: usize>(sexp: SEXP, dims: &[usize; NDIM]) {
865    unsafe {
866        let (dim_sexp, dim_slice) = crate::into_r::alloc_r_vector::<i32>(NDIM);
867        let _guard = crate::OwnedProtect::new(dim_sexp);
868
869        for (slot, &d) in dim_slice.iter_mut().zip(dims.iter()) {
870            *slot = i32::try_from(d).unwrap_or_else(|_| {
871                {
    ::core::panicking::panic_fmt(format_args!("array dimension {0} exceeds i32::MAX",
            d));
};panic!("array dimension {d} exceeds i32::MAX");
872            });
873        }
874
875        sexp.set_dim(dim_sexp);
876    }
877}
878// endregion
879
880// region: Debug implementation
881
882impl<T: RNativeType, const NDIM: usize> std::fmt::Debug for RArray<T, NDIM> {
883    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
884        f.debug_struct("RArray")
885            .field("ndim", &NDIM)
886            .field("len", &self.len())
887            .field("sexp", &self.sexp)
888            .finish()
889    }
890}
891// endregion
892
893// region: Tests
894
895#[cfg(test)]
896mod tests;
897// endregion