Tidy up PluginGroupBuilder by moving Plugin index retrieval to it's own function (#4446)

# Objective

- Clean up duplicate code in the add_before/add_after functions in PluginGroupBuilder.

## Solution

- moved index retrieval code to a private function index_of() for the PluginGroupBuilder.
- change is just tidying up. No real change to functionality.
This commit is contained in:
Ian Johnson 2022-05-02 13:20:54 +00:00
parent 2c145826a3
commit e9db69af81

View file

@ -23,6 +23,22 @@ pub struct PluginGroupBuilder {
}
impl PluginGroupBuilder {
/// Finds the index of a target [`Plugin`]. Panics if the target's [`TypeId`] is not found.
fn index_of<Target: Plugin>(&mut self) -> usize {
let index = self
.order
.iter()
.position(|&ty| ty == TypeId::of::<Target>());
match index {
Some(i) => i,
None => panic!(
"Plugin does not exist in group: {}.",
std::any::type_name::<Target>()
),
}
}
/// Appends a [`Plugin`] to the [`PluginGroupBuilder`].
pub fn add<T: Plugin>(&mut self, plugin: T) -> &mut Self {
self.order.push(TypeId::of::<T>());
@ -38,18 +54,7 @@ impl PluginGroupBuilder {
/// Configures a [`Plugin`] to be built before another plugin.
pub fn add_before<Target: Plugin, T: Plugin>(&mut self, plugin: T) -> &mut Self {
let target_index = self
.order
.iter()
.enumerate()
.find(|(_i, ty)| **ty == TypeId::of::<Target>())
.map(|(i, _)| i)
.unwrap_or_else(|| {
panic!(
"Plugin does not exist: {}.",
std::any::type_name::<Target>()
)
});
let target_index = self.index_of::<Target>();
self.order.insert(target_index, TypeId::of::<T>());
self.plugins.insert(
TypeId::of::<T>(),
@ -63,18 +68,7 @@ impl PluginGroupBuilder {
/// Configures a [`Plugin`] to be built after another plugin.
pub fn add_after<Target: Plugin, T: Plugin>(&mut self, plugin: T) -> &mut Self {
let target_index = self
.order
.iter()
.enumerate()
.find(|(_i, ty)| **ty == TypeId::of::<Target>())
.map(|(i, _)| i)
.unwrap_or_else(|| {
panic!(
"Plugin does not exist: {}.",
std::any::type_name::<Target>()
)
});
let target_index = self.index_of::<Target>();
self.order.insert(target_index + 1, TypeId::of::<T>());
self.plugins.insert(
TypeId::of::<T>(),