Skip to main content

fx_torrent/bencode/
error.rs

1use serde::de::{Expected, Unexpected};
2use serde::{de, ser};
3use std::fmt::Display;
4use std::{io, result};
5use thiserror::Error;
6
7/// The error alias for bencode operations.
8pub type Result<T> = result::Result<T, Error>;
9
10/// The errors that might occur within bencode operations.
11#[derive(Debug, Error)]
12pub enum Error {
13    #[error("{0}")]
14    InvalidType(String),
15    #[error("{0}")]
16    InvalidValue(String),
17    #[error("{0}")]
18    InvalidLength(String),
19    #[error("unknown variant: {0}, (expected one of: {1}")]
20    UnknownVariant(String, String),
21    #[error("unknown field: {0}, (expected one of: {1})")]
22    UnknownField(String, String),
23    #[error("missing field: {0}")]
24    MissingField(String),
25    #[error("duplicate field: {0}")]
26    DuplicateField(String),
27    #[error("an io error occurred, {0}")]
28    Io(io::Error),
29    #[error("{0}")]
30    Custom(String),
31}
32
33impl Error {}
34
35impl ser::Error for Error {
36    fn custom<T>(msg: T) -> Self
37    where
38        T: Display,
39    {
40        Self::Custom(msg.to_string())
41    }
42}
43
44impl de::Error for Error {
45    fn custom<T>(msg: T) -> Self
46    where
47        T: Display,
48    {
49        Self::Custom(msg.to_string())
50    }
51
52    fn invalid_type(unexp: Unexpected, exp: &dyn Expected) -> Self {
53        Self::InvalidType(format!("invalid type: {unexp} (expected: `{exp}`)"))
54    }
55
56    fn invalid_value(unexp: Unexpected, exp: &dyn Expected) -> Self {
57        Self::InvalidValue(format!("invalid value: {unexp} (expected: `{exp}`)"))
58    }
59
60    fn invalid_length(len: usize, exp: &dyn Expected) -> Self {
61        Self::InvalidLength(format!("invalid length: {len} (expected: `{exp}`)"))
62    }
63
64    fn unknown_variant(variant: &str, expected: &'static [&'static str]) -> Self {
65        Self::UnknownVariant(variant.to_string(), expected.join(", "))
66    }
67
68    fn unknown_field(field: &str, expected: &'static [&'static str]) -> Self {
69        Self::UnknownField(field.to_string(), expected.join(", "))
70    }
71
72    fn missing_field(field: &'static str) -> Self {
73        Self::MissingField(field.to_string())
74    }
75
76    fn duplicate_field(field: &'static str) -> Self {
77        Self::DuplicateField(field.to_string())
78    }
79}
80
81impl From<io::Error> for Error {
82    fn from(err: io::Error) -> Self {
83        Self::Io(err)
84    }
85}