pco/
errors.rs

1use std::error::Error;
2use std::fmt::{Display, Formatter};
3use std::{fmt, io};
4
5/// The different kinds of errors the library can return.
6#[derive(Clone, Copy, Debug, PartialEq, Eq)]
7#[non_exhaustive]
8pub enum ErrorKind {
9  /// `Compatibility` errors occur during decompression, indicating the library
10  /// version is not up-to-date enough for the provided data.
11  Compatibility,
12  /// `Corruption` errors occur during decompression, indicating the
13  /// provided data is inconsistent or violates the pco format.
14  /// It also applies to cases where standalone files were read but a wrapped
15  /// format was detected, or vice versa.
16  Corruption,
17  /// `InsufficientData` errors occur during decompression, indicating
18  /// the decompressor reached the end of the provided data before finishing.
19  InsufficientData,
20  /// `InvalidArgument` errors usually occur during compression, indicating
21  /// the parameters provided to a function were invalid.
22  InvalidArgument,
23  /// `Io` errors are propagated from `Read` or `Write`
24  /// implementations passed to pco.
25  Io(io::ErrorKind),
26}
27
28/// The error type used in results for all `pco` functionality.
29#[derive(Clone, Debug, PartialEq, Eq)]
30pub struct PcoError {
31  pub kind: ErrorKind,
32  pub message: String,
33}
34
35impl PcoError {
36  pub(crate) fn new<S: AsRef<str>>(kind: ErrorKind, message: S) -> Self {
37    PcoError {
38      kind,
39      message: message.as_ref().to_string(),
40    }
41  }
42
43  pub(crate) fn compatibility<S: AsRef<str>>(message: S) -> Self {
44    Self::new(ErrorKind::Compatibility, message)
45  }
46
47  pub(crate) fn corruption<S: AsRef<str>>(message: S) -> Self {
48    Self::new(ErrorKind::Corruption, message)
49  }
50
51  pub(crate) fn insufficient_data<S: AsRef<str>>(message: S) -> Self {
52    Self::new(ErrorKind::InsufficientData, message)
53  }
54
55  pub(crate) fn invalid_argument<S: AsRef<str>>(message: S) -> Self {
56    Self::new(ErrorKind::InvalidArgument, message)
57  }
58}
59
60impl Display for PcoError {
61  fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
62    write!(
63      f,
64      "pco {:?} error: {}",
65      self.kind, &self.message
66    )
67  }
68}
69
70impl From<io::Error> for PcoError {
71  fn from(err: io::Error) -> Self {
72    PcoError {
73      kind: ErrorKind::Io(err.kind()),
74      message: format!("{}", err),
75    }
76  }
77}
78
79impl Error for PcoError {}
80
81pub type PcoResult<T> = Result<T, PcoError>;