Skip to main content

miniextendr_api/from_r/
cow_and_paths.rs

1//! Cow, PathBuf, OsString, and string collection conversions.
2//!
3//! - `Cow<'_, [T]>` — owned copy of R native vectors
4//! - `Cow<'_, str>` — owned copy of R character scalars
5//! - `PathBuf` / `OsString` — from STRSXP via `String` intermediary
6//! - `HashSet<String>` / `BTreeSet<String>` — string set conversions
7//!
8//! # Tradeoff
9//!
10//! These [`TryFromSexp`] impls reject mismatched
11//! [`SEXPTYPE`](crate::SEXPTYPE)s — there is no looser coercion path for `Cow` / `PathBuf` /
12//! `OsString`. Raw `Cow` conversions own their data and may outlive the source.
13//! [`super::TryFromRoot`] supplies the borrowing path with a root-bound lifetime;
14//! generated wrappers use it for explicit `Cow` parameters.
15
16use std::borrow::Cow;
17use std::collections::{BTreeSet, HashSet};
18use std::ffi::OsString;
19use std::path::PathBuf;
20
21use crate::SEXP;
22use crate::from_r::{SexpError, SexpTypeError, TryFromSexp, map_strsxp_with, try_charsxp_to_str};
23
24/// Convert an R native vector to an owned `Cow`.
25///
26/// A raw SEXP carries no borrow lifetime. Use [`super::TryFromRoot`] to borrow
27/// without copying; generated wrappers select that path for `Cow<'_, [T]>`.
28impl<T: crate::RNativeType> TryFromSexp for Cow<'_, [T]> {
29    type Error = SexpTypeError;
30
31    fn try_from_sexp(sexp: SEXP) -> Result<Self, Self::Error> {
32        let slice: &[T] = TryFromSexp::try_from_sexp(sexp)?;
33        Ok(Cow::Owned(slice.to_vec()))
34    }
35
36    unsafe fn try_from_sexp_unchecked(sexp: SEXP) -> Result<Self, Self::Error> {
37        let slice: &[T] = unsafe { TryFromSexp::try_from_sexp_unchecked(sexp)? };
38        Ok(Cow::Owned(slice.to_vec()))
39    }
40}
41
42/// Convert an R character scalar to an owned `Cow`.
43///
44/// The same scalar/NA semantics as `String`. Borrowing requires
45/// [`super::TryFromRoot`], which generated wrappers use for `Cow<'_, str>`.
46impl TryFromSexp for Cow<'_, str> {
47    type Error = SexpError;
48    const CHARACTER_ONLY: bool = true;
49
50    fn try_from_sexp(sexp: SEXP) -> Result<Self, Self::Error> {
51        String::try_from_sexp(sexp).map(Cow::Owned)
52    }
53
54    unsafe fn try_from_sexp_unchecked(sexp: SEXP) -> Result<Self, Self::Error> {
55        unsafe { String::try_from_sexp_unchecked(sexp) }.map(Cow::Owned)
56    }
57}
58
59/// Convert a character vector to owned strings; NA becomes an empty string.
60/// Generated wrappers borrow instead through [`super::TryFromRoot`].
61impl TryFromSexp for Vec<Cow<'_, str>> {
62    type Error = SexpError;
63    const CHARACTER_ONLY: bool = true;
64
65    fn try_from_sexp(sexp: SEXP) -> Result<Self, Self::Error> {
66        Vec::<String>::try_from_sexp(sexp)
67            .map(|values| values.into_iter().map(Cow::Owned).collect())
68    }
69}
70
71/// Convert a character vector to owned strings, preserving NA as `None`.
72/// Generated wrappers borrow instead through [`super::TryFromRoot`].
73impl TryFromSexp for Vec<Option<Cow<'_, str>>> {
74    type Error = SexpError;
75    const CHARACTER_ONLY: bool = true;
76
77    fn try_from_sexp(sexp: SEXP) -> Result<Self, Self::Error> {
78        Vec::<Option<String>>::try_from_sexp(sexp)
79            .map(|values| values.into_iter().map(|v| v.map(Cow::Owned)).collect())
80    }
81}
82
83/// Convert R character vector to `Vec<String>`.
84///
85/// # NA and Encoding Handling
86///
87/// **Warning:** This conversion is lossy for NA values: `NA_character_`
88/// values are converted to empty string `""`. If you need to preserve NA
89/// semantics, use `Vec<Option<String>>` instead:
90///
91/// ```ignore
92/// let strings: Vec<Option<String>> = sexp.try_into()?;
93/// // NA values will be None, valid strings will be Some(s)
94/// ```
95///
96/// Latin-1 elements are translated to UTF-8. Elements marked as bytes, or
97/// that are not valid UTF-8, are refused, all of them in one error that
98/// lists their positions (`marked as bytes, not text (elements 2, 4)`).
99impl TryFromSexp for Vec<String> {
100    type Error = SexpError;
101    const CHARACTER_ONLY: bool = true;
102
103    fn try_from_sexp(sexp: SEXP) -> Result<Self, Self::Error> {
104        map_strsxp_with(sexp, |charsxp, _i| {
105            if charsxp == SEXP::na_string() {
106                Ok(String::new())
107            } else {
108                unsafe { try_charsxp_to_str(charsxp) }.map(str::to_owned)
109            }
110        })
111    }
112}
113
114/// Convert R character vector to `Vec<&str>`.
115///
116/// **Warning:** `NA_character_` values are converted to empty string `""`.
117impl TryFromSexp for Vec<&'static str> {
118    type Error = SexpError;
119    const CHARACTER_ONLY: bool = true;
120
121    fn try_from_sexp(sexp: SEXP) -> Result<Self, Self::Error> {
122        map_strsxp_with(sexp, |charsxp, _i| {
123            if charsxp == SEXP::na_string() || charsxp == SEXP::blank_string() {
124                return Ok("");
125            }
126            unsafe { try_charsxp_to_str(charsxp) }
127        })
128    }
129}
130
131/// Convert R character vector to `Vec<Option<&str>>`.
132impl TryFromSexp for Vec<Option<&'static str>> {
133    type Error = SexpError;
134    const CHARACTER_ONLY: bool = true;
135
136    fn try_from_sexp(sexp: SEXP) -> Result<Self, Self::Error> {
137        map_strsxp_with(sexp, |charsxp, _i| {
138            if charsxp == SEXP::na_string() {
139                return Ok(None);
140            }
141            if charsxp == SEXP::blank_string() {
142                return Ok(Some(""));
143            }
144            unsafe { try_charsxp_to_str(charsxp) }.map(Some)
145        })
146    }
147}
148
149macro_rules! impl_set_string_try_from_sexp {
150    ($(#[$meta:meta])* $set_ty:ident) => {
151        $(#[$meta])*
152        impl TryFromSexp for $set_ty<String> {
153            type Error = SexpError;
154            const CHARACTER_ONLY: bool = true;
155
156            fn try_from_sexp(sexp: SEXP) -> Result<Self, Self::Error> {
157                let vec: Vec<String> = TryFromSexp::try_from_sexp(sexp)?;
158                Ok(vec.into_iter().collect())
159            }
160        }
161    };
162}
163
164#[doc = r" Convert R character vector to `HashSet<String>`."]
impl TryFromSexp for HashSet<String> {
    type Error = SexpError;
    const CHARACTER_ONLY: bool = true;
    fn try_from_sexp(sexp: SEXP) -> Result<Self, Self::Error> {
        let vec: Vec<String> = TryFromSexp::try_from_sexp(sexp)?;
        Ok(vec.into_iter().collect())
    }
}impl_set_string_try_from_sexp!(
165    /// Convert R character vector to `HashSet<String>`.
166    HashSet
167);
168#[doc = r" Convert R character vector to `BTreeSet<String>`."]
impl TryFromSexp for BTreeSet<String> {
    type Error = SexpError;
    const CHARACTER_ONLY: bool = true;
    fn try_from_sexp(sexp: SEXP) -> Result<Self, Self::Error> {
        let vec: Vec<String> = TryFromSexp::try_from_sexp(sexp)?;
        Ok(vec.into_iter().collect())
    }
}impl_set_string_try_from_sexp!(
169    /// Convert R character vector to `BTreeSet<String>`.
170    BTreeSet
171);
172// endregion
173
174// region: String-wrapper type conversions (PathBuf, OsString)
175
176/// Generate TryFromSexp impls for types that are `From<String>` (scalar, Option,
177/// Vec, `Vec<Option>`). Used for PathBuf and OsString which delegate to String conversion.
178macro_rules! impl_string_wrapper_try_from_sexp {
179    (
180        $(#[$scalar_meta:meta])*
181        scalar: $ty:ty;
182        $(#[$option_meta:meta])*
183        option: $ty2:ty;
184        $(#[$vec_meta:meta])*
185        vec: $ty3:ty;
186        $(#[$vec_option_meta:meta])*
187        vec_option: $ty4:ty;
188    ) => {
189        $(#[$scalar_meta])*
190        impl TryFromSexp for $ty {
191            type Error = SexpError;
192            const CHARACTER_ONLY: bool = true;
193
194            #[inline]
195            fn try_from_sexp(sexp: SEXP) -> Result<Self, Self::Error> {
196                let s: String = TryFromSexp::try_from_sexp(sexp)?;
197                Ok(<$ty>::from(s))
198            }
199
200            #[inline]
201            unsafe fn try_from_sexp_unchecked(sexp: SEXP) -> Result<Self, Self::Error> {
202                let s: String = unsafe { TryFromSexp::try_from_sexp_unchecked(sexp)? };
203                Ok(<$ty>::from(s))
204            }
205        }
206
207        $(#[$option_meta])*
208        impl TryFromSexp for Option<$ty> {
209            type Error = SexpError;
210            const CHARACTER_ONLY: bool = true;
211
212            #[inline]
213            fn try_from_sexp(sexp: SEXP) -> Result<Self, Self::Error> {
214                let opt: Option<String> = TryFromSexp::try_from_sexp(sexp)?;
215                Ok(opt.map(<$ty>::from))
216            }
217
218            #[inline]
219            unsafe fn try_from_sexp_unchecked(sexp: SEXP) -> Result<Self, Self::Error> {
220                let opt: Option<String> = unsafe { TryFromSexp::try_from_sexp_unchecked(sexp)? };
221                Ok(opt.map(<$ty>::from))
222            }
223        }
224
225        $(#[$vec_meta])*
226        impl TryFromSexp for Vec<$ty> {
227            type Error = SexpError;
228            const CHARACTER_ONLY: bool = true;
229
230            fn try_from_sexp(sexp: SEXP) -> Result<Self, Self::Error> {
231                let vec: Vec<String> = TryFromSexp::try_from_sexp(sexp)?;
232                Ok(vec.into_iter().map(<$ty>::from).collect())
233            }
234
235            unsafe fn try_from_sexp_unchecked(sexp: SEXP) -> Result<Self, Self::Error> {
236                let vec: Vec<String> = unsafe { TryFromSexp::try_from_sexp_unchecked(sexp)? };
237                Ok(vec.into_iter().map(<$ty>::from).collect())
238            }
239        }
240
241        $(#[$vec_option_meta])*
242        impl TryFromSexp for Vec<Option<$ty>> {
243            type Error = SexpError;
244            const CHARACTER_ONLY: bool = true;
245
246            fn try_from_sexp(sexp: SEXP) -> Result<Self, Self::Error> {
247                let vec: Vec<Option<String>> = TryFromSexp::try_from_sexp(sexp)?;
248                Ok(vec.into_iter().map(|opt| opt.map(<$ty>::from)).collect())
249            }
250
251            unsafe fn try_from_sexp_unchecked(sexp: SEXP) -> Result<Self, Self::Error> {
252                let vec: Vec<Option<String>> = unsafe { TryFromSexp::try_from_sexp_unchecked(sexp)? };
253                Ok(vec.into_iter().map(|opt| opt.map(<$ty>::from)).collect())
254            }
255        }
256    };
257}
258
259#[doc = r" Convert R character scalar (STRSXP of length 1) to `PathBuf`."]
#[doc = r""]
#[doc = r" # NA Handling"]
#[doc = r""]
#[doc =
r#" **Warning:** `NA_character_` is converted to empty path `""`. This is lossy!"#]
#[doc =
r" If you need to distinguish between NA and empty strings, use `Option<PathBuf>` instead."]
impl TryFromSexp for PathBuf {
    type Error = SexpError;
    const CHARACTER_ONLY: bool = true;
    #[inline]
    fn try_from_sexp(sexp: SEXP) -> Result<Self, Self::Error> {
        let s: String = TryFromSexp::try_from_sexp(sexp)?;
        Ok(<PathBuf>::from(s))
    }
    #[inline]
    unsafe fn try_from_sexp_unchecked(sexp: SEXP)
        -> Result<Self, Self::Error> {
        let s: String =
            unsafe { TryFromSexp::try_from_sexp_unchecked(sexp)? };
        Ok(<PathBuf>::from(s))
    }
}
#[doc =
r" NA-aware PathBuf conversion: returns `None` for `NA_character_` or `NULL`."]
impl TryFromSexp for Option<PathBuf> {
    type Error = SexpError;
    const CHARACTER_ONLY: bool = true;
    #[inline]
    fn try_from_sexp(sexp: SEXP) -> Result<Self, Self::Error> {
        let opt: Option<String> = TryFromSexp::try_from_sexp(sexp)?;
        Ok(opt.map(<PathBuf>::from))
    }
    #[inline]
    unsafe fn try_from_sexp_unchecked(sexp: SEXP)
        -> Result<Self, Self::Error> {
        let opt: Option<String> =
            unsafe { TryFromSexp::try_from_sexp_unchecked(sexp)? };
        Ok(opt.map(<PathBuf>::from))
    }
}
#[doc = r" Convert R character vector (STRSXP) to `Vec<PathBuf>`."]
#[doc = r""]
#[doc = r" # NA Handling"]
#[doc = r""]
#[doc =
r" **Warning:** `NA_character_` elements are converted to empty paths."]
#[doc = r" Use `Vec<Option<PathBuf>>` if you need to preserve NA values."]
impl TryFromSexp for Vec<PathBuf> {
    type Error = SexpError;
    const CHARACTER_ONLY: bool = true;
    fn try_from_sexp(sexp: SEXP) -> Result<Self, Self::Error> {
        let vec: Vec<String> = TryFromSexp::try_from_sexp(sexp)?;
        Ok(vec.into_iter().map(<PathBuf>::from).collect())
    }
    unsafe fn try_from_sexp_unchecked(sexp: SEXP)
        -> Result<Self, Self::Error> {
        let vec: Vec<String> =
            unsafe { TryFromSexp::try_from_sexp_unchecked(sexp)? };
        Ok(vec.into_iter().map(<PathBuf>::from).collect())
    }
}
#[doc =
r" Convert R character vector (STRSXP) to `Vec<Option<PathBuf>>` with NA support."]
#[doc = r""]
#[doc = r" `NA_character_` elements are converted to `None`."]
impl TryFromSexp for Vec<Option<PathBuf>> {
    type Error = SexpError;
    const CHARACTER_ONLY: bool = true;
    fn try_from_sexp(sexp: SEXP) -> Result<Self, Self::Error> {
        let vec: Vec<Option<String>> = TryFromSexp::try_from_sexp(sexp)?;
        Ok(vec.into_iter().map(|opt| opt.map(<PathBuf>::from)).collect())
    }
    unsafe fn try_from_sexp_unchecked(sexp: SEXP)
        -> Result<Self, Self::Error> {
        let vec: Vec<Option<String>> =
            unsafe { TryFromSexp::try_from_sexp_unchecked(sexp)? };
        Ok(vec.into_iter().map(|opt| opt.map(<PathBuf>::from)).collect())
    }
}impl_string_wrapper_try_from_sexp!(
260    /// Convert R character scalar (STRSXP of length 1) to `PathBuf`.
261    ///
262    /// # NA Handling
263    ///
264    /// **Warning:** `NA_character_` is converted to empty path `""`. This is lossy!
265    /// If you need to distinguish between NA and empty strings, use `Option<PathBuf>` instead.
266    scalar: PathBuf;
267    /// NA-aware PathBuf conversion: returns `None` for `NA_character_` or `NULL`.
268    option: PathBuf;
269    /// Convert R character vector (STRSXP) to `Vec<PathBuf>`.
270    ///
271    /// # NA Handling
272    ///
273    /// **Warning:** `NA_character_` elements are converted to empty paths.
274    /// Use `Vec<Option<PathBuf>>` if you need to preserve NA values.
275    vec: PathBuf;
276    /// Convert R character vector (STRSXP) to `Vec<Option<PathBuf>>` with NA support.
277    ///
278    /// `NA_character_` elements are converted to `None`.
279    vec_option: PathBuf;
280);
281
282#[doc = r" Convert R character scalar (STRSXP of length 1) to `OsString`."]
#[doc = r""]
#[doc =
r" Since R strings are converted to UTF-8, the resulting `OsString` contains"]
#[doc = r" valid UTF-8 data."]
#[doc = r""]
#[doc = r" # NA Handling"]
#[doc = r""]
#[doc =
r" **Warning:** `NA_character_` is converted to empty string. This is lossy!"]
#[doc =
r" If you need to distinguish between NA and empty strings, use `Option<OsString>` instead."]
impl TryFromSexp for OsString {
    type Error = SexpError;
    const CHARACTER_ONLY: bool = true;
    #[inline]
    fn try_from_sexp(sexp: SEXP) -> Result<Self, Self::Error> {
        let s: String = TryFromSexp::try_from_sexp(sexp)?;
        Ok(<OsString>::from(s))
    }
    #[inline]
    unsafe fn try_from_sexp_unchecked(sexp: SEXP)
        -> Result<Self, Self::Error> {
        let s: String =
            unsafe { TryFromSexp::try_from_sexp_unchecked(sexp)? };
        Ok(<OsString>::from(s))
    }
}
#[doc =
r" NA-aware OsString conversion: returns `None` for `NA_character_` or `NULL`."]
impl TryFromSexp for Option<OsString> {
    type Error = SexpError;
    const CHARACTER_ONLY: bool = true;
    #[inline]
    fn try_from_sexp(sexp: SEXP) -> Result<Self, Self::Error> {
        let opt: Option<String> = TryFromSexp::try_from_sexp(sexp)?;
        Ok(opt.map(<OsString>::from))
    }
    #[inline]
    unsafe fn try_from_sexp_unchecked(sexp: SEXP)
        -> Result<Self, Self::Error> {
        let opt: Option<String> =
            unsafe { TryFromSexp::try_from_sexp_unchecked(sexp)? };
        Ok(opt.map(<OsString>::from))
    }
}
#[doc = r" Convert R character vector (STRSXP) to `Vec<OsString>`."]
#[doc = r""]
#[doc = r" # NA Handling"]
#[doc = r""]
#[doc =
r" **Warning:** `NA_character_` elements are converted to empty strings."]
#[doc = r" Use `Vec<Option<OsString>>` if you need to preserve NA values."]
impl TryFromSexp for Vec<OsString> {
    type Error = SexpError;
    const CHARACTER_ONLY: bool = true;
    fn try_from_sexp(sexp: SEXP) -> Result<Self, Self::Error> {
        let vec: Vec<String> = TryFromSexp::try_from_sexp(sexp)?;
        Ok(vec.into_iter().map(<OsString>::from).collect())
    }
    unsafe fn try_from_sexp_unchecked(sexp: SEXP)
        -> Result<Self, Self::Error> {
        let vec: Vec<String> =
            unsafe { TryFromSexp::try_from_sexp_unchecked(sexp)? };
        Ok(vec.into_iter().map(<OsString>::from).collect())
    }
}
#[doc =
r" Convert R character vector (STRSXP) to `Vec<Option<OsString>>` with NA support."]
#[doc = r""]
#[doc = r" `NA_character_` elements are converted to `None`."]
impl TryFromSexp for Vec<Option<OsString>> {
    type Error = SexpError;
    const CHARACTER_ONLY: bool = true;
    fn try_from_sexp(sexp: SEXP) -> Result<Self, Self::Error> {
        let vec: Vec<Option<String>> = TryFromSexp::try_from_sexp(sexp)?;
        Ok(vec.into_iter().map(|opt| opt.map(<OsString>::from)).collect())
    }
    unsafe fn try_from_sexp_unchecked(sexp: SEXP)
        -> Result<Self, Self::Error> {
        let vec: Vec<Option<String>> =
            unsafe { TryFromSexp::try_from_sexp_unchecked(sexp)? };
        Ok(vec.into_iter().map(|opt| opt.map(<OsString>::from)).collect())
    }
}impl_string_wrapper_try_from_sexp!(
283    /// Convert R character scalar (STRSXP of length 1) to `OsString`.
284    ///
285    /// Since R strings are converted to UTF-8, the resulting `OsString` contains
286    /// valid UTF-8 data.
287    ///
288    /// # NA Handling
289    ///
290    /// **Warning:** `NA_character_` is converted to empty string. This is lossy!
291    /// If you need to distinguish between NA and empty strings, use `Option<OsString>` instead.
292    scalar: OsString;
293    /// NA-aware OsString conversion: returns `None` for `NA_character_` or `NULL`.
294    option: OsString;
295    /// Convert R character vector (STRSXP) to `Vec<OsString>`.
296    ///
297    /// # NA Handling
298    ///
299    /// **Warning:** `NA_character_` elements are converted to empty strings.
300    /// Use `Vec<Option<OsString>>` if you need to preserve NA values.
301    vec: OsString;
302    /// Convert R character vector (STRSXP) to `Vec<Option<OsString>>` with NA support.
303    ///
304    /// `NA_character_` elements are converted to `None`.
305    vec_option: OsString;
306);
307// endregion