Module neon::types::extract

source ·
Expand description

Traits and utilities for extract Rust data from JavaScript values.

The full list of included extractors can be found on TryFromJs.

§Extracting Handles

JavaScript arguments may be extracted into a Rust tuple.

fn greet(mut cx: FunctionContext) -> JsResult<JsString> {
    let (greeting, name): (Handle<JsString>, Handle<JsString>) = cx.args()?;
    let message = format!("{}, {}!", greeting.value(&mut cx), name.value(&mut cx));

    Ok(cx.string(message))
}

§Extracting Native Types

It’s also possible to extract directly into native Rust types instead of a Handle.

fn add(mut cx: FunctionContext) -> JsResult<JsNumber> {
    let (a, b): (f64, f64) = cx.args()?;

    Ok(cx.number(a + b))
}

§Extracting Option

It’s also possible to mix Handle, Rust types, and even Option for handling null and undefined.

fn get_or_default(mut cx: FunctionContext) -> JsResult<JsValue> {
    let (n, default_value): (Option<f64>, Handle<JsValue>) = cx.args()?;

    if let Some(n) = n {
        return Ok(cx.number(n).upcast());
    }

    Ok(default_value)
}

§Additional Extractors

In some cases, the expected JavaScript type is ambiguous. For example, when trying to extract an f64, the argument may be a Date instead of a number. Newtype extractors are provided to help.


fn add_hours(mut cx: FunctionContext) -> JsResult<JsDate> {
    const MS_PER_HOUR: f64 = 60.0 * 60.0 * 1000.0;

    let (Date(date), hours): (Date, f64) = cx.args()?;
    let date = date + hours * MS_PER_HOUR;

    cx.date(date).or_throw(&mut cx)
}

§Overloaded Functions

It’s common in JavaScript to overload function signatures. This can be implemented with FunctionContext::args_opt or Context::try_catch.


fn add(mut cx: FunctionContext, a: f64, b: f64) -> Handle<JsNumber> {
    cx.number(a + b)
}

fn concat(mut cx: FunctionContext, a: String, b: String) -> Handle<JsString> {
    cx.string(a + &b)
}

fn combine(mut cx: FunctionContext) -> JsResult<JsValue> {
    if let Some((a, b)) = cx.args_opt()? {
        return Ok(add(cx, a, b).upcast());
    }

    let (a, b) = cx.args()?;

    Ok(concat(cx, a, b).upcast())
}

Note well, in this example, type annotations are not required on the tuple because Rust is able to infer it from the type arguments on add and concat.

Structs§

Traits§

  • Trait specifying values that may be extracted from function arguments.
  • Extract Rust data from a JavaScript value