1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
//! The core WebAssembly spec does not specify how imports are to be resolved
//! to exports. This file provides one possible way to manage multiple instances
//! and resolve imports to exports among them.

use super::HashMap;
use crate::resolver::Resolver;
use std::string::String;
use wasmtime_runtime::{Export, InstanceHandle};

/// A namespace containing instances keyed by name.
///
/// Note that `Namespace` implements the `Resolver` trait, so it can resolve
/// imports using defined exports.
pub struct Namespace {
    /// Mapping from identifiers to indices in `self.instances`.
    names: HashMap<String, InstanceHandle>,
}

impl Namespace {
    /// Construct a new `Namespace`.
    pub fn new() -> Self {
        Self {
            names: HashMap::new(),
        }
    }

    /// Install a new `InstanceHandle` in this `Namespace`, optionally with the
    /// given name.
    pub fn name_instance(&mut self, name: String, instance: InstanceHandle) {
        self.names.insert(name, instance);
    }

    /// Get the instance registered with the given `instance_name`.
    pub fn get_instance(&mut self, name: &str) -> Option<&mut InstanceHandle> {
        self.names.get_mut(name)
    }
}

impl Resolver for Namespace {
    fn resolve(&mut self, name: &str, field: &str) -> Option<Export> {
        if let Some(instance) = self.names.get_mut(name) {
            instance.lookup(field)
        } else {
            None
        }
    }
}