oden/oden-js/src/atom.rs

65 lines
1.6 KiB
Rust

use crate::{ContextRef, Runtime, ValueResult};
use oden_js_sys as sys;
use std::marker;
use std::ops::Deref;
pub struct AtomRef<'r> {
pub(crate) atom: sys::JSAtom,
_marker: marker::PhantomData<&'r Runtime>,
}
impl<'r> AtomRef<'r> {
pub(crate) fn from_raw(atom: sys::JSAtom, _ctx: &ContextRef<'r>) -> AtomRef<'r> {
AtomRef {
atom,
_marker: marker::PhantomData,
}
}
pub fn dup(&self, context: &ContextRef<'r>) -> Atom<'r> {
unsafe {
sys::JS_DupAtom(context.ctx, self.atom);
}
Atom::from_raw(self.atom, context)
}
pub fn to_value(&self, context: &ContextRef<'r>) -> ValueResult<'r> {
context.check_exception(unsafe { sys::JS_AtomToValue(context.ctx, self.atom) })
}
pub fn to_string_value(&self, context: &ContextRef<'r>) -> ValueResult<'r> {
context.check_exception(unsafe { sys::JS_AtomToString(context.ctx, self.atom) })
}
}
pub struct Atom<'r> {
atom: AtomRef<'r>,
rt: *mut sys::JSRuntime,
_phantom: marker::PhantomData<&'r Runtime>,
}
impl<'r> Atom<'r> {
pub(crate) fn from_raw(atom: sys::JSAtom, ctx: &ContextRef<'r>) -> Self {
Atom {
atom: AtomRef::from_raw(atom, ctx),
rt: unsafe { sys::JS_GetRuntime(ctx.ctx) },
_phantom: marker::PhantomData,
}
}
}
impl<'r> Deref for Atom<'r> {
type Target = AtomRef<'r>;
fn deref(&self) -> &Self::Target {
&self.atom
}
}
impl<'r> Drop for Atom<'r> {
fn drop(&mut self) {
unsafe {
sys::JS_FreeAtomRT(self.rt, self.atom.atom);
}
}
}