Skip to content

Add AsHandleValue trait to safely convert Heap<Value> to HandleValue #592

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions mozjs/src/gc/root.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ use std::ops::Deref;
use std::ptr;

use crate::jsapi::{jsid, JSContext, JSFunction, JSObject, JSScript, JSString, Symbol, Value, JS};
use mozjs_sys::jsapi::JS::Heap;
use mozjs_sys::jsgc::{RootKind, Rooted};

use crate::jsapi::Handle as RawHandle;
Expand Down Expand Up @@ -197,6 +198,23 @@ impl<'a, T> Deref for Handle<'a, T> {
}
}

/// Allows safe and ergonomic conversion of a rooted `Heap<Value>` into a `HandleValue`.
///
/// This avoids repeating unsafe `from_raw` conversions at call sites,
/// and ensures the lifetime is tied to the borrow of the `Heap<Value>`.
pub trait AsHandleValue<'a> {
fn as_handle_value(&'a self) -> HandleValue<'a>;
}

impl<'a> AsHandleValue<'a> for Heap<Value> {
#[allow(unsafe_code)]
fn as_handle_value(&'a self) -> HandleValue<'a> {
// SAFETY: The value is rooted and kept alive by the `Heap<Value>`,
// making it safe to convert to a `HandleValue` and pass to SpiderMonkey.
unsafe { HandleValue::from_raw(self.handle()) }
}
}

impl<'a, T> MutableHandle<'a, T> {
pub unsafe fn from_marked_location(ptr: *mut T) -> Self {
MutableHandle::new(&mut *ptr)
Expand Down
Loading