1use crate::coerce::TryCoerce;
34use crate::from_r::{BatchedErrors, SexpError, TryFromSexp};
35use crate::into_r::IntoR;
36use crate::{IsNA, SEXP, SEXPTYPE, SexpExt};
37
38fn panic_strict_vec_batched(container: &str, errors: BatchedErrors) -> ! {
48 {
::core::panicking::panic_fmt(format_args!("strict conversion failed for {1}: {0}; use a non-strict function to allow lossy f64 widening",
errors.element_message(), container));
};panic!(
49 "strict conversion failed for {container}: {}; use a non-strict function to allow \
50 lossy f64 widening",
51 errors.element_message()
52 );
53}
54
55#[doc(hidden)]
65pub trait StrictRInt: Copy + std::fmt::Display {
66 const NAME: &'static str;
68
69 fn to_r_int(self) -> Option<i32>;
72
73 fn range_reason(self) -> String;
75}
76
77macro_rules! impl_strict_r_int {
78 (signed: $($t:ty),*) => {$(
79 impl StrictRInt for $t {
80 const NAME: &'static str = stringify!($t);
81 #[inline]
82 fn to_r_int(self) -> Option<i32> {
83 i32::try_from(self).ok().filter(|&v| !v.is_na())
84 }
85 fn range_reason(self) -> String {
86 format!(
87 "{} value {self} is outside R integer range ({}..={})",
88 Self::NAME,
89 i32::MIN + 1,
90 i32::MAX
91 )
92 }
93 }
94 )*};
95 (unsigned: $($t:ty),*) => {$(
96 impl StrictRInt for $t {
97 const NAME: &'static str = stringify!($t);
98 #[inline]
99 fn to_r_int(self) -> Option<i32> {
100 i32::try_from(self).ok()
101 }
102 fn range_reason(self) -> String {
103 format!("{} value {self} exceeds R integer max ({})", Self::NAME, i32::MAX)
104 }
105 }
106 )*};
107}
108
109impl StrictRInt for i64 {
const NAME: &'static str = "i64";
#[inline]
fn to_r_int(self) -> Option<i32> {
i32::try_from(self).ok().filter(|&v| !v.is_na())
}
fn range_reason(self) -> String {
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} value {3} is outside R integer range ({1}..={2})",
Self::NAME, i32::MIN + 1, i32::MAX, self))
})
}
}
impl StrictRInt for isize {
const NAME: &'static str = "isize";
#[inline]
fn to_r_int(self) -> Option<i32> {
i32::try_from(self).ok().filter(|&v| !v.is_na())
}
fn range_reason(self) -> String {
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} value {3} is outside R integer range ({1}..={2})",
Self::NAME, i32::MIN + 1, i32::MAX, self))
})
}
}impl_strict_r_int!(signed: i64, isize);
110impl StrictRInt for u64 {
const NAME: &'static str = "u64";
#[inline]
fn to_r_int(self) -> Option<i32> { i32::try_from(self).ok() }
fn range_reason(self) -> String {
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} value {2} exceeds R integer max ({1})",
Self::NAME, i32::MAX, self))
})
}
}
impl StrictRInt for usize {
const NAME: &'static str = "usize";
#[inline]
fn to_r_int(self) -> Option<i32> { i32::try_from(self).ok() }
fn range_reason(self) -> String {
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} value {2} exceeds R integer max ({1})",
Self::NAME, i32::MAX, self))
})
}
}impl_strict_r_int!(unsigned: u64, usize);
111
112fn checked_scalar_into_sexp<T: StrictRInt>(val: T) -> SEXP {
114 match val.to_r_int() {
115 Some(v) => v.into_sexp(),
116 None => {
::core::panicking::panic_fmt(format_args!("strict conversion failed: {0}; use a non-strict function to allow lossy f64 widening",
val.range_reason()));
}panic!(
117 "strict conversion failed: {}; use a non-strict function to allow lossy f64 widening",
118 val.range_reason()
119 ),
120 }
121}
122
123fn checked_elems_into_sexp<T: StrictRInt>(
128 container: &str,
129 elems: impl ExactSizeIterator<Item = Option<T>>,
130) -> SEXP {
131 let mut coerced: Vec<Option<i32>> = Vec::with_capacity(elems.len());
132 let mut errors = BatchedErrors::default();
133 for (i, elem) in elems.enumerate() {
134 match elem.map(|x| (x, x.to_r_int())) {
135 Some((_, Some(v))) => coerced.push(Some(v)),
136 Some((x, None)) => errors.push(i, || x.range_reason()),
137 None => coerced.push(None),
138 }
139 }
140 if !errors.is_empty() {
141 panic_strict_vec_batched(container, errors);
142 }
143 coerced.into_sexp()
144}
145
146#[doc(hidden)]
149pub fn checked_slice_into_sexp<T: StrictRInt>(container: &str, values: &[T]) -> SEXP {
150 checked_elems_into_sexp(container, values.iter().copied().map(Some))
151}
152
153#[doc(hidden)]
162pub fn checked_rows_into_sexp<T: StrictRInt, R: AsRef<[T]>>(
163 container: &str,
164 rows: impl ExactSizeIterator<Item = Option<R>>,
165) -> SEXP {
166 let mut coerced: Vec<Option<Vec<i32>>> = Vec::with_capacity(rows.len());
167 let mut errors = BatchedErrors::default();
168 for (i, row) in rows.enumerate() {
169 coerced.push(row.map(|row| {
170 let row = row.as_ref();
171 let mut out = Vec::with_capacity(row.len());
172 for (j, &x) in row.iter().enumerate() {
173 match x.to_r_int() {
174 Some(v) => out.push(v),
175 None => errors.push(i, || {
176 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} at inner position {1}",
x.range_reason(), j + 1))
})format!("{} at inner position {}", x.range_reason(), j + 1)
177 }),
178 }
179 }
180 out
181 }));
182 }
183 if !errors.is_empty() {
184 panic_strict_vec_batched(container, errors);
185 }
186 coerced.into_sexp()
187}
188
189#[inline]
194pub fn checked_into_sexp_i64(val: i64) -> SEXP {
195 checked_scalar_into_sexp(val)
196}
197
198#[inline]
200pub fn checked_into_sexp_u64(val: u64) -> SEXP {
201 checked_scalar_into_sexp(val)
202}
203
204#[inline]
206pub fn checked_into_sexp_isize(val: isize) -> SEXP {
207 checked_scalar_into_sexp(val)
208}
209
210#[inline]
212pub fn checked_into_sexp_usize(val: usize) -> SEXP {
213 checked_scalar_into_sexp(val)
214}
215
216pub fn checked_vec_i64_into_sexp(val: Vec<i64>) -> SEXP {
221 checked_elems_into_sexp("Vec<i64>", val.into_iter().map(Some))
222}
223
224pub fn checked_vec_u64_into_sexp(val: Vec<u64>) -> SEXP {
229 checked_elems_into_sexp("Vec<u64>", val.into_iter().map(Some))
230}
231
232pub fn checked_vec_isize_into_sexp(val: Vec<isize>) -> SEXP {
234 checked_elems_into_sexp("Vec<isize>", val.into_iter().map(Some))
235}
236
237pub fn checked_vec_usize_into_sexp(val: Vec<usize>) -> SEXP {
239 checked_elems_into_sexp("Vec<usize>", val.into_iter().map(Some))
240}
241
242pub fn checked_vec_option_i64_into_sexp(val: Vec<Option<i64>>) -> SEXP {
249 checked_elems_into_sexp("Vec<Option<i64>>", val.into_iter())
250}
251
252pub fn checked_vec_option_u64_into_sexp(val: Vec<Option<u64>>) -> SEXP {
257 checked_elems_into_sexp("Vec<Option<u64>>", val.into_iter())
258}
259
260pub fn checked_vec_option_isize_into_sexp(val: Vec<Option<isize>>) -> SEXP {
262 checked_elems_into_sexp("Vec<Option<isize>>", val.into_iter())
263}
264
265pub fn checked_vec_option_usize_into_sexp(val: Vec<Option<usize>>) -> SEXP {
267 checked_elems_into_sexp("Vec<Option<usize>>", val.into_iter())
268}
269
270#[inline]
273pub fn checked_option_i64_into_sexp(val: Option<i64>) -> SEXP {
274 match val {
275 Some(x) => checked_into_sexp_i64(x),
276 None => Option::<i32>::None.into_sexp(),
277 }
278}
279
280#[inline]
283pub fn checked_option_u64_into_sexp(val: Option<u64>) -> SEXP {
284 match val {
285 Some(x) => checked_into_sexp_u64(x),
286 None => Option::<i32>::None.into_sexp(),
287 }
288}
289
290#[inline]
292pub fn checked_option_isize_into_sexp(val: Option<isize>) -> SEXP {
293 match val {
294 Some(x) => checked_into_sexp_isize(x),
295 None => Option::<i32>::None.into_sexp(),
296 }
297}
298
299#[inline]
301pub fn checked_option_usize_into_sexp(val: Option<usize>) -> SEXP {
302 match val {
303 Some(x) => checked_into_sexp_usize(x),
304 None => Option::<i32>::None.into_sexp(),
305 }
306}
307
308pub fn checked_vec_vec_i64_into_sexp(val: Vec<Vec<i64>>) -> SEXP {
312 checked_rows_into_sexp("Vec<Vec<i64>>", val.into_iter().map(Some))
313}
314
315pub fn checked_vec_vec_u64_into_sexp(val: Vec<Vec<u64>>) -> SEXP {
318 checked_rows_into_sexp("Vec<Vec<u64>>", val.into_iter().map(Some))
319}
320
321pub fn checked_vec_vec_isize_into_sexp(val: Vec<Vec<isize>>) -> SEXP {
324 checked_rows_into_sexp("Vec<Vec<isize>>", val.into_iter().map(Some))
325}
326
327pub fn checked_vec_vec_usize_into_sexp(val: Vec<Vec<usize>>) -> SEXP {
330 checked_rows_into_sexp("Vec<Vec<usize>>", val.into_iter().map(Some))
331}
332
333pub fn checked_vec_option_vec_i64_into_sexp(val: Vec<Option<Vec<i64>>>) -> SEXP {
336 checked_rows_into_sexp("Vec<Option<Vec<i64>>>", val.into_iter())
337}
338
339pub fn checked_vec_option_vec_u64_into_sexp(val: Vec<Option<Vec<u64>>>) -> SEXP {
342 checked_rows_into_sexp("Vec<Option<Vec<u64>>>", val.into_iter())
343}
344
345pub fn checked_vec_option_vec_isize_into_sexp(val: Vec<Option<Vec<isize>>>) -> SEXP {
348 checked_rows_into_sexp("Vec<Option<Vec<isize>>>", val.into_iter())
349}
350
351pub fn checked_vec_option_vec_usize_into_sexp(val: Vec<Option<Vec<usize>>>) -> SEXP {
354 checked_rows_into_sexp("Vec<Option<Vec<usize>>>", val.into_iter())
355}
356
357const NA_NOT_ALLOWED: &str = "NA is not allowed";
370
371#[inline]
377pub fn checked_try_from_sexp_i64(sexp: SEXP) -> Result<i64, SexpError> {
378 checked_try_from_sexp_numeric_scalar::<i64>(sexp)
379}
380
381#[inline]
383pub fn checked_try_from_sexp_u64(sexp: SEXP) -> Result<u64, SexpError> {
384 checked_try_from_sexp_numeric_scalar::<u64>(sexp)
385}
386
387#[inline]
389pub fn checked_try_from_sexp_isize(sexp: SEXP) -> Result<isize, SexpError> {
390 let val = checked_try_from_sexp_i64(sexp)?;
391 narrow::<i64, isize>(val).map_err(SexpError::InvalidValue)
392}
393
394#[inline]
396pub fn checked_try_from_sexp_usize(sexp: SEXP) -> Result<usize, SexpError> {
397 let val = checked_try_from_sexp_u64(sexp)?;
398 narrow::<u64, usize>(val).map_err(SexpError::InvalidValue)
399}
400
401pub fn checked_vec_try_from_sexp_i64(sexp: SEXP) -> Result<Vec<i64>, SexpError> {
403 checked_vec_try_from_sexp_numeric::<i64>(sexp)
404}
405
406pub fn checked_vec_try_from_sexp_u64(sexp: SEXP) -> Result<Vec<u64>, SexpError> {
408 checked_vec_try_from_sexp_numeric::<u64>(sexp)
409}
410
411pub fn checked_vec_try_from_sexp_isize(sexp: SEXP) -> Result<Vec<isize>, SexpError> {
413 let vals = checked_vec_try_from_sexp_i64(sexp)?;
414 batch_elements(&vals, narrow::<i64, isize>)
415}
416
417pub fn checked_vec_try_from_sexp_usize(sexp: SEXP) -> Result<Vec<usize>, SexpError> {
419 let vals = checked_vec_try_from_sexp_u64(sexp)?;
420 batch_elements(&vals, narrow::<u64, usize>)
421}
422
423pub fn checked_vec_option_try_from_sexp_i64(sexp: SEXP) -> Result<Vec<Option<i64>>, SexpError> {
429 checked_vec_option_try_from_sexp_numeric::<i64>(sexp)
430}
431
432pub fn checked_vec_option_try_from_sexp_u64(sexp: SEXP) -> Result<Vec<Option<u64>>, SexpError> {
434 checked_vec_option_try_from_sexp_numeric::<u64>(sexp)
435}
436
437pub fn checked_vec_option_try_from_sexp_isize(sexp: SEXP) -> Result<Vec<Option<isize>>, SexpError> {
439 let vals = checked_vec_option_try_from_sexp_i64(sexp)?;
440 batch_elements(&vals, |opt| opt.map(narrow::<i64, isize>).transpose())
441}
442
443pub fn checked_vec_option_try_from_sexp_usize(sexp: SEXP) -> Result<Vec<Option<usize>>, SexpError> {
445 let vals = checked_vec_option_try_from_sexp_u64(sexp)?;
446 batch_elements(&vals, |opt| opt.map(narrow::<u64, usize>).transpose())
447}
448
449fn narrow<S, T>(val: S) -> Result<T, String>
452where
453 S: Copy + std::fmt::Display,
454 T: TryFrom<S>,
455{
456 T::try_from(val).map_err(|_| ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{1} does not fit in {0}",
std::any::type_name::<T>(), val))
})format!("{val} does not fit in {}", std::any::type_name::<T>()))
457}
458
459fn strict_type_error(actual: SEXPTYPE) -> SexpError {
461 crate::from_r::SexpTypeError {
462 expected: SEXPTYPE::INTSXP,
463 actual,
464 }
465 .into()
466}
467
468fn batch_elements<S: Copy, U>(
472 slice: &[S],
473 convert: impl Fn(S) -> Result<U, String>,
474) -> Result<Vec<U>, SexpError> {
475 let mut out = Vec::with_capacity(slice.len());
476 let mut errors = BatchedErrors::default();
477 for (i, &v) in slice.iter().enumerate() {
478 match convert(v) {
479 Ok(x) => out.push(x),
480 Err(reason) => errors.push(i, || reason),
481 }
482 }
483 if errors.is_empty() {
484 Ok(out)
485 } else {
486 Err(errors.into_element_error())
487 }
488}
489
490fn strict_int_elt<T>(v: i32) -> Result<Option<T>, String>
492where
493 i32: TryCoerce<T>,
494 <i32 as TryCoerce<T>>::Error: std::fmt::Display,
495{
496 if v.is_na() {
497 return Ok(None);
498 }
499 TryCoerce::<T>::try_coerce(v)
500 .map(Some)
501 .map_err(|e| e.to_string())
502}
503
504fn strict_real_elt<T>(v: f64) -> Result<Option<T>, String>
507where
508 f64: TryCoerce<T>,
509 <f64 as TryCoerce<T>>::Error: std::fmt::Display,
510{
511 if v.is_na() {
512 return Ok(None);
513 }
514 TryCoerce::<T>::try_coerce(v)
515 .map(Some)
516 .map_err(|e| e.to_string())
517}
518
519#[inline]
522fn checked_try_from_sexp_numeric_scalar<T>(sexp: SEXP) -> Result<T, SexpError>
523where
524 i32: TryCoerce<T>,
525 f64: TryCoerce<T>,
526 <i32 as TryCoerce<T>>::Error: std::fmt::Display,
527 <f64 as TryCoerce<T>>::Error: std::fmt::Display,
528{
529 let actual = sexp.type_of();
530 let value = match actual {
531 SEXPTYPE::INTSXP => {
532 let value: i32 = TryFromSexp::try_from_sexp(sexp)?;
533 strict_int_elt::<T>(value)
534 }
535 SEXPTYPE::REALSXP => {
536 let value: f64 = TryFromSexp::try_from_sexp(sexp)?;
537 strict_real_elt::<T>(value)
538 }
539 _ => return Err(strict_type_error(actual)),
540 };
541 match value {
542 Ok(Some(v)) => Ok(v),
543 Ok(None) => Err(crate::from_r::SexpNaError { sexp_type: actual }.into()),
544 Err(reason) => Err(SexpError::InvalidValue(reason)),
545 }
546}
547
548fn checked_vec_try_from_sexp_numeric<T>(sexp: SEXP) -> Result<Vec<T>, SexpError>
551where
552 i32: TryCoerce<T>,
553 f64: TryCoerce<T>,
554 <i32 as TryCoerce<T>>::Error: std::fmt::Display,
555 <f64 as TryCoerce<T>>::Error: std::fmt::Display,
556{
557 let required = |v: Option<T>| v.ok_or_else(|| NA_NOT_ALLOWED.to_string());
558 match sexp.type_of() {
559 SEXPTYPE::INTSXP => {
560 let slice: &[i32] = unsafe { sexp.as_slice() };
561 batch_elements(slice, |v| strict_int_elt::<T>(v).and_then(required))
562 }
563 SEXPTYPE::REALSXP => {
564 let slice: &[f64] = unsafe { sexp.as_slice() };
565 batch_elements(slice, |v| strict_real_elt::<T>(v).and_then(required))
566 }
567 actual => Err(strict_type_error(actual)),
568 }
569}
570
571fn checked_vec_option_try_from_sexp_numeric<T>(sexp: SEXP) -> Result<Vec<Option<T>>, SexpError>
577where
578 i32: TryCoerce<T>,
579 f64: TryCoerce<T>,
580 <i32 as TryCoerce<T>>::Error: std::fmt::Display,
581 <f64 as TryCoerce<T>>::Error: std::fmt::Display,
582{
583 match sexp.type_of() {
584 SEXPTYPE::INTSXP => {
585 let slice: &[i32] = unsafe { sexp.as_slice() };
586 batch_elements(slice, strict_int_elt::<T>)
587 }
588 SEXPTYPE::REALSXP => {
589 let slice: &[f64] = unsafe { sexp.as_slice() };
590 batch_elements(slice, strict_real_elt::<T>)
591 }
592 actual => Err(strict_type_error(actual)),
593 }
594}
595
596#[cfg(test)]
597mod tests;
598