Skip to main content

miniextendr_api/from_r/
collections.rs

1//! Collection conversions (HashMap, BTreeMap, HashSet, BTreeSet).
2//!
3//! Named R lists convert to `HashMap<String, V>` / `BTreeMap<String, V>`.
4//! Unnamed R vectors convert to `HashSet<T>` / `BTreeSet<T>` for native types.
5//! Nested lists convert to `Vec<HashMap<String, V>>` etc.
6//!
7//! # Tradeoff
8//!
9//! These impls live on [`TryFromSexp`], so the
10//! shape (named-vs-unnamed) is strictly enforced and element conversion
11//! delegates to the `V: TryFromSexp` bound. Failure mode: feeding an unnamed
12//! list into a `HashMap<String, V>` parameter yields a `SexpError`, not
13//! silently empty keys.
14//!
15//! Outbound counterpart: `crate::into_r::collections`.
16
17use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
18
19use crate::from_r::{
20    SexpError, SexpTypeError, TryFromSexp, map_vecsxp_with, name_refusal, try_charsxp_to_str,
21};
22use crate::{RLogical, SEXP, SEXPTYPE, SexpExt};
23
24macro_rules! impl_map_try_from_sexp {
25    ($(#[$meta:meta])* $map_ty:ident, $create:expr) => {
26        $(#[$meta])*
27        impl<V: TryFromSexp> TryFromSexp for $map_ty<String, V>
28        where
29            V::Error: Into<SexpError>,
30        {
31            const NATIVE_BORROW: Option<crate::from_r::NativeBorrow> = crate::from_r::NativeBorrow::in_list(V::NATIVE_BORROW);
32
33            type Error = SexpError;
34            // Each value is a top-level element of the named list, read by its
35            // own type: `no_na` stays top-level on a map.
36            #[inline]
37            fn __mx_has_na(&self) -> bool {
38                self.values().any(V::__mx_has_na)
39            }
40
41            fn try_from_sexp(sexp: SEXP) -> Result<Self, Self::Error> {
42                named_list_to_map(sexp, $create)
43            }
44        }
45    };
46}
47
48#[doc = r" Convert R named list (VECSXP) to HashMap<String, V>."]
#[doc = r""]
#[doc =
r" See `named_list_to_map` for NA/empty name handling (elements with NA/empty"]
#[doc = r#" names map to key `""` and may silently overwrite each other)."#]
impl<V: TryFromSexp> TryFromSexp for HashMap<String, V> where
    V::Error: Into<SexpError> {
    const NATIVE_BORROW: Option<crate::from_r::NativeBorrow> =
        crate::from_r::NativeBorrow::in_list(V::NATIVE_BORROW);
    type Error = SexpError;
    #[inline]
    fn __mx_has_na(&self) -> bool { self.values().any(V::__mx_has_na) }
    fn try_from_sexp(sexp: SEXP) -> Result<Self, Self::Error> {
        named_list_to_map(sexp, HashMap::with_capacity)
    }
}impl_map_try_from_sexp!(
49    /// Convert R named list (VECSXP) to HashMap<String, V>.
50    ///
51    /// See `named_list_to_map` for NA/empty name handling (elements with NA/empty
52    /// names map to key `""` and may silently overwrite each other).
53    HashMap, HashMap::with_capacity
54);
55#[doc = r" Convert R named list (VECSXP) to BTreeMap<String, V>."]
#[doc = r""]
#[doc =
r" See `named_list_to_map` for NA/empty name handling (elements with NA/empty"]
#[doc = r#" names map to key `""` and may silently overwrite each other)."#]
impl<V: TryFromSexp> TryFromSexp for BTreeMap<String, V> where
    V::Error: Into<SexpError> {
    const NATIVE_BORROW: Option<crate::from_r::NativeBorrow> =
        crate::from_r::NativeBorrow::in_list(V::NATIVE_BORROW);
    type Error = SexpError;
    #[inline]
    fn __mx_has_na(&self) -> bool { self.values().any(V::__mx_has_na) }
    fn try_from_sexp(sexp: SEXP) -> Result<Self, Self::Error> {
        named_list_to_map(sexp, |_| BTreeMap::new())
    }
}impl_map_try_from_sexp!(
56    /// Convert R named list (VECSXP) to BTreeMap<String, V>.
57    ///
58    /// See `named_list_to_map` for NA/empty name handling (elements with NA/empty
59    /// names map to key `""` and may silently overwrite each other).
60    BTreeMap, |_| BTreeMap::new()
61);
62
63/// Helper to convert R named list to a map type.
64///
65/// Returns an error if the list has duplicate non-empty, non-NA names.
66///
67/// # NA and Empty Name Handling
68///
69/// **Warning:** Elements with NA or empty names are converted with key `""`:
70/// - `NA` names become empty string key `""`
71/// - Empty string names `""` stay as `""`
72/// - If multiple elements have NA/empty names, later ones **silently overwrite** earlier ones
73///
74/// This means data loss can occur without error if your list has multiple
75/// unnamed or NA-named elements.
76///
77/// **Example of silent data loss:**
78/// ```r
79/// # In R:
80/// x <- list(a = 1, 2, 3)  # Elements 2 and 3 have empty names
81/// # After conversion, only one of them survives under key ""
82/// ```
83///
84/// If you need all elements regardless of names, use `Vec<(String, V)>` instead,
85/// or convert the list to a vector first.
86fn named_list_to_map<V, M, F>(sexp: SEXP, create_map: F) -> Result<M, SexpError>
87where
88    V: TryFromSexp,
89    V::Error: Into<SexpError>,
90    M: Extend<(String, V)>,
91    F: FnOnce(usize) -> M,
92{
93    let actual = sexp.type_of();
94    if actual != SEXPTYPE::VECSXP {
95        return Err(SexpTypeError {
96            expected: SEXPTYPE::VECSXP,
97            actual,
98        }
99        .into());
100    }
101
102    let len = sexp.len();
103    let mut map = create_map(len);
104
105    // Get names attribute
106    let names = sexp.get_names();
107    let has_names = names.type_of() == SEXPTYPE::STRSXP && names.len() == len;
108
109    // Single-pass: check duplicates AND convert in one loop
110    let mut seen = HashSet::with_capacity(len);
111
112    for i in 0..len {
113        let key = if has_names {
114            let charsxp = names.string_elt(i as crate::R_xlen_t);
115            if charsxp == SEXP::na_string() {
116                String::new()
117            } else {
118                unsafe { try_charsxp_to_str(charsxp) }
119                    .map_err(|e| name_refusal(i, &e))?
120                    .to_owned()
121            }
122        } else {
123            // Use index as key if no names
124            i.to_string()
125        };
126
127        // Check duplicate for non-empty keys
128        if !key.is_empty() && !seen.insert(key.clone()) {
129            return Err(SexpError::DuplicateName(key));
130        }
131
132        let elem = sexp.vector_elt(i as crate::R_xlen_t);
133        let value = V::try_from_sexp(elem).map_err(|e| e.into())?;
134        map.extend(std::iter::once((key, value)));
135    }
136
137    Ok(map)
138}
139
140macro_rules! impl_vec_map_try_from_sexp {
141    ($(#[$meta:meta])* $map_ty:ident) => {
142        $(#[$meta])*
143        impl<V: TryFromSexp> TryFromSexp for Vec<$map_ty<String, V>>
144        where
145            V::Error: Into<SexpError>,
146        {
147            const NATIVE_BORROW: Option<crate::from_r::NativeBorrow> = crate::from_r::NativeBorrow::in_list(<$map_ty<String, V> as TryFromSexp>::NATIVE_BORROW);
148
149    type Error = SexpError;
150
151            fn try_from_sexp(sexp: SEXP) -> Result<Self, Self::Error> {
152                list_to_vec_of_maps::<$map_ty<String, V>>(sexp)
153            }
154        }
155    };
156}
157
158#[doc = r" Convert R list of named lists to `Vec<HashMap<String, V>>`."]
impl<V: TryFromSexp> TryFromSexp for Vec<HashMap<String, V>> where
    V::Error: Into<SexpError> {
    const NATIVE_BORROW: Option<crate::from_r::NativeBorrow> =
        crate::from_r::NativeBorrow::in_list(<HashMap<String, V> as
                TryFromSexp>::NATIVE_BORROW);
    type Error = SexpError;
    fn try_from_sexp(sexp: SEXP) -> Result<Self, Self::Error> {
        list_to_vec_of_maps::<HashMap<String, V>>(sexp)
    }
}impl_vec_map_try_from_sexp!(
159    /// Convert R list of named lists to `Vec<HashMap<String, V>>`.
160    HashMap
161);
162#[doc = r" Convert R list of named lists to `Vec<BTreeMap<String, V>>`."]
impl<V: TryFromSexp> TryFromSexp for Vec<BTreeMap<String, V>> where
    V::Error: Into<SexpError> {
    const NATIVE_BORROW: Option<crate::from_r::NativeBorrow> =
        crate::from_r::NativeBorrow::in_list(<BTreeMap<String, V> as
                TryFromSexp>::NATIVE_BORROW);
    type Error = SexpError;
    fn try_from_sexp(sexp: SEXP) -> Result<Self, Self::Error> {
        list_to_vec_of_maps::<BTreeMap<String, V>>(sexp)
    }
}impl_vec_map_try_from_sexp!(
163    /// Convert R list of named lists to `Vec<BTreeMap<String, V>>`.
164    BTreeMap
165);
166
167/// Helper to convert R list (VECSXP) to `Vec<M>` where each element is
168/// converted via `M: TryFromSexp`.
169fn list_to_vec_of_maps<M>(sexp: SEXP) -> Result<Vec<M>, SexpError>
170where
171    M: TryFromSexp,
172    M::Error: Into<SexpError>,
173{
174    map_vecsxp_with(sexp, |_i, elem| M::try_from_sexp(elem).map_err(Into::into))
175}
176
177macro_rules! impl_set_try_from_sexp_native {
178    ($set:ident<$t:ty>) => {
179        impl TryFromSexp for $set<$t> {
180            type Error = SexpTypeError;
181
182            fn try_from_sexp(sexp: SEXP) -> Result<Self, Self::Error> {
183                let slice: &[$t] = TryFromSexp::try_from_sexp(sexp)?;
184                Ok(slice.iter().copied().collect())
185            }
186        }
187    };
188}
189
190impl TryFromSexp for HashSet<i32> {
    type Error = SexpTypeError;
    fn try_from_sexp(sexp: SEXP) -> Result<Self, Self::Error> {
        let slice: &[i32] = TryFromSexp::try_from_sexp(sexp)?;
        Ok(slice.iter().copied().collect())
    }
}impl_set_try_from_sexp_native!(HashSet<i32>);
191impl TryFromSexp for HashSet<u8> {
    type Error = SexpTypeError;
    fn try_from_sexp(sexp: SEXP) -> Result<Self, Self::Error> {
        let slice: &[u8] = TryFromSexp::try_from_sexp(sexp)?;
        Ok(slice.iter().copied().collect())
    }
}impl_set_try_from_sexp_native!(HashSet<u8>);
192impl TryFromSexp for HashSet<RLogical> {
    type Error = SexpTypeError;
    fn try_from_sexp(sexp: SEXP) -> Result<Self, Self::Error> {
        let slice: &[RLogical] = TryFromSexp::try_from_sexp(sexp)?;
        Ok(slice.iter().copied().collect())
    }
}impl_set_try_from_sexp_native!(HashSet<RLogical>);
193impl TryFromSexp for BTreeSet<i32> {
    type Error = SexpTypeError;
    fn try_from_sexp(sexp: SEXP) -> Result<Self, Self::Error> {
        let slice: &[i32] = TryFromSexp::try_from_sexp(sexp)?;
        Ok(slice.iter().copied().collect())
    }
}impl_set_try_from_sexp_native!(BTreeSet<i32>);
194impl TryFromSexp for BTreeSet<u8> {
    type Error = SexpTypeError;
    fn try_from_sexp(sexp: SEXP) -> Result<Self, Self::Error> {
        let slice: &[u8] = TryFromSexp::try_from_sexp(sexp)?;
        Ok(slice.iter().copied().collect())
    }
}impl_set_try_from_sexp_native!(BTreeSet<u8>);
195
196macro_rules! impl_vec_try_from_sexp_native {
197    ($t:ty) => {
198        impl TryFromSexp for Vec<$t> {
199            type Error = SexpTypeError;
200
201            fn try_from_sexp(sexp: SEXP) -> Result<Self, Self::Error> {
202                let slice: &[$t] = TryFromSexp::try_from_sexp(sexp)?;
203                Ok(slice.to_vec())
204            }
205        }
206    };
207}
208
209impl TryFromSexp for Vec<i32> {
    type Error = SexpTypeError;
    fn try_from_sexp(sexp: SEXP) -> Result<Self, Self::Error> {
        let slice: &[i32] = TryFromSexp::try_from_sexp(sexp)?;
        Ok(slice.to_vec())
    }
}impl_vec_try_from_sexp_native!(i32);
210impl TryFromSexp for Vec<f64> {
    type Error = SexpTypeError;
    fn try_from_sexp(sexp: SEXP) -> Result<Self, Self::Error> {
        let slice: &[f64] = TryFromSexp::try_from_sexp(sexp)?;
        Ok(slice.to_vec())
    }
}impl_vec_try_from_sexp_native!(f64);
211impl TryFromSexp for Vec<u8> {
    type Error = SexpTypeError;
    fn try_from_sexp(sexp: SEXP) -> Result<Self, Self::Error> {
        let slice: &[u8] = TryFromSexp::try_from_sexp(sexp)?;
        Ok(slice.to_vec())
    }
}impl_vec_try_from_sexp_native!(u8);
212impl TryFromSexp for Vec<RLogical> {
    type Error = SexpTypeError;
    fn try_from_sexp(sexp: SEXP) -> Result<Self, Self::Error> {
        let slice: &[RLogical] = TryFromSexp::try_from_sexp(sexp)?;
        Ok(slice.to_vec())
    }
}impl_vec_try_from_sexp_native!(RLogical);
213impl TryFromSexp for Vec<crate::Rcomplex> {
    type Error = SexpTypeError;
    fn try_from_sexp(sexp: SEXP) -> Result<Self, Self::Error> {
        let slice: &[crate::Rcomplex] = TryFromSexp::try_from_sexp(sexp)?;
        Ok(slice.to_vec())
    }
}impl_vec_try_from_sexp_native!(crate::Rcomplex);
214// endregion