-
Notifications
You must be signed in to change notification settings - Fork 285
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
Add neon::types::JsMap #1080
Draft
touilleMan
wants to merge
2
commits into
neon-bindings:main
Choose a base branch
from
touilleMan:js-map-object
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Draft
Add neon::types::JsMap #1080
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,170 @@ | ||
use crate::{ | ||
context::{internal::Env, Context, Cx}, handle::{internal::TransparentNoCopyWrapper, Handle, Root}, object::Object, result::{JsResult, NeonResult}, sys::raw, thread::LocalKey, types::{private, JsFunction, JsObject, Value} | ||
}; | ||
|
||
use super::extract::{TryFromJs, TryIntoJs}; | ||
|
||
#[derive(Debug)] | ||
#[repr(transparent)] | ||
/// The type of JavaScript | ||
/// [`Map`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map) | ||
/// objects. | ||
pub struct JsMap(raw::Local); | ||
|
||
impl JsMap { | ||
pub fn new<'cx>(cx: &mut Cx<'cx>) -> NeonResult<Handle<'cx, Self>> { | ||
let map = cx | ||
.global::<JsFunction>("Map")? | ||
.construct_with(cx) | ||
.apply::<JsObject, _>(cx)?; | ||
|
||
Ok(map.downcast_or_throw(cx)?) | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. FYI, downcasting is necessary. Since it's possible to override global.Map = function Map() {
return new Array();
};
new Map() instanceof Map
// false |
||
} | ||
|
||
pub fn size(&self, cx: &mut Cx) -> NeonResult<f64> { | ||
self.prop(cx, "size").get() | ||
} | ||
|
||
pub fn clear(&self, cx: &mut Cx) -> NeonResult<()> { | ||
self.method(cx, "clear")?.call() | ||
} | ||
|
||
pub fn delete<'cx, K>( | ||
&self, | ||
cx: &mut Cx<'cx>, | ||
key: K, | ||
) -> NeonResult<bool> | ||
where K: TryIntoJs<'cx> { | ||
self.method(cx, "delete")?.arg(key)?.call() | ||
} | ||
|
||
pub fn entries<'cx, R>(&self, cx: &mut Cx<'cx>) -> NeonResult<R> | ||
where R: TryFromJs<'cx> | ||
{ | ||
self.method(cx, "entries")?.call() | ||
} | ||
|
||
pub fn for_each<'cx, F, R>( | ||
&self, | ||
cx: &mut Cx<'cx>, | ||
cb: F, | ||
) -> NeonResult<R> | ||
where F: TryIntoJs<'cx>, R: TryFromJs<'cx> | ||
{ | ||
self.method(cx, "forEach")?.arg(cb)?.call() | ||
} | ||
|
||
pub fn get<'cx, K, R>( | ||
&self, | ||
cx: &mut Cx<'cx>, | ||
key: K, | ||
) -> NeonResult<R> | ||
where | ||
K: TryIntoJs<'cx>, | ||
R: TryFromJs<'cx> | ||
{ | ||
self.method(cx, "get")?.arg(key)?.call() | ||
} | ||
|
||
pub fn has<'cx, K>( | ||
&self, | ||
cx: &mut Cx<'cx>, | ||
key: K, | ||
) -> NeonResult<bool> | ||
where | ||
K: TryIntoJs<'cx>, | ||
{ | ||
self.method(cx, "has")?.arg(key)?.call() | ||
} | ||
|
||
pub fn keys<'cx, R>(&self, cx: &mut Cx<'cx>) -> NeonResult<R> | ||
where | ||
R: TryFromJs<'cx> | ||
{ | ||
self.method(cx, "keys")?.call() | ||
} | ||
|
||
pub fn set<'cx, K, V>( | ||
&self, | ||
cx: &mut Cx<'cx>, | ||
key: K, | ||
value: V, | ||
) -> NeonResult<Handle<'cx, JsMap>> | ||
where | ||
K: TryIntoJs<'cx>, | ||
V: TryIntoJs<'cx> | ||
{ | ||
self.method(cx, "set")?.arg(key)?.arg(value)?.call() | ||
} | ||
|
||
pub fn values<'cx, R>(&self, cx: &mut Cx<'cx>) -> NeonResult<R> | ||
where | ||
R: TryFromJs<'cx> | ||
{ | ||
self.method(cx, "values")?.call() | ||
} | ||
|
||
pub fn group_by<'cx, A, B, R>( | ||
cx: &mut Cx<'cx>, | ||
elements: A, | ||
cb: B, | ||
) -> NeonResult<R> | ||
where | ||
A: TryIntoJs<'cx>, | ||
B: TryIntoJs<'cx>, | ||
R: TryFromJs<'cx> | ||
{ | ||
// TODO: This is broken and leads to a `failed to downcast any to object` error | ||
// when trying to downcast `Map.groupBy` into a `JsFunction`... | ||
cx.global::<JsObject>("Map")? | ||
.method(cx, "groupBy")? | ||
.arg(elements)? | ||
.arg(cb)? | ||
.call() | ||
} | ||
} | ||
|
||
unsafe impl TransparentNoCopyWrapper for JsMap { | ||
type Inner = raw::Local; | ||
|
||
fn into_inner(self) -> Self::Inner { | ||
self.0 | ||
} | ||
} | ||
|
||
impl private::ValueInternal for JsMap { | ||
fn name() -> &'static str { | ||
"Map" | ||
} | ||
|
||
fn is_typeof<Other: Value>(env: Env, other: &Other) -> bool { | ||
Cx::with_context(env, |mut cx| { | ||
let ctor = map_constructor(&mut cx).unwrap(); | ||
other.instance_of(&mut cx, &*ctor) | ||
}) | ||
} | ||
|
||
fn to_local(&self) -> raw::Local { | ||
self.0 | ||
} | ||
|
||
unsafe fn from_local(_env: Env, h: raw::Local) -> Self { | ||
Self(h) | ||
} | ||
} | ||
|
||
impl Value for JsMap {} | ||
|
||
impl Object for JsMap {} | ||
|
||
fn global_map_constructor<'cx>(cx: &mut Cx<'cx>) -> JsResult<'cx, JsFunction> { | ||
cx.global::<JsFunction>("Map") | ||
} | ||
|
||
fn map_constructor<'cx>(cx: &mut Cx<'cx>) -> JsResult<'cx, JsFunction> { | ||
static MAP_CONSTRUCTOR: LocalKey<Root<JsFunction>> = LocalKey::new(); | ||
|
||
MAP_CONSTRUCTOR | ||
.get_or_try_init(cx, |cx| global_map_constructor(cx).map(|f| f.root(cx))) | ||
.map(|f| f.to_inner(cx)) | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,151 @@ | ||
var addon = require(".."); | ||
var assert = require("chai").assert; | ||
|
||
describe("JsMap", function () { | ||
it("return a JsMap built in Rust", function () { | ||
assert.deepEqual(new Map(), addon.return_js_map()); | ||
}); | ||
|
||
it("return a JsMap with a number as keys and values", function () { | ||
assert.deepEqual( | ||
new Map([ | ||
[1, 1000], | ||
[-1, -1000], | ||
]), | ||
addon.return_js_map_with_number_as_keys_and_values() | ||
); | ||
}); | ||
|
||
it("return a JsMap with heterogeneous keys/values", function () { | ||
assert.deepEqual( | ||
new Map([ | ||
["a", 1], | ||
[26, "z"], | ||
]), | ||
addon.return_js_map_with_heterogeneous_keys_and_values() | ||
); | ||
}); | ||
|
||
it("can read from a JsMap", function () { | ||
const map = new Map([ | ||
[1, "a"], | ||
[2, "b"], | ||
]); | ||
assert.strictEqual(addon.read_js_map(map, 2), "b"); | ||
}); | ||
|
||
it("can get size from a JsMap", function () { | ||
const map = new Map([ | ||
[1, "a"], | ||
[2, "b"], | ||
]); | ||
assert.strictEqual(addon.get_js_map_size(map), 2); | ||
assert.strictEqual(addon.get_js_map_size(new Map()), 0); | ||
}); | ||
|
||
it("can modify a JsMap", function () { | ||
const map = new Map([[1, "a"]]); | ||
addon.modify_js_map(map, 2, "b"); | ||
assert.deepEqual( | ||
map, | ||
new Map([ | ||
[1, "a"], | ||
[2, "b"], | ||
]) | ||
); | ||
}); | ||
|
||
it("returns undefined when accessing outside JsMap bounds", function () { | ||
assert.strictEqual(addon.read_js_map(new Map(), "x"), undefined); | ||
}); | ||
|
||
it("can clear a JsMap", function () { | ||
const map = new Map([[1, "a"]]); | ||
addon.clear_js_map(map); | ||
assert.deepEqual(map, new Map()); | ||
}); | ||
|
||
it("can delete key from JsMap", function () { | ||
const map = new Map([ | ||
[1, "a"], | ||
["z", 26], | ||
]); | ||
|
||
assert.strictEqual(addon.delete_js_map(map, "unknown"), false); | ||
assert.deepEqual( | ||
map, | ||
new Map([ | ||
[1, "a"], | ||
["z", 26], | ||
]) | ||
); | ||
|
||
assert.strictEqual(addon.delete_js_map(map, 1), true); | ||
assert.deepEqual(map, new Map([["z", 26]])); | ||
|
||
assert.strictEqual(addon.delete_js_map(map, "z"), true); | ||
assert.deepEqual(map, new Map()); | ||
}); | ||
|
||
it("can use `has` on JsMap", function () { | ||
const map = new Map([ | ||
[1, "a"], | ||
["z", 26], | ||
]); | ||
|
||
assert.strictEqual(addon.has_js_map(map, 1), true); | ||
assert.strictEqual(addon.has_js_map(map, "z"), true); | ||
assert.strictEqual(addon.has_js_map(map, "unknown"), false); | ||
}); | ||
|
||
it("can use `forEach` on JsMap", function () { | ||
const map = new Map([ | ||
[1, "a"], | ||
["z", 26], | ||
]); | ||
const collected = []; | ||
|
||
assert.strictEqual( | ||
addon.for_each_js_map(map, (value, key, map) => { | ||
collected.push([key, value, map]); | ||
}), | ||
undefined | ||
); | ||
|
||
assert.deepEqual(collected, [ | ||
[1, "a", map], | ||
["z", 26, map], | ||
]); | ||
}); | ||
|
||
it("can use `groupBy` on JsMap", function () { | ||
const inventory = [ | ||
{ name: "asparagus", type: "vegetables", quantity: 9 }, | ||
{ name: "bananas", type: "fruit", quantity: 5 }, | ||
{ name: "goat", type: "meat", quantity: 23 }, | ||
{ name: "cherries", type: "fruit", quantity: 12 }, | ||
{ name: "fish", type: "meat", quantity: 22 }, | ||
]; | ||
|
||
const restock = { restock: true }; | ||
const sufficient = { restock: false }; | ||
const result = addon.group_by_js_map(inventory, ({ quantity }) => | ||
quantity < 6 ? restock : sufficient | ||
); | ||
assert.deepEqual( | ||
result, | ||
new Map([ | ||
[restock, [{ name: "bananas", type: "fruit", quantity: 5 }]], | ||
[ | ||
sufficient, | ||
[ | ||
{ name: "asparagus", type: "vegetables", quantity: 9 }, | ||
{ name: "goat", type: "meat", quantity: 23 }, | ||
{ name: "cherries", type: "fruit", quantity: 12 }, | ||
{ name: "fish", type: "meat", quantity: 22 }, | ||
], | ||
], | ||
]) | ||
); | ||
}); | ||
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This is awesome! Thanks for adding it. I think we should add it as a method on the
Value
trait.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Would you mind opening a separate PR to implement this? It's a great feature and we can get it merged pretty quick.
I'm happy to pick it up if you prefer.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Done, I've also added a dedicated test