use std::ffi::CString;
use savvy_ffi::{R_GlobalEnv, R_NilValue, Rboolean_TRUE, SEXP};
const THE_SENTINEL_VALUE: SEXP = std::ptr::null_mut() as SEXP;
use crate::{Sexp, savvy_err};
use super::utils::str_to_symsxp;
pub struct EnvironmentSexp(pub SEXP);
impl EnvironmentSexp {
#[inline]
pub fn inner(&self) -> savvy_ffi::SEXP {
self.0
}
pub fn get<T: AsRef<str>>(&self, name: T) -> crate::error::Result<Option<crate::Sexp>> {
let sym = str_to_symsxp(name)?.ok_or(savvy_err!("name must not be empty"))?;
let sexp = unsafe {
crate::unwind_protect(|| {
if savvy_ffi::R_existsVarInFrame(self.0, sym) == Rboolean_TRUE {
savvy_ffi::Rf_eval(sym, self.0)
} else {
THE_SENTINEL_VALUE
}
})?
};
if sexp == THE_SENTINEL_VALUE {
Ok(None)
} else {
Ok(Some(Sexp(sexp)))
}
}
pub fn contains<T: AsRef<str>>(&self, name: T) -> crate::error::Result<bool> {
let sym = str_to_symsxp(name)?.ok_or(savvy_err!("name must not be empty"))?;
let res = unsafe {
crate::unwind_protect(|| {
if savvy_ffi::R_existsVarInFrame(self.0, sym) == Rboolean_TRUE {
THE_SENTINEL_VALUE
} else {
R_NilValue
}
})? == THE_SENTINEL_VALUE
};
Ok(res)
}
pub fn set<T: AsRef<str>>(&self, name: T, value: Sexp) -> crate::error::Result<()> {
let name_cstr = CString::new(name.as_ref())?;
unsafe {
crate::unwind_protect(|| {
savvy_ffi::Rf_defineVar(savvy_ffi::Rf_install(name_cstr.as_ptr()), value.0, self.0);
R_NilValue
})?
};
Ok(())
}
pub fn global_env() -> Self {
Self(unsafe { R_GlobalEnv })
}
}
impl TryFrom<Sexp> for EnvironmentSexp {
type Error = crate::error::Error;
fn try_from(value: Sexp) -> crate::error::Result<Self> {
value.assert_environment()?;
Ok(Self(value.0))
}
}
impl From<EnvironmentSexp> for Sexp {
fn from(value: EnvironmentSexp) -> Self {
Self(value.inner())
}
}
impl From<EnvironmentSexp> for crate::error::Result<Sexp> {
fn from(value: EnvironmentSexp) -> Self {
Ok(<Sexp>::from(value))
}
}