use std::any::{Any, TypeId};
use std::fmt;
use crate::Bus;
#[derive(Clone, Copy)]
pub struct Contract {
pub name: &'static str,
pub version: &'static str,
pub requires: &'static [&'static Contract],
type_id: fn() -> TypeId,
}
impl Contract {
pub const fn new<C: ?Sized + 'static>(
name: &'static str,
version: &'static str,
requires: &'static [&'static Contract],
) -> Contract {
Contract {
name,
version,
requires,
type_id: TypeId::of::<C>,
}
}
pub fn type_id(&self) -> TypeId {
(self.type_id)()
}
}
impl PartialEq for Contract {
fn eq(&self, other: &Contract) -> bool {
self.type_id() == other.type_id()
}
}
impl Eq for Contract {}
impl fmt::Debug for Contract {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{} {}", self.name, self.version)
}
}
impl fmt::Display for Contract {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.name)
}
}
pub fn offers(bus: &dyn Bus, contract: &Contract) -> bool {
bus.capability(contract.type_id()).is_some() && contract.requires.iter().all(|r| offers(bus, r))
}
#[derive(Clone, Copy)]
pub struct Facet {
pub contract: &'static Contract,
pub data: &'static (dyn Any + Send + Sync),
}
impl Facet {
pub const fn new(contract: &'static Contract, data: &'static (dyn Any + Send + Sync)) -> Facet {
Facet { contract, data }
}
pub fn get<T: Any>(&self) -> Option<&'static T> {
self.data.downcast_ref::<T>()
}
pub fn find<T: Any>(facets: &[Facet], contract: &Contract) -> Option<&'static T> {
facets
.iter()
.filter(|f| f.contract == contract)
.find_map(Facet::get::<T>)
}
}
impl PartialEq for Facet {
fn eq(&self, other: &Facet) -> bool {
self.contract == other.contract && (*self.data).type_id() == (*other.data).type_id()
}
}
impl Eq for Facet {}
impl fmt::Debug for Facet {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "Facet({})", self.contract.name)
}
}