From 6ade74128cdbfe290df2040144f26575a2034e61 Mon Sep 17 00:00:00 2001 From: Tony Arcieri Date: Fri, 28 Jun 2019 20:11:25 -0700 Subject: [PATCH] component: impl PartialOrd for Box A pattern that may prove useful for `dyn Component` generally... --- src/component.rs | 30 +++++++++++++++++++++++++++++- src/component/registry.rs | 16 +++------------- 2 files changed, 32 insertions(+), 14 deletions(-) diff --git a/src/component.rs b/src/component.rs index c896cdcd..9ea9e689 100644 --- a/src/component.rs +++ b/src/component.rs @@ -7,7 +7,7 @@ mod registry; pub use self::{name::Name, registry::Registry}; use crate::{application::Application, error::FrameworkError, shutdown::Shutdown, Version}; -use std::{fmt::Debug, slice::Iter}; +use std::{cmp::Ordering, fmt::Debug, slice::Iter}; /// Application components. /// @@ -47,3 +47,31 @@ where Ok(()) } } + +impl PartialEq for Box> +where + A: Application, +{ + fn eq(&self, other: &Self) -> bool { + self.name() == other.name() + } +} + +impl PartialOrd for Box> +where + A: Application, +{ + fn partial_cmp(&self, other: &Self) -> Option { + if other.dependencies().any(|dep| *dep == self.name()) { + if self.dependencies().any(|dep| *dep == other.name()) { + None + } else { + Some(Ordering::Greater) + } + } else if self.dependencies().any(|dep| *dep == other.name()) { + Some(Ordering::Less) + } else { + Some(Ordering::Equal) + } + } +} diff --git a/src/component/registry.rs b/src/component/registry.rs index a7e3075c..2274de5b 100644 --- a/src/component/registry.rs +++ b/src/component/registry.rs @@ -6,7 +6,7 @@ use crate::{ error::{FrameworkError, FrameworkErrorKind::ComponentError}, shutdown::Shutdown, }; -use std::{borrow::Borrow, cmp::Ordering, collections::HashSet, slice}; +use std::{borrow::Borrow, collections::HashSet, slice}; /// The component registry provides a system for runtime registration of /// application components which can interact with each other dynamically. @@ -86,20 +86,10 @@ where /// on others after their dependencies. /// /// Exits the application if the ordering cannot be resolved. - // TODO(tarcieri): impl `PartialOrd` on `Component` fn sort(&mut self) { self.components.sort_by(|a, b| { - if b.dependencies().any(|dep| *dep == a.name()) { - if a.dependencies().any(|dep| *dep == b.name()) { - application::exit::bad_component_order(a.borrow(), b.borrow()); - } else { - Ordering::Greater - } - } else if a.dependencies().any(|dep| *dep == b.name()) { - Ordering::Less - } else { - Ordering::Equal - } + a.partial_cmp(b) + .unwrap_or_else(|| application::exit::bad_component_order(a.borrow(), b.borrow())) }) } }