error.rs 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. use std::fmt::{self, Display};
  2. use serde::{ser, de};
  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. }
  17. impl std::error::Error for Error {}
  18. impl Display for Error {
  19. fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
  20. match self {
  21. Error::Message(message) => formatter.write_str(message),
  22. Error::Io(io_error) => io_error.fmt(formatter),
  23. Error::Eof => formatter.write_str("unexpected end of input"),
  24. Error::UnknownLength => formatter.write_str("sequence had an unknown length"),
  25. Error::SequenceTooLong(length) => formatter.write_fmt(
  26. format_args!("sequence was longer than 2**32 - 1: {}", length)
  27. ),
  28. Error::TooManyVariants(length) => formatter.write_fmt(
  29. format_args!("too many variants to be serialized, the limit is 2**16: {}", length)
  30. ),
  31. Error::TypeConversion => formatter.write_str("type conversion failed"),
  32. Error::NotSupported(message) => formatter.write_fmt(format_args!(
  33. "Operation is not supported: {}", message)),
  34. Error::InvalidUtf8Char => formatter.write_str("Invalid UTF-8 character encountered."),
  35. Error::Format(fmt_error) => fmt_error.fmt(formatter),
  36. }
  37. }
  38. }
  39. impl ser::Error for Error {
  40. fn custom<T: Display>(message: T) -> Self {
  41. Error::Message(message.to_string())
  42. }
  43. }
  44. impl de::Error for Error {
  45. fn custom<T: Display>(message: T) -> Self {
  46. Error::Message(message.to_string())
  47. }
  48. }
  49. pub trait MapError<T> {
  50. /// Returns self if no error occurred, otherwise converts the error to a serde_blocktree error.
  51. fn map_error(self) -> Result<T>;
  52. }
  53. impl<T> MapError<T> for std::io::Result<T> {
  54. fn map_error(self) -> Result<T> {
  55. self.map_err(Error::Io)
  56. }
  57. }