miniextendr_api/
factor.rs1use std::ops::Deref;
27use std::sync::OnceLock;
28
29use crate::altrep_traits::NA_INTEGER;
30use crate::from_r::{
31 BatchedErrors, SexpError, SexpLengthError, SexpNaError, TryFromSexp, charsxp_to_cow_lossy,
32};
33use crate::gc_protect::OwnedProtect;
34use crate::into_r::IntoR;
35use crate::sys::Rf_allocVector;
36use crate::{IsNA, SEXP, SEXPTYPE, SexpExt};
37
38static FACTOR_CLASS: OnceLock<SEXP> = OnceLock::new();
41
42pub(crate) fn factor_class_sexp() -> SEXP {
43 *FACTOR_CLASS.get_or_init(|| build_levels_sexp_cached(&["factor"]))
44}
45pub trait RFactor: crate::match_arg::MatchArg + Copy + 'static {
54 fn to_level_index(self) -> i32;
56
57 fn from_level_index(idx: i32) -> Option<Self>;
59}
60pub fn build_levels_sexp(levels: &[&str]) -> SEXP {
74 build_levels_sexp_protected(levels).get()
75}
76
77fn build_levels_sexp_protected(levels: &[&str]) -> OwnedProtect {
79 if levels.iter().any(|level| level.as_bytes().contains(&0)) {
82 {
::core::panicking::panic_fmt(format_args!("level name contains null byte"));
};panic!("level name contains null byte");
83 }
84 let len = levels.len().try_into().expect("too many factor levels");
85 unsafe {
86 let sexp = OwnedProtect::new(Rf_allocVector(SEXPTYPE::STRSXP, len));
87 for (i, level) in (0..len).zip(levels) {
88 sexp.set_string_elt(i, SEXP::charsxp(level));
91 }
92 sexp
93 }
94}
95
96pub fn build_levels_sexp_cached(levels: &[&str]) -> SEXP {
98 unsafe {
99 let sexp = build_levels_sexp_protected(levels);
100 crate::sys::R_PreserveObject(sexp.get());
101 sexp.get()
102 }
103}
104
105pub fn build_factor(indices: &[i32], levels: SEXP) -> SEXP {
110 unsafe {
111 let (sexp, dst) = crate::into_r::alloc_r_vector::<i32>(indices.len());
112 let sexp = OwnedProtect::new(sexp);
114 dst.copy_from_slice(indices);
115 sexp.set_levels(levels);
116 sexp.set_class(factor_class_sexp());
117 sexp.get()
118 }
119}
120
121pub fn build_factor_with_levels(indices: &[i32], level_names: &[&str]) -> SEXP {
136 let levels = build_levels_sexp_protected(level_names);
137 build_factor(indices, levels.get())
138}
139pub(crate) fn validate_factor_levels(sexp: SEXP, expected: &[&str]) -> Result<(), SexpError> {
145 if !sexp.is_factor() {
146 return Err(SexpError::InvalidValue("expected a factor".into()));
147 }
148
149 let levels = sexp.get_levels();
150 if levels.type_of() != SEXPTYPE::STRSXP {
151 return Err(SexpError::InvalidValue("levels is not STRSXP".into()));
152 }
153
154 let n = levels.len();
155 if n != expected.len() {
156 return Err(SexpError::InvalidValue(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("expected {0} levels, got {1}",
expected.len(), n))
})format!(
157 "expected {} levels, got {}",
158 expected.len(),
159 n
160 )));
161 }
162
163 for (i, exp) in expected.iter().enumerate() {
164 let charsxp = levels.string_elt(i as isize);
165 let actual = unsafe { charsxp_to_cow_lossy(charsxp) };
166 if actual != *exp {
167 return Err(SexpError::InvalidValue(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("level {0}: expected \'{1}\', got \'{2}\'",
i + 1, exp, actual))
})format!(
168 "level {}: expected '{}', got '{}'",
169 i + 1,
170 exp,
171 actual
172 )));
173 }
174 }
175
176 Ok(())
177}
178fn code_not_a_level(code: i32) -> String {
185 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("code {0} is not a level of the factor",
code))
})format!("code {code} is not a level of the factor")
186}
187
188fn read_factor_codes<U>(
192 sexp: SEXP,
193 elt: impl Fn(i32) -> Result<U, String>,
194) -> Result<Vec<U>, SexpError> {
195 let len = sexp.len();
196 let mut result = Vec::with_capacity(len);
197 let mut errors = BatchedErrors::default();
198 for i in 0..len {
199 match elt(sexp.integer_elt(i as isize)) {
200 Ok(v) => result.push(v),
201 Err(reason) => errors.push(i, || reason),
202 }
203 }
204 if errors.is_empty() {
205 Ok(result)
206 } else {
207 Err(errors.into_element_error())
208 }
209}
210
211#[inline]
213pub fn factor_from_sexp<T: RFactor>(sexp: SEXP) -> Result<T, SexpError> {
214 validate_factor_levels(sexp, T::CHOICES)?;
215
216 let len = sexp.len();
217 if len != 1 {
218 return Err(SexpLengthError {
219 expected: 1,
220 actual: len,
221 }
222 .into());
223 }
224
225 let idx = sexp.integer_elt(0);
226 if idx.is_na() {
227 return Err(SexpNaError {
228 sexp_type: SEXPTYPE::INTSXP,
229 }
230 .into());
231 }
232
233 T::from_level_index(idx).ok_or_else(|| SexpError::InvalidValue(code_not_a_level(idx)))
234}
235
236#[inline]
239pub(crate) fn factor_vec_from_sexp<T: UnitEnumFactor>(sexp: SEXP) -> Result<Vec<T>, SexpError> {
240 validate_factor_levels(sexp, T::FACTOR_LEVELS)?;
241 read_factor_codes(sexp, |idx| {
242 if idx.is_na() {
243 return Err("NA is not allowed".to_string());
244 }
245 T::from_factor_index(idx).ok_or_else(|| code_not_a_level(idx))
246 })
247}
248
249#[inline]
251pub(crate) fn factor_option_vec_from_sexp<T: RFactor>(
252 sexp: SEXP,
253) -> Result<Vec<Option<T>>, SexpError> {
254 validate_factor_levels(sexp, T::CHOICES)?;
255 read_factor_codes(sexp, |idx| {
256 if idx.is_na() {
257 return Ok(None);
258 }
259 T::from_level_index(idx)
260 .map(Some)
261 .ok_or_else(|| code_not_a_level(idx))
262 })
263}
264
265#[inline]
272pub fn unit_factor_option_vec_from_sexp<T: UnitEnumFactor>(
273 sexp: SEXP,
274) -> Result<Vec<Option<T>>, SexpError> {
275 validate_factor_levels(sexp, T::FACTOR_LEVELS)?;
276 read_factor_codes(sexp, |idx| {
277 if idx.is_na() {
278 return Ok(None);
279 }
280 T::from_factor_index(idx)
281 .map(Some)
282 .ok_or_else(|| code_not_a_level(idx))
283 })
284}
285#[derive(#[automatically_derived]impl<T: ::core::fmt::Debug> ::core::fmt::Debug for
FactorVec<T> {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field1_finish(f, "FactorVec",
&&self.0)
}
}Debug, #[automatically_derived]impl<T: ::core::clone::Clone> ::core::clone::Clone for
FactorVec<T> {
#[inline]
fn clone(&self) -> Self {
FactorVec(::core::clone::Clone::clone(&self.0))
}
}Clone)]
294pub struct FactorVec<T>(pub Vec<T>);
295
296impl<T> FactorVec<T> {
297 pub fn new(vec: Vec<T>) -> Self {
299 Self(vec)
300 }
301
302 pub fn into_inner(self) -> Vec<T> {
304 self.0
305 }
306}
307
308impl<T> From<Vec<T>> for FactorVec<T> {
309 fn from(vec: Vec<T>) -> Self {
310 Self(vec)
311 }
312}
313
314impl<T> Deref for FactorVec<T> {
315 type Target = Vec<T>;
316 fn deref(&self) -> &Self::Target {
317 &self.0
318 }
319}
320
321impl<T> std::ops::DerefMut for FactorVec<T> {
322 fn deref_mut(&mut self) -> &mut Self::Target {
323 &mut self.0
324 }
325}
326
327impl<T: UnitEnumFactor> IntoR for FactorVec<T> {
328 type Error = std::convert::Infallible;
329 fn try_into_sexp(self) -> Result<crate::SEXP, Self::Error> {
330 Ok(self.into_sexp())
331 }
332 unsafe fn try_into_sexp_unchecked(self) -> Result<crate::SEXP, Self::Error> {
333 self.try_into_sexp()
334 }
335 fn into_sexp(self) -> SEXP {
336 let indices: Vec<i32> = self.0.into_iter().map(T::to_factor_index).collect();
337 build_factor_with_levels(&indices, T::FACTOR_LEVELS)
340 }
341}
342
343impl<T: UnitEnumFactor> TryFromSexp for FactorVec<T> {
344 type Error = SexpError;
345 const CHARACTER_ONLY: bool = true;
346 fn try_from_sexp(sexp: SEXP) -> Result<Self, Self::Error> {
347 factor_vec_from_sexp(sexp).map(FactorVec)
348 }
349}
350
351#[derive(#[automatically_derived]impl<T: ::core::fmt::Debug> ::core::fmt::Debug for
FactorOptionVec<T> {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field1_finish(f,
"FactorOptionVec", &&self.0)
}
}Debug, #[automatically_derived]impl<T: ::core::clone::Clone> ::core::clone::Clone for
FactorOptionVec<T> {
#[inline]
fn clone(&self) -> Self {
FactorOptionVec(::core::clone::Clone::clone(&self.0))
}
}Clone)]
353pub struct FactorOptionVec<T>(pub Vec<Option<T>>);
354
355impl<T> FactorOptionVec<T> {
356 pub fn new(vec: Vec<Option<T>>) -> Self {
358 Self(vec)
359 }
360
361 pub fn into_inner(self) -> Vec<Option<T>> {
363 self.0
364 }
365}
366
367impl<T> From<Vec<Option<T>>> for FactorOptionVec<T> {
368 fn from(vec: Vec<Option<T>>) -> Self {
369 Self(vec)
370 }
371}
372
373impl<T> Deref for FactorOptionVec<T> {
374 type Target = Vec<Option<T>>;
375 fn deref(&self) -> &Self::Target {
376 &self.0
377 }
378}
379
380impl<T> std::ops::DerefMut for FactorOptionVec<T> {
381 fn deref_mut(&mut self) -> &mut Self::Target {
382 &mut self.0
383 }
384}
385
386impl<T: RFactor + crate::match_arg::MatchArg> UnitEnumFactor for T {
388 const FACTOR_LEVELS: &'static [&'static str] = T::CHOICES;
389 fn to_factor_index(self) -> i32 {
390 self.to_level_index()
391 }
392 fn from_factor_index(idx: i32) -> Option<Self> {
393 T::from_level_index(idx)
394 }
395}
396
397impl<T: RFactor> TryFromSexp for FactorOptionVec<T> {
398 type Error = SexpError;
399 const CHARACTER_ONLY: bool = true;
400 fn try_from_sexp(sexp: SEXP) -> Result<Self, Self::Error> {
401 factor_option_vec_from_sexp(sexp).map(FactorOptionVec)
402 }
403}
404
405pub trait UnitEnumFactor: Sized {
423 const FACTOR_LEVELS: &'static [&'static str];
425
426 fn to_factor_index(self) -> i32;
428
429 fn from_factor_index(idx: i32) -> Option<Self>;
435}
436
437impl<T: UnitEnumFactor> IntoR for FactorOptionVec<T> {
438 type Error = std::convert::Infallible;
439 fn try_into_sexp(self) -> Result<crate::SEXP, Self::Error> {
440 Ok(self.into_sexp())
441 }
442 unsafe fn try_into_sexp_unchecked(self) -> Result<crate::SEXP, Self::Error> {
443 self.try_into_sexp()
444 }
445 fn into_sexp(self) -> SEXP {
446 let indices: Vec<i32> = self
450 .0
451 .into_iter()
452 .map(|opt| match opt {
453 None => NA_INTEGER,
454 Some(v) => v.to_factor_index(),
455 })
456 .collect();
457 build_factor_with_levels(&indices, T::FACTOR_LEVELS)
458 }
459}
460#[cfg(test)]
465mod tests;
466