neon-bindings / neon

Rust bindings for writing safe and fast native Node.js modules.
https://www.neon-bindings.com/
Apache License 2.0
8.01k stars 283 forks source link

Expose Map #1072

Open touilleMan opened 3 days ago

touilleMan commented 3 days ago

The Map object type seems to be missing from the bindings.

Given it requires the use of new to be instantiated (just like e.g. Promise), I guess it should be exposed in those bindings.

I'm currently trying to create an instance of Map with the bindings, but it seems rather complex since using new requires to to use the napi unsafe api... is there something I've missed here ?

My current solution is to use the eval function to create the Map, which is a bit wasteful ^^

        let new_map_code = cx.string("(function() { return new Map(); })");
        let js_map = neon::reflect::eval(cx, new_map_code)?.downcast_or_throw::<JsObject, _>(cx)?;

So would you accept a PR to add Map in the bindings ?

kjvalencik commented 3 days ago

This would be a great addition and I would be open to merging it as a feature. We tend to limit our features to those that are available through the Node-API and map is not (Promise is). With that said, Map is a global and we already have the utilities to construct globals.

let map = cx.global::<JsFunction>("Map")?
    .construct_with(&cx)
    .apply::<JsObject, _>(&mut cx)?;

We could have a JsMap type by checking instanceof of checks. Unfortunately, because there aren't Node-API bindings, we would still need to do property lookups in order to invoke methods.

It's all possible, just going to be a bit heavy on the FFI cost.