use std::cell::{RefCell, Ref, RefMut};
use std::cmp::PartialEq;
use emacs_module::emacs_value;
use crate::{subr, Env, Result, FromLisp, Transfer};
#[derive(Debug, Clone, Copy)]
pub struct Value<'e> {
pub(crate) raw: emacs_value,
pub env: &'e Env,
}
impl<'e> Value<'e> {
#[doc(hidden)]
pub unsafe fn new(raw: emacs_value, env: &'e Env) -> Self {
Self { raw, env }
}
#[doc(hidden)]
#[inline]
pub fn protect(self) -> Self {
let Self { env, raw } = self;
if let Some(protected) = &env.protected {
protected.borrow_mut().push(unsafe_raw_call_no_exit!(env, make_global_ref, raw));
}
self
}
pub fn is_not_nil(&self) -> bool {
let env = self.env;
unsafe_raw_call_no_exit!(env, is_not_nil, self.raw)
}
#[deprecated(since = "0.20.0", note = "Please use `==` instead")]
#[allow(clippy::should_implement_trait)]
pub fn eq(&self, other: Value<'e>) -> bool {
let env = self.env;
unsafe_raw_call_no_exit!(env, eq, self.raw, other.raw)
}
#[inline(always)]
pub fn into_rust<T: FromLisp<'e>>(self) -> Result<T> {
FromLisp::from_lisp(self)
}
#[inline]
pub fn into_ref<T: 'static>(self) -> Result<Ref<'e, T>> {
let container: &RefCell<T> = self.into_rust()?;
Ok(container.try_borrow()?)
}
#[inline]
pub fn into_ref_mut<T: 'static>(self) -> Result<RefMut<'e, T>> {
let container: &RefCell<T> = self.into_rust()?;
Ok(container.try_borrow_mut()?)
}
pub unsafe fn get_mut<T: Transfer>(&mut self) -> Result<&mut T> {
self.get_raw_pointer().map(|r| &mut *r)
}
pub fn car<T: FromLisp<'e>>(self) -> Result<T> {
self.env.call(subr::car, (self,))?.into_rust()
}
pub fn cdr<T: FromLisp<'e>>(self) -> Result<T> {
self.env.call(subr::cdr, (self,))?.into_rust()
}
}
impl<'e> PartialEq for Value<'e> {
fn eq(&self, other: &Self) -> bool {
unsafe_raw_call_no_exit!(self.env, eq, self.raw, other.raw)
}
}