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
use std::{future::Future, rc::Rc};

use crate::framed::{OnDisconnect, State};
use crate::ws;

pub struct WsSink(Rc<WsSinkInner>);

struct WsSinkInner {
    state: State,
    codec: ws::Codec,
}

impl WsSink {
    pub(crate) fn new(state: State, codec: ws::Codec) -> Self {
        Self(Rc::new(WsSinkInner { state, codec }))
    }

    /// Endcode and send message to the peer.
    pub fn send(
        &self,
        item: ws::Message,
    ) -> impl Future<Output = Result<(), ws::ProtocolError>> {
        let inner = self.0.clone();

        async move {
            inner.state.write().encode(item, &inner.codec)?;
            Ok(())
        }
    }

    /// Notify when connection get disconnected
    pub fn on_disconnect(&self) -> OnDisconnect {
        self.0.state.on_disconnect()
    }
}