error.rs 2.5 KB

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