1use serde::ser::{Serialize, SerializeStruct, Serializer};
2use std::fmt::Display;
3use std::num::ParseIntError;
4use std::string::FromUtf8Error;
5
6use hex::FromHexError;
7
8#[derive(Debug, Clone)]
9pub enum Error {
10 IOCoreError(String),
11 IOError(String),
12 InvalidUtf8(String),
13 ParseIntError(String),
14 FileSystemError(String),
15 ComparisonError(String),
16 DecodingError(String),
17 EncodingError(String),
18}
19
20impl Serialize for Error {
21 fn serialize<S: Serializer>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
22 where
23 S: serde::Serializer,
24 {
25 let mut s = serializer.serialize_struct("Error", 2)?;
26 s.serialize_field("variant", &self.variant())?;
27 s.serialize_field("message", &format!("{}", self))?;
28 s.end()
29 }
30}
31impl Display for Error {
32 fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
33 write!(
34 f,
35 "{}",
36 match self {
37 Self::IOCoreError(e) => format!("{}", e),
38 Self::InvalidUtf8(e) => e.to_string(),
39 Self::IOError(e) => e.to_string(),
40 Self::FileSystemError(e) => e.to_string(),
41 Self::ComparisonError(e) => e.to_string(),
42 Self::ParseIntError(e) => e.to_string(),
43 Self::DecodingError(e) => e.to_string(),
44 Self::EncodingError(e) => e.to_string(),
45 }
46 )
47 }
48}
49
50impl Error {
51 pub fn variant(&self) -> String {
52 match self {
53 Error::IOCoreError(_) => "IOCoreError",
54 Error::InvalidUtf8(_) => "InvalidUtf8",
55 Error::IOError(_) => "IOError",
56 Error::FileSystemError(_) => "FileSystemError",
57 Error::ComparisonError(_) => "ComparisonError",
58 Error::ParseIntError(_) => "ParseIntError",
59 Error::DecodingError(_) => "DecodingError",
60 Error::EncodingError(_) => "EncodingError",
61 }
62 .to_string()
63 }
64}
65
66impl std::error::Error for Error {}
67
68impl From<ParseIntError> for Error {
69 fn from(e: ParseIntError) -> Self {
70 Error::ParseIntError(format!("{}", e))
71 }
72}
73impl From<iocore::Error> for Error {
74 fn from(e: iocore::Error) -> Self {
75 Error::IOCoreError(format!("{}", e))
76 }
77}
78impl From<Box<bincode::ErrorKind>> for Error {
79 fn from(e: Box<bincode::ErrorKind>) -> Self {
80 Error::IOCoreError(format!("{}", e))
81 }
82}
83impl From<FromUtf8Error> for Error {
84 fn from(e: FromUtf8Error) -> Self {
85 Error::InvalidUtf8(format!("{}", e))
86 }
87}
88impl From<FromHexError> for Error {
89 fn from(e: FromHexError) -> Self {
90 Error::DecodingError(format!("{}", e))
91 }
92}
93impl From<std::io::Error> for Error {
94 fn from(e: std::io::Error) -> Self {
95 Error::IOError(format!("{}", e))
96 }
97}
98pub type Result<T> = std::result::Result<T, Error>;
99
100pub fn ok() -> Result<()> {
101 Ok(())
102}