extendr-api 0.9.0

Safe and user friendly bindings to the R programming language.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
//! There are various ways an [`Robj`] may be converted into different types `T`.
//!
//! This module defines these conversions on `&Robj`. Due to internal reference
//! counting measure of [`ownership`]-module, it is cheaper to copy `&Robj`,
//! than copying `Robj`, as the latter will incur an increase in reference counting.
//!
//!
//! [`ownership`]: crate::ownership
use super::*;
use crate as extendr_api;
use crate::conversions::try_into_int::FloatToInt;

macro_rules! impl_try_from_scalar_integer {
    ($t:ty) => {
        impl TryFrom<&Robj> for $t {
            type Error = Error;

            /// Convert a numeric object to an integer value.
            fn try_from(robj: &Robj) -> Result<Self> {
                // Check if the value is a scalar
                match robj.len() {
                    0 => return Err(Error::ExpectedNonZeroLength(robj.clone())),
                    1 => {}
                    _ => return Err(Error::ExpectedScalar(robj.clone())),
                };

                // Check if the value is not a missing value
                if robj.is_na() {
                    return Err(Error::MustNotBeNA(robj.clone()));
                }

                // If the conversion is int-to-int, check the limits. This
                // needs to be done by `TryFrom` because the conversion by `as`
                // is problematic when converting a negative value to unsigned
                // integer types (e.g. `-1i32 as u8` becomes 255).
                if let Some(v) = robj.as_integer() {
                    return Self::try_from(v).map_err(|_| Error::OutOfLimits(robj.clone()));
                }

                // If the conversion is float-to-int, check if the value is
                // integer-like (i.e., an integer, or a float representing a
                // whole number).
                if let Some(v) = robj.as_real() {
                    return v
                        .try_into_int()
                        .map_err(|conv_err| Error::ExpectedWholeNumber(robj.clone(), conv_err));
                }

                Err(Error::ExpectedNumeric(robj.clone()))
            }
        }
    };
}

macro_rules! impl_try_from_scalar_real {
    ($t:ty) => {
        impl TryFrom<&Robj> for $t {
            type Error = Error;

            /// Convert a numeric object to a real value.
            fn try_from(robj: &Robj) -> Result<Self> {
                // Check if the value is a scalar
                match robj.len() {
                    0 => return Err(Error::ExpectedNonZeroLength(robj.clone())),
                    1 => {}
                    _ => return Err(Error::ExpectedScalar(robj.clone())),
                };

                // Check if the value is not a missing value
                if robj.is_na() {
                    return Err(Error::MustNotBeNA(robj.clone()));
                }

                // `<Robj>::as_xxx()` methods can work only when the underlying
                // `SEXP` is the corresponding type, so we cannot use `as_real()`
                // directly on `INTSXP`.
                if let Some(v) = robj.as_real() {
                    // f64 to f32 and f64 to f64 is always safe.
                    return Ok(v as Self);
                }
                if let Some(v) = robj.as_integer() {
                    // An i32 R integer can be represented exactly by f64, but might be truncated in f32.
                    return Ok(v as Self);
                }

                Err(Error::ExpectedNumeric(robj.clone()))
            }
        }
    };
}

macro_rules! impl_typed_slice_conversions {
    ($type:ty, $error:ident, $desc:expr) => {
        impl_typed_slice_conversions!($type, $error, $error, $error, $desc);
    };
    ($type:ty, $vec_error:ident, $slice_error:ident, $mut_error:ident, $desc:expr) => {
        impl TryFrom<&Robj> for Vec<$type> {
            type Error = Error;

            #[doc = concat!("Convert ", $desc, " into `Vec<", stringify!($type), ">`.")]
            #[doc = "Note: Unless you plan to store the result, use a slice instead."]
            fn try_from(robj: &Robj) -> Result<Self> {
                robj.as_typed_slice()
                    .map(<[_]>::to_vec)
                    .ok_or_else(|| Error::$vec_error(robj.clone()))
            }
        }

        impl TryFrom<&Robj> for &[$type] {
            type Error = Error;

            #[doc = concat!("Convert ", $desc, " into `&[", stringify!($type), "]`.")]
            fn try_from(robj: &Robj) -> Result<Self> {
                robj.as_typed_slice()
                    .ok_or_else(|| Error::$slice_error(robj.clone()))
            }
        }

        impl TryFrom<&mut Robj> for &mut [$type] {
            type Error = Error;

            #[doc = concat!("Convert ", $desc, " into `&mut [", stringify!($type), "]`.")]
            fn try_from(robj: &mut Robj) -> Result<Self> {
                robj.as_typed_slice_mut()
                    .ok_or_else(|| Error::$mut_error(robj.clone()))
            }
        }

        impl TryFrom<&Robj> for Option<&[$type]> {
            type Error = Error;

            #[doc = concat!("Convert ", $desc, " into `Option<&[", stringify!($type), "]>`.")]
            fn try_from(robj: &Robj) -> Result<Self> {
                if robj.is_null() || robj.is_na() {
                    Ok(None)
                } else {
                    Ok(Some(<&[$type]>::try_from(robj)?))
                }
            }
        }

        impl TryFrom<&mut Robj> for Option<&mut [$type]> {
            type Error = Error;

            #[doc = concat!("Convert ", $desc, " into `Option<&mut [", stringify!($type), "]>`.")]
            fn try_from(robj: &mut Robj) -> Result<Self> {
                if robj.is_null() || robj.is_na() {
                    Ok(None)
                } else {
                    Ok(Some(<&mut [$type]>::try_from(robj)?))
                }
            }
        }

        impl TryFrom<&Robj> for &$type {
            type Error = Error;

            #[doc = concat!("Convert ", $desc, " into `&", stringify!($type), "`.")]
            fn try_from(robj: &Robj) -> Result<Self> {
                let slice: &[$type] = robj.try_into()?;

                if slice.is_empty() {
                    return Err(Error::ExpectedNonZeroLength(robj.clone()));
                }
                if slice.len() != 1 {
                    return Err(Error::ExpectedScalar(robj.clone()));
                }
                let Some(value) = slice.get(0) else {
                    unreachable!()
                };
                if value.is_na() {
                    return Err(Error::MustNotBeNA(robj.clone()));
                }
                Ok(value)
            }
        }

        impl TryFrom<&mut Robj> for &mut $type {
            type Error = Error;

            #[doc = concat!("Convert ", $desc, " into `&mut ", stringify!($type), "`.")]
            fn try_from(robj: &mut Robj) -> Result<Self> {
                let slice: &mut [$type] = robj.try_into()?;

                if slice.is_empty() {
                    return Err(Error::ExpectedNonZeroLength(robj.clone()));
                }
                if slice.len() != 1 {
                    return Err(Error::ExpectedScalar(robj.clone()));
                }
                let Some(value) = slice.get_mut(0) else {
                    unreachable!()
                };
                if value.is_na() {
                    return Err(Error::MustNotBeNA(robj.clone()));
                }
                Ok(value)
            }
        }
    };
}

impl_try_from_scalar_integer!(u8);
impl_try_from_scalar_integer!(u16);
impl_try_from_scalar_integer!(u32);
impl_try_from_scalar_integer!(u64);
impl_try_from_scalar_integer!(usize);
impl_try_from_scalar_integer!(i8);
impl_try_from_scalar_integer!(i16);
impl_try_from_scalar_integer!(i32);
impl_try_from_scalar_integer!(i64);
impl_try_from_scalar_integer!(isize);
impl_try_from_scalar_real!(f32);
impl_try_from_scalar_real!(f64);

impl TryFrom<&Robj> for bool {
    type Error = Error;

    /// Convert an LGLSXP object into a boolean.
    /// NAs are not allowed.
    fn try_from(robj: &Robj) -> Result<Self> {
        if robj.is_na() {
            Err(Error::MustNotBeNA(robj.clone()))
        } else {
            Ok(<Rbool>::try_from(robj)?.is_true())
        }
    }
}

impl TryFrom<&Robj> for &str {
    type Error = Error;

    /// Convert a scalar STRSXP object into a string slice.
    /// NAs are not allowed.
    fn try_from(robj: &Robj) -> Result<Self> {
        if robj.is_na() {
            return Err(Error::MustNotBeNA(robj.clone()));
        }
        match robj.len() {
            0 => Err(Error::ExpectedNonZeroLength(robj.clone())),
            1 => {
                if let Some(s) = robj.as_str() {
                    Ok(s)
                } else {
                    Err(Error::ExpectedString(robj.clone()))
                }
            }
            _ => Err(Error::ExpectedScalar(robj.clone())),
        }
    }
}

impl TryFrom<&Robj> for Option<&str> {
    type Error = Error;

    fn try_from(robj: &Robj) -> Result<Self> {
        if robj.is_null() || robj.is_na() {
            Ok(None)
        } else {
            Ok(Some(<&str>::try_from(robj)?))
        }
    }
}

impl TryFrom<&Robj> for String {
    type Error = Error;

    /// Convert an scalar STRSXP object into a String.
    /// Note: Unless you plan to store the result, use a string slice instead.
    /// NAs are not allowed.
    fn try_from(robj: &Robj) -> Result<Self> {
        <&str>::try_from(robj).map(|s| s.to_string())
    }
}

impl_typed_slice_conversions!(i32, ExpectedInteger, "an INTSXP object");
impl_typed_slice_conversions!(Rint, ExpectedInteger, "an INTSXP object");
impl_typed_slice_conversions!(Rfloat, ExpectedReal, "a REALSXP object");
impl_typed_slice_conversions!(
    Rbool,
    ExpectedInteger,
    ExpectedLogical,
    ExpectedLogical,
    "a LGLSXP object"
);
impl_typed_slice_conversions!(Rcplx, ExpectedComplex, "a complex object");
impl_typed_slice_conversions!(u8, ExpectedRaw, "a RAWSXP object");
impl_typed_slice_conversions!(f64, ExpectedReal, "a REALSXP object");

impl TryFrom<&Robj> for Vec<String> {
    type Error = Error;

    /// Convert a STRSXP object into a vector of `String`s.
    /// Note: Unless you plan to store the result, use a slice instead.
    fn try_from(robj: &Robj) -> Result<Self> {
        if let Some(iter) = robj.as_str_iter() {
            // check for NA's in the string vector
            if iter.clone().any(|s| s.is_na()) {
                Err(Error::MustNotBeNA(robj.clone()))
            } else {
                Ok(iter.map(|s| s.to_string()).collect::<Vec<String>>())
            }
        } else {
            Err(Error::ExpectedString(robj.clone()))
        }
    }
}

impl TryFrom<&Robj> for Rcplx {
    type Error = Error;

    fn try_from(robj: &Robj) -> Result<Self> {
        // Check if the value is a scalar
        match robj.len() {
            0 => return Err(Error::ExpectedNonZeroLength(robj.clone())),
            1 => {}
            _ => return Err(Error::ExpectedScalar(robj.clone())),
        };

        // Check if the value is not a missing value.
        if robj.is_na() {
            return Ok(Rcplx::na());
        }

        // This should always work, NA is handled above.
        if let Some(v) = robj.as_real() {
            return Ok(Rcplx::from(v));
        }

        // Any integer (32 bit) can be represented as f64,
        // this always works.
        if let Some(v) = robj.as_integer() {
            return Ok(Rcplx::from(v as f64));
        }

        // Complex slices return their first element.
        if let Some(s) = robj.as_typed_slice() {
            return Ok(s[0]);
        }

        Err(Error::ExpectedComplex(robj.clone()))
    }
}

// Convert TryFrom<&Robj> into TryFrom<Robj>. Sadly, we are unable to make a blanket
// conversion using GetSexp with the current version of Rust.
macro_rules! impl_try_from_robj {
    ($(@generics<$generics:tt>)? $type:ty $(where $($where_clause:tt)*)?) => {
        impl$(<$generics>)? TryFrom<Robj> for $type $(where $($where_clause)*)? {
            type Error = Error;

            fn try_from(robj: Robj) -> Result<Self> {
                Self::try_from(&robj)
            }
        }

        impl$(<$generics>)? TryFrom<&Robj> for Option<$type> $(where $($where_clause)*)? {
            type Error = Error;

            fn try_from(robj: &Robj) -> Result<Self> {
                if robj.is_null() || robj.is_na() {
                    Ok(None)
                } else {
                    Ok(Some(<$type>::try_from(robj)?))
                }
            }
        }

        impl$(<$generics>)? TryFrom<Robj> for Option<$type> $(where $($where_clause)*)? {
            type Error = Error;

            fn try_from(robj: Robj) -> Result<Self> {
                Self::try_from(&robj)
            }
        }
    };
}
#[rustfmt::skip]
impl_try_from_robj!(u8);
impl_try_from_robj!(u16);
impl_try_from_robj!(u32);
impl_try_from_robj!(u64);
impl_try_from_robj!(usize);

impl_try_from_robj!(i8);
impl_try_from_robj!(i16);
impl_try_from_robj!(i32);
impl_try_from_robj!(i64);
impl_try_from_robj!(isize);

impl_try_from_robj!(bool);

impl_try_from_robj!(Rint);
impl_try_from_robj!(Rfloat);
impl_try_from_robj!(Rbool);
impl_try_from_robj!(Rcplx);

impl_try_from_robj!(f32);
impl_try_from_robj!(f64);

impl_try_from_robj!(Vec::<String>);
impl_try_from_robj!(Vec::<Rint>);
impl_try_from_robj!(Vec::<Rfloat>);
impl_try_from_robj!(Vec::<Rbool>);
impl_try_from_robj!(Vec::<Rcplx>);
impl_try_from_robj!(Vec::<u8>);
impl_try_from_robj!(Vec::<i32>);
impl_try_from_robj!(Vec::<f64>);

impl_try_from_robj!(String);

impl_try_from_robj!(@generics<T> HashMap::<&str, T> where T: TryFrom<Robj, Error = error::Error>);
impl_try_from_robj!(@generics<T> HashMap::<String,T> where T: TryFrom<Robj, Error = error::Error>);

impl_try_from_robj!(HashMap::<&str, Robj>);
impl_try_from_robj!(HashMap::<String, Robj>);

impl TryFrom<&Robj> for Option<()> {
    type Error = Error;

    fn try_from(value: &Robj) -> Result<Self> {
        if value.is_null() {
            Ok(Some(()))
        } else {
            Err(Error::ExpectedNull(value.clone()))
        }
    }
}

impl TryFrom<Robj> for Option<()> {
    type Error = Error;
    fn try_from(robj: Robj) -> Result<Self> {
        Self::try_from(&robj)
    }
}

impl<T> TryFrom<&Robj> for HashMap<&str, T>
where
    T: TryFrom<Robj, Error = error::Error>,
{
    type Error = Error;

    fn try_from(value: &Robj) -> Result<Self> {
        let value: List = value.try_into()?;

        let value = value
            .iter()
            .map(|(name, value)| -> Result<(&str, T)> { value.try_into().map(|x| (name, x)) })
            .collect::<Result<HashMap<_, _>>>()?;

        Ok(value)
    }
}

impl<T> TryFrom<&Robj> for HashMap<String, T>
where
    T: TryFrom<Robj, Error = error::Error>,
{
    type Error = Error;
    fn try_from(value: &Robj) -> Result<Self> {
        let value: HashMap<&str, _> = value.try_into()?;
        Ok(value.into_iter().map(|(k, v)| (k.to_string(), v)).collect())
    }
}

macro_rules! impl_try_from_robj_for_arrays {
    ($slice_type:ty) => {
        impl<const N: usize> TryFrom<&Robj> for [$slice_type; N] {
            type Error = Error;

            fn try_from(value: &Robj) -> Result<Self> {
                let value: &[$slice_type] = value.try_into()?;
                if value.len() != N {
                    return Err(Error::ExpectedLength(N));
                }
                let value: Self = value
                    .try_into()
                    .map_err(|error| format!("{}", error).to_string())?;
                Ok(value)
            }
        }

        // TODO: the following can be integrated into `impl_try_from_robj` later

        impl<const N: usize> TryFrom<Robj> for [$slice_type; N] {
            type Error = Error;

            fn try_from(robj: Robj) -> Result<Self> {
                Self::try_from(&robj)
            }
        }

        impl<const N: usize> TryFrom<&Robj> for Option<[$slice_type; N]> {
            type Error = Error;

            fn try_from(robj: &Robj) -> Result<Self> {
                if robj.is_null() || robj.is_na() {
                    Ok(None)
                } else {
                    Ok(Some(<[$slice_type; N]>::try_from(robj)?))
                }
            }
        }

        impl<const N: usize> TryFrom<Robj> for Option<[$slice_type; N]> {
            type Error = Error;

            fn try_from(robj: Robj) -> Result<Self> {
                Self::try_from(&robj)
            }
        }
    };
}

impl_try_from_robj_for_arrays!(Rint);
impl_try_from_robj_for_arrays!(Rfloat);
impl_try_from_robj_for_arrays!(Rbool);
impl_try_from_robj_for_arrays!(Rcplx);
impl_try_from_robj_for_arrays!(u8);
impl_try_from_robj_for_arrays!(i32);
impl_try_from_robj_for_arrays!(f64);

// Choosing arity 12.. As the Rust compiler did for these [Tuple to array conversion](https://doc.rust-lang.org/stable/std/primitive.tuple.html#trait-implementations-1)
// Single-element tuple manually implemented to avoid clippy::needless_question_mark

// We implement the 1-length tuple variant manually
// so that we avoid clippy needless Ok(?) lint
impl<T0> TryFrom<&Robj> for (T0,)
where
    T0: for<'a> TryFrom<&'a Robj, Error = Error>,
{
    type Error = Error;

    fn try_from(robj: &Robj) -> Result<Self> {
        let list: List = robj.try_into()?;
        if list.len() != 1 {
            return Err(Error::ExpectedLength(1));
        }
        Ok(((&list.elt(0)?).try_into()?,))
    }
}

impl<T0> TryFrom<Robj> for (T0,)
where
    T0: for<'a> TryFrom<&'a Robj, Error = Error>,
{
    type Error = Error;

    fn try_from(robj: Robj) -> Result<Self> {
        Self::try_from(&robj)
    }
}

impl<T0> TryFrom<&Robj> for Option<(T0,)>
where
    T0: for<'a> TryFrom<&'a Robj, Error = Error>,
{
    type Error = Error;

    fn try_from(robj: &Robj) -> Result<Self> {
        if robj.is_null() || robj.is_na() {
            Ok(None)
        } else {
            <(T0,)>::try_from(robj).map(Some)
        }
    }
}

impl<T0> TryFrom<Robj> for Option<(T0,)>
where
    T0: for<'a> TryFrom<&'a Robj, Error = Error>,
{
    type Error = Error;

    fn try_from(robj: Robj) -> Result<Self> {
        Self::try_from(&robj)
    }
}

impl_try_from_robj_tuples!((2, 12));

// The following is necessary because it is impossible to define `TryFrom<Robj> for &Robj` as
// it requires returning a reference to a owned (moved) value
impl TryFrom<&Robj> for HashMap<&str, Robj> {
    type Error = Error;

    fn try_from(value: &Robj) -> Result<Self> {
        let value: List = value.try_into()?;
        Ok(value.into_iter().collect())
    }
}

impl TryFrom<&Robj> for HashMap<String, Robj> {
    type Error = Error;
    fn try_from(value: &Robj) -> Result<Self> {
        let value: HashMap<&str, _> = value.try_into()?;
        Ok(value.into_iter().map(|(k, v)| (k.to_string(), v)).collect())
    }
}