Skip to content
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

feat(neon): Extractors #997

Closed
wants to merge 1 commit into from
Closed

feat(neon): Extractors #997

wants to merge 1 commit into from

Conversation

kjvalencik
Copy link
Member

Extract Rust data from JavaScript values and arguments.

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

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

@dherman
Copy link
Collaborator

dherman commented Sep 1, 2023

Since you have to return NeonResult for full generality, I do agree that nested Results for the overloading case would be awkward. But I wonder if we should consider a Result<Option> version of args called something like match_args or args_opt. That would allow you to do the overloading example like this:

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())
}

This is slightly more readable IMO, but it also means you're not accidentally suppressing actual JavaScript exceptions that might occur, so it's more correct.

@kjvalencik
Copy link
Member Author

@dherman I'm having a difficult time picturing how that ladders up from the TryFromJs trait. Would we have a specialized error that means "wrong type" that we could use for this? Something like a combination of DowncastResult and Throw?

@kjvalencik
Copy link
Member Author

pub trait TryFromJs<'cx>: Sized {
    type Error: Error + Send + Sync + 'static;

    fn try_from_js<C>(cx: &mut C, v: Handle<'cx, JsValue>) -> NeonResult<Result<Self, Self::Error>>
        where C: Context<'cx>;

    fn from_js<C>(cx: &mut C, v: Handle<'cx, JsValue>) -> NeonResult<Self>
        where C: Context<'cx>
    {
        Self::try_from_js(cx, v)?.or_throw(cx)
    }
}

@kjvalencik kjvalencik closed this Mar 26, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants