#![doc = include_str!("../README.md")]
#![forbid(unsafe_code)]
#![warn(missing_docs)]
mod tools;
mod types;
use std::any::{Any, TypeId, type_name};
use std::sync::Arc;
use std::time::Duration;
pub use tools::{declare_all, missing_targets, order_dump};
pub use types::*;
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct PointKey {
pub id: &'static str,
pub kind: PointKind,
pub type_id: TypeId,
pub type_name: &'static str,
}
impl PointKey {
pub fn of<P: Point>() -> PointKey {
PointKey {
id: P::ID,
kind: P::KIND,
type_id: TypeId::of::<P>(),
type_name: type_name::<P>(),
}
}
}
pub type AnyInput = Arc<dyn Any + Send + Sync>;
pub type AnyValue = Box<dyn Any + Send>;
pub type AnyListener = Arc<
dyn Fn(&(dyn Any + Send + Sync), &mut (dyn Any + Send)) -> Result<(), HookError> + Send + Sync,
>;
pub type CloneFn = fn(&(dyn Any + Send)) -> AnyValue;
pub type FreshFn = fn() -> AnyValue;
pub type FailureSink = Arc<dyn Fn(&Failure) + Send + Sync>;
pub trait Bus: Send + Sync {
fn declare_point(&self, point: PointKey, spec: PointSpec) -> Result<(), Refused>;
fn listen_any(
&self,
point: PointKey,
id: String,
opts: ListenOpts,
run: AnyListener,
) -> Result<(), Refused>;
fn unlisten(&self, point: &str, id: &str) -> bool;
fn forget(&self, owner: &str) -> usize;
fn alter_any(
&self,
point: PointKey,
input: AnyInput,
value: AnyValue,
clone: CloneFn,
) -> Altered<AnyValue>;
fn collect_any(&self, point: PointKey, input: AnyInput, fresh: FreshFn) -> Collected<AnyValue>;
fn add_failure_sink(&self, sink: FailureSink);
fn points(&self) -> Vec<PointInfo>;
fn listeners(&self, point: &str) -> Option<Vec<ListenerInfo>>;
}
impl<B: Bus + ?Sized> Bus for Arc<B> {
fn declare_point(&self, point: PointKey, spec: PointSpec) -> Result<(), Refused> {
(**self).declare_point(point, spec)
}
fn listen_any(
&self,
point: PointKey,
id: String,
opts: ListenOpts,
run: AnyListener,
) -> Result<(), Refused> {
(**self).listen_any(point, id, opts, run)
}
fn unlisten(&self, point: &str, id: &str) -> bool {
(**self).unlisten(point, id)
}
fn forget(&self, owner: &str) -> usize {
(**self).forget(owner)
}
fn alter_any(
&self,
point: PointKey,
input: AnyInput,
value: AnyValue,
clone: CloneFn,
) -> Altered<AnyValue> {
(**self).alter_any(point, input, value, clone)
}
fn collect_any(&self, point: PointKey, input: AnyInput, fresh: FreshFn) -> Collected<AnyValue> {
(**self).collect_any(point, input, fresh)
}
fn add_failure_sink(&self, sink: FailureSink) {
(**self).add_failure_sink(sink);
}
fn points(&self) -> Vec<PointInfo> {
(**self).points()
}
fn listeners(&self, point: &str) -> Option<Vec<ListenerInfo>> {
(**self).listeners(point)
}
}
fn clone_value<V: Clone + Send + 'static>(value: &(dyn Any + Send)) -> AnyValue {
match value.downcast_ref::<V>() {
Some(v) => Box::new(v.clone()),
None => panic!(
"a bus implementation passed a value that is not a `{}`",
type_name::<V>()
),
}
}
fn fresh_value<V: Default + Send + 'static>() -> AnyValue {
Box::new(V::default())
}
fn typed<P: Point>(value: AnyValue) -> P::Value {
match value.downcast::<P::Value>() {
Ok(v) => *v,
Err(_) => panic!(
"the bus returned a value of another type than `{}`'s ({})",
P::ID,
type_name::<P::Value>()
),
}
}
impl<'a> dyn Bus + 'a {
pub fn declare<P: Point>(&self, spec: PointSpec) -> Result<(), Refused> {
self.declare_point(PointKey::of::<P>(), spec)
}
pub fn listen<P: Point>(
&self,
id: impl Into<String>,
opts: ListenOpts,
run: impl Fn(&P::Input, &mut P::Value) -> Result<(), HookError> + Send + Sync + 'static,
) -> Result<(), Refused> {
self.listen_any(PointKey::of::<P>(), id.into(), opts, erase::<P>(run))
}
pub fn alter<P: Point>(&self, input: P::Input, value: P::Value) -> Altered<P::Value>
where
P::Value: Clone,
{
let out = self.alter_any(
PointKey::of::<P>(),
Arc::new(input),
Box::new(value),
clone_value::<P::Value>,
);
Altered {
value: typed::<P>(out.value),
failures: out.failures,
}
}
pub fn collect<P: Point>(&self, input: P::Input) -> Collected<P::Value>
where
P::Value: Default,
{
let out = self.collect_any(
PointKey::of::<P>(),
Arc::new(input),
fresh_value::<P::Value>,
);
Collected {
parts: out
.parts
.into_iter()
.map(|(id, v)| (id, typed::<P>(v)))
.collect(),
failures: out.failures,
}
}
pub fn on_failure(&self, sink: impl Fn(&Failure) + Send + Sync + 'static) {
self.add_failure_sink(Arc::new(sink));
}
}
pub fn erase<P: Point>(
run: impl Fn(&P::Input, &mut P::Value) -> Result<(), HookError> + Send + Sync + 'static,
) -> AnyListener {
Arc::new(move |input, value| {
let Some(input) = input.downcast_ref::<P::Input>() else {
return Err(HookError(format!(
"`{}`: the input is not a `{}`",
P::ID,
type_name::<P::Input>()
)));
};
let Some(value) = value.downcast_mut::<P::Value>() else {
return Err(HookError(format!(
"`{}`: the value is not a `{}`",
P::ID,
type_name::<P::Value>()
)));
};
run(input, value)
})
}
#[derive(Clone, Copy, Debug)]
pub struct PointDecl {
pub id: &'static str,
pub kind: PointKind,
pub description: &'static str,
pub deadline: Option<Duration>,
key: fn() -> PointKey,
}
impl PointDecl {
pub const fn of<P: Point>(description: &'static str) -> PointDecl {
PointDecl {
id: P::ID,
kind: P::KIND,
description,
deadline: None,
key: PointKey::of::<P>,
}
}
pub const fn deadline(mut self, deadline: Duration) -> PointDecl {
self.deadline = Some(deadline);
self
}
pub fn key(&self) -> PointKey {
(self.key)()
}
pub fn spec(&self) -> PointSpec {
let spec = PointSpec::new(self.description);
match self.deadline {
Some(d) => spec.deadline(d),
None => spec,
}
}
}