extendr_api/wrapper/
complexes.rs1use 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#[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 r_prefix: COMPLEX,
36 SEXP: CPLXSXP
37);
38
39impl Complexes {
40 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
49impl Deref for Complexes {
60 type Target = [Rcplx];
61
62 fn deref(&self) -> &Self::Target {
64 unsafe {
65 let ptr = dataptr(self.get()) as *const Rcplx;
66 crate::robj::vector_slice(ptr, self.len())
67 }
68 }
69}
70
71impl DerefMut for Complexes {
72 fn deref_mut(&mut self) -> &mut Self::Target {
74 unsafe {
75 let ptr = dataptr(self.get_mut()) as *mut Rcplx;
76 crate::robj::vector_slice_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>) -> Result<Self> {
95 Ok(Self { robj: value.into() })
96 }
97}
98
99#[cfg(test)]
100mod tests {
101 use super::*;
102
103 #[test]
104 fn new() {
105 test! {
106 let vec = Complexes::new(10);
107 assert_eq!(vec.is_complex(), true);
108 assert_eq!(vec.len(), 10);
109 }
110 }
111
112 #[test]
113 fn new_with_na() {
114 use crate::na::CanBeNA;
115 test! {
116 let vec = Complexes::new_with_na(10);
117 let manual_vec = (0..10).map(|_| Rcplx::na()).collect::<Complexes>();
118 assert_eq!(vec, manual_vec);
119 assert_eq!(vec.len(), manual_vec.len());
120 }
121 }
122
123 #[test]
124 fn test_try_from_vec_c64_conversion() {
125 test! {
126 let vec = vec![c64::new(0., 0.), c64::new(1., 1.), c64::new(0., 1.)];
127 let vec_rob: Complexes = vec.clone().try_into().unwrap();
128 let vec_rob_slice: &[c64] = vec_rob.robj.as_typed_slice().unwrap();
129 assert_eq!(vec_rob_slice, vec.as_slice());
130 }
131 }
132}