cuprate/net/epee-encoding/src/error.rs

56 lines
1.3 KiB
Rust
Raw Normal View History

use core::{
fmt::{Debug, Formatter},
num::TryFromIntError,
str::Utf8Error,
};
2024-01-29 22:32:16 +00:00
pub type Result<T> = core::result::Result<T, Error>;
#[cfg_attr(feature = "std", derive(thiserror::Error))]
pub enum Error {
#[cfg_attr(feature = "std", error("IO error: {0}"))]
IO(&'static str),
#[cfg_attr(feature = "std", error("Format error: {0}"))]
Format(&'static str),
#[cfg_attr(feature = "std", error("Value error: {0}"))]
2024-01-30 17:53:03 +00:00
Value(String),
2024-01-29 22:32:16 +00:00
}
impl Error {
fn field_name(&self) -> &'static str {
match self {
Error::IO(_) => "io",
Error::Format(_) => "format",
Error::Value(_) => "value",
}
}
2024-01-30 17:53:03 +00:00
fn field_data(&self) -> &str {
2024-01-29 22:32:16 +00:00
match self {
Error::IO(data) => data,
Error::Format(data) => data,
Error::Value(data) => data,
}
}
}
impl Debug for Error {
fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
f.debug_struct("Error")
.field(self.field_name(), &self.field_data())
.finish()
}
}
impl From<TryFromIntError> for Error {
fn from(_: TryFromIntError) -> Self {
2024-01-30 17:53:03 +00:00
Error::Value("Int is too large".to_string())
2024-01-29 22:32:16 +00:00
}
}
impl From<Utf8Error> for Error {
fn from(_: Utf8Error) -> Self {
2024-01-30 17:53:03 +00:00
Error::Value("Invalid utf8 str".to_string())
2024-01-29 22:32:16 +00:00
}
}