error.rs 2.5 KB

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