error.rs 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  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. InvalidUtf8,
  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) => {
  30. formatter.write_fmt(format_args!("sequence was longer than 2**32 - 1: {length}",))
  31. }
  32. Error::TooManyVariants(length) => formatter.write_fmt(format_args!(
  33. "too many variants to be serialized, the limit is 2**16: {length}",
  34. )),
  35. Error::TypeConversion => formatter.write_str("type conversion failed"),
  36. Error::NotSupported(message) => {
  37. formatter.write_fmt(format_args!("Operation is not supported: {message}"))
  38. }
  39. Error::InvalidUtf8 => formatter.write_str("Invalid UTF-8 character encountered."),
  40. Error::Format(fmt_error) => fmt_error.fmt(formatter),
  41. Error::Custom(err) => err.fmt(formatter),
  42. }
  43. }
  44. }
  45. impl Error {
  46. pub fn custom<E: Into<Box<dyn std::error::Error + Send + Sync>> + 'static>(err: E) -> Error {
  47. Error::Custom(err.into())
  48. }
  49. }
  50. impl ser::Error for Error {
  51. fn custom<T: Display>(message: T) -> Self {
  52. Error::Message(message.to_string())
  53. }
  54. }
  55. impl de::Error for Error {
  56. fn custom<T: Display>(message: T) -> Self {
  57. Error::Message(message.to_string())
  58. }
  59. }
  60. impl From<Error> for io::Error {
  61. fn from(err: Error) -> Self {
  62. io::Error::new(io::ErrorKind::Other, err)
  63. }
  64. }
  65. pub trait MapError<T> {
  66. /// Returns self if no error occurred, otherwise converts the error to a serde_blocktree error.
  67. fn map_error(self) -> Result<T>;
  68. }
  69. impl<T> MapError<T> for std::io::Result<T> {
  70. fn map_error(self) -> Result<T> {
  71. self.map_err(Error::Io)
  72. }
  73. }