Add convenient functions and operators for Module and module resolvers.
This commit is contained in:
@@ -3,7 +3,7 @@ use crate::module::{Module, ModuleResolver};
|
||||
use crate::result::EvalAltResult;
|
||||
use crate::token::Position;
|
||||
|
||||
use crate::stdlib::{boxed::Box, collections::HashMap, string::String};
|
||||
use crate::stdlib::{boxed::Box, collections::HashMap, ops::AddAssign, string::String};
|
||||
|
||||
/// Module resolution service that serves modules added into it.
|
||||
///
|
||||
@@ -45,9 +45,6 @@ impl StaticModuleResolver {
|
||||
pub fn new() -> Self {
|
||||
Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
impl StaticModuleResolver {
|
||||
/// Add a module keyed by its path.
|
||||
pub fn insert<S: Into<String>>(&mut self, path: S, module: Module) {
|
||||
self.0.insert(path.into(), module);
|
||||
@@ -68,6 +65,10 @@ impl StaticModuleResolver {
|
||||
pub fn iter_mut(&mut self) -> impl Iterator<Item = (&str, &mut Module)> {
|
||||
self.0.iter_mut().map(|(k, v)| (k.as_str(), v))
|
||||
}
|
||||
/// Get a mutable iterator of all the modules.
|
||||
pub fn into_iter(self) -> impl Iterator<Item = (String, Module)> {
|
||||
self.0.into_iter()
|
||||
}
|
||||
/// Get an iterator of all the module paths.
|
||||
pub fn paths(&self) -> impl Iterator<Item = &str> {
|
||||
self.0.keys().map(String::as_str)
|
||||
@@ -84,6 +85,21 @@ impl StaticModuleResolver {
|
||||
pub fn clear(&mut self) {
|
||||
self.0.clear();
|
||||
}
|
||||
/// Is this `StaticModuleResolver` empty?
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.0.is_empty()
|
||||
}
|
||||
/// Get the number of modules in this `StaticModuleResolver`.
|
||||
pub fn len(&self) -> usize {
|
||||
self.0.len()
|
||||
}
|
||||
/// Merge another `StaticModuleResolver` into this.
|
||||
/// The other `StaticModuleResolver` is consumed.
|
||||
pub fn merge(&mut self, other: Self) {
|
||||
if !other.is_empty() {
|
||||
self.0.extend(other.0.into_iter());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl ModuleResolver for StaticModuleResolver {
|
||||
@@ -94,3 +110,9 @@ impl ModuleResolver for StaticModuleResolver {
|
||||
.ok_or_else(|| EvalAltResult::ErrorModuleNotFound(path.into(), pos).into())
|
||||
}
|
||||
}
|
||||
|
||||
impl AddAssign<Self> for StaticModuleResolver {
|
||||
fn add_assign(&mut self, rhs: Self) {
|
||||
self.merge(rhs);
|
||||
}
|
||||
}
|
||||
|
Reference in New Issue
Block a user