1use crate::SexpExt;
26use crate::from_r::{SexpError, SexpLengthError, SexpNaError, SexpTypeError, TryFromSexp};
27use crate::into_r::IntoR;
28use crate::sexp_types::{Rcomplex, SEXPTYPE};
29use crate::{IsNA, SEXP};
30
31#[derive(#[automatically_derived]impl ::core::fmt::Debug for RValue {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
Self::Null => ::core::fmt::Formatter::write_str(f, "Null"),
Self::Logical(__self_0) =>
::core::fmt::Formatter::debug_struct_field1_finish(f,
"Logical", &__self_0),
Self::Integer(__self_0) =>
::core::fmt::Formatter::debug_struct_field1_finish(f,
"Integer", &__self_0),
Self::Double(__self_0) =>
::core::fmt::Formatter::debug_struct_field1_finish(f,
"Double", &__self_0),
Self::Complex(__self_0) =>
::core::fmt::Formatter::debug_struct_field1_finish(f,
"Complex", &__self_0),
Self::Character(__self_0) =>
::core::fmt::Formatter::debug_struct_field1_finish(f,
"Character", &__self_0),
Self::Raw(__self_0) =>
::core::fmt::Formatter::debug_struct_field1_finish(f, "Raw",
&__self_0),
Self::List(__self_0) =>
::core::fmt::Formatter::debug_struct_field1_finish(f, "List",
&__self_0),
}
}
}Debug, #[automatically_derived]impl ::core::clone::Clone for RValue {
#[inline]
fn clone(&self) -> Self {
match self {
Self::Null => RValue::Null,
Self::Logical(__self_0) =>
RValue::Logical(::core::clone::Clone::clone(__self_0)),
Self::Integer(__self_0) =>
RValue::Integer(::core::clone::Clone::clone(__self_0)),
Self::Double(__self_0) =>
RValue::Double(::core::clone::Clone::clone(__self_0)),
Self::Complex(__self_0) =>
RValue::Complex(::core::clone::Clone::clone(__self_0)),
Self::Character(__self_0) =>
RValue::Character(::core::clone::Clone::clone(__self_0)),
Self::Raw(__self_0) =>
RValue::Raw(::core::clone::Clone::clone(__self_0)),
Self::List(__self_0) =>
RValue::List(::core::clone::Clone::clone(__self_0)),
}
}
}Clone)]
33pub enum RValue {
34 Null,
36 Logical(Vec<Option<bool>>),
38 Integer(Vec<Option<i32>>),
40 Double(Vec<f64>),
42 Complex(Vec<Rcomplex>),
44 Character(Vec<Option<String>>),
46 Raw(Vec<u8>),
48 List(Vec<(Option<String>, RValue)>),
50}
51
52impl IntoR for RValue {
55 type Error = std::convert::Infallible;
56
57 fn try_into_sexp(self) -> Result<SEXP, Self::Error> {
58 Ok(self.into_sexp())
59 }
60
61 unsafe fn try_into_sexp_unchecked(self) -> Result<SEXP, Self::Error> {
62 self.try_into_sexp()
63 }
64
65 fn into_sexp(self) -> SEXP {
66 match self {
67 RValue::Null => SEXP::nil(),
68 RValue::Logical(v) => v.into_sexp(),
69 RValue::Integer(v) => v.into_sexp(),
70 RValue::Double(v) => v.into_sexp(),
71 RValue::Complex(v) => v.into_sexp(),
72 RValue::Character(v) => v.into_sexp(),
73 RValue::Raw(v) => v.into_sexp(),
74 RValue::List(pairs) => list_into_sexp(pairs),
75 }
76 }
77}
78
79fn list_into_sexp(pairs: Vec<(Option<String>, RValue)>) -> SEXP {
85 use crate::list::List;
86 unsafe {
89 let scope = crate::gc_protect::ProtectScope::new();
90 if pairs.iter().any(|(name, _)| name.is_some()) {
91 let named: Vec<(String, SEXP)> = pairs
93 .into_iter()
94 .map(|(name, val)| (name.unwrap_or_default(), scope.protect_raw(val.into_sexp())))
95 .collect();
96 List::from_raw_pairs(named).into_sexp()
97 } else {
98 let values: Vec<SEXP> = pairs
99 .into_iter()
100 .map(|(_, val)| scope.protect_raw(val.into_sexp()))
101 .collect();
102 List::from_raw_values(values).into_sexp()
103 }
104 }
105}
106
107impl TryFromSexp for RValue {
112 type Error = SexpError;
113
114 fn try_from_sexp(sexp: SEXP) -> Result<Self, Self::Error> {
115 let n = sexp.len();
116 match sexp.type_of() {
117 SEXPTYPE::NILSXP => Ok(RValue::Null),
118 SEXPTYPE::LGLSXP => Ok(RValue::Logical(
119 (0..n as isize)
120 .map(|i| {
121 let x = sexp.logical_elt(i);
122 (!x.is_na()).then_some(x != 0)
123 })
124 .collect(),
125 )),
126 SEXPTYPE::INTSXP => Ok(RValue::Integer(
127 (0..n as isize)
128 .map(|i| {
129 let x = sexp.integer_elt(i);
130 (!x.is_na()).then_some(x)
131 })
132 .collect(),
133 )),
134 SEXPTYPE::REALSXP => Ok(RValue::Double(
136 (0..n as isize).map(|i| sexp.real_elt(i)).collect(),
137 )),
138 SEXPTYPE::CPLXSXP => Ok(RValue::Complex(
139 (0..n as isize).map(|i| sexp.complex_elt(i)).collect(),
140 )),
141 SEXPTYPE::STRSXP => crate::from_r::map_strsxp_with(sexp, |charsxp, _| {
144 if charsxp.is_na_string() {
145 Ok(None)
146 } else {
147 unsafe { crate::from_r::try_charsxp_to_str(charsxp) }
149 .map(|s| Some(s.to_string()))
150 }
151 })
152 .map(RValue::Character),
153 SEXPTYPE::RAWSXP => Ok(RValue::Raw(unsafe { sexp.as_slice::<u8>() }.to_vec())),
155 SEXPTYPE::VECSXP => {
156 let names = sexp.get_names();
157 let mut pairs = Vec::with_capacity(n);
158 for i in 0..n as isize {
159 let name = if names.is_nil()
162 || !names.is_character()
163 || names.string_elt(i).is_na_string()
164 {
165 None
166 } else {
167 let name =
169 unsafe { crate::from_r::try_charsxp_to_str(names.string_elt(i)) }
170 .map_err(|e| {
171 crate::from_r::name_refusal(
172 usize::try_from(i).expect("a list index is non-negative"),
173 &e,
174 )
175 })?;
176 (!name.is_empty()).then(|| name.to_string())
177 };
178 pairs.push((name, RValue::try_from_sexp(sexp.vector_elt(i))?));
179 }
180 Ok(RValue::List(pairs))
181 }
182 other => Err(SexpError::InvalidValue(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("RValue cannot represent SEXP of type {0:?} (only R data vectors are modelled)",
other))
})format!(
183 "RValue cannot represent SEXP of type {other:?} (only R data vectors are modelled)"
184 ))),
185 }
186 }
187}
188
189impl From<i32> for RValue {
194 fn from(v: i32) -> Self {
195 RValue::Integer(::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[Some(v)]))vec![Some(v)])
196 }
197}
198impl From<f64> for RValue {
199 fn from(v: f64) -> Self {
200 RValue::Double(::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[v]))vec![v])
201 }
202}
203impl From<bool> for RValue {
204 fn from(v: bool) -> Self {
205 RValue::Logical(::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[Some(v)]))vec![Some(v)])
206 }
207}
208impl From<String> for RValue {
209 fn from(v: String) -> Self {
210 RValue::Character(::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[Some(v)]))vec![Some(v)])
211 }
212}
213impl From<&str> for RValue {
214 fn from(v: &str) -> Self {
215 RValue::Character(::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[Some(v.to_string())]))vec![Some(v.to_string())])
216 }
217}
218impl From<Vec<i32>> for RValue {
219 fn from(v: Vec<i32>) -> Self {
220 RValue::Integer(v.into_iter().map(Some).collect())
221 }
222}
223impl From<Vec<f64>> for RValue {
224 fn from(v: Vec<f64>) -> Self {
225 RValue::Double(v)
226 }
227}
228impl From<Vec<bool>> for RValue {
229 fn from(v: Vec<bool>) -> Self {
230 RValue::Logical(v.into_iter().map(Some).collect())
231 }
232}
233impl From<Vec<String>> for RValue {
234 fn from(v: Vec<String>) -> Self {
235 RValue::Character(v.into_iter().map(Some).collect())
236 }
237}
238impl From<Vec<&str>> for RValue {
239 fn from(v: Vec<&str>) -> Self {
240 RValue::Character(v.into_iter().map(|s| Some(s.to_string())).collect())
241 }
242}
243
244macro_rules! impl_tuple_rvalue {
249 ($n:literal, $name:literal; $($T:ident $R:ident $idx:tt),+) => {
250 impl<$($T: Into<RValue>),+> From<($($T,)+)> for RValue {
251 fn from(value: ($($T,)+)) -> Self {
252 Self::List(vec![$((None, value.$idx.into()),)+])
253 }
254 }
255 };
256}
257
258impl<A: Into<RValue>, B: Into<RValue>, C: Into<RValue>, D: Into<RValue>,
E: Into<RValue>, F: Into<RValue>, G: Into<RValue>, H: Into<RValue>,
I: Into<RValue>, J: Into<RValue>, K: Into<RValue>, L: Into<RValue>>
From<(A, B, C, D, E, F, G, H, I, J, K, L)> for RValue {
fn from(value: (A, B, C, D, E, F, G, H, I, J, K, L)) -> Self {
Self::List(::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(None, value.0.into()), (None, value.1.into()),
(None, value.2.into()), (None, value.3.into()),
(None, value.4.into()), (None, value.5.into()),
(None, value.6.into()), (None, value.7.into()),
(None, value.8.into()), (None, value.9.into()),
(None, value.10.into()), (None, value.11.into())])))
}
}crate::tuple_macros::for_each_tuple!(impl_tuple_rvalue);
259
260impl From<Option<i32>> for RValue {
269 fn from(v: Option<i32>) -> Self {
270 RValue::Integer(::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[v]))vec![v])
271 }
272}
273impl From<Option<f64>> for RValue {
274 fn from(v: Option<f64>) -> Self {
275 RValue::Double(::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[v.unwrap_or(crate::altrep_traits::NA_REAL)]))vec![v.unwrap_or(crate::altrep_traits::NA_REAL)])
276 }
277}
278impl From<Option<bool>> for RValue {
279 fn from(v: Option<bool>) -> Self {
280 RValue::Logical(::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[v]))vec![v])
281 }
282}
283impl From<Option<String>> for RValue {
284 fn from(v: Option<String>) -> Self {
285 RValue::Character(::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[v]))vec![v])
286 }
287}
288impl From<Option<&str>> for RValue {
289 fn from(v: Option<&str>) -> Self {
290 RValue::Character(::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[v.map(str::to_string)]))vec![v.map(str::to_string)])
291 }
292}
293impl From<Vec<Option<i32>>> for RValue {
294 fn from(v: Vec<Option<i32>>) -> Self {
295 RValue::Integer(v)
296 }
297}
298impl From<Vec<Option<f64>>> for RValue {
299 fn from(v: Vec<Option<f64>>) -> Self {
300 RValue::Double(
301 v.into_iter()
302 .map(|x| x.unwrap_or(crate::altrep_traits::NA_REAL))
303 .collect(),
304 )
305 }
306}
307impl From<Vec<Option<bool>>> for RValue {
308 fn from(v: Vec<Option<bool>>) -> Self {
309 RValue::Logical(v)
310 }
311}
312impl From<Vec<Option<String>>> for RValue {
313 fn from(v: Vec<Option<String>>) -> Self {
314 RValue::Character(v)
315 }
316}
317impl From<Vec<Option<&str>>> for RValue {
318 fn from(v: Vec<Option<&str>>) -> Self {
319 RValue::Character(v.into_iter().map(|s| s.map(str::to_string)).collect())
320 }
321}
322
323impl From<i64> for RValue {
327 fn from(v: i64) -> Self {
328 match i32::try_from(v) {
329 Ok(n) if !n.is_na() => RValue::Integer(::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[Some(n)]))vec![Some(n)]),
330 _ => RValue::Double(::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[v as f64]))vec![v as f64]),
333 }
334 }
335}
336impl From<u32> for RValue {
337 fn from(v: u32) -> Self {
340 RValue::from(i64::from(v))
341 }
342}
343
344impl RValue {
349 pub fn sexptype(&self) -> SEXPTYPE {
351 match self {
352 RValue::Null => SEXPTYPE::NILSXP,
353 RValue::Logical(_) => SEXPTYPE::LGLSXP,
354 RValue::Integer(_) => SEXPTYPE::INTSXP,
355 RValue::Double(_) => SEXPTYPE::REALSXP,
356 RValue::Complex(_) => SEXPTYPE::CPLXSXP,
357 RValue::Character(_) => SEXPTYPE::STRSXP,
358 RValue::Raw(_) => SEXPTYPE::RAWSXP,
359 RValue::List(_) => SEXPTYPE::VECSXP,
360 }
361 }
362
363 pub fn is_null(&self) -> bool {
365 #[allow(non_exhaustive_omitted_patterns)] match self {
RValue::Null => true,
_ => false,
}matches!(self, RValue::Null)
366 }
367
368 pub fn debug<T: std::fmt::Debug>(value: T) -> Self {
378 RValue::Character(::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[Some(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0:?}", value))
}))]))vec![Some(format!("{value:?}"))])
379 }
380
381 pub fn as_i32(&self) -> Option<i32> {
387 match self {
388 RValue::Integer(v) if v.len() == 1 => v[0],
389 _ => None,
390 }
391 }
392
393 pub fn as_f64(&self) -> Option<f64> {
399 match self {
400 RValue::Double(v) if v.len() == 1 => {
401 let x = v[0];
402 (!x.is_na()).then_some(x)
403 }
404 _ => None,
405 }
406 }
407
408 pub fn as_bool(&self) -> Option<bool> {
410 match self {
411 RValue::Logical(v) if v.len() == 1 => v[0],
412 _ => None,
413 }
414 }
415
416 pub fn as_str(&self) -> Option<&str> {
418 match self {
419 RValue::Character(v) if v.len() == 1 => v[0].as_deref(),
420 _ => None,
421 }
422 }
423}
424
425fn wrong_type(expected: SEXPTYPE, actual: &RValue) -> SexpError {
427 SexpError::Type(SexpTypeError {
428 expected,
429 actual: actual.sexptype(),
430 })
431}
432
433macro_rules! try_from_scalar_opt {
439 ($t:ty, $variant:ident, $ty:expr) => {
440 impl TryFrom<RValue> for $t {
441 type Error = SexpError;
442 fn try_from(value: RValue) -> Result<Self, SexpError> {
443 match value {
444 RValue::$variant(xs) => {
445 if xs.len() != 1 {
446 return Err(SexpError::Length(SexpLengthError {
447 expected: 1,
448 actual: xs.len(),
449 }));
450 }
451 xs.into_iter()
452 .next()
453 .unwrap()
454 .ok_or(SexpError::Na(SexpNaError { sexp_type: $ty }))
455 }
456 other => Err(wrong_type($ty, &other)),
457 }
458 }
459 }
460 };
461}
462impl TryFrom<RValue> for i32 {
type Error = SexpError;
fn try_from(value: RValue) -> Result<Self, SexpError> {
match value {
RValue::Integer(xs) => {
if xs.len() != 1 {
return Err(SexpError::Length(SexpLengthError {
expected: 1,
actual: xs.len(),
}));
}
xs.into_iter().next().unwrap().ok_or(SexpError::Na(SexpNaError {
sexp_type: SEXPTYPE::INTSXP,
}))
}
other => Err(wrong_type(SEXPTYPE::INTSXP, &other)),
}
}
}try_from_scalar_opt!(i32, Integer, SEXPTYPE::INTSXP);
463impl TryFrom<RValue> for bool {
type Error = SexpError;
fn try_from(value: RValue) -> Result<Self, SexpError> {
match value {
RValue::Logical(xs) => {
if xs.len() != 1 {
return Err(SexpError::Length(SexpLengthError {
expected: 1,
actual: xs.len(),
}));
}
xs.into_iter().next().unwrap().ok_or(SexpError::Na(SexpNaError {
sexp_type: SEXPTYPE::LGLSXP,
}))
}
other => Err(wrong_type(SEXPTYPE::LGLSXP, &other)),
}
}
}try_from_scalar_opt!(bool, Logical, SEXPTYPE::LGLSXP);
464impl TryFrom<RValue> for String {
type Error = SexpError;
fn try_from(value: RValue) -> Result<Self, SexpError> {
match value {
RValue::Character(xs) => {
if xs.len() != 1 {
return Err(SexpError::Length(SexpLengthError {
expected: 1,
actual: xs.len(),
}));
}
xs.into_iter().next().unwrap().ok_or(SexpError::Na(SexpNaError {
sexp_type: SEXPTYPE::STRSXP,
}))
}
other => Err(wrong_type(SEXPTYPE::STRSXP, &other)),
}
}
}try_from_scalar_opt!(String, Character, SEXPTYPE::STRSXP);
465
466impl TryFrom<RValue> for f64 {
468 type Error = SexpError;
469 fn try_from(value: RValue) -> Result<Self, SexpError> {
470 match value {
471 RValue::Double(xs) => {
472 if xs.len() != 1 {
473 return Err(SexpError::Length(SexpLengthError {
474 expected: 1,
475 actual: xs.len(),
476 }));
477 }
478 let x = xs[0];
479 if x.is_na() {
481 Err(SexpError::Na(SexpNaError {
482 sexp_type: SEXPTYPE::REALSXP,
483 }))
484 } else {
485 Ok(x)
486 }
487 }
488 other => Err(wrong_type(SEXPTYPE::REALSXP, &other)),
489 }
490 }
491}
492
493macro_rules! try_from_vec {
495 ($t:ty, $variant:ident, $ty:expr) => {
496 impl TryFrom<RValue> for $t {
497 type Error = SexpError;
498 fn try_from(value: RValue) -> Result<Self, SexpError> {
499 match value {
500 RValue::$variant(xs) => Ok(xs),
501 other => Err(wrong_type($ty, &other)),
502 }
503 }
504 }
505 };
506}
507impl TryFrom<RValue> for Vec<Option<bool>> {
type Error = SexpError;
fn try_from(value: RValue) -> Result<Self, SexpError> {
match value {
RValue::Logical(xs) => Ok(xs),
other => Err(wrong_type(SEXPTYPE::LGLSXP, &other)),
}
}
}try_from_vec!(Vec<Option<bool>>, Logical, SEXPTYPE::LGLSXP);
508impl TryFrom<RValue> for Vec<Option<i32>> {
type Error = SexpError;
fn try_from(value: RValue) -> Result<Self, SexpError> {
match value {
RValue::Integer(xs) => Ok(xs),
other => Err(wrong_type(SEXPTYPE::INTSXP, &other)),
}
}
}try_from_vec!(Vec<Option<i32>>, Integer, SEXPTYPE::INTSXP);
509impl TryFrom<RValue> for Vec<f64> {
type Error = SexpError;
fn try_from(value: RValue) -> Result<Self, SexpError> {
match value {
RValue::Double(xs) => Ok(xs),
other => Err(wrong_type(SEXPTYPE::REALSXP, &other)),
}
}
}try_from_vec!(Vec<f64>, Double, SEXPTYPE::REALSXP);
510impl TryFrom<RValue> for Vec<Rcomplex> {
type Error = SexpError;
fn try_from(value: RValue) -> Result<Self, SexpError> {
match value {
RValue::Complex(xs) => Ok(xs),
other => Err(wrong_type(SEXPTYPE::CPLXSXP, &other)),
}
}
}try_from_vec!(Vec<Rcomplex>, Complex, SEXPTYPE::CPLXSXP);
511impl TryFrom<RValue> for Vec<Option<String>> {
type Error = SexpError;
fn try_from(value: RValue) -> Result<Self, SexpError> {
match value {
RValue::Character(xs) => Ok(xs),
other => Err(wrong_type(SEXPTYPE::STRSXP, &other)),
}
}
}try_from_vec!(Vec<Option<String>>, Character, SEXPTYPE::STRSXP);
512impl TryFrom<RValue> for Vec<u8> {
type Error = SexpError;
fn try_from(value: RValue) -> Result<Self, SexpError> {
match value {
RValue::Raw(xs) => Ok(xs),
other => Err(wrong_type(SEXPTYPE::RAWSXP, &other)),
}
}
}try_from_vec!(Vec<u8>, Raw, SEXPTYPE::RAWSXP);
513impl TryFrom<RValue> for Vec<(Option<String>, RValue)> {
type Error = SexpError;
fn try_from(value: RValue) -> Result<Self, SexpError> {
match value {
RValue::List(xs) => Ok(xs),
other => Err(wrong_type(SEXPTYPE::VECSXP, &other)),
}
}
}try_from_vec!(Vec<(Option<String>, RValue)>, List, SEXPTYPE::VECSXP);
514
515#[cfg(test)]
518mod tests;