websocket_base/
result.rs

1//! The result type used within Rust-WebSocket
2
3use std;
4use std::convert::From;
5use std::error::Error;
6use std::fmt;
7use std::io;
8use std::str::Utf8Error;
9
10/// The type used for WebSocket results
11pub type WebSocketResult<T> = Result<T, WebSocketError>;
12
13/// This module contains convenience types to make working with Futures and
14/// websocket results easier.
15#[cfg(feature = "async")]
16pub mod r#async {
17	use super::WebSocketError;
18	use futures::Future;
19
20	/// The most common Future in this library, it is simply some result `I` or
21	/// a `WebSocketError`. This is analogous to the `WebSocketResult` type.
22	pub type WebSocketFuture<I> = Box<dyn Future<Item = I, Error = WebSocketError> + Send>;
23}
24
25/// Represents a WebSocket error
26#[derive(Debug)]
27pub enum WebSocketError {
28	/// A WebSocket protocol error
29	ProtocolError(&'static str),
30	/// Invalid WebSocket data frame error
31	DataFrameError(&'static str),
32	/// No data available
33	NoDataAvailable,
34	/// An input/output error
35	IoError(io::Error),
36	/// A UTF-8 error
37	Utf8Error(Utf8Error),
38	/// Other error from higher-level crate, for downcasting
39	Other(Box<dyn std::error::Error + Send + Sync + 'static>),
40}
41
42impl fmt::Display for WebSocketError {
43	fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
44		fmt.write_str("WebSocketError: ")?;
45		match self {
46			WebSocketError::ProtocolError(_) => fmt.write_str("WebSocket protocol error"),
47			WebSocketError::DataFrameError(_) => fmt.write_str("WebSocket data frame error"),
48			WebSocketError::NoDataAvailable => fmt.write_str("No data available"),
49			WebSocketError::IoError(_) => fmt.write_str("I/O failure"),
50			WebSocketError::Utf8Error(_) => fmt.write_str("UTF-8 failure"),
51			WebSocketError::Other(x) => x.fmt(fmt),
52		}
53	}
54}
55
56impl Error for WebSocketError {
57	fn source(&self) -> Option<&(dyn Error + 'static)> {
58		match *self {
59			WebSocketError::IoError(ref error) => Some(error),
60			WebSocketError::Utf8Error(ref error) => Some(error),
61			WebSocketError::Other(ref error) => error.source(),
62			_ => None,
63		}
64	}
65}
66
67impl From<io::Error> for WebSocketError {
68	fn from(err: io::Error) -> WebSocketError {
69		if err.kind() == io::ErrorKind::UnexpectedEof {
70			return WebSocketError::NoDataAvailable;
71		}
72		WebSocketError::IoError(err)
73	}
74}
75
76impl From<Utf8Error> for WebSocketError {
77	fn from(err: Utf8Error) -> WebSocketError {
78		WebSocketError::Utf8Error(err)
79	}
80}