Skip to content

Commit

Permalink
Tidy up PluginGroupBuilder by moving Plugin index retrieval to it's o…
Browse files Browse the repository at this point in the history
…wn 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.
  • Loading branch information
its-justus committed May 2, 2022
1 parent 2c14582 commit e9db69a
Showing 1 changed file with 18 additions and 24 deletions.
42 changes: 18 additions & 24 deletions crates/bevy_app/src/plugin_group.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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>());
Expand All @@ -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>(),
Expand All @@ -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>(),
Expand Down

0 comments on commit e9db69a

Please sign in to comment.