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