Skip to content

Commit

Permalink
Access to raw v8::Context slots (denoland#1092)
Browse files Browse the repository at this point in the history
Co-authored-by: Bartek Iwańczuk <[email protected]>
  • Loading branch information
littledivy and bartlomieju authored Oct 18, 2022
1 parent c06986c commit 8a3a049
Show file tree
Hide file tree
Showing 2 changed files with 67 additions and 0 deletions.
27 changes: 27 additions & 0 deletions src/context.rs
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@ extern "C" {

impl Context {
const ANNEX_SLOT: c_int = 1;
const INTERNAL_SLOT_COUNT: c_int = 1;

/// Creates a new context.
#[inline(always)]
Expand Down Expand Up @@ -307,6 +308,32 @@ impl Context {
}
}

#[inline(always)]
pub unsafe fn set_aligned_pointer_in_embedder_data(
&self,
slot: i32,
data: *mut c_void,
) {
v8__Context__SetAlignedPointerInEmbedderData(
self,
slot + Self::INTERNAL_SLOT_COUNT,
data,
)
}

#[inline(always)]
pub fn get_aligned_pointer_from_embedder_data(
&self,
slot: i32,
) -> *mut c_void {
unsafe {
v8__Context__GetAlignedPointerFromEmbedderData(
self,
slot + Self::INTERNAL_SLOT_COUNT,
)
}
}

/// Create a new context from a (non-default) context snapshot. There
/// is no way to provide a global object template since we do not create
/// a new global object from template, but we can reuse a global object.
Expand Down
40 changes: 40 additions & 0 deletions tests/test_api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7674,6 +7674,46 @@ fn isolate_data_slots() {
assert_eq!(actual1, expected1);
}

#[test]
fn context_embedder_data() {
let _setup_guard = setup();
let isolate = &mut v8::Isolate::new(Default::default());
let global_context;

let expected0 = "Bla";
let expected1 = 123.456f64;
{
let scope = &mut v8::HandleScope::new(isolate);
let context = v8::Context::new(scope);

unsafe {
context.set_aligned_pointer_in_embedder_data(
0,
&expected0 as *const _ as *mut &str as *mut c_void,
);
context.set_aligned_pointer_in_embedder_data(
1,
&expected1 as *const _ as *mut f64 as *mut c_void,
);
}

global_context = v8::Global::new(scope, context);
}

{
let scope = &mut v8::HandleScope::new(isolate);
let context = global_context.open(scope);
let actual0 =
context.get_aligned_pointer_from_embedder_data(0) as *mut &str;
let actual0 = unsafe { *actual0 };
assert_eq!(actual0, expected0);

let actual1 = context.get_aligned_pointer_from_embedder_data(1) as *mut f64;
let actual1 = unsafe { *actual1 };
assert_eq!(actual1, expected1);
}
}

#[test]
fn host_create_shadow_realm_context_callback() {
let _setup_guard = setup();
Expand Down

0 comments on commit 8a3a049

Please sign in to comment.