]> git.lizzy.rs Git - mt_rudp.git/blob - src/error.rs
async
[mt_rudp.git] / src / error.rs
1 use crate::{CtlType, InPkt, PktType};
2 use num_enum::TryFromPrimitiveError;
3 use std::{fmt, io};
4 use tokio::sync::mpsc::error::SendError;
5
6 #[derive(Debug)]
7 pub enum Error {
8     IoError(io::Error),
9     InvalidProtoId(u32),
10     InvalidPeerID,
11     InvalidChannel(u8),
12     InvalidType(u8),
13     InvalidCtlType(u8),
14     RemoteDisco,
15     LocalDisco,
16 }
17
18 impl From<io::Error> for Error {
19     fn from(err: io::Error) -> Self {
20         Self::IoError(err)
21     }
22 }
23
24 impl From<TryFromPrimitiveError<PktType>> for Error {
25     fn from(err: TryFromPrimitiveError<PktType>) -> Self {
26         Self::InvalidType(err.number)
27     }
28 }
29
30 impl From<TryFromPrimitiveError<CtlType>> for Error {
31     fn from(err: TryFromPrimitiveError<CtlType>) -> Self {
32         Self::InvalidType(err.number)
33     }
34 }
35
36 impl From<SendError<InPkt>> for Error {
37     fn from(_err: SendError<InPkt>) -> Self {
38         Self::LocalDisco // technically not a disconnect but a local drop
39     }
40 }
41
42 impl fmt::Display for Error {
43     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
44         use Error::*;
45         write!(f, "RUDP Error: ")?;
46
47         match self {
48             IoError(err) => write!(f, "IO Error: {}", err),
49             InvalidProtoId(id) => write!(f, "Invalid Protocol ID: {id}"),
50             InvalidPeerID => write!(f, "Invalid Peer ID"),
51             InvalidChannel(ch) => write!(f, "Invalid Channel: {ch}"),
52             InvalidType(tp) => write!(f, "Invalid Type: {tp}"),
53             InvalidCtlType(tp) => write!(f, "Invalid Control Type: {tp}"),
54             RemoteDisco => write!(f, "Remote Disconnected"),
55             LocalDisco => write!(f, "Local Disconnected"),
56         }
57     }
58 }