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
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
use alloc::{
    format,
    str::Utf8Error,
    string::{FromUtf8Error, String, ToString},
};
use core::{fmt::Display, num::ParseIntError};

#[cfg(feature = "std")]
use std::sync::Arc;

use snafu::Snafu;

use crate::state_tracker;

#[derive(Debug, Clone, Snafu)]
pub struct Error {
    context: Option<String>,
    source: ErrorKind,
}

// An enumeration of potential errors that appear during bencode deserialization.
#[derive(Debug, Clone, Snafu)]
pub enum ErrorKind {
    /// Error that occurs if the serialized structure contains invalid semantics.
    #[cfg(feature = "std")]
    #[snafu(display("malformed content discovered: {}", source))]
    MalformedContent { source: Arc<dyn std::error::Error> },

    /// Error that occurs if the serialized structure contains invalid semantics.
    #[cfg(not(feature = "std"))]
    #[snafu(display("malformed content discovered"))]
    MalformedContent,

    /// Error that occurs if the serialized structure is incomplete.
    #[snafu(display("missing field: {}", field))]
    MissingField { field: String },

    /// Error in the bencode structure (e.g. a missing field and seperator).
    #[snafu(display("bencode encoding corrupted ({})", source))]
    StructureError {
        source: state_tracker::StructureError,
    },

    /// Error that occurs if the serialized structure contains an unexpected field.
    #[snafu(display("unexpected field: {}", field))]
    UnexpectedField { field: String },

    /// Error through an unexpected bencode token during deserialization.
    #[snafu(display("discovered {} but expected {}", expected, discovered))]
    UnexpectedToken {
        expected: String,
        discovered: String,
    },
}

pub trait ResultExt {
    fn context(self, context: impl Display) -> Self;
}

impl Error {
    pub fn context(mut self, context: impl Display) -> Self {
        if let Some(current) = self.context.as_mut() {
            *current = format!("{}.{}", context, current);
        } else {
            self.context = Some(context.to_string());
        }

        self
    }

    /// Raised when there is a general error while deserializing a type.
    /// The message should not be capitalized and should not end with a period.
    #[cfg(feature = "std")]
    pub fn malformed_content<SourceT>(source: SourceT) -> Self
    where
        SourceT: std::error::Error + Send + Sync + 'static,
    {
        let error = Arc::new(source);
        ErrorKind::MalformedContent { source: error }.into()
    }

    #[cfg(not(feature = "std"))]
    pub fn malformed_content<T>(_cause: T) -> Self {
        Self::from(ErrorKind::MalformedContent)
    }

    // Returns a `Error::MissingField` which contains the name of the field.
    pub fn missing_field(field_name: impl Display) -> Self {
        Error::from(ErrorKind::MissingField {
            field: field_name.to_string(),
        })
    }

    /// Returns a `Error::UnexpectedField` which contains the name of the field.
    pub fn unexpected_field(field_name: impl Display) -> Self {
        Error::from(ErrorKind::UnexpectedField {
            field: field_name.to_string(),
        })
    }

    /// Returns a `Error::UnexpectedElement` which contains a custom error message.
    pub fn unexpected_token(expected: impl Display, discovered: impl Display) -> Self {
        Error::from(ErrorKind::UnexpectedToken {
            expected: expected.to_string(),
            discovered: discovered.to_string(),
        })
    }
}

impl From<ErrorKind> for Error {
    fn from(kind: ErrorKind) -> Self {
        Self {
            context: None,
            source: kind,
        }
    }
}

impl From<state_tracker::StructureError> for Error {
    fn from(error: state_tracker::StructureError) -> Self {
        Self::from(ErrorKind::StructureError { source: error })
    }
}

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

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

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

impl<T> ResultExt for Result<T, Error> {
    fn context(self, context: impl Display) -> Self {
        self.map_err(|err| err.context(context))
    }
}