1use 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
91pub type RVector<T> = RArray<T, 1>;
95
96pub type RMatrix<T> = RArray<T, 2>;
98
99pub type RArray3D<T> = RArray<T, 3>;
101#[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 _marker: PhantomData<*const T>,
125}
126impl<T, const NDIM: usize> RArray<T, NDIM> {
131 #[inline]
139 pub const unsafe fn from_sexp_unchecked(sexp: SEXP) -> Self {
140 Self {
141 sexp,
142 _marker: PhantomData,
143 }
144 }
145
146 #[inline]
148 pub const fn as_sexp(&self) -> SEXP {
149 self.sexp
150 }
151
152 #[inline]
154 pub fn into_inner(self) -> SEXP {
155 self.sexp
156 }
157
158 #[inline]
164 pub unsafe fn dims(&self) -> [usize; NDIM] {
165 unsafe { get_dims::<NDIM>(self.sexp) }
166 }
167
168 #[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 #[inline]
185 pub fn len(&self) -> usize {
186 self.sexp.len()
187 }
188
189 #[inline]
191 pub fn is_empty(&self) -> bool {
192 self.len() == 0
193 }
194
195 #[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}
223impl<T: RNativeType, const NDIM: usize> RArray<T, NDIM> {
228 #[inline]
240 pub unsafe fn from_sexp(sexp: SEXP) -> Result<Self, SexpError> {
241 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 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 #[inline]
273 pub unsafe fn as_slice(&self) -> &[T] {
274 unsafe { self.sexp.as_slice() }
275 }
276
277 #[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 #[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 #[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 #[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}
361impl<T: RNativeType> RMatrix<T> {
366 #[inline]
372 pub unsafe fn nrow(&self) -> usize {
373 unsafe { self.dim(0) }
374 }
375
376 #[inline]
382 pub unsafe fn ncol(&self) -> usize {
383 unsafe { self.dim(1) }
384 }
385
386 #[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 #[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 #[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 #[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}
448impl<T: RNativeType, const NDIM: usize> RArray<T, NDIM> {
453 #[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 #[inline]
475 pub unsafe fn get_names(&self) -> Option<SEXP> {
476 self.get_attr_opt(SEXP::names_symbol())
478 }
479
480 #[inline]
488 pub unsafe fn get_class(&self) -> Option<SEXP> {
489 self.get_attr_opt(SEXP::class_symbol())
491 }
492
493 #[inline]
501 pub unsafe fn get_dimnames(&self) -> Option<SEXP> {
502 self.get_attr_opt(SEXP::dimnames_symbol())
504 }
505
506 #[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 #[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 #[inline]
567 pub unsafe fn set_names(&mut self, names: SEXP) {
568 self.sexp.set_names(names);
569 }
570
571 #[inline]
579 pub unsafe fn set_class(&mut self, class: SEXP) {
580 self.sexp.set_class(class);
581 }
582
583 #[inline]
591 pub unsafe fn set_dimnames(&mut self, dimnames: SEXP) {
592 self.sexp.set_dimnames(dimnames);
593 }
594 }
596impl<T: RNativeType, const NDIM: usize> RArray<T, NDIM> {
601 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 let sexp = unsafe { sys::Rf_allocVector(T::SEXP_TYPE, total_len as R_xlen_t) };
638
639 unsafe { set_dims::<NDIM>(sexp, &dims) };
641
642 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 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}
670impl<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}
685use crate::RLogical;
694use crate::coerce::TryCoerce;
695use crate::sys::{self};
696
697fn 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
710macro_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 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 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 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 #[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
780impl<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> {
#[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> {
#[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> {
#[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> {
#[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> {
#[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> {
#[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> {
#[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> {
#[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
790impl<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> {
#[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
793impl<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> {
#[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);
795impl<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}
815fn get_ndim(sexp: SEXP) -> usize {
821 {
822 let dim_sexp = sexp.get_dim();
823 if dim_sexp.type_of() != SEXPTYPE::INTSXP {
824 1
826 } else {
827 dim_sexp.len()
828 }
829 }
830}
831
832unsafe 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 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
859unsafe 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}
878impl<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#[cfg(test)]
896mod tests;
897