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

TryFromJs from JsMap for HashMap & BtreeMap #3998

Merged
merged 6 commits into from
Nov 3, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 32 additions & 0 deletions core/engine/src/builtins/map/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -501,6 +501,38 @@ impl Map {
}
}

/// Call `f` for each `(key, value)` in the `Map`.
///
/// Can not be used in [`Self::for_each`] because in that case will be
/// incorrect order for next steps of the algo:
/// ```txt
/// 2. Perform ? RequireInternalSlot(M, [[MapData]]).
/// 3. If IsCallable(callbackfn) is false, throw a TypeError exception.
/// ```
pub(crate) fn rust_for_each<F>(this: &JsValue, mut f: F) -> JsResult<()>
where
F: FnMut(&JsValue, &JsValue) -> JsResult<()>,
{
// See `Self::for_each` for comments on the algo.

let map = this
.as_object()
.filter(|obj| obj.is::<OrderedMap<JsValue>>())
.ok_or_else(|| JsNativeError::typ().with_message("`this` is not a Map"))?;

let _lock = map
.downcast_mut::<OrderedMap<JsValue>>()
.expect("checked that `this` was a map")
.lock(map.clone());

let map = map
.downcast_ref::<OrderedMap<JsValue>>()
.expect("checked that `this` was a map");

let mut map_iter = map.iter();
map_iter.try_for_each(|(k, v)| f(k, v))
}

/// `Map.prototype.values()`
///
/// Returns a new Iterator object that contains the values for each element in the Map object in insertion order.
Expand Down
10 changes: 10 additions & 0 deletions core/engine/src/object/builtins/jsmap.rs
Original file line number Diff line number Diff line change
Expand Up @@ -402,6 +402,16 @@ impl JsMap {
)
}

/// Executes the provided callback function for each key-value pair within the [`JsMap`].
#[inline]
pub fn rust_for_each<F>(&self, f: F) -> JsResult<()>
nekevss marked this conversation as resolved.
Show resolved Hide resolved
where
F: FnMut(&JsValue, &JsValue) -> JsResult<()>,
{
let this = self.inner.clone().into();
Map::rust_for_each(&this, f)
}

/// Returns a new [`JsMapIterator`] object that yields the `value` for each element within the [`JsMap`] in insertion order.
#[inline]
pub fn values(&self, context: &mut Context) -> JsResult<JsMapIterator> {
Expand Down
2 changes: 1 addition & 1 deletion core/engine/src/value/conversions/try_from_js.rs
Original file line number Diff line number Diff line change
Expand Up @@ -573,7 +573,7 @@ fn js_map_into_rust_map() -> JsResult<()> {
let hash_map = HashMap::<String, i32>::try_from_js(&js_value, &mut context)?;
let btree_map = BTreeMap::<String, i32>::try_from_js(&js_value, &mut context)?;

let expect = vec![("a".into(), 1), ("aboba".into(), 42024), ("b".into(), 3)];
let expect = [("a".into(), 1), ("aboba".into(), 42024), ("b".into(), 3)];

let expected_hash_map: HashMap<String, _> = expect.iter().cloned().collect();
assert_eq!(expected_hash_map, hash_map);
Expand Down
62 changes: 9 additions & 53 deletions core/engine/src/value/conversions/try_from_js/collections.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,7 @@
use std::collections::{BTreeMap, HashMap};
use std::hash::Hash;

use boa_macros::js_str;

use crate::builtins::iterable::IteratorResult;
use crate::object::{JsArray, JsMap};
use crate::object::JsMap;
use crate::value::TryFromJs;
use crate::{Context, JsNativeError, JsResult, JsValue};

Expand All @@ -25,14 +22,13 @@ where
// JsMap case
if let Ok(js_map) = JsMap::from_object(object.clone()) {
let mut map = Self::default();
let f = |key, value, context: &mut _| {
js_map.rust_for_each(|key, value| {
map.insert(
K::try_from_js(&key, context)?,
V::try_from_js(&value, context)?,
K::try_from_js(key, context)?,
V::try_from_js(value, context)?,
);
Ok(())
};
for_each_elem_in_js_map(&js_map, f, context)?;
})?;
return Ok(map);
}

Expand Down Expand Up @@ -69,14 +65,13 @@ where
// JsMap case
if let Ok(js_map) = JsMap::from_object(object.clone()) {
let mut map = Self::default();
let f = |key, value, context: &mut _| {
js_map.rust_for_each(|key, value| {
map.insert(
K::try_from_js(&key, context)?,
V::try_from_js(&value, context)?,
K::try_from_js(key, context)?,
V::try_from_js(value, context)?,
);
Ok(())
};
for_each_elem_in_js_map(&js_map, f, context)?;
})?;
return Ok(map);
}

Expand All @@ -96,42 +91,3 @@ where
.collect()
}
}

fn for_each_elem_in_js_map<F>(js_map: &JsMap, mut f: F, context: &mut Context) -> JsResult<()>
where
F: FnMut(JsValue, JsValue, &mut Context) -> JsResult<()>,
{
let unexp_obj_err = || {
JsResult::Err(
JsNativeError::typ()
.with_message("MapIterator return unexpected object")
.into(),
)
};

let iter = js_map.entries(context)?;
loop {
let next = iter.next(context).and_then(IteratorResult::from_value)?;
let iter_obj = next.object();

let done = iter_obj.get(js_str!("done"), context)?;
let Some(done) = done.as_boolean() else {
return unexp_obj_err();
};
if done {
break;
}

let value = iter_obj.get(js_str!("value"), context)?;
let Some(js_obj) = value.as_object() else {
return unexp_obj_err();
};
let arr = JsArray::from_object(js_obj.clone())?;

let key = arr.at(0, context)?;
let value = arr.at(1, context)?;

f(key, value, context)?;
}
Ok(())
}
Loading