wasmer/lib/runtime/src/import.rs

61 lines
1.4 KiB
Rust
Raw Normal View History

2019-01-12 21:24:17 +00:00
use crate::export::Export;
2019-01-11 03:59:57 +00:00
use hashbrown::{hash_map::Entry, HashMap};
2019-01-12 21:24:17 +00:00
pub trait Namespace {
2019-01-13 21:44:14 +00:00
fn get_export(&mut self, name: &str) -> Option<Export>;
2019-01-12 21:24:17 +00:00
}
2019-01-11 03:59:57 +00:00
pub struct Imports {
2019-01-12 21:24:17 +00:00
map: HashMap<String, Box<dyn Namespace>>,
2019-01-11 03:59:57 +00:00
}
impl Imports {
pub fn new() -> Self {
Self {
map: HashMap::new(),
}
}
2019-01-13 03:02:19 +00:00
pub fn register<S, N>(&mut self, name: S, namespace: N) -> Option<Box<dyn Namespace>>
where
S: Into<String>,
N: Namespace + 'static,
{
2019-01-12 21:24:17 +00:00
match self.map.entry(name.into()) {
Entry::Vacant(empty) => {
empty.insert(Box::new(namespace));
None
}
Entry::Occupied(mut occupied) => Some(occupied.insert(Box::new(namespace))),
}
2019-01-11 03:59:57 +00:00
}
2019-01-12 21:24:17 +00:00
2019-01-13 21:44:14 +00:00
pub fn get_namespace(&mut self, namespace: &str) -> Option<&mut (dyn Namespace + 'static)> {
self.map
.get_mut(namespace)
.map(|namespace| &mut **namespace)
2019-01-11 03:59:57 +00:00
}
}
pub struct NamespaceMap {
2019-01-13 21:44:14 +00:00
map: HashMap<String, Export>,
}
impl NamespaceMap {
pub fn new() -> Self {
Self {
map: HashMap::new(),
}
}
pub fn insert(&mut self, name: impl Into<String>, export: Export) -> Option<Export> {
self.map.insert(name.into(), export)
}
}
impl Namespace for NamespaceMap {
2019-01-13 21:44:14 +00:00
fn get_export(&mut self, name: &str) -> Option<Export> {
self.map.get(name).cloned()
}
2019-01-13 21:44:14 +00:00
}