Skip to main content

miniextendr_api/from_r/
logical.rs

1//! Logical type conversions (Rboolean, bool, Option variants).
2//!
3//! **`LGLSXP` literals here are the source of truth (#882).** `bool`/`Rboolean`
4//! are deliberately *not* `RNativeType` — R logical vectors are stored as `i32`
5//! (that's `RLogical`), and these impls translate the three-state TRUE/FALSE/NA
6//! `LGLSXP` payload into a two-state Rust `bool`. There is no `T::SEXP_TYPE` to
7//! derive the tag from for `bool`; the literal is the boundary, leave it.
8//!
9//! Handles the three R logical states (TRUE, FALSE, NA) and maps them to Rust:
10//!
11//! | Rust Type | NA Handling |
12//! |-----------|-------------|
13//! | `Rboolean` | Error on NA |
14//! | `bool` | Error on NA |
15//! | `Option<Rboolean>` | `None` on NA |
16//! | `Option<bool>` | `None` on NA |
17//!
18//! # Tradeoff
19//!
20//! Use `Option<bool>` / `Option<Rboolean>` if R might pass `NA` — the plain
21//! `bool` / `Rboolean` impls treat NA as a conversion failure. Failure mode
22//! of binding a plain `bool` when callers can pass `NA`: every NA argument
23//! surfaces as `SexpNaError` at the call site, which is usually not what you
24//! want for an interactive R API.
25//!
26//! The optional native scalars live here too: `Option<i32>`, `Option<f64>`,
27//! `Option<u8>` and `Option<Rcomplex>` read `NULL`, their own type's `NA`
28//! (raw has none) and a plain `NA`, R's untyped missing value, as `None`
29//! (#2305, [`is_null_or_plain_na`]). A logical `NA` is already `None` for
30//! the logical forms.
31//!
32//! Outbound counterpart: `bool` / `Option<bool>` impls in
33//! [`crate::into_r`].
34
35use crate::from_r::{
36    SexpError, SexpNaError, TryFromSexp, is_null_or_plain_na, is_null_or_plain_na_unchecked,
37};
38use crate::{IsNA, RLogical, Rboolean, SEXP, SEXPTYPE, SexpExt};
39
40impl TryFromSexp for Rboolean {
41    type Error = SexpError;
42
43    #[inline]
44    fn try_from_sexp(sexp: SEXP) -> Result<Self, Self::Error> {
45        let raw: RLogical = TryFromSexp::try_from_sexp(sexp)?;
46        match raw.to_option_bool() {
47            Some(false) => Ok(Rboolean::FALSE),
48            Some(true) => Ok(Rboolean::TRUE),
49            None => Err(SexpNaError {
50                sexp_type: SEXPTYPE::LGLSXP,
51            }
52            .into()),
53        }
54    }
55
56    #[inline]
57    unsafe fn try_from_sexp_unchecked(sexp: SEXP) -> Result<Self, Self::Error> {
58        let raw: RLogical = unsafe { TryFromSexp::try_from_sexp_unchecked(sexp)? };
59        match raw.to_option_bool() {
60            Some(false) => Ok(Rboolean::FALSE),
61            Some(true) => Ok(Rboolean::TRUE),
62            None => Err(SexpNaError {
63                sexp_type: SEXPTYPE::LGLSXP,
64            }
65            .into()),
66        }
67    }
68}
69
70impl TryFromSexp for Option<Rboolean> {
71    type Error = SexpError;
72
73    #[inline]
74    fn try_from_sexp(sexp: SEXP) -> Result<Self, Self::Error> {
75        if sexp.type_of() == SEXPTYPE::NILSXP {
76            return Ok(None);
77        }
78        let raw: RLogical = TryFromSexp::try_from_sexp(sexp)?;
79        match raw.to_option_bool() {
80            Some(false) => Ok(Some(Rboolean::FALSE)),
81            Some(true) => Ok(Some(Rboolean::TRUE)),
82            None => Ok(None),
83        }
84    }
85
86    #[inline]
87    unsafe fn try_from_sexp_unchecked(sexp: SEXP) -> Result<Self, Self::Error> {
88        if sexp.type_of() == SEXPTYPE::NILSXP {
89            return Ok(None);
90        }
91        let raw: RLogical = unsafe { TryFromSexp::try_from_sexp_unchecked(sexp)? };
92        match raw.to_option_bool() {
93            Some(false) => Ok(Some(Rboolean::FALSE)),
94            Some(true) => Ok(Some(Rboolean::TRUE)),
95            None => Ok(None),
96        }
97    }
98}
99
100impl TryFromSexp for bool {
101    type Error = SexpError;
102
103    #[inline]
104    fn try_from_sexp(sexp: SEXP) -> Result<Self, Self::Error> {
105        let raw: RLogical = TryFromSexp::try_from_sexp(sexp)?;
106        raw.to_option_bool().ok_or_else(|| {
107            SexpNaError {
108                sexp_type: SEXPTYPE::LGLSXP,
109            }
110            .into()
111        })
112    }
113
114    #[inline]
115    unsafe fn try_from_sexp_unchecked(sexp: SEXP) -> Result<Self, Self::Error> {
116        let raw: RLogical = unsafe { TryFromSexp::try_from_sexp_unchecked(sexp)? };
117        raw.to_option_bool().ok_or_else(|| {
118            SexpNaError {
119                sexp_type: SEXPTYPE::LGLSXP,
120            }
121            .into()
122        })
123    }
124}
125
126impl TryFromSexp for Option<bool> {
127    type Error = SexpError;
128
129    #[inline]
130    fn try_from_sexp(sexp: SEXP) -> Result<Self, Self::Error> {
131        // NULL -> None
132        if sexp.type_of() == SEXPTYPE::NILSXP {
133            return Ok(None);
134        }
135        let raw: RLogical = TryFromSexp::try_from_sexp(sexp)?;
136        Ok(raw.to_option_bool())
137    }
138
139    #[inline]
140    unsafe fn try_from_sexp_unchecked(sexp: SEXP) -> Result<Self, Self::Error> {
141        // NULL -> None
142        if sexp.type_of() == SEXPTYPE::NILSXP {
143            return Ok(None);
144        }
145        let raw: RLogical = unsafe { TryFromSexp::try_from_sexp_unchecked(sexp)? };
146        Ok(raw.to_option_bool())
147    }
148}
149
150impl TryFromSexp for Option<RLogical> {
151    type Error = SexpError;
152
153    #[inline]
154    fn try_from_sexp(sexp: SEXP) -> Result<Self, Self::Error> {
155        if sexp.type_of() == SEXPTYPE::NILSXP {
156            return Ok(None);
157        }
158        let raw: RLogical = TryFromSexp::try_from_sexp(sexp)?;
159        if raw.is_na() { Ok(None) } else { Ok(Some(raw)) }
160    }
161
162    #[inline]
163    unsafe fn try_from_sexp_unchecked(sexp: SEXP) -> Result<Self, Self::Error> {
164        if sexp.type_of() == SEXPTYPE::NILSXP {
165            return Ok(None);
166        }
167        let raw: RLogical = unsafe { TryFromSexp::try_from_sexp_unchecked(sexp)? };
168        if raw.is_na() { Ok(None) } else { Ok(Some(raw)) }
169    }
170}
171
172impl TryFromSexp for Option<i32> {
173    type Error = SexpError;
174
175    #[inline]
176    fn try_from_sexp(sexp: SEXP) -> Result<Self, Self::Error> {
177        if is_null_or_plain_na(sexp) {
178            return Ok(None);
179        }
180        // The i32 TryFromSexp impl now returns SexpNaError for NA_integer_.
181        // Treat that as None here; propagate all other errors.
182        match TryFromSexp::try_from_sexp(sexp) {
183            Ok(value) => Ok(Some(value)),
184            Err(SexpError::Na(_)) => Ok(None),
185            Err(e) => Err(e),
186        }
187    }
188
189    #[inline]
190    unsafe fn try_from_sexp_unchecked(sexp: SEXP) -> Result<Self, Self::Error> {
191        if unsafe { is_null_or_plain_na_unchecked(sexp) } {
192            return Ok(None);
193        }
194        match unsafe { TryFromSexp::try_from_sexp_unchecked(sexp) } {
195            Ok(value) => Ok(Some(value)),
196            Err(SexpError::Na(_)) => Ok(None),
197            Err(e) => Err(e),
198        }
199    }
200}
201
202impl TryFromSexp for Option<f64> {
203    type Error = SexpError;
204
205    #[inline]
206    fn try_from_sexp(sexp: SEXP) -> Result<Self, Self::Error> {
207        if is_null_or_plain_na(sexp) {
208            return Ok(None);
209        }
210        let value: f64 = TryFromSexp::try_from_sexp(sexp)?;
211        if value.is_na() {
212            Ok(None)
213        } else {
214            Ok(Some(value))
215        }
216    }
217
218    #[inline]
219    unsafe fn try_from_sexp_unchecked(sexp: SEXP) -> Result<Self, Self::Error> {
220        if unsafe { is_null_or_plain_na_unchecked(sexp) } {
221            return Ok(None);
222        }
223        let value: f64 = unsafe { TryFromSexp::try_from_sexp_unchecked(sexp)? };
224        if value.is_na() {
225            Ok(None)
226        } else {
227            Ok(Some(value))
228        }
229    }
230}
231
232impl TryFromSexp for Option<u8> {
233    type Error = SexpError;
234
235    #[inline]
236    fn try_from_sexp(sexp: SEXP) -> Result<Self, Self::Error> {
237        if is_null_or_plain_na(sexp) {
238            return Ok(None);
239        }
240        let value: u8 = TryFromSexp::try_from_sexp(sexp)?;
241        Ok(Some(value))
242    }
243
244    #[inline]
245    unsafe fn try_from_sexp_unchecked(sexp: SEXP) -> Result<Self, Self::Error> {
246        if unsafe { is_null_or_plain_na_unchecked(sexp) } {
247            return Ok(None);
248        }
249        let value: u8 = unsafe { TryFromSexp::try_from_sexp_unchecked(sexp)? };
250        Ok(Some(value))
251    }
252}
253
254impl TryFromSexp for Option<crate::Rcomplex> {
255    type Error = SexpError;
256
257    #[inline]
258    fn try_from_sexp(sexp: SEXP) -> Result<Self, Self::Error> {
259        if is_null_or_plain_na(sexp) {
260            return Ok(None);
261        }
262        let value: crate::Rcomplex = TryFromSexp::try_from_sexp(sexp)?;
263        // R's complex `NA` check: either part is `NA_real_` (`R_IsNA`).
264        if value.is_na() {
265            Ok(None)
266        } else {
267            Ok(Some(value))
268        }
269    }
270
271    #[inline]
272    unsafe fn try_from_sexp_unchecked(sexp: SEXP) -> Result<Self, Self::Error> {
273        if unsafe { is_null_or_plain_na_unchecked(sexp) } {
274            return Ok(None);
275        }
276        let value: crate::Rcomplex = unsafe { TryFromSexp::try_from_sexp_unchecked(sexp)? };
277        if value.is_na() {
278            Ok(None)
279        } else {
280            Ok(Some(value))
281        }
282    }
283}
284// endregion