extendr_api/wrapper/
complexes.rs

1use super::scalar::{c64, Rcplx};
2use super::*;
3use extendr_ffi::{dataptr, R_xlen_t, Rcomplex, COMPLEX_GET_REGION, SEXPTYPE::CPLXSXP};
4use std::iter::FromIterator;
5
6/// An obscure `NA`-aware wrapper for R's complex vectors.
7/// Can be used to iterate over vectors obtained from R
8/// or to create new vectors that can be returned back to R.
9/// ```
10/// use extendr_api::prelude::*;
11/// test! {
12///     let mut vec = (0..5).map(|i| c64::from(i as f64)).collect::<Complexes>();
13///     assert_eq!(vec.len(), 5);
14/// }
15/// ```
16#[derive(PartialEq, Clone)]
17pub struct Complexes {
18    pub(crate) robj: Robj,
19}
20
21macros::gen_vector_wrapper_impl!(
22    vector_type: Complexes,
23    scalar_type: Rcplx,
24    primitive_type: c64,
25    r_prefix: COMPLEX,
26    SEXP: CPLXSXP,
27    doc_name: complex,
28    altrep_constructor: make_altcomplex_from_iterator,
29);
30
31macros::gen_from_iterator_impl!(
32    vector_type: Complexes,
33    collect_from_type: c64,
34    underlying_type: Rcplx,
35    SEXP: CPLXSXP,
36    assignment: |dest: &mut Rcplx, val: c64| *dest = val.into()
37);
38
39impl Complexes {
40    /// Get a region of elements from the vector.
41    pub fn get_region(&self, index: usize, dest: &mut [Rcplx]) -> usize {
42        unsafe {
43            let ptr: *mut Rcomplex = dest.as_mut_ptr() as *mut Rcomplex;
44            COMPLEX_GET_REGION(self.get(), index as R_xlen_t, dest.len() as R_xlen_t, ptr) as usize
45        }
46    }
47}
48
49// There is no SET_COMPLEX_ELT
50//
51// impl Complexes {
52//     pub fn set_elt(&mut self, index: usize, val: Rcplx) {
53//         unsafe {
54//             SET_COMPLEX_ELT(self.get(), index as R_xlen_t, val.inner());
55//         }
56//     }
57// }
58
59impl Deref for Complexes {
60    type Target = [Rcplx];
61
62    /// Treat Complexes as if it is a slice, like `Vec<Rcplx>`
63    fn deref(&self) -> &Self::Target {
64        unsafe {
65            let ptr = dataptr(self.get()) as *const Rcplx;
66            std::slice::from_raw_parts(ptr, self.len())
67        }
68    }
69}
70
71impl DerefMut for Complexes {
72    /// Treat Complexes as if it is a mutable slice, like `Vec<Rcplx>`
73    fn deref_mut(&mut self) -> &mut Self::Target {
74        unsafe {
75            let ptr = dataptr(self.get_mut()) as *mut Rcplx;
76            std::slice::from_raw_parts_mut(ptr, self.len())
77        }
78    }
79}
80
81impl std::fmt::Debug for Complexes {
82    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
83        if self.len() == 1 {
84            write!(f, "{:?}", self.elt(0))
85        } else {
86            f.debug_list().entries(self.iter()).finish()
87        }
88    }
89}
90
91impl TryFrom<Vec<c64>> for Complexes {
92    type Error = Error;
93
94    fn try_from(value: Vec<c64>) -> std::result::Result<Self, Self::Error> {
95        Ok(Self { robj: value.into() })
96    }
97}
98
99#[cfg(test)]
100mod tests {
101    use super::*;
102    use crate as extendr_api;
103
104    #[test]
105    fn test_try_from_vec_c64_conversion() {
106        test! {
107            let vec = vec![c64::new(0., 0.), c64::new(1., 1.), c64::new(0., 1.)];
108            let vec_rob: Complexes = vec.clone().try_into().unwrap();
109            let vec_rob_slice: &[c64] = vec_rob.robj.as_typed_slice().unwrap();
110            assert_eq!(vec_rob_slice, vec.as_slice());
111        }
112    }
113}