rhai/src/packages/map_basic.rs

68 lines
1.7 KiB
Rust
Raw Normal View History

2020-04-21 17:01:10 +02:00
use super::{reg_binary, reg_binary_mut, reg_unary_mut};
use crate::any::Dynamic;
use crate::def_package;
use crate::engine::Map;
use crate::fn_register::map_dynamic as map;
use crate::parser::INT;
2020-04-24 06:39:24 +02:00
use crate::stdlib::{
string::{String, ToString},
vec::Vec,
};
2020-04-21 17:01:10 +02:00
fn map_get_keys(map: &mut Map) -> Vec<Dynamic> {
map.iter()
2020-04-22 08:55:40 +02:00
.map(|(k, _)| k.to_string().into())
2020-04-21 17:01:10 +02:00
.collect::<Vec<_>>()
}
2020-04-21 17:01:10 +02:00
fn map_get_values(map: &mut Map) -> Vec<Dynamic> {
map.iter().map(|(_, v)| v.clone()).collect::<Vec<_>>()
}
2020-04-21 17:01:10 +02:00
#[cfg(not(feature = "no_object"))]
2020-04-22 08:55:40 +02:00
def_package!(crate:BasicMapPackage:"Basic object map utilities.", lib, {
2020-04-21 17:01:10 +02:00
reg_binary_mut(
lib,
"has",
|map: &mut Map, prop: String| map.contains_key(&prop),
map,
);
reg_unary_mut(lib, "len", |map: &mut Map| map.len() as INT, map);
reg_unary_mut(lib, "clear", |map: &mut Map| map.clear(), map);
reg_binary_mut(
lib,
"remove",
2020-04-22 08:55:40 +02:00
|x: &mut Map, name: String| x.remove(&name).unwrap_or_else(|| ().into()),
2020-04-21 17:01:10 +02:00
map,
);
reg_binary_mut(
lib,
"mixin",
|map1: &mut Map, map2: Map| {
map2.into_iter().for_each(|(key, value)| {
map1.insert(key, value);
});
},
map,
);
reg_binary(
lib,
"+",
|mut map1: Map, map2: Map| {
map2.into_iter().for_each(|(key, value)| {
map1.insert(key, value);
});
map1
},
map,
);
// Register map access functions
#[cfg(not(feature = "no_index"))]
reg_unary_mut(lib, "keys", map_get_keys, map);
#[cfg(not(feature = "no_index"))]
reg_unary_mut(lib, "values", map_get_values, map);
});