Skip to main content

kcp/
error.rs

1use std::error::Error as StdError;
2use std::fmt;
3use std::io::{self, ErrorKind};
4
5/// KCP protocol errors
6#[derive(Debug)]
7pub enum Error {
8    ConvInconsistent(u32, u32),
9    InvalidMtu(usize),
10    InvalidSegmentSize(usize),
11    InvalidSegmentDataSize(usize, usize),
12    IoError(io::Error),
13    NeedUpdate,
14    RecvQueueEmpty,
15    ExpectingFragment,
16    UnsupportedCmd(u8),
17    UserBufTooBig,
18    UserBufTooSmall,
19    TokenMismatch(u32, u32),
20}
21
22impl StdError for Error {
23    fn cause(&self) -> Option<&dyn StdError> {
24        match *self {
25            Error::IoError(ref e) => Some(e),
26            _ => None,
27        }
28    }
29}
30
31impl fmt::Display for Error {
32    fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
33        match *self {
34            Error::ConvInconsistent(ref s, ref o) => {
35                write!(f, "conv inconsistent, expected {}, found {}", *s, *o)
36            }
37            Error::InvalidMtu(ref e) => write!(f, "invalid mtu {}", *e),
38            Error::InvalidSegmentSize(ref e) => write!(f, "invalid segment size of {}", *e),
39            Error::InvalidSegmentDataSize(ref s, ref o) => {
40                write!(
41                    f,
42                    "invalid segment data size, expected {}, found {}",
43                    *s, *o
44                )
45            }
46            Error::IoError(ref e) => e.fmt(f),
47            Error::UnsupportedCmd(ref e) => write!(f, "cmd {} is not supported", *e),
48            ref e => write!(f, "{}", e),
49        }
50    }
51}
52
53fn make_io_error<T>(kind: ErrorKind, msg: T) -> io::Error
54where
55    T: Into<Box<dyn StdError + Send + Sync>>,
56{
57    io::Error::new(kind, msg)
58}
59
60impl From<Error> for io::Error {
61    fn from(err: Error) -> io::Error {
62        let kind = match err {
63            Error::ConvInconsistent(..) => ErrorKind::Other,
64            Error::InvalidMtu(..) => ErrorKind::Other,
65            Error::InvalidSegmentSize(..) => ErrorKind::Other,
66            Error::InvalidSegmentDataSize(..) => ErrorKind::Other,
67            Error::IoError(err) => return err,
68            Error::NeedUpdate => ErrorKind::Other,
69            Error::RecvQueueEmpty => ErrorKind::WouldBlock,
70            Error::ExpectingFragment => ErrorKind::WouldBlock,
71            Error::UnsupportedCmd(..) => ErrorKind::Other,
72            Error::UserBufTooBig => ErrorKind::Other,
73            Error::UserBufTooSmall => ErrorKind::Other,
74            Error::TokenMismatch(..) => ErrorKind::Other,
75        };
76
77        make_io_error(kind, err)
78    }
79}
80
81impl From<io::Error> for Error {
82    fn from(err: io::Error) -> Error {
83        Error::IoError(err)
84    }
85}