use crate::script::*;
#[derive(Clone, PartialEq)]
pub struct ScriptMap(pub(crate) crate::value::ValueMap);
impl ScriptMap {
pub fn as_value_map(&self) -> &crate::value::ValueMap {
&self.0
}
}
impl IntoIterator for ScriptMap {
type Item = Dynamic;
type IntoIter = std::vec::IntoIter<Dynamic>;
fn into_iter(self) -> Self::IntoIter {
self.0
.into_iter()
.map(|(key, value)| {
Dynamic::from_array(vec![
element_property_to_dynamic(key),
element_property_to_dynamic(value),
])
})
.collect::<Vec<Dynamic>>()
.into_iter()
}
}
pub(crate) fn map_key_text(key: &ElementProperty) -> String {
match key {
ElementProperty::String(_) => crate::value::physical::to_json_text(key).unwrap_or_default(),
other => crate::value::physical::to_display_text(other).to_string(),
}
}
pub(crate) fn script_map_text(
map: &ScriptMap,
limit: &crate::traversal::render::ItemLimit,
) -> String {
let keep = limit.keep(map.0.len());
let mut entries: Vec<String> = map
.0
.iter()
.take(keep)
.map(|(key, value)| {
format!(
"{}: {}",
map_key_text(key),
bounded_debug_value(&element_property_to_dynamic(value.clone()), limit)
)
})
.collect();
if keep < map.0.len() {
entries.push(crate::traversal::render::CUT_MARKER.to_string());
}
format!("{{{}}}", entries.join(", "))
}
pub(crate) fn script_map_to_rhai_map(
map: &ScriptMap,
) -> Result<rhai::Map, Box<rhai::EvalAltResult>> {
let mut out = rhai::Map::new();
for (key, value) in map.0.iter() {
match key {
ElementProperty::String(name) => {
out.insert(
name.as_str().into(),
element_property_to_dynamic(value.clone()),
);
}
other => {
return Err(script_error_from_script(
crate::error::ScriptError::ArgumentMismatch {
step_name: "to_map".to_string(),
expected: "a map whose keys are all strings".to_string(),
actual: format!("a map with the non-string key {}", map_key_text(other)),
},
));
}
}
}
Ok(out)
}
pub(crate) fn script_error_from_script(err: crate::error::ScriptError) -> Box<rhai::EvalAltResult> {
Box::new(rhai::EvalAltResult::ErrorRuntime(
Dynamic::from(crate::error::format_diagnostic(&err)),
rhai::Position::NONE,
))
}