wasmer/lib/runtime/src/import.rs

48 lines
1.2 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 {
fn get_export(&self, name: &str) -> Option<Export>;
}
impl Namespace for HashMap<String, Export> {
fn get_export(&self, name: &str) -> Option<Export> {
self.get(name).cloned()
}
}
impl<'a> Namespace for HashMap<&'a str, Export> {
fn get_export(&self, name: &str) -> Option<Export> {
self.get(name).cloned()
}
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 03:02:19 +00:00
pub fn get_namespace(&self, namespace: &str) -> Option<&dyn Namespace> {
self.map.get(namespace).map(|namespace| &**namespace)
2019-01-11 03:59:57 +00:00
}
}