use wry_bindgen_runtime::wire::Runtime as RuntimeState;
use wry_bindgen_runtime::wire::{
DecodedData, EncodedData, JsRef, ObjectBorrowError, ObjectHandle, ObjectRef, ObjectRefMut,
ObjectTakeError,
};
use crate::BatchableResult;
pub struct Runtime<'a> {
backend: &'a mut RuntimeState,
}
impl Runtime<'_> {
pub fn insert_object<T: 'static>(&mut self, obj: T) -> ObjectHandle {
self.backend.insert_object_box(alloc::boxed::Box::new(obj))
}
pub fn object_ref<T: 'static>(
&mut self,
handle: ObjectHandle,
) -> Result<ObjectRef<T>, ObjectBorrowError> {
self.backend.object_ref(handle)
}
pub fn object_mut<T: 'static>(
&mut self,
handle: ObjectHandle,
) -> Result<ObjectRefMut<T>, ObjectBorrowError> {
self.backend.object_mut(handle)
}
pub fn object_is<T: 'static>(&self, handle: ObjectHandle) -> bool {
self.backend.object_is::<T>(handle)
}
pub fn remove_object<T: 'static>(
&mut self,
handle: ObjectHandle,
) -> Result<T, ObjectTakeError> {
self.backend.remove_object_untyped(handle).and_then(|obj| {
obj.downcast::<T>()
.map(|obj| *obj)
.map_err(|_| ObjectTakeError::TypeMismatch)
})
}
pub(crate) fn next_placeholder_ref(&mut self) -> JsRef {
self.backend.next_placeholder_ref()
}
}
pub fn with_runtime<R>(f: impl FnOnce(&mut Runtime) -> R) -> R {
wry_bindgen_runtime::wire::with_runtime(|backend| f(&mut Runtime { backend }))
}
pub(crate) fn with_backend<R>(f: impl FnOnce(&mut RuntimeState) -> R) -> R {
wry_bindgen_runtime::wire::with_runtime(f)
}
pub(crate) fn run_js_sync<R: BatchableResult + 'static>(
fn_id: u32,
add_args: impl FnOnce(&mut EncodedData),
) -> R {
wry_bindgen_runtime::wire::run_js_sync(
fn_id,
add_args,
|backend| R::try_placeholder(&mut Runtime { backend }),
|data: &mut DecodedData<'_>| R::decode(data).expect("Failed to decode return value"),
)
}