error.rs 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. use serde::{de, ser};
  2. use std::fmt::{self, Display};
  3. pub type Result<T> = std::result::Result<T, Error>;
  4. #[derive(Debug)]
  5. pub enum Error {
  6. Message(String),
  7. Io(std::io::Error),
  8. Eof,
  9. UnknownLength,
  10. SequenceTooLong(usize),
  11. TooManyVariants(u32),
  12. TypeConversion,
  13. NotSupported(&'static str),
  14. InvalidUtf8Char,
  15. Format(std::fmt::Error),
  16. Custom(Box<dyn std::error::Error + Send + Sync>),
  17. }
  18. impl std::error::Error for Error {}
  19. impl Display for Error {
  20. fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
  21. match self {
  22. Error::Message(message) => formatter.write_str(message),
  23. Error::Io(io_error) => io_error.fmt(formatter),
  24. Error::Eof => formatter.write_str("unexpected end of input"),
  25. Error::UnknownLength => formatter.write_str("sequence had an unknown length"),
  26. Error::SequenceTooLong(length) => formatter.write_fmt(format_args!(
  27. "sequence was longer than 2**32 - 1: {}",
  28. length
  29. )),
  30. Error::TooManyVariants(length) => formatter.write_fmt(format_args!(
  31. "too many variants to be serialized, the limit is 2**16: {}",
  32. length
  33. )),
  34. Error::TypeConversion => formatter.write_str("type conversion failed"),
  35. Error::NotSupported(message) => {
  36. formatter.write_fmt(format_args!("Operation is not supported: {}", message))
  37. }
  38. Error::InvalidUtf8Char => formatter.write_str("Invalid UTF-8 character encountered."),
  39. Error::Format(fmt_error) => fmt_error.fmt(formatter),
  40. Error::Custom(err) => err.fmt(formatter),
  41. }
  42. }
  43. }
  44. impl Error {
  45. pub fn custom<E: Into<Box<dyn std::error::Error + Send + Sync>> + 'static>(err: E) -> Error {
  46. Error::Custom(err.into())
  47. }
  48. }
  49. impl ser::Error for Error {
  50. fn custom<T: Display>(message: T) -> Self {
  51. Error::Message(message.to_string())
  52. }
  53. }
  54. impl de::Error for Error {
  55. fn custom<T: Display>(message: T) -> Self {
  56. Error::Message(message.to_string())
  57. }
  58. }
  59. pub trait MapError<T> {
  60. /// Returns self if no error occurred, otherwise converts the error to a serde_blocktree error.
  61. fn map_error(self) -> Result<T>;
  62. }
  63. impl<T> MapError<T> for std::io::Result<T> {
  64. fn map_error(self) -> Result<T> {
  65. self.map_err(Error::Io)
  66. }
  67. }