error.rs 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  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. }
  12. impl std::error::Error for Error {}
  13. impl Display for Error {
  14. fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
  15. match self {
  16. Error::Message(message) => formatter.write_str(message),
  17. Error::Io(io_error) => io_error.fmt(formatter),
  18. Error::Eof => formatter.write_str("unexpected end of input"),
  19. Error::UnknownLength => formatter.write_str("sequence had an unknown length"),
  20. Error::SequenceTooLong(length) => formatter.write_fmt(
  21. format_args!("sequence was longer than 2**32 - 1: {}", length)),
  22. }
  23. }
  24. }
  25. impl ser::Error for Error {
  26. fn custom<T: Display>(message: T) -> Self {
  27. Error::Message(message.to_string())
  28. }
  29. }
  30. impl de::Error for Error {
  31. fn custom<T: Display>(message: T) -> Self {
  32. Error::Message(message.to_string())
  33. }
  34. }
  35. pub trait MapError<T> {
  36. /// Returns self if no error occurred, otherwise converts the error to a serde_blocktree error.
  37. fn map_error(self) -> Result<T>;
  38. }
  39. impl<T> MapError<T> for std::io::Result<T> {
  40. fn map_error(self) -> Result<T> {
  41. self.or_else(|err| Result::Err(Error::Io(err)))
  42. }
  43. }