2019-06-26 15:19:40 +06:00
|
|
|
use std::fmt;
|
2019-12-11 16:44:09 +06:00
|
|
|
use std::rc::Rc;
|
2019-06-26 15:19:40 +06:00
|
|
|
|
2019-12-11 16:44:09 +06:00
|
|
|
use actix_utils::oneshot;
|
2019-11-14 18:38:24 +06:00
|
|
|
use futures::future::{Future, FutureExt};
|
2019-06-26 15:19:40 +06:00
|
|
|
|
2019-12-11 14:36:11 +06:00
|
|
|
use crate::dispatcher::Message;
|
2019-06-26 15:19:40 +06:00
|
|
|
|
2019-12-11 16:44:09 +06:00
|
|
|
pub struct Sink<T>(Rc<dyn Fn(Message<T>)>);
|
2019-06-26 15:19:40 +06:00
|
|
|
|
2019-12-11 16:44:09 +06:00
|
|
|
impl<T> Clone for Sink<T> {
|
2019-06-26 15:19:40 +06:00
|
|
|
fn clone(&self) -> Self {
|
|
|
|
Sink(self.0.clone())
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-12-11 16:44:09 +06:00
|
|
|
impl<T> Sink<T> {
|
|
|
|
pub(crate) fn new(tx: Rc<dyn Fn(Message<T>)>) -> Self {
|
2019-06-26 15:19:40 +06:00
|
|
|
Sink(tx)
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Close connection
|
|
|
|
pub fn close(&self) {
|
2019-12-11 16:44:09 +06:00
|
|
|
(self.0)(Message::Close);
|
2019-06-26 15:19:40 +06:00
|
|
|
}
|
|
|
|
|
|
|
|
/// Close connection
|
2019-11-14 18:38:24 +06:00
|
|
|
pub fn wait_close(&self) -> impl Future<Output = ()> {
|
2019-06-26 15:19:40 +06:00
|
|
|
let (tx, rx) = oneshot::channel();
|
2019-12-11 16:44:09 +06:00
|
|
|
(self.0)(Message::WaitClose(tx));
|
2019-06-26 15:19:40 +06:00
|
|
|
|
2019-11-14 18:38:24 +06:00
|
|
|
rx.map(|_| ())
|
2019-06-26 15:19:40 +06:00
|
|
|
}
|
|
|
|
|
|
|
|
/// Send item
|
|
|
|
pub fn send(&self, item: T) {
|
2019-12-11 16:44:09 +06:00
|
|
|
(self.0)(Message::Item(item));
|
2019-06-26 15:19:40 +06:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-12-11 16:44:09 +06:00
|
|
|
impl<T> fmt::Debug for Sink<T> {
|
2019-12-02 22:30:09 +06:00
|
|
|
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
|
2019-06-26 15:19:40 +06:00
|
|
|
fmt.debug_struct("Sink").finish()
|
|
|
|
}
|
|
|
|
}
|