rhai/src/packages/map_basic.rs

65 lines
1.8 KiB
Rust
Raw Normal View History

#![cfg(not(feature = "no_object"))]
2020-07-31 16:30:23 +02:00
use crate::any::Dynamic;
use crate::def_package;
use crate::engine::Map;
2020-05-25 07:44:28 +02:00
use crate::parser::{ImmutableString, INT};
2020-08-14 18:04:10 +02:00
use crate::plugin::*;
use crate::stdlib::vec::Vec;
2020-04-24 06:39:24 +02:00
2020-04-22 08:55:40 +02:00
def_package!(crate:BasicMapPackage:"Basic object map utilities.", lib, {
lib.combine_flatten(exported_module!(map_functions));
2020-08-14 18:04:10 +02:00
});
#[export_module]
mod map_functions {
2020-08-20 16:11:41 +02:00
#[inline(always)]
2020-08-14 18:04:10 +02:00
pub fn has(map: &mut Map, prop: ImmutableString) -> bool {
map.contains_key(&prop)
}
#[rhai_fn(name = "len", get = "len")]
2020-08-20 16:11:41 +02:00
#[inline(always)]
2020-08-14 18:04:10 +02:00
pub fn len(map: &mut Map) -> INT {
map.len() as INT
}
2020-08-20 16:11:41 +02:00
#[inline(always)]
2020-08-14 18:04:10 +02:00
pub fn clear(map: &mut Map) {
2020-05-13 13:21:42 +02:00
map.clear();
2020-08-14 18:04:10 +02:00
}
#[inline(always)]
2020-08-14 18:04:10 +02:00
pub fn remove(x: &mut Map, name: ImmutableString) -> Dynamic {
x.remove(&name).unwrap_or_else(|| ().into())
}
#[rhai_fn(name = "mixin", name = "+=")]
2020-08-14 18:04:10 +02:00
pub fn mixin(map1: &mut Map, map2: Map) {
map2.into_iter().for_each(|(key, value)| {
map1.insert(key, value);
2020-08-14 18:04:10 +02:00
});
}
#[rhai_fn(name = "+")]
pub fn merge(mut map1: Map, map2: Map) -> Map {
2020-08-14 18:04:10 +02:00
map2.into_iter().for_each(|(key, value)| {
map1.insert(key, value);
});
map1
2020-08-14 18:04:10 +02:00
}
pub fn fill_with(map1: &mut Map, map2: Map) {
2020-08-14 18:04:10 +02:00
map2.into_iter().for_each(|(key, value)| {
if !map1.contains_key(&key) {
map1.insert(key, value);
}
2020-08-14 18:04:10 +02:00
});
}
2020-04-21 17:01:10 +02:00
2020-08-22 16:26:49 +02:00
#[cfg(not(feature = "no_index"))]
pub mod indexing {
pub fn keys(map: &mut Map) -> Vec<Dynamic> {
map.iter().map(|(k, _)| k.clone().into()).collect()
}
pub fn values(map: &mut Map) -> Vec<Dynamic> {
map.iter().map(|(_, v)| v.clone()).collect()
}
2020-08-14 18:04:10 +02:00
}
}