extendr_api/wrapper/
doubles.rs

1use super::scalar::{Rfloat, Scalar};
2use super::*;
3use extendr_ffi::{
4    dataptr, R_xlen_t, REAL_GET_REGION, REAL_IS_SORTED, REAL_NO_NA, SET_REAL_ELT, SEXPTYPE::REALSXP,
5};
6use std::iter::FromIterator;
7
8/// An obscure `NA`-aware wrapper for R's double vectors.
9/// Can be used to iterate over vectors obtained from R
10/// or to create new vectors that can be returned back to R.
11/// ```
12/// use extendr_api::prelude::*;
13/// test! {
14///     let mut vec = (0..5).map(|i| (i as f64)).collect::<Doubles>();
15///     vec.iter_mut().for_each(|v| *v = *v + 10.0);
16///     assert_eq!(vec.elt(0), 10.0);
17///     let sum = vec.iter().sum::<Rfloat>();
18///     assert_eq!(sum, 60.0);
19/// }
20/// ```
21#[derive(PartialEq, Clone)]
22pub struct Doubles {
23    pub(crate) robj: Robj,
24}
25
26macros::gen_vector_wrapper_impl!(
27    vector_type: Doubles,
28    scalar_type: Rfloat,
29    primitive_type: f64,
30    r_prefix: REAL,
31    SEXP: REALSXP,
32    doc_name: double,
33    altrep_constructor: make_altreal_from_iterator,
34);
35
36macros::gen_from_iterator_impl!(
37    vector_type: Doubles,
38    collect_from_type: f64,
39    underlying_type: f64,
40    SEXP: REALSXP,
41    assignment: |dest: &mut f64, val: f64| *dest = val
42);
43
44impl Doubles {
45    /// Get a region of elements from the vector.
46    pub fn get_region(&self, index: usize, dest: &mut [Rfloat]) -> usize {
47        unsafe {
48            let ptr: *mut f64 = dest.as_mut_ptr() as *mut f64;
49            REAL_GET_REGION(self.get(), index as R_xlen_t, dest.len() as R_xlen_t, ptr) as usize
50        }
51    }
52
53    /// Return `TRUE` if the vector is sorted, `FALSE` if not, or `NA_BOOL` if unknown.
54    pub fn is_sorted(&self) -> Rbool {
55        unsafe { REAL_IS_SORTED(self.get()).into() }
56    }
57
58    /// Return `TRUE` if the vector has no `NA`s, `FALSE` if any, or `NA_BOOL` if unknown.
59    pub fn no_na(&self) -> Rbool {
60        unsafe { REAL_NO_NA(self.get()).into() }
61    }
62}
63
64// TODO: this should be a trait.
65impl Doubles {
66    pub fn set_elt(&mut self, index: usize, val: Rfloat) {
67        single_threaded(|| unsafe {
68            SET_REAL_ELT(self.get_mut(), index as R_xlen_t, val.inner());
69        })
70    }
71}
72
73impl Deref for Doubles {
74    type Target = [Rfloat];
75
76    /// Treat Doubles as if it is a slice, like `Vec<Rfloat>`
77    fn deref(&self) -> &Self::Target {
78        unsafe {
79            let ptr = dataptr(self.get()) as *const Rfloat;
80            std::slice::from_raw_parts(ptr, self.len())
81        }
82    }
83}
84
85impl DerefMut for Doubles {
86    /// Treat Doubles as if it is a mutable slice, like `Vec<Rfloat>`
87    fn deref_mut(&mut self) -> &mut Self::Target {
88        unsafe {
89            let ptr = dataptr(self.get_mut()) as *mut Rfloat;
90            std::slice::from_raw_parts_mut(ptr, self.len())
91        }
92    }
93}
94
95impl std::fmt::Debug for Doubles {
96    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
97        if self.len() == 1 {
98            write!(f, "{:?}", self.elt(0))
99        } else {
100            f.debug_list().entries(self.iter()).finish()
101        }
102    }
103}
104
105impl TryFrom<Vec<f64>> for Doubles {
106    type Error = Error;
107
108    fn try_from(value: Vec<f64>) -> std::result::Result<Self, Self::Error> {
109        Ok(Self { robj: value.into() })
110    }
111}
112
113#[cfg(test)]
114mod tests {
115    use super::*;
116    use crate as extendr_api;
117
118    #[test]
119    fn test_vec_f64_doubles_conversion() {
120        test! {
121            let test_vec = vec![0., 1., std::f64::consts::PI, -1.];
122            let test_doubles: Doubles = test_vec.clone().try_into().unwrap();
123            let test_doubles_slice = test_doubles.robj.as_real_slice().unwrap();
124            assert_eq!(test_doubles_slice, test_vec);
125        }
126    }
127}