open_net/api/ws/
message.rs1use bytes::Bytes;
2
3#[derive(Clone, Debug, Eq, PartialEq)]
5pub enum Message {
6 Text(
8 String,
10 ),
11 Binary(
13 Bytes,
15 ),
16}
17
18impl Message {
19 pub fn text(value: impl Into<String>) -> Self {
21 Self::Text(value.into())
22 }
23
24 pub fn binary(value: impl Into<Bytes>) -> Self {
26 Self::Binary(value.into())
27 }
28
29 pub fn as_text(&self) -> Option<&str> {
31 match self {
32 Self::Text(value) => Some(value),
33 Self::Binary(_) => None,
34 }
35 }
36
37 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 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 pub fn len(&self) -> usize {
55 self.as_bytes().len()
56 }
57
58 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;