1use crate::peer::extension;
2use crate::{bencode, PieceIndex};
3use std::io;
4use std::net::SocketAddr;
5use thiserror::Error;
6use tokio::time::error::Elapsed;
7
8pub type Result<T> = std::result::Result<T, Error>;
10
11#[derive(Debug, Error)]
13pub enum Error {
14 #[error("peer id is invalid")]
16 InvalidPeerId,
17 #[error("invalid message length, expected {0} but got {1}")]
19 InvalidLength(u32, u32),
20 #[error("piece index {0} is invalid")]
22 InvalidPiece(PieceIndex),
23 #[error("invalid state {0}")]
25 InvalidState(String),
26 #[error("unsupported message type {0}")]
28 UnsupportedMessage(u8),
29 #[error("unsupported version {0}")]
31 UnsupportedVersion(u32),
32 #[error("extension number {0} is not supported")]
34 UnsupportedExtensions(u8),
35 #[error("handshake with {0} failed, {1}")]
37 Handshake(SocketAddr, String),
38 #[error("failed to parse message, {0}")]
40 Parsing(String),
41 #[error("an io error occurred, {0}")]
43 Io(io::Error),
44 #[error("an extension error occurred, {0}")]
46 Extension(extension::Error),
47 #[error("the payload exceeds the maximum size of {0}")]
49 TooLarge(usize),
50 #[error("the peer connection is closed")]
52 Closed,
53}
54
55impl PartialEq for Error {
56 fn eq(&self, other: &Self) -> bool {
57 match (self, other) {
58 (Error::InvalidPeerId, Error::InvalidPeerId) => true,
59 (Error::InvalidLength(_, _), Error::InvalidLength(_, _)) => true,
60 (Error::InvalidPiece(_), Error::InvalidPiece(_)) => true,
61 (Error::InvalidState(_), Error::InvalidState(_)) => true,
62 (Error::UnsupportedMessage(_), Error::UnsupportedMessage(_)) => true,
63 (Error::UnsupportedVersion(_), Error::UnsupportedVersion(_)) => true,
64 (Error::UnsupportedExtensions(_), Error::UnsupportedExtensions(_)) => true,
65 (Error::Handshake(_, _), Error::Handshake(_, _)) => true,
66 (Error::Parsing(_), Error::Parsing(_)) => true,
67 (Error::Io(_), Error::Io(_)) => true,
68 (Error::Extension(lt), Error::Extension(rt)) => lt == rt,
69 (Error::Closed, Error::Closed) => true,
70 _ => false,
71 }
72 }
73}
74
75impl From<crate::TorrentError> for Error {
76 fn from(error: crate::TorrentError) -> Self {
77 Self::Io(io::Error::new(io::ErrorKind::Other, error))
78 }
79}
80
81impl From<bencode::Error> for Error {
82 fn from(error: bencode::Error) -> Self {
83 Self::Parsing(error.to_string())
84 }
85}
86
87impl From<io::Error> for Error {
88 fn from(error: io::Error) -> Self {
89 Self::Io(error)
90 }
91}
92
93impl From<Elapsed> for Error {
94 fn from(error: Elapsed) -> Self {
95 Self::Io(io::Error::new(io::ErrorKind::TimedOut, error))
96 }
97}
98
99#[cfg(test)]
100mod tests {
101 use super::*;
102
103 #[test]
104 fn test_error_from_io() {
105 let error = io::Error::from(io::ErrorKind::UnexpectedEof);
106
107 let result = Error::from(error);
108
109 if let Error::Io(_) = result {
110 return;
111 } else {
112 assert!(false, "expected Error::Io, got {:?} instead", result)
113 }
114 }
115}