-
-
Notifications
You must be signed in to change notification settings - Fork 408
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Adding TryFromJs implementations for BTreeMap and HashMap (#3844)
- Loading branch information
Showing
2 changed files
with
111 additions
and
0 deletions.
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
64 changes: 64 additions & 0 deletions
64
core/engine/src/value/conversions/try_from_js/collections.rs
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,64 @@ | ||
//! [`JsValue`] conversions for std collections. | ||
use std::collections::{BTreeMap, HashMap}; | ||
use std::hash::Hash; | ||
|
||
use crate::value::TryFromJs; | ||
use crate::{Context, JsNativeError, JsResult, JsValue}; | ||
|
||
impl<K, V> TryFromJs for BTreeMap<K, V> | ||
where | ||
K: TryFromJs + Ord, | ||
V: TryFromJs, | ||
{ | ||
fn try_from_js(value: &JsValue, context: &mut Context) -> JsResult<Self> { | ||
let JsValue::Object(object) = value else { | ||
return Err(JsNativeError::typ() | ||
.with_message("cannot convert value to a BTreeMap") | ||
.into()); | ||
}; | ||
|
||
let keys = object.__own_property_keys__(context)?; | ||
|
||
keys.into_iter() | ||
.map(|key| { | ||
let js_value = object.get(key.clone(), context)?; | ||
let js_key: JsValue = key.into(); | ||
|
||
let key = K::try_from_js(&js_key, context)?; | ||
let value = V::try_from_js(&js_value, context)?; | ||
|
||
Ok((key, value)) | ||
}) | ||
.collect() | ||
} | ||
} | ||
|
||
impl<K, V, S> TryFromJs for HashMap<K, V, S> | ||
where | ||
K: TryFromJs + Ord + Hash, | ||
V: TryFromJs, | ||
S: std::hash::BuildHasher + Default, | ||
{ | ||
fn try_from_js(value: &JsValue, context: &mut Context) -> JsResult<Self> { | ||
let JsValue::Object(object) = value else { | ||
return Err(JsNativeError::typ() | ||
.with_message("cannot convert value to a BTreeMap") | ||
.into()); | ||
}; | ||
|
||
let keys = object.__own_property_keys__(context)?; | ||
|
||
keys.into_iter() | ||
.map(|key| { | ||
let js_value = object.get(key.clone(), context)?; | ||
let js_key: JsValue = key.into(); | ||
|
||
let key = K::try_from_js(&js_key, context)?; | ||
let value = V::try_from_js(&js_value, context)?; | ||
|
||
Ok((key, value)) | ||
}) | ||
.collect() | ||
} | ||
} |