denoland / rusty_v8

Rust bindings for the V8 JavaScript engine
https://crates.io/crates/v8
MIT License
3.13k stars 300 forks source link

chore: Add a couple convenience casting functions to `v8::Local` #1533

Closed nathanwhit closed 1 month ago

nathanwhit commented 1 month ago

Adds cast and try_cast methods to v8::Local, to make casting more ergonomic. There was already an existing cast function on Local, which did an unchecked cast. This PR renames the old cast to cast_unchecked for clarity (and so we can repurpose cast).

Currently, to go from v8::Local<A> to v8::Local<B>, in order to guide type inference you often end up writing

v8::Local::<v8::Function>::try_from(v8_value);

// try_into is no better because you can't easily give a type annotation
let func: v8::Local<v8::Function> = v8_value.try_into().unwrap();

We have > 100 instances of this in test_api.rs alone, and deno is similar.

With this PR, you can instead use the turbofish the give the type annotation


if let Ok(func) = v8_value.try_cast::<v8::Function>() {
// do stuff
}

// shorthand, panics if cast fails
v8_value.cast::<v8::Function>();

This plays much more nicely with chaining methods, and is less verbose.