Skip to main content

open_net/api/ws/
message.rs

1use bytes::Bytes;
2
3/// Owned business payload; protocol control frames use dedicated APIs.
4#[derive(Clone, Debug, Eq, PartialEq)]
5pub enum Message {
6    /// UTF-8 text payload.
7    Text(
8        /// Owned text body.
9        String,
10    ),
11    /// Binary payload with no UTF-8 requirement.
12    Binary(
13        /// Binary body whose backing storage can be shared by clones.
14        Bytes,
15    ),
16}
17
18impl Message {
19    /// Creates a text message from any string-like value.
20    pub fn text(value: impl Into<String>) -> Self {
21        Self::Text(value.into())
22    }
23
24    /// Creates a binary message from bytes.
25    pub fn binary(value: impl Into<Bytes>) -> Self {
26        Self::Binary(value.into())
27    }
28
29    /// Returns the text body, or `None` for binary messages.
30    pub fn as_text(&self) -> Option<&str> {
31        match self {
32            Self::Text(value) => Some(value),
33            Self::Binary(_) => None,
34        }
35    }
36
37    /// Returns the payload bytes for either message variant.
38    pub fn as_bytes(&self) -> &[u8] {
39        match self {
40            Self::Text(value) => value.as_bytes(),
41            Self::Binary(value) => value.as_ref(),
42        }
43    }
44
45    /// Converts the payload into shared bytes, consuming the message.
46    pub fn into_bytes(self) -> Bytes {
47        match self {
48            Self::Text(value) => Bytes::from(value),
49            Self::Binary(value) => value,
50        }
51    }
52
53    /// Returns the payload length in bytes.
54    pub fn len(&self) -> usize {
55        self.as_bytes().len()
56    }
57
58    /// Reports whether the payload is empty.
59    pub fn is_empty(&self) -> bool {
60        self.as_bytes().is_empty()
61    }
62}
63
64impl From<String> for Message {
65    fn from(value: String) -> Self {
66        Self::Text(value)
67    }
68}
69
70impl From<&str> for Message {
71    fn from(value: &str) -> Self {
72        Self::Text(value.to_owned())
73    }
74}
75
76impl From<Bytes> for Message {
77    fn from(value: Bytes) -> Self {
78        Self::Binary(value)
79    }
80}
81
82impl From<Vec<u8>> for Message {
83    fn from(value: Vec<u8>) -> Self {
84        Self::Binary(Bytes::from(value))
85    }
86}
87
88impl From<&[u8]> for Message {
89    fn from(value: &[u8]) -> Self {
90        Self::Binary(Bytes::copy_from_slice(value))
91    }
92}
93
94#[cfg(test)]
95#[path = "message_tests.rs"]
96mod tests;