use sys::JSContextGetGlobalObject;
use crate::{sys, JSClass, JSContext, JSContextGroup, JSException, JSObject, JSString, JSValue};
use std::ptr;
impl JSContext {
pub const unsafe fn from_raw(raw: sys::JSGlobalContextRef) -> Self {
Self { raw }
}
pub fn new() -> Self {
Self::default()
}
pub fn new_with_class(global_object_class: &JSClass) -> Self {
unsafe { Self::from_raw(sys::JSGlobalContextCreate(global_object_class.raw)) }
}
pub fn group(&self) -> JSContextGroup {
let group = unsafe { sys::JSContextGetGroup(self.raw) };
unsafe {
sys::JSContextGroupRetain(group);
};
JSContextGroup { raw: group }
}
pub fn name(&self) -> Option<JSString> {
let result = unsafe { sys::JSGlobalContextCopyName(self.raw) };
if result.is_null() {
None
} else {
Some(JSString { raw: result })
}
}
pub fn set_name<S: Into<JSString>>(&self, name: S) {
unsafe { sys::JSGlobalContextSetName(self.raw, name.into().raw) }
}
pub fn global_object(&self) -> Result<JSObject, JSException> {
let global_object = unsafe { JSContextGetGlobalObject(self.raw) };
if global_object.is_null() {
Err(unsafe { JSValue::from_raw(self.raw, global_object) }.into())
} else {
Ok(unsafe { JSObject::from_raw(self.raw, global_object) })
}
}
}
impl Default for JSContext {
fn default() -> Self {
unsafe { Self::from_raw(sys::JSGlobalContextCreate(ptr::null_mut())) }
}
}
impl Drop for JSContext {
fn drop(&mut self) {
unsafe { sys::JSGlobalContextRelease(self.raw) }
}
}
#[cfg(test)]
mod tests {
use crate::JSContext;
#[test]
fn context_group() {
let ctx = JSContext::new();
let _g = ctx.group();
}
#[test]
fn context_names() {
let ctx = JSContext::new();
assert!(ctx.name().is_none());
ctx.set_name("test thread");
assert_eq!(ctx.name().unwrap(), "test thread");
}
#[test]
fn global_object() {
let ctx = JSContext::new();
let global_object = ctx.global_object().unwrap();
let some_property = global_object.get_property("Array");
assert!(!some_property.is_undefined());
}
}