aboutsummaryrefslogtreecommitdiff
path: root/src/error.rs
blob: 55566fafa2c5f42594395de599b2b07146d3104f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
use crate::prelude::*;
use num_enum::TryFromPrimitiveError;
use std::{fmt, io};
use tokio::sync::mpsc::error::SendError;

#[derive(Debug)]
pub enum Error {
    IoError(io::Error),
    InvalidProtoId(u32),
    InvalidChannel(u8),
    InvalidType(u8),
    InvalidCtlType(u8),
    PeerIDAlreadySet,
    InvalidChunkIndex(usize, usize),
    InvalidChunkCount(usize, usize),
    RemoteDisco(bool),
    LocalDisco,
}

impl From<io::Error> for Error {
    fn from(err: io::Error) -> Self {
        Self::IoError(err)
    }
}

impl From<TryFromPrimitiveError<PktType>> for Error {
    fn from(err: TryFromPrimitiveError<PktType>) -> Self {
        Self::InvalidType(err.number)
    }
}

impl From<TryFromPrimitiveError<CtlType>> for Error {
    fn from(err: TryFromPrimitiveError<CtlType>) -> Self {
        Self::InvalidType(err.number)
    }
}

impl From<SendError<InPkt>> for Error {
    fn from(_err: SendError<InPkt>) -> Self {
        Self::LocalDisco
    }
}

impl fmt::Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        use Error::*;
        write!(f, "rudp: ")?;

        match self {
            IoError(err) => write!(f, "IO error: {err}"),
            InvalidProtoId(id) => write!(f, "invalid protocol ID: {id}"),
            InvalidChannel(ch) => write!(f, "invalid channel: {ch}"),
            InvalidType(tp) => write!(f, "invalid type: {tp}"),
            InvalidCtlType(tp) => write!(f, "invalid control type: {tp}"),
            PeerIDAlreadySet => write!(f, "peer ID already set"),
            InvalidChunkIndex(i, n) => write!(f, "chunk index {i} bigger than chunk count {n}"),
            InvalidChunkCount(o, n) => write!(f, "chunk count changed from {o} to {n}"),
            RemoteDisco(to) => write!(
                f,
                "remote disconnected{}",
                if *to { " (timeout)" } else { "" }
            ),
            LocalDisco => write!(f, "local disconnected"),
        }
    }
}

impl std::error::Error for Error {}