vdf_serde/
error.rs

1//! When serializing or deserializing VDF goes wrong
2
3use std::fmt::{self, Display};
4
5use serde::{de, ser};
6
7/// Alias for a `Result` with the error type `vdf_serde::Error`
8pub type Result<T> = std::result::Result<T, Error>;
9
10/// This type represents all possible errors that can occur when serializing or
11/// deserializing VDF data
12#[derive(Clone, Debug, PartialEq, Hash)]
13pub enum Error {
14    /// An error carried up from the specific Serialize/Deserialize implementation
15    Message(String),
16
17    /// Unsupported Serde data type
18    UnsupportedType(&'static str),
19
20    /// EOF too early
21    EarlyEOF,
22
23    /// EOF too late
24    LateEOF,
25
26    /// Tokenization error
27    /// (This could be a nom::Err but I don't want ancient nom in my type signature)
28    Tokenize(String),
29
30    /// A mismatch between an expected token and a real token
31    Expected(&'static str, String),
32
33    /// Failed to parse from a string to some other type
34    StringParse(String)
35}
36
37impl ser::Error for Error {
38    fn custom<T: Display>(msg: T) -> Self {
39        Error::Message(msg.to_string())
40    }
41}
42
43impl de::Error for Error {
44    fn custom<T: Display>(msg: T) -> Self {
45        Error::Message(msg.to_string())
46    }
47}
48
49impl Display for Error {
50    fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
51        match self {
52            Error::Message(msg) => formatter.write_str(msg),
53            Error::UnsupportedType(r#type) => write!(formatter, "unsupported Serde data type {} used", r#type),
54            Error::EarlyEOF => formatter.write_str("input ended early"),
55            Error::LateEOF => formatter.write_str("input ended late"),
56            Error::Tokenize(err) => formatter.write_str(err),
57            Error::Expected(wanted, got) => write!(formatter, "expected {}, got {}", wanted, got),
58            Error::StringParse(err) => formatter.write_str(err),
59        }
60    }
61}
62
63impl std::error::Error for Error {}