Skip to main content

links_notation/binary/
error.rs

1//! Errors from binary links notation codecs.
2
3use std::{error::Error, fmt, io};
4
5/// A failure while encoding or decoding a packet or LiNo document.
6#[derive(Debug)]
7pub enum BinaryError {
8    Io(io::Error),
9    Malformed(String),
10    InvalidLino(String),
11    LimitExceeded(String),
12    Unencodable(String),
13}
14
15impl BinaryError {
16    pub(crate) fn malformed(message: impl Into<String>) -> Self {
17        Self::Malformed(message.into())
18    }
19}
20
21impl fmt::Display for BinaryError {
22    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
23        let (kind, detail) = match self {
24            Self::Io(error) => return write!(f, "I/O error: {error}"),
25            Self::Malformed(detail) => ("malformed message", detail),
26            Self::InvalidLino(detail) => ("invalid LiNo", detail),
27            Self::LimitExceeded(detail) => ("limit exceeded", detail),
28            Self::Unencodable(detail) => ("cannot encode", detail),
29        };
30        write!(f, "{kind}: {detail}")
31    }
32}
33
34impl Error for BinaryError {
35    fn source(&self) -> Option<&(dyn Error + 'static)> {
36        match self {
37            Self::Io(error) => Some(error),
38            _ => None,
39        }
40    }
41}
42
43impl From<io::Error> for BinaryError {
44    fn from(error: io::Error) -> Self {
45        Self::Io(error)
46    }
47}
48
49/// Result returned by the binary codecs.
50pub type BinaryResult<T> = Result<T, BinaryError>;