use crate::Result;
use std::rc::Rc;
pub type Detach = Box<dyn FnOnce()>;
pub type EventHandler<T> = Rc<dyn Fn(Rc<T>)>;
type Attach<T> = Rc<dyn Fn(EventHandler<T>) -> Result<Detach>>;
pub struct EventSource<T>(pub(crate) Attach<T>);
impl<T> Clone for EventSource<T> {
fn clone(&self) -> Self {
Self(self.0.clone())
}
}
impl<T> EventSource<T> {
pub fn new(subscribe: impl Fn(EventHandler<T>) -> Result<Detach> + 'static) -> Self {
Self(Rc::new(subscribe))
}
}
pub(crate) type Size<T> = Rc<dyn Fn(&T) -> Result<usize>>;
pub struct EventOptions<T> {
pub(crate) max_pending: usize,
pub(crate) max_bytes: Option<usize>,
pub(crate) size: Option<Size<T>>,
pub(crate) coalesce: bool,
}
impl<T> Default for EventOptions<T> {
fn default() -> Self {
Self {
max_pending: 64,
max_bytes: None,
size: None,
coalesce: false,
}
}
}
impl<T> EventOptions<T> {
pub fn pending(mut self, maximum: usize) -> Self {
self.max_pending = maximum;
self
}
pub fn bytes(mut self, maximum: usize, size: impl Fn(&T) -> Result<usize> + 'static) -> Self {
self.max_bytes = Some(maximum);
self.size = Some(Rc::new(size));
self
}
pub fn coalesce(mut self) -> Self {
self.coalesce = true;
self
}
}