Optimize PackagesCollection.

This commit is contained in:
Stephen Chung 2020-11-19 10:24:43 +08:00
parent a8cdb661f8
commit d35a7eeaa8

View File

@ -50,33 +50,44 @@ pub type PackageLibrary = Shared<Module>;
/// Type containing a collection of `PackageLibrary` instances.
/// All function and type iterator keys in the loaded packages are indexed for fast access.
#[derive(Debug, Clone, Default)]
pub(crate) struct PackagesCollection(StaticVec<PackageLibrary>);
pub(crate) struct PackagesCollection(Option<StaticVec<PackageLibrary>>);
impl PackagesCollection {
/// Add a `PackageLibrary` into the `PackagesCollection`.
///
/// Packages are searched in reverse order.
pub fn add(&mut self, package: PackageLibrary) {
if self.0.is_none() {
self.0 = Some(Default::default());
}
// Later packages override previous ones.
self.0.insert(0, package);
self.0.as_mut().unwrap().insert(0, package);
}
/// Does the specified function hash key exist in the `PackagesCollection`?
#[allow(dead_code)]
pub fn contains_fn(&self, hash: u64) -> bool {
self.0.iter().any(|p| p.contains_fn(hash, false))
self.0
.as_ref()
.map_or(false, |x| x.iter().any(|p| p.contains_fn(hash, false)))
}
/// Get specified function via its hash key.
pub fn get_fn(&self, hash: u64) -> Option<&CallableFunction> {
self.0.iter().find_map(|p| p.get_fn(hash, false))
self.0
.as_ref()
.and_then(|x| x.iter().find_map(|p| p.get_fn(hash, false)))
}
/// Does the specified TypeId iterator exist in the `PackagesCollection`?
#[allow(dead_code)]
pub fn contains_iter(&self, id: TypeId) -> bool {
self.0.iter().any(|p| p.contains_iter(id))
self.0
.as_ref()
.map_or(false, |x| x.iter().any(|p| p.contains_iter(id)))
}
/// Get the specified TypeId iterator.
pub fn get_iter(&self, id: TypeId) -> Option<IteratorFn> {
self.0.iter().find_map(|p| p.get_iter(id))
self.0
.as_ref()
.and_then(|x| x.iter().find_map(|p| p.get_iter(id)))
}
}