tungstenite/protocol/
message.rs

1use super::frame::{CloseFrame, Frame};
2use crate::{
3    error::{CapacityError, Error, Result},
4    protocol::frame::Utf8Bytes,
5};
6use std::{fmt, result::Result as StdResult, str};
7
8mod string_collect {
9    use utf8::DecodeError;
10
11    use crate::error::{Error, Result};
12
13    #[derive(Debug)]
14    pub struct StringCollector {
15        data: String,
16        incomplete: Option<utf8::Incomplete>,
17    }
18
19    impl StringCollector {
20        pub fn new() -> Self {
21            StringCollector { data: String::new(), incomplete: None }
22        }
23
24        pub fn len(&self) -> usize {
25            self.data
26                .len()
27                .saturating_add(self.incomplete.map(|i| i.buffer_len as usize).unwrap_or(0))
28        }
29
30        pub fn extend<T: AsRef<[u8]>>(&mut self, tail: T) -> Result<()> {
31            let mut input: &[u8] = tail.as_ref();
32
33            if let Some(mut incomplete) = self.incomplete.take() {
34                if let Some((result, rest)) = incomplete.try_complete(input) {
35                    input = rest;
36                    match result {
37                        Ok(text) => self.data.push_str(text),
38                        Err(result_bytes) => {
39                            return Err(Error::Utf8(String::from_utf8_lossy(result_bytes).into()))
40                        }
41                    }
42                } else {
43                    input = &[];
44                    self.incomplete = Some(incomplete);
45                }
46            }
47
48            if !input.is_empty() {
49                match utf8::decode(input) {
50                    Ok(text) => {
51                        self.data.push_str(text);
52                        Ok(())
53                    }
54                    Err(DecodeError::Incomplete { valid_prefix, incomplete_suffix }) => {
55                        self.data.push_str(valid_prefix);
56                        self.incomplete = Some(incomplete_suffix);
57                        Ok(())
58                    }
59                    Err(DecodeError::Invalid { valid_prefix, invalid_sequence, .. }) => {
60                        self.data.push_str(valid_prefix);
61                        Err(Error::Utf8(String::from_utf8_lossy(invalid_sequence).into()))
62                    }
63                }
64            } else {
65                Ok(())
66            }
67        }
68
69        pub fn into_string(self) -> Result<String> {
70            if let Some(incomplete) = self.incomplete {
71                Err(Error::Utf8(format!("incomplete string: {incomplete:?}")))
72            } else {
73                Ok(self.data)
74            }
75        }
76    }
77}
78
79use self::string_collect::StringCollector;
80use bytes::Bytes;
81
82/// A struct representing the incomplete message.
83#[derive(Debug)]
84pub struct IncompleteMessage {
85    collector: IncompleteMessageCollector,
86}
87
88#[derive(Debug)]
89enum IncompleteMessageCollector {
90    Text(StringCollector),
91    Binary(Vec<u8>),
92}
93
94impl IncompleteMessage {
95    /// Create new.
96    pub fn new(message_type: MessageType) -> Self {
97        IncompleteMessage {
98            collector: match message_type {
99                MessageType::Binary => IncompleteMessageCollector::Binary(Vec::new()),
100                MessageType::Text => IncompleteMessageCollector::Text(StringCollector::new()),
101            },
102        }
103    }
104
105    /// Get the current filled size of the buffer.
106    pub fn len(&self) -> usize {
107        match self.collector {
108            IncompleteMessageCollector::Text(ref t) => t.len(),
109            IncompleteMessageCollector::Binary(ref b) => b.len(),
110        }
111    }
112
113    /// Add more data to an existing message.
114    pub fn extend<T: AsRef<[u8]>>(&mut self, tail: T, size_limit: Option<usize>) -> Result<()> {
115        // Always have a max size. This ensures an error in case of concatenating two buffers
116        // of more than `usize::max_value()` bytes in total.
117        let max_size = size_limit.unwrap_or_else(usize::max_value);
118        let my_size = self.len();
119        let portion_size = tail.as_ref().len();
120        // Be careful about integer overflows here.
121        if my_size > max_size || portion_size > max_size - my_size {
122            return Err(Error::Capacity(CapacityError::MessageTooLong {
123                size: my_size + portion_size,
124                max_size,
125            }));
126        }
127
128        match self.collector {
129            IncompleteMessageCollector::Binary(ref mut v) => {
130                v.extend(tail.as_ref());
131                Ok(())
132            }
133            IncompleteMessageCollector::Text(ref mut t) => t.extend(tail),
134        }
135    }
136
137    /// Convert an incomplete message into a complete one.
138    pub fn complete(self) -> Result<Message> {
139        match self.collector {
140            IncompleteMessageCollector::Binary(v) => Ok(Message::Binary(v.into())),
141            IncompleteMessageCollector::Text(t) => {
142                let text = t.into_string()?;
143                Ok(Message::text(text))
144            }
145        }
146    }
147}
148
149/// The type of incomplete message.
150pub enum MessageType {
151    Text,
152    Binary,
153}
154
155/// An enum representing the various forms of a WebSocket message.
156#[derive(Debug, Eq, PartialEq, Clone)]
157pub enum Message {
158    /// A text WebSocket message
159    Text(Utf8Bytes),
160    /// A binary WebSocket message
161    Binary(Bytes),
162    /// A ping message with the specified payload
163    ///
164    /// The payload here must have a length less than 125 bytes
165    Ping(Bytes),
166    /// A pong message with the specified payload
167    ///
168    /// The payload here must have a length less than 125 bytes
169    Pong(Bytes),
170    /// A close message with the optional close frame.
171    Close(Option<CloseFrame>),
172    /// Raw frame. Note, that you're not going to get this value while reading the message.
173    Frame(Frame),
174}
175
176impl Message {
177    /// Create a new text WebSocket message from a stringable.
178    pub fn text<S>(string: S) -> Message
179    where
180        S: Into<Utf8Bytes>,
181    {
182        Message::Text(string.into())
183    }
184
185    /// Create a new binary WebSocket message by converting to `Bytes`.
186    pub fn binary<B>(bin: B) -> Message
187    where
188        B: Into<Bytes>,
189    {
190        Message::Binary(bin.into())
191    }
192
193    /// Indicates whether a message is a text message.
194    pub fn is_text(&self) -> bool {
195        matches!(*self, Message::Text(_))
196    }
197
198    /// Indicates whether a message is a binary message.
199    pub fn is_binary(&self) -> bool {
200        matches!(*self, Message::Binary(_))
201    }
202
203    /// Indicates whether a message is a ping message.
204    pub fn is_ping(&self) -> bool {
205        matches!(*self, Message::Ping(_))
206    }
207
208    /// Indicates whether a message is a pong message.
209    pub fn is_pong(&self) -> bool {
210        matches!(*self, Message::Pong(_))
211    }
212
213    /// Indicates whether a message is a close message.
214    pub fn is_close(&self) -> bool {
215        matches!(*self, Message::Close(_))
216    }
217
218    /// Get the length of the WebSocket message.
219    pub fn len(&self) -> usize {
220        match *self {
221            Message::Text(ref string) => string.len(),
222            Message::Binary(ref data) | Message::Ping(ref data) | Message::Pong(ref data) => {
223                data.len()
224            }
225            Message::Close(ref data) => data.as_ref().map(|d| d.reason.len()).unwrap_or(0),
226            Message::Frame(ref frame) => frame.len(),
227        }
228    }
229
230    /// Returns true if the WebSocket message has no content.
231    /// For example, if the other side of the connection sent an empty string.
232    pub fn is_empty(&self) -> bool {
233        self.len() == 0
234    }
235
236    /// Consume the WebSocket and return it as binary data.
237    pub fn into_data(self) -> Bytes {
238        match self {
239            Message::Text(utf8) => utf8.into(),
240            Message::Binary(data) | Message::Ping(data) | Message::Pong(data) => data,
241            Message::Close(None) => <_>::default(),
242            Message::Close(Some(frame)) => frame.reason.into(),
243            Message::Frame(frame) => frame.into_payload(),
244        }
245    }
246
247    /// Attempt to consume the WebSocket message and convert it to a String.
248    pub fn into_text(self) -> Result<Utf8Bytes> {
249        match self {
250            Message::Text(txt) => Ok(txt),
251            Message::Binary(data) | Message::Ping(data) | Message::Pong(data) => {
252                Ok(data.try_into()?)
253            }
254            Message::Close(None) => Ok(<_>::default()),
255            Message::Close(Some(frame)) => Ok(frame.reason),
256            Message::Frame(frame) => Ok(frame.into_text()?),
257        }
258    }
259
260    /// Attempt to get a &str from the WebSocket message,
261    /// this will try to convert binary data to utf8.
262    pub fn to_text(&self) -> Result<&str> {
263        match *self {
264            Message::Text(ref string) => Ok(string.as_str()),
265            Message::Binary(ref data) | Message::Ping(ref data) | Message::Pong(ref data) => {
266                Ok(str::from_utf8(data)?)
267            }
268            Message::Close(None) => Ok(""),
269            Message::Close(Some(ref frame)) => Ok(&frame.reason),
270            Message::Frame(ref frame) => Ok(frame.to_text()?),
271        }
272    }
273}
274
275impl From<String> for Message {
276    #[inline]
277    fn from(string: String) -> Self {
278        Message::text(string)
279    }
280}
281
282impl<'s> From<&'s str> for Message {
283    #[inline]
284    fn from(string: &'s str) -> Self {
285        Message::text(string)
286    }
287}
288
289impl<'b> From<&'b [u8]> for Message {
290    #[inline]
291    fn from(data: &'b [u8]) -> Self {
292        Message::binary(Bytes::copy_from_slice(data))
293    }
294}
295
296impl From<Bytes> for Message {
297    fn from(data: Bytes) -> Self {
298        Message::binary(data)
299    }
300}
301
302impl From<Vec<u8>> for Message {
303    #[inline]
304    fn from(data: Vec<u8>) -> Self {
305        Message::binary(data)
306    }
307}
308
309impl From<Message> for Bytes {
310    #[inline]
311    fn from(message: Message) -> Self {
312        message.into_data()
313    }
314}
315
316impl fmt::Display for Message {
317    fn fmt(&self, f: &mut fmt::Formatter) -> StdResult<(), fmt::Error> {
318        if let Ok(string) = self.to_text() {
319            write!(f, "{string}")
320        } else {
321            write!(f, "Binary Data<length={}>", self.len())
322        }
323    }
324}
325
326#[cfg(test)]
327mod tests {
328    use super::*;
329
330    #[test]
331    fn display() {
332        let t = Message::text("test".to_owned());
333        assert_eq!(t.to_string(), "test".to_owned());
334
335        let bin = Message::binary(vec![0, 1, 3, 4, 241]);
336        assert_eq!(bin.to_string(), "Binary Data<length=5>".to_owned());
337    }
338
339    #[test]
340    fn binary_convert() {
341        let bin = [6u8, 7, 8, 9, 10, 241];
342        let msg = Message::from(&bin[..]);
343        assert!(msg.is_binary());
344        assert!(msg.into_text().is_err());
345    }
346
347    #[test]
348    fn binary_convert_bytes() {
349        let bin = Bytes::from_iter([6u8, 7, 8, 9, 10, 241]);
350        let msg = Message::from(bin);
351        assert!(msg.is_binary());
352        assert!(msg.into_text().is_err());
353    }
354
355    #[test]
356    fn binary_convert_vec() {
357        let bin = vec![6u8, 7, 8, 9, 10, 241];
358        let msg = Message::from(bin);
359        assert!(msg.is_binary());
360        assert!(msg.into_text().is_err());
361    }
362
363    #[test]
364    fn binary_convert_into_bytes() {
365        let bin = vec![6u8, 7, 8, 9, 10, 241];
366        let bin_copy = bin.clone();
367        let msg = Message::from(bin);
368        let serialized: Bytes = msg.into();
369        assert_eq!(bin_copy, serialized);
370    }
371
372    #[test]
373    fn text_convert() {
374        let s = "kiwotsukete";
375        let msg = Message::from(s);
376        assert!(msg.is_text());
377    }
378}