Skip to main content

miniextendr_api/from_r/
strings.rs

1//! String conversions — STRSXP requires special handling via `STRING_ELT`.
2//!
3//! R stores strings as STRSXP (vector of CHARSXP). Each element requires
4//! `STRING_ELT` + `R_CHAR` to extract, unlike numeric vectors which expose
5//! a contiguous data pointer.
6//!
7//! Covers: `&str`, `String`, `char`, `Option<&str>`, `Option<String>`,
8//! `Vec<String>`, `Vec<&str>`, `Box<[String]>`.
9//!
10//! # Tradeoff
11//!
12//! Prefer borrowed `&str` / `Vec<&str>` over owned `String` / `Vec<String>`
13//! when the data only needs to live for the `.Call` — borrowed strings point
14//! straight into R's CHARSXP pool with no allocation. Use `Option<String>`
15//! / `Vec<Option<String>>` when callers may pass `NA_character_`; the plain
16//! `String` / `Vec<String>` impls map NA to `""`, which is lossy. The optional
17//! forms preserve the distinction as `None`.
18//!
19//! UTF-8/ASCII strings use a zero-copy fast path. Other text encodings are
20//! translated to UTF-8; an R string marked as `bytes`, or one that is not
21//! valid UTF-8, is refused with an [`SexpError::InvalidValue`] (an argument
22//! error in R: `'x' must be a single string: marked as bytes, not text`). Outbound
23//! counterparts: `String` / `&str` impls in [`crate::into_r`].
24
25use crate::SEXP;
26use crate::from_r::{
27    SexpError, TryFromSexp, is_null_or_plain_na, is_null_or_plain_na_unchecked, scalar_charsxp,
28    scalar_charsxp_unchecked, try_charsxp_to_str, try_charsxp_to_str_unchecked,
29};
30
31/// Convert R character vector (STRSXP) to Rust &str.
32///
33/// Extracts the first element of the character vector and returns it as a UTF-8 string.
34/// The Rust type uses a static lifetime for API convenience, but the borrow is
35/// only valid while the source CHARSXP remains reachable.
36///
37/// # NA Handling
38///
39/// **Warning:** `NA_character_` is converted to empty string `""`. This is lossy!
40/// If you need to distinguish between NA and empty strings, use `Option<String>` instead:
41///
42/// ```ignore
43/// let maybe_str: Option<String> = sexp.try_into()?;
44/// ```
45///
46/// # Safety
47/// The returned &str is only valid as long as R doesn't garbage collect the CHARSXP.
48/// For ALTSTRING inputs, rooting the source alone may not retain its elements.
49/// Use `TryFromRoot` to retain uncached elements for the call's scope.
50impl TryFromSexp for &'static str {
51    type Error = SexpError;
52    const CHARACTER_ONLY: bool = true;
53
54    #[inline]
55    fn try_from_sexp(sexp: SEXP) -> Result<Self, Self::Error> {
56        let charsxp = scalar_charsxp(sexp)?;
57
58        // Check for NA_STRING or R_BlankString
59        if charsxp == SEXP::na_string() {
60            return Ok("");
61        }
62        if charsxp == SEXP::blank_string() {
63            return Ok("");
64        }
65
66        // Use LENGTH-based conversion (O(1)) instead of CStr::from_ptr (O(n) strlen)
67        unsafe { try_charsxp_to_str(charsxp) }
68    }
69
70    unsafe fn __mx_try_from_rooted(root: crate::Root<'_>) -> Result<Self, Self::Error> {
71        let charsxp = scalar_charsxp(root.get())?;
72        if charsxp == SEXP::na_string() || charsxp == SEXP::blank_string() {
73            return Ok("");
74        }
75        let charsxp = unsafe { root.protect_child(charsxp) }.get();
76        unsafe { try_charsxp_to_str(charsxp) }
77    }
78
79    #[inline]
80    unsafe fn try_from_sexp_unchecked(sexp: SEXP) -> Result<Self, Self::Error> {
81        let charsxp = unsafe { scalar_charsxp_unchecked(sexp)? };
82
83        // Check for NA_STRING or R_BlankString
84        if charsxp == SEXP::na_string() {
85            return Ok("");
86        }
87        if charsxp == SEXP::blank_string() {
88            return Ok("");
89        }
90
91        // Use LENGTH-based conversion (O(1)) instead of CStr::from_ptr (O(n) strlen)
92        unsafe { try_charsxp_to_str_unchecked(charsxp) }
93    }
94}
95
96/// `NULL`, `NA_character_` and a plain `NA` (#2305) read as `None`.
97impl TryFromSexp for Option<&'static str> {
98    type Error = SexpError;
99    const CHARACTER_ONLY: bool = true;
100
101    #[inline]
102    fn try_from_sexp(sexp: SEXP) -> Result<Self, Self::Error> {
103        if is_null_or_plain_na(sexp) {
104            return Ok(None);
105        }
106
107        let charsxp = scalar_charsxp(sexp)?;
108        if charsxp == SEXP::na_string() {
109            return Ok(None);
110        }
111        if charsxp == SEXP::blank_string() {
112            return Ok(Some(""));
113        }
114
115        unsafe { try_charsxp_to_str(charsxp) }.map(Some)
116    }
117
118    unsafe fn __mx_try_from_rooted(root: crate::Root<'_>) -> Result<Self, Self::Error> {
119        if is_null_or_plain_na(root.get()) {
120            return Ok(None);
121        }
122        let charsxp = scalar_charsxp(root.get())?;
123        if charsxp == SEXP::na_string() {
124            return Ok(None);
125        }
126        if charsxp == SEXP::blank_string() {
127            return Ok(Some(""));
128        }
129        let charsxp = unsafe { root.protect_child(charsxp) }.get();
130        unsafe { try_charsxp_to_str(charsxp) }.map(Some)
131    }
132
133    #[inline]
134    unsafe fn try_from_sexp_unchecked(sexp: SEXP) -> Result<Self, Self::Error> {
135        if unsafe { is_null_or_plain_na_unchecked(sexp) } {
136            return Ok(None);
137        }
138
139        let charsxp = unsafe { scalar_charsxp_unchecked(sexp)? };
140        if charsxp == SEXP::na_string() {
141            return Ok(None);
142        }
143        if charsxp == SEXP::blank_string() {
144            return Ok(Some(""));
145        }
146
147        unsafe { try_charsxp_to_str_unchecked(charsxp) }.map(Some)
148    }
149}
150
151/// Convert R character vector (STRSXP) to Rust char.
152///
153/// Extracts the first character of the first element of the character vector.
154/// Returns an error if the string is empty, NA, or has more than one character.
155impl TryFromSexp for char {
156    type Error = SexpError;
157    const CHARACTER_ONLY: bool = true;
158
159    #[inline]
160    fn try_from_sexp(sexp: SEXP) -> Result<Self, Self::Error> {
161        let s: &str = TryFromSexp::try_from_sexp(sexp)?;
162        let mut chars = s.chars();
163        match (chars.next(), chars.next()) {
164            (Some(c), None) => Ok(c),
165            (None, _) => Err(SexpError::InvalidValue(
166                "empty string cannot be converted to char".to_string(),
167            )),
168            (Some(_), Some(_)) => Err(SexpError::InvalidValue(
169                "string has more than one character".to_string(),
170            )),
171        }
172    }
173
174    #[inline]
175    unsafe fn try_from_sexp_unchecked(sexp: SEXP) -> Result<Self, Self::Error> {
176        let s: &str = unsafe { TryFromSexp::try_from_sexp_unchecked(sexp)? };
177        let mut chars = s.chars();
178        match (chars.next(), chars.next()) {
179            (Some(c), None) => Ok(c),
180            (None, _) => Err(SexpError::InvalidValue(
181                "empty string cannot be converted to char".to_string(),
182            )),
183            (Some(_), Some(_)) => Err(SexpError::InvalidValue(
184                "string has more than one character".to_string(),
185            )),
186        }
187    }
188}
189
190/// Convert R character vector (STRSXP) to owned Rust String.
191///
192/// Extracts the first element and creates an owned copy.
193///
194/// # NA Handling
195///
196/// **Warning:** `NA_character_` is converted to empty string `""`. This is lossy!
197/// If you need to distinguish between NA and empty strings, use `Option<String>` instead:
198///
199/// ```ignore
200/// let maybe_str: Option<String> = sexp.try_into()?;
201/// ```
202impl TryFromSexp for String {
203    type Error = SexpError;
204    const CHARACTER_ONLY: bool = true;
205
206    #[inline]
207    fn try_from_sexp(sexp: SEXP) -> Result<Self, Self::Error> {
208        let charsxp = scalar_charsxp(sexp)?;
209
210        if charsxp == SEXP::na_string() {
211            return Ok(String::new());
212        }
213
214        unsafe { try_charsxp_to_str(charsxp) }.map(str::to_owned)
215    }
216
217    #[inline]
218    unsafe fn try_from_sexp_unchecked(sexp: SEXP) -> Result<Self, Self::Error> {
219        let charsxp = unsafe { scalar_charsxp_unchecked(sexp)? };
220
221        if charsxp == SEXP::na_string() {
222            return Ok(String::new());
223        }
224
225        unsafe { try_charsxp_to_str_unchecked(charsxp) }.map(str::to_owned)
226    }
227}
228
229/// NA-aware string conversion: returns `None` for `NA_character_`, and for
230/// `NULL` and a plain `NA`, R's untyped missing value (#2305).
231///
232/// Use this when you need to distinguish between NA and empty strings:
233/// ```ignore
234/// let maybe_str: Option<String> = sexp.try_into()?;
235/// match maybe_str {
236///     Some(s) => println!("Got string: {}", s),
237///     None => println!("Got NA"),
238/// }
239/// ```
240impl TryFromSexp for Option<String> {
241    type Error = SexpError;
242    const CHARACTER_ONLY: bool = true;
243
244    #[inline]
245    fn try_from_sexp(sexp: SEXP) -> Result<Self, Self::Error> {
246        if is_null_or_plain_na(sexp) {
247            return Ok(None);
248        }
249
250        let charsxp = scalar_charsxp(sexp)?;
251
252        // Return None for NA_STRING
253        if charsxp == SEXP::na_string() {
254            return Ok(None);
255        }
256
257        unsafe { try_charsxp_to_str(charsxp) }.map(|s| Some(s.to_owned()))
258    }
259
260    #[inline]
261    unsafe fn try_from_sexp_unchecked(sexp: SEXP) -> Result<Self, Self::Error> {
262        // For Option<String>, unchecked is same as checked (NA check is semantic, not safety)
263        Self::try_from_sexp(sexp)
264    }
265}
266// endregion
267
268// region: Owned unsized strings
269//
270// Preserve String's scalar/NA semantics and vector diagnostics. Each string is
271// owned before returning, so no CHARSXP borrow escapes in an Rc/Arc/Box.
272macro_rules! impl_owned_str_from_r {
273    ($owner:ident) => {
274        impl TryFromSexp for $owner<str> {
275            type Error = SexpError;
276            const CHARACTER_ONLY: bool = true;
277            fn try_from_sexp(sexp: SEXP) -> Result<Self, Self::Error> {
278                String::try_from_sexp(sexp).map(Self::from)
279            }
280            unsafe fn try_from_sexp_unchecked(sexp: SEXP) -> Result<Self, Self::Error> {
281                unsafe { String::try_from_sexp_unchecked(sexp) }.map(Self::from)
282            }
283        }
284        impl TryFromSexp for Option<$owner<str>> {
285            type Error = SexpError;
286            const CHARACTER_ONLY: bool = true;
287            fn try_from_sexp(sexp: SEXP) -> Result<Self, Self::Error> {
288                Option::<String>::try_from_sexp(sexp).map(|v| v.map($owner::from))
289            }
290            unsafe fn try_from_sexp_unchecked(sexp: SEXP) -> Result<Self, Self::Error> {
291                unsafe { Option::<String>::try_from_sexp_unchecked(sexp) }
292                    .map(|v| v.map($owner::from))
293            }
294        }
295        impl TryFromSexp for Vec<$owner<str>> {
296            type Error = SexpError;
297            const CHARACTER_ONLY: bool = true;
298            fn try_from_sexp(sexp: SEXP) -> Result<Self, Self::Error> {
299                Vec::<String>::try_from_sexp(sexp)
300                    .map(|v| v.into_iter().map($owner::from).collect())
301            }
302            unsafe fn try_from_sexp_unchecked(sexp: SEXP) -> Result<Self, Self::Error> {
303                unsafe { Vec::<String>::try_from_sexp_unchecked(sexp) }
304                    .map(|v| v.into_iter().map($owner::from).collect())
305            }
306        }
307        impl TryFromSexp for Vec<Option<$owner<str>>> {
308            type Error = SexpError;
309            const CHARACTER_ONLY: bool = true;
310            fn try_from_sexp(sexp: SEXP) -> Result<Self, Self::Error> {
311                Vec::<Option<String>>::try_from_sexp(sexp)
312                    .map(|v| v.into_iter().map(|s| s.map($owner::from)).collect())
313            }
314            unsafe fn try_from_sexp_unchecked(sexp: SEXP) -> Result<Self, Self::Error> {
315                unsafe { Vec::<Option<String>>::try_from_sexp_unchecked(sexp) }
316                    .map(|v| v.into_iter().map(|s| s.map($owner::from)).collect())
317            }
318        }
319    };
320}
321use std::rc::Rc;
322use std::sync::Arc;
323impl TryFromSexp for Box<str> {
    type Error = SexpError;
    const CHARACTER_ONLY: bool = true;
    fn try_from_sexp(sexp: SEXP) -> Result<Self, Self::Error> {
        String::try_from_sexp(sexp).map(Self::from)
    }
    unsafe fn try_from_sexp_unchecked(sexp: SEXP)
        -> Result<Self, Self::Error> {
        unsafe { String::try_from_sexp_unchecked(sexp) }.map(Self::from)
    }
}
impl TryFromSexp for Option<Box<str>> {
    type Error = SexpError;
    const CHARACTER_ONLY: bool = true;
    fn try_from_sexp(sexp: SEXP) -> Result<Self, Self::Error> {
        Option::<String>::try_from_sexp(sexp).map(|v| v.map(Box::from))
    }
    unsafe fn try_from_sexp_unchecked(sexp: SEXP)
        -> Result<Self, Self::Error> {
        unsafe {
                Option::<String>::try_from_sexp_unchecked(sexp)
            }.map(|v| v.map(Box::from))
    }
}
impl TryFromSexp for Vec<Box<str>> {
    type Error = SexpError;
    const CHARACTER_ONLY: bool = true;
    fn try_from_sexp(sexp: SEXP) -> Result<Self, Self::Error> {
        Vec::<String>::try_from_sexp(sexp).map(|v|
                v.into_iter().map(Box::from).collect())
    }
    unsafe fn try_from_sexp_unchecked(sexp: SEXP)
        -> Result<Self, Self::Error> {
        unsafe {
                Vec::<String>::try_from_sexp_unchecked(sexp)
            }.map(|v| v.into_iter().map(Box::from).collect())
    }
}
impl TryFromSexp for Vec<Option<Box<str>>> {
    type Error = SexpError;
    const CHARACTER_ONLY: bool = true;
    fn try_from_sexp(sexp: SEXP) -> Result<Self, Self::Error> {
        Vec::<Option<String>>::try_from_sexp(sexp).map(|v|
                v.into_iter().map(|s| s.map(Box::from)).collect())
    }
    unsafe fn try_from_sexp_unchecked(sexp: SEXP)
        -> Result<Self, Self::Error> {
        unsafe {
                Vec::<Option<String>>::try_from_sexp_unchecked(sexp)
            }.map(|v| v.into_iter().map(|s| s.map(Box::from)).collect())
    }
}impl_owned_str_from_r!(Box);
324impl TryFromSexp for Rc<str> {
    type Error = SexpError;
    const CHARACTER_ONLY: bool = true;
    fn try_from_sexp(sexp: SEXP) -> Result<Self, Self::Error> {
        String::try_from_sexp(sexp).map(Self::from)
    }
    unsafe fn try_from_sexp_unchecked(sexp: SEXP)
        -> Result<Self, Self::Error> {
        unsafe { String::try_from_sexp_unchecked(sexp) }.map(Self::from)
    }
}
impl TryFromSexp for Option<Rc<str>> {
    type Error = SexpError;
    const CHARACTER_ONLY: bool = true;
    fn try_from_sexp(sexp: SEXP) -> Result<Self, Self::Error> {
        Option::<String>::try_from_sexp(sexp).map(|v| v.map(Rc::from))
    }
    unsafe fn try_from_sexp_unchecked(sexp: SEXP)
        -> Result<Self, Self::Error> {
        unsafe {
                Option::<String>::try_from_sexp_unchecked(sexp)
            }.map(|v| v.map(Rc::from))
    }
}
impl TryFromSexp for Vec<Rc<str>> {
    type Error = SexpError;
    const CHARACTER_ONLY: bool = true;
    fn try_from_sexp(sexp: SEXP) -> Result<Self, Self::Error> {
        Vec::<String>::try_from_sexp(sexp).map(|v|
                v.into_iter().map(Rc::from).collect())
    }
    unsafe fn try_from_sexp_unchecked(sexp: SEXP)
        -> Result<Self, Self::Error> {
        unsafe {
                Vec::<String>::try_from_sexp_unchecked(sexp)
            }.map(|v| v.into_iter().map(Rc::from).collect())
    }
}
impl TryFromSexp for Vec<Option<Rc<str>>> {
    type Error = SexpError;
    const CHARACTER_ONLY: bool = true;
    fn try_from_sexp(sexp: SEXP) -> Result<Self, Self::Error> {
        Vec::<Option<String>>::try_from_sexp(sexp).map(|v|
                v.into_iter().map(|s| s.map(Rc::from)).collect())
    }
    unsafe fn try_from_sexp_unchecked(sexp: SEXP)
        -> Result<Self, Self::Error> {
        unsafe {
                Vec::<Option<String>>::try_from_sexp_unchecked(sexp)
            }.map(|v| v.into_iter().map(|s| s.map(Rc::from)).collect())
    }
}impl_owned_str_from_r!(Rc);
325impl TryFromSexp for Arc<str> {
    type Error = SexpError;
    const CHARACTER_ONLY: bool = true;
    fn try_from_sexp(sexp: SEXP) -> Result<Self, Self::Error> {
        String::try_from_sexp(sexp).map(Self::from)
    }
    unsafe fn try_from_sexp_unchecked(sexp: SEXP)
        -> Result<Self, Self::Error> {
        unsafe { String::try_from_sexp_unchecked(sexp) }.map(Self::from)
    }
}
impl TryFromSexp for Option<Arc<str>> {
    type Error = SexpError;
    const CHARACTER_ONLY: bool = true;
    fn try_from_sexp(sexp: SEXP) -> Result<Self, Self::Error> {
        Option::<String>::try_from_sexp(sexp).map(|v| v.map(Arc::from))
    }
    unsafe fn try_from_sexp_unchecked(sexp: SEXP)
        -> Result<Self, Self::Error> {
        unsafe {
                Option::<String>::try_from_sexp_unchecked(sexp)
            }.map(|v| v.map(Arc::from))
    }
}
impl TryFromSexp for Vec<Arc<str>> {
    type Error = SexpError;
    const CHARACTER_ONLY: bool = true;
    fn try_from_sexp(sexp: SEXP) -> Result<Self, Self::Error> {
        Vec::<String>::try_from_sexp(sexp).map(|v|
                v.into_iter().map(Arc::from).collect())
    }
    unsafe fn try_from_sexp_unchecked(sexp: SEXP)
        -> Result<Self, Self::Error> {
        unsafe {
                Vec::<String>::try_from_sexp_unchecked(sexp)
            }.map(|v| v.into_iter().map(Arc::from).collect())
    }
}
impl TryFromSexp for Vec<Option<Arc<str>>> {
    type Error = SexpError;
    const CHARACTER_ONLY: bool = true;
    fn try_from_sexp(sexp: SEXP) -> Result<Self, Self::Error> {
        Vec::<Option<String>>::try_from_sexp(sexp).map(|v|
                v.into_iter().map(|s| s.map(Arc::from)).collect())
    }
    unsafe fn try_from_sexp_unchecked(sexp: SEXP)
        -> Result<Self, Self::Error> {
        unsafe {
                Vec::<Option<String>>::try_from_sexp_unchecked(sexp)
            }.map(|v| v.into_iter().map(|s| s.map(Arc::from)).collect())
    }
}impl_owned_str_from_r!(Arc);
326// endregion