Add ModuleResolversCollection.

This commit is contained in:
Stephen Chung 2020-07-07 23:44:23 +08:00
parent ff6d205c1d
commit 236ba40784

View File

@ -1145,6 +1145,7 @@ pub trait ModuleResolver: SendSync {
/// Re-export module resolvers.
#[cfg(not(feature = "no_module"))]
pub mod resolvers {
pub use super::collection::ModuleResolversCollection;
#[cfg(not(feature = "no_std"))]
#[cfg(not(target_arch = "wasm32"))]
pub use super::file::FileModuleResolver;
@ -1340,9 +1341,6 @@ mod stat {
/// Module resolution service that serves modules added into it.
///
/// `StaticModuleResolver` is a smart pointer to a `HashMap<String, Module>`.
/// It can simply be treated as `&HashMap<String, Module>`.
///
/// # Examples
///
/// ```
@ -1436,3 +1434,86 @@ mod stat {
}
}
}
/// Module resolver collection.
#[cfg(not(feature = "no_module"))]
mod collection {
use super::*;
/// Module resolution service that holds a collection of module resolves,
/// to be searched in sequential order.
///
/// # Examples
///
/// ```
/// use rhai::{Engine, Module};
/// use rhai::module_resolvers::{StaticModuleResolver, ModuleResolversCollection};
///
/// let mut collection = ModuleResolversCollection::new();
///
/// let resolver = StaticModuleResolver::new();
/// collection.push(resolver);
///
/// let mut engine = Engine::new();
/// engine.set_module_resolver(Some(collection));
/// ```
#[derive(Default)]
pub struct ModuleResolversCollection(Vec<Box<dyn ModuleResolver>>);
impl ModuleResolversCollection {
/// Create a new `ModuleResolversCollection`.
///
/// # Examples
///
/// ```
/// use rhai::{Engine, Module};
/// use rhai::module_resolvers::{StaticModuleResolver, ModuleResolversCollection};
///
/// let mut collection = ModuleResolversCollection::new();
///
/// let resolver = StaticModuleResolver::new();
/// collection.push(resolver);
///
/// let mut engine = Engine::new();
/// engine.set_module_resolver(Some(collection));
/// ```
pub fn new() -> Self {
Default::default()
}
}
impl ModuleResolversCollection {
/// Add a module keyed by its path.
pub fn push(&mut self, resolver: impl ModuleResolver + 'static) {
self.0.push(Box::new(resolver));
}
/// Get an iterator of all the module resolvers.
pub fn iter(&self) -> impl Iterator<Item = &dyn ModuleResolver> {
self.0.iter().map(|v| v.as_ref())
}
/// Remove all module resolvers.
pub fn clear(&mut self) {
self.0.clear();
}
}
impl ModuleResolver for ModuleResolversCollection {
fn resolve(
&self,
engine: &Engine,
path: &str,
pos: Position,
) -> Result<Module, Box<EvalAltResult>> {
for resolver in self.0.iter() {
if let Ok(module) = resolver.resolve(engine, path, pos) {
return Ok(module);
}
}
Err(Box::new(EvalAltResult::ErrorModuleNotFound(
path.into(),
pos,
)))
}
}
}