websocket_codec/
opcode.rs

1/// Represents an opcode as defined by the WebSocket protocol.
2#[derive(Copy, Clone, Debug, PartialEq)]
3pub enum Opcode {
4    /// UTF-8 text.
5    Text,
6    /// Arbitrary binary data.
7    Binary,
8    /// Close control frame.
9    Close,
10    /// Ping control frame.
11    Ping,
12    /// Pong control frame.
13    Pong,
14}
15
16impl Opcode {
17    /// Returns `true` if `self` is `Text`.
18    pub fn is_text(self) -> bool {
19        matches!(self, Self::Text)
20    }
21
22    /// Returns `true` if `self` is `Close`, `Ping` or `Pong`.
23    pub fn is_control(self) -> bool {
24        matches!(self, Self::Close | Self::Ping | Self::Pong)
25    }
26
27    /// Converts `u8` to `Opcode`.
28    ///
29    /// Returns `None` for unrecognised and unsupported opcodes.
30    pub fn try_from(data: u8) -> Option<Self> {
31        let opcode = match data {
32            1 => Self::Text,
33            2 => Self::Binary,
34            8 => Self::Close,
35            9 => Self::Ping,
36            10 => Self::Pong,
37            _ => {
38                return None;
39            }
40        };
41
42        Some(opcode)
43    }
44}
45
46impl From<Opcode> for u8 {
47    fn from(opcode: Opcode) -> Self {
48        match opcode {
49            Opcode::Text => 1,
50            Opcode::Binary => 2,
51            Opcode::Close => 8,
52            Opcode::Ping => 9,
53            Opcode::Pong => 10,
54        }
55    }
56}