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
use std::{string, io}; use std::error::Error; use std::fmt::Display; #[derive(Debug)] pub enum ProtoError { UnexpectedVariant, MessageTooLong, StringEncoding(string::FromUtf8Error), IO(io::Error), Serialization(String), Deserialization(String) } impl From<ProtoError> for () { fn from(_e: ProtoError) -> () { () } } impl From<io::Error> for ProtoError { fn from(e: io::Error) -> ProtoError { ProtoError::IO(e) } } impl From<string::FromUtf8Error> for ProtoError { fn from(e: string::FromUtf8Error) -> ProtoError { ProtoError::StringEncoding(e) } } impl serde::ser::Error for ProtoError { fn custom<T: Display>(msg: T) -> Self { ProtoError::Serialization(msg.to_string()) } } impl serde::de::Error for ProtoError { fn custom<T: Display>(msg: T) -> Self { ProtoError::Deserialization(msg.to_string()) } } impl std::error::Error for ProtoError { fn source(&self) -> Option<&(dyn Error + 'static)> { match self { ProtoError::UnexpectedVariant => None, ProtoError::MessageTooLong => None, ProtoError::StringEncoding(e) => Some(e), ProtoError::IO(e) => Some(e), ProtoError::Serialization(_) => None, ProtoError::Deserialization(_) => None } } } impl std::fmt::Display for ProtoError { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { match self { ProtoError::UnexpectedVariant => f.write_str("Unexpected variant"), ProtoError::MessageTooLong => f.write_str("Message too long"), ProtoError::StringEncoding(_) => f.write_str("String encoding failed"), ProtoError::IO(_) => f.write_str("I/O Error"), ProtoError::Serialization(_) => f.write_str("Serialization Error"), ProtoError::Deserialization(_) => f.write_str("Deserialization Error") } } } pub type ProtoResult<T> = Result<T, ProtoError>;