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
//! Custom error

use serde::{de, ser};
use std::fmt::Display;

// pub type Result<T> = core::result::Result<T, Error>;

/// Custom serialization/deserialization errors
#[derive(Debug, thiserror::Error)]
pub enum Error {
    /// Custom error with message
    #[error("Message {0}")]
    Message(String),

    /// IO error
    #[error("IO {0}")]
    Io(std::io::Error),

    /// Invalid format code
    #[error("Invalid format code")]
    InvalidFormatCode,

    /// Invalid value
    #[error("Invalid value")]
    InvalidValue,

    /// A described type is found while a primitive type is expected
    #[error("Expecting non-described constructor")]
    IsDescribedType,

    /// Found invalid UTF-8 encoding
    #[error("Invalid UTF-8 encoding")]
    InvalidUtf8Encoding,

    /// Sequence type length mismatch
    #[error("Sequence length mismatch")]
    SequenceLengthMismatch,

    /// Length is invalid
    #[error("Invalid length")]
    InvalidLength,
}

impl Error {
    pub(crate) fn too_long() -> Self {
        let io_err = std::io::Error::new(std::io::ErrorKind::Other, "Too long");
        Self::Io(io_err)
    }

    pub(crate) fn unexpected_eof(
        error: impl Into<Box<dyn std::error::Error + Send + Sync>>,
    ) -> Self {
        let io_err = std::io::Error::new(std::io::ErrorKind::UnexpectedEof, error);
        Self::Io(io_err)
    }
}

impl ser::Error for Error {
    fn custom<T>(msg: T) -> Self
    where
        T: std::fmt::Display,
    {
        Self::Message(msg.to_string())
    }
}

impl de::Error for Error {
    fn custom<T>(msg: T) -> Self
    where
        T: Display,
    {
        Self::Message(msg.to_string())
    }
}

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

impl From<std::string::FromUtf8Error> for Error {
    fn from(_: std::string::FromUtf8Error) -> Self {
        Error::InvalidUtf8Encoding
    }
}

impl From<std::str::Utf8Error> for Error {
    fn from(_: std::str::Utf8Error) -> Self {
        Error::InvalidUtf8Encoding
    }
}