Skip to content

Commit

Permalink
extendr_enum: Added R_FactorSymbol to have a
Browse files Browse the repository at this point in the history
permanently protected `"factor"` class name to use when
constructing factors.
  • Loading branch information
CGMossa committed Feb 17, 2024
1 parent 9b7c2e5 commit 8e1ba1f
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 4 deletions.
6 changes: 4 additions & 2 deletions extendr-api/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -418,8 +418,10 @@ pub const NA_STRING: Option<&str> = None;
pub const NA_LOGICAL: Rbool = Rbool::na_value();

thread_local! {
pub static R_FACTOR_STRING: once_cell::unsync::Lazy<Robj> = once_cell::unsync::Lazy::new(||{
"factor".into_robj()
#[allow(non_upper_case_globals)]
pub static R_FactorSymbol: once_cell::unsync::Lazy<SEXP> = once_cell::unsync::Lazy::new(||{
let factor_c_string = CString::new("factor").unwrap();
unsafe { libR_sys::Rf_install(factor_c_string.as_ptr()) }
});
}

Expand Down
7 changes: 5 additions & 2 deletions extendr-macros/src/extendr_enum.rs
Original file line number Diff line number Diff line change
Expand Up @@ -110,9 +110,12 @@ pub(crate) fn extendr_enum(item_enum: syn::ItemEnum) -> proc_macro::TokenStream
let strings_enum = once_cell::unsync::Lazy::force(strings_enum);
libR_sys::Rf_setAttrib(robj.get(), libR_sys::R_LevelsSymbol, strings_enum.get());
});
extendr_api::R_FACTOR_STRING.with(|factor_class| {
extendr_api::R_FactorSymbol.with(|factor_class| {
let factor_class = once_cell::unsync::Lazy::force(factor_class);
libR_sys::Rf_setAttrib(robj.get(), libR_sys::R_ClassSymbol, factor_class.get());
// a symbol is permanent, so no need to protect it
// printname is CHARSXP, and we need a STRSXP, hence `Rf_ScalarString`
// doesn't need protection, because it gets inserted into a protected `SEXP` immediately
libR_sys::Rf_setAttrib(robj.get(), libR_sys::R_ClassSymbol, libR_sys::Rf_ScalarString(libR_sys::PRINTNAME(*factor_class)));
});
}
Ok(robj)
Expand Down

0 comments on commit 8e1ba1f

Please sign in to comment.