error.rs 2.1 KB

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