open_net/api/ws/
message.rs1use bytes::Bytes;
2use std::fmt;
3
4#[derive(Clone, Eq, PartialEq)]
8pub enum Message {
9 Text(
11 String,
13 ),
14 Binary(
16 Bytes,
18 ),
19}
20
21impl fmt::Debug for Message {
22 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
23 let variant = match self {
24 Self::Text(_) => "Text",
25 Self::Binary(_) => "Binary",
26 };
27 formatter
28 .debug_struct(variant)
29 .field("bytes", &self.len())
30 .finish()
31 }
32}
33
34impl Message {
35 pub fn text(value: impl Into<String>) -> Self {
37 Self::Text(value.into())
38 }
39
40 pub fn binary(value: impl Into<Bytes>) -> Self {
42 Self::Binary(value.into())
43 }
44
45 pub fn as_text(&self) -> Option<&str> {
47 match self {
48 Self::Text(value) => Some(value),
49 Self::Binary(_) => None,
50 }
51 }
52
53 pub fn as_bytes(&self) -> &[u8] {
55 match self {
56 Self::Text(value) => value.as_bytes(),
57 Self::Binary(value) => value.as_ref(),
58 }
59 }
60
61 pub fn into_bytes(self) -> Bytes {
63 match self {
64 Self::Text(value) => Bytes::from(value),
65 Self::Binary(value) => value,
66 }
67 }
68
69 pub fn len(&self) -> usize {
71 self.as_bytes().len()
72 }
73
74 pub fn is_empty(&self) -> bool {
76 self.as_bytes().is_empty()
77 }
78}
79
80impl From<String> for Message {
81 fn from(value: String) -> Self {
82 Self::Text(value)
83 }
84}
85
86impl From<&str> for Message {
87 fn from(value: &str) -> Self {
88 Self::Text(value.to_owned())
89 }
90}
91
92impl From<Bytes> for Message {
93 fn from(value: Bytes) -> Self {
94 Self::Binary(value)
95 }
96}
97
98impl From<Vec<u8>> for Message {
99 fn from(value: Vec<u8>) -> Self {
100 Self::Binary(Bytes::from(value))
101 }
102}
103
104impl From<&[u8]> for Message {
105 fn from(value: &[u8]) -> Self {
106 Self::Binary(Bytes::copy_from_slice(value))
107 }
108}
109
110#[cfg(test)]
111#[path = "message_tests.rs"]
112mod tests;