hydra_websockets/
websocket_command.rs

1use smallvec::SmallVec;
2
3use crate::CloseCode;
4use crate::WebsocketMessage;
5
6/// Internal websocket command representation.
7pub(crate) enum WebsocketCommand {
8    Send(WebsocketMessage),
9    Close(CloseCode, String),
10}
11
12/// A command buffer returned from a websocket callback.
13pub struct WebsocketCommands {
14    pub(crate) buffer: SmallVec<[WebsocketCommand; 6]>,
15}
16
17impl WebsocketCommands {
18    /// Constructs a new websocket command buffer.
19    pub fn new() -> Self {
20        Self {
21            buffer: SmallVec::new(),
22        }
23    }
24
25    /// Constructs a new websocket command buffer to send `message`.
26    pub fn with_send<T: Into<WebsocketMessage>>(message: T) -> Self {
27        let mut result = Self::new();
28
29        result.send(message);
30        result
31    }
32
33    /// Constructs a new websocket command buffer to close the websocket gracefully.
34    pub fn with_close<T: Into<String>>(code: CloseCode, reason: T) -> Self {
35        let mut result = Self::new();
36
37        result.close(code, reason);
38        result
39    }
40
41    /// Sends the message to the websocket client.
42    pub fn send<T: Into<WebsocketMessage>>(&mut self, message: T) {
43        self.buffer.push(WebsocketCommand::Send(message.into()));
44    }
45
46    /// Gracefully close the websocket with the given `code` and `reason`.
47    pub fn close<T: Into<String>>(&mut self, code: CloseCode, reason: T) {
48        self.buffer
49            .push(WebsocketCommand::Close(code, reason.into()));
50    }
51}
52
53impl Default for WebsocketCommands {
54    fn default() -> Self {
55        Self::new()
56    }
57}