pub trait FromV8<'a>: Sized {
type Error: Error + Send + Sync + 'static;
// Required method
fn from_v8(
scope: &mut HandleScope<'a>,
value: Local<'a, Value>,
) -> Result<Self, Self::Error>;
}
Expand description
A conversion from a v8 value to a rust value.
When writing a op, or otherwise writing a function in Rust called
from JS, arguments passed from JS are represented as v8::Local<v8::Value>>
.
To convert these values into custom Rust types, you can implement the FromV8
trait.
Once you’ve implemented this trait, you can use the #[from_v8]
attribute
to tell the op2
macro to use your implementation to convert the argument
to the desired type.
§Example
ⓘ
use deno_core::FromV8;
use deno_core::convert::Smi;
use deno_core::op2;
struct Foo(i32);
impl<'a> FromV8<'a> for Foo {
// This conversion can fail, so we use `deno_core::error::StdAnyError` as the error type.
// Any error type that implements `std::error::Error` can be used here.
type Error = deno_core::error::StdAnyError;
fn from_v8(scope: &mut v8::HandleScope<'a>, value: v8::Local<'a, v8::Value>) -> Result<Self, Self::Error> {
/// We expect this value to be a `v8::Integer`, so we use the [`Smi`][deno_core::convert::Smi] wrapper type to convert it.
Smi::from_v8(scope, value).map(|Smi(v)| Foo(v))
}
}
// using the `#[from_v8]` attribute tells the `op2` macro to call this implementation.
#[op2]
fn op_foo(#[from_v8] foo: Foo) {
let Foo(_) = foo;
}
Required Associated Types§
Required Methods§
Dyn Compatibility§
This trait is not dyn compatible.
In older versions of Rust, dyn compatibility was called "object safety", so this trait is not object safe.