Skip to main content

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  /// `Corruption` errors occur during decompression, indicating the
10  /// provided data is inconsistent or violates the pco format.
11  /// These may arise when the decompressor version is too old.
12  /// They may also apply to cases where standalone files were read using the
13  /// wrapped API, or vice versa.
14  Corruption,
15  /// `InsufficientData` errors occur during decompression, indicating
16  /// the decompressor reached the end of the provided data before finishing.
17  InsufficientData,
18  /// `InvalidArgument` errors usually occur during compression, indicating
19  /// the parameters provided to a function were invalid.
20  InvalidArgument,
21  /// `Io` errors are propagated from `Read` or `Write`
22  /// implementations passed to pco.
23  Io(io::ErrorKind),
24}
25
26/// The error type used in results for all `pco` functionality.
27#[derive(Clone, Debug, PartialEq, Eq)]
28pub struct PcoError {
29  pub kind: ErrorKind,
30  pub message: String,
31}
32
33impl PcoError {
34  pub(crate) fn new<S: AsRef<str>>(kind: ErrorKind, message: S) -> Self {
35    PcoError {
36      kind,
37      message: message.as_ref().to_string(),
38    }
39  }
40
41  pub(crate) fn corruption<S: AsRef<str>>(message: S) -> Self {
42    Self::new(ErrorKind::Corruption, message)
43  }
44
45  pub(crate) fn insufficient_data<S: AsRef<str>>(message: S) -> Self {
46    Self::new(ErrorKind::InsufficientData, message)
47  }
48
49  pub(crate) fn invalid_argument<S: AsRef<str>>(message: S) -> Self {
50    Self::new(ErrorKind::InvalidArgument, message)
51  }
52}
53
54impl Display for PcoError {
55  fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
56    write!(
57      f,
58      "pco {:?} error: {}",
59      self.kind, &self.message
60    )
61  }
62}
63
64impl From<io::Error> for PcoError {
65  fn from(err: io::Error) -> Self {
66    PcoError {
67      kind: ErrorKind::Io(err.kind()),
68      message: format!("{}", err),
69    }
70  }
71}
72
73impl Error for PcoError {}
74
75pub type PcoResult<T> = Result<T, PcoError>;