1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
use std::fmt;

use futures::unsync::{mpsc, oneshot};
use futures::Future;

use crate::dispatcher::FramedMessage;

pub struct Sink<T>(mpsc::UnboundedSender<FramedMessage<T>>);

impl<T> Clone for Sink<T> {
    fn clone(&self) -> Self {
        Sink(self.0.clone())
    }
}

impl<T> Sink<T> {
    pub(crate) fn new(tx: mpsc::UnboundedSender<FramedMessage<T>>) -> Self {
        Sink(tx)
    }

    /// Close connection
    pub fn close(&self) {
        let _ = self.0.unbounded_send(FramedMessage::Close);
    }

    /// Close connection
    pub fn wait_close(&self) -> impl Future<Item = (), Error = ()> {
        let (tx, rx) = oneshot::channel();
        let _ = self.0.unbounded_send(FramedMessage::WaitClose(tx));

        rx.map_err(|_| ())
    }

    /// Send item
    pub fn send(&self, item: T) {
        let _ = self.0.unbounded_send(FramedMessage::Message(item));
    }
}

impl<T> fmt::Debug for Sink<T> {
    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
        fmt.debug_struct("Sink").finish()
    }
}