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
use super::*;
use crate::wrapper::matrix::MatrixConversions;

/// Trait used for incomming parameter conversion.
pub trait FromRobj<'a>: Sized {
    // Convert an incomming Robj from R into a value or an error.
    fn from_robj(_robj: &'a Robj) -> std::result::Result<Self, &'static str> {
        Err("unable to convert value from R object")
    }
}

macro_rules! impl_prim_from_robj {
    ($t: ty) => {
        impl<'a> FromRobj<'a> for $t {
            fn from_robj(robj: &'a Robj) -> std::result::Result<Self, &'static str> {
                if let Some(v) = robj.as_integer_slice() {
                    match v.len() {
                        0 => Err("Input must be of length 1. Vector of length zero given."),
                        1 => {
                            if !v[0].is_na() {
                                Ok(v[0] as Self)
                            } else {
                                Err("Input must not be NA.")
                            }
                        }
                        _ => Err("Input must be of length 1. Vector of length >1 given."),
                    }
                } else if let Some(v) = robj.as_real_slice() {
                    match v.len() {
                        0 => Err("Input must be of length 1. Vector of length zero given."),
                        1 => {
                            if !v[0].is_na() {
                                Ok(v[0] as Self)
                            } else {
                                Err("Input must not be NA.")
                            }
                        }
                        _ => Err("Input must be of length 1. Vector of length >1 given."),
                    }
                } else {
                    Err("unable to convert R object to primitive")
                }
            }
        }
    };
}

impl_prim_from_robj!(u8);
impl_prim_from_robj!(u16);
impl_prim_from_robj!(u32);
impl_prim_from_robj!(u64);
impl_prim_from_robj!(i8);
impl_prim_from_robj!(i16);
impl_prim_from_robj!(i32);
impl_prim_from_robj!(i64);
impl_prim_from_robj!(f32);
impl_prim_from_robj!(f64);

impl<'a> FromRobj<'a> for bool {
    fn from_robj(robj: &'a Robj) -> std::result::Result<Self, &'static str> {
        if let Some(v) = robj.as_logical_slice() {
            match v.len() {
                0 => Err("Input must be of length 1. Vector of length zero given."),
                1 => {
                    if !v[0].is_na() {
                        Ok(v[0].to_bool())
                    } else {
                        Err("Input must not be NA.")
                    }
                }
                _ => Err("Input must be of length 1. Vector of length >1 given."),
            }
        } else {
            Err("Not a logical object.")
        }
    }
}

impl<'a> FromRobj<'a> for &'a str {
    fn from_robj(robj: &'a Robj) -> std::result::Result<Self, &'static str> {
        if robj.is_na() {
            Err("Input must not be NA.")
        } else if let Some(s) = robj.as_str() {
            Ok(s)
        } else {
            Err("Not a string object.")
        }
    }
}

impl<'a> FromRobj<'a> for String {
    fn from_robj(robj: &'a Robj) -> std::result::Result<Self, &'static str> {
        if robj.is_na() {
            Err("Input must not be NA.")
        } else if let Some(s) = robj.as_str() {
            Ok(s.to_string())
        } else {
            Err("not a string object")
        }
    }
}

impl<'a> FromRobj<'a> for Vec<i32> {
    fn from_robj(robj: &'a Robj) -> std::result::Result<Self, &'static str> {
        if let Some(v) = robj.as_integer_slice() {
            Ok(Vec::from(v))
        } else {
            Err("not an integer or logical vector")
        }
    }
}

impl<'a> FromRobj<'a> for Vec<f64> {
    fn from_robj(robj: &'a Robj) -> std::result::Result<Self, &'static str> {
        if let Some(v) = robj.as_real_slice() {
            Ok(Vec::from(v))
        } else {
            Err("not a floating point vector")
        }
    }
}

impl<'a> FromRobj<'a> for Vec<String> {
    fn from_robj(robj: &'a Robj) -> std::result::Result<Self, &'static str> {
        if robj.is_na() {
            Err("Input must be a character vector. Got 'NA'.")
        } else if let Some(v) = robj.as_string_vector() {
            let str_vec = v.to_vec();
            // check for NA's in the string vector
            // The check is by-value, so `<&str>::is_na()` cannot be used
            if let Some(_str) = str_vec.iter().find(|&s| *s == <&str>::na()) {
                Err("Input vector cannot contain NA's.")
            } else {
                Ok(str_vec)
            }
        } else {
            Err("Input must be a character vector.")
        }
    }
}

macro_rules! impl_iter_from_robj {
    ($t: ty, $iter_fn: ident, $msg: expr) => {
        impl<'a> FromRobj<'a> for $t {
            fn from_robj(robj: &'a Robj) -> std::result::Result<Self, &'static str> {
                if let Some(v) = robj.$iter_fn() {
                    Ok(v)
                } else {
                    Err($msg)
                }
            }
        }
    };
}

impl_iter_from_robj!(StrIter, as_str_iter, "Not a character vector.");

/// Pass-through Robj conversion, essentially a clone.
impl<'a> FromRobj<'a> for Robj {
    fn from_robj(robj: &'a Robj) -> std::result::Result<Self, &'static str> {
        Ok(unsafe { Robj::from_sexp(robj.get()) })
    }
}

impl<'a> FromRobj<'a> for HashMap<String, Robj> {
    fn from_robj(robj: &'a Robj) -> std::result::Result<Self, &'static str> {
        if let Some(iter) = robj.as_list().map(|l| l.iter()) {
            Ok(iter
                .map(|(k, v)| (k.to_string(), v))
                .collect::<HashMap<String, Robj>>())
        } else {
            Err("expected a list")
        }
    }
}

impl<'a> FromRobj<'a> for HashMap<&str, Robj> {
    fn from_robj(robj: &'a Robj) -> std::result::Result<Self, &'static str> {
        if let Some(iter) = robj.as_list().map(|l| l.iter()) {
            Ok(iter.map(|(k, v)| (k, v)).collect::<HashMap<&str, Robj>>())
        } else {
            Err("expected a list")
        }
    }
}

// NA-sensitive integer input handling
impl<'a> FromRobj<'a> for Option<i32> {
    fn from_robj(robj: &'a Robj) -> std::result::Result<Self, &'static str> {
        if robj.is_na() {
            Ok(None)
        } else if let Some(val) = robj.as_integer() {
            Ok(Some(val))
        } else {
            Err("expected an integer scalar")
        }
    }
}

// NA-sensitive logical input handling
impl<'a> FromRobj<'a> for Option<bool> {
    fn from_robj(robj: &'a Robj) -> std::result::Result<Self, &'static str> {
        if let Some(val) = robj.as_logical() {
            if val.is_na() {
                Ok(None)
            } else {
                Ok(Some(val.is_true()))
            }
        } else {
            Err("expected a logical scalar")
        }
    }
}

// NA-sensitive real input handling
impl<'a> FromRobj<'a> for Option<f64> {
    fn from_robj(robj: &'a Robj) -> std::result::Result<Self, &'static str> {
        if robj.is_na() {
            Ok(None)
        } else if let Some(val) = robj.as_real() {
            Ok(Some(val))
        } else {
            Err("expected a real scalar")
        }
    }
}

// NA-sensitive string input handling
impl<'a> FromRobj<'a> for Option<&'a str> {
    fn from_robj(robj: &'a Robj) -> std::result::Result<Self, &'static str> {
        if robj.is_na() {
            Ok(None)
        } else if let Some(val) = robj.as_str() {
            Ok(Some(val))
        } else {
            Err("expected a character scalar")
        }
    }
}

// NA-sensitive string input handling
impl<'a> FromRobj<'a> for Option<String> {
    fn from_robj(robj: &'a Robj) -> std::result::Result<Self, &'static str> {
        if robj.is_na() {
            Ok(None)
        } else if let Some(val) = robj.as_str() {
            Ok(Some(val.to_string()))
        } else {
            Err("expected a character scalar")
        }
    }
}

impl<'a, T> FromRobj<'a> for &'a [T]
where
    Robj: AsTypedSlice<'a, T>,
{
    fn from_robj(robj: &'a Robj) -> std::result::Result<Self, &'static str> {
        if let Some(slice) = robj.as_typed_slice() {
            Ok(slice)
        } else {
            Err("Expected a vector type.")
        }
    }
}

// Matrix input parameters.
impl<'a, T: 'a> FromRobj<'a> for RArray<T, [usize; 2]>
where
    Robj: AsTypedSlice<'a, T>,
{
    fn from_robj(robj: &'a Robj) -> std::result::Result<Self, &'static str> {
        match robj.as_matrix() {
            Some(x) => Ok(x),
            _ => Err("Expected a matrix."),
        }
    }
}

// Matrix input parameters.
impl<'a, T: 'a> FromRobj<'a> for RMatrix3D<T>
where
    Robj: AsTypedSlice<'a, T>,
{
    fn from_robj(robj: &'a Robj) -> std::result::Result<Self, &'static str> {
        match robj.as_matrix3d() {
            Some(x) => Ok(x),
            _ => Err("Expected a matrix."),
        }
    }
}