1use crate::Algorithm;
2use std::{error::Error, fmt};
3
4pub type Result<T> = std::result::Result<T, CompressionError>;
5
6#[derive(Clone, Debug, Eq, PartialEq)]
7pub enum CompressionError {
8 BufferOperationFailed {
9 operation: &'static str,
10 algorithm: Algorithm,
11 input_len: usize,
12 output_capacity: usize,
13 },
14 StreamInitFailed {
15 operation: &'static str,
16 algorithm: Algorithm,
17 },
18 StreamProcessFailed {
19 operation: &'static str,
20 algorithm: Algorithm,
21 status: i32,
22 },
23 StreamStalled {
24 operation: &'static str,
25 algorithm: Algorithm,
26 },
27 StreamFinished {
28 operation: &'static str,
29 algorithm: Algorithm,
30 },
31 OperationFailed {
32 operation: &'static str,
33 code: i32,
34 },
35 NullHandle {
36 operation: &'static str,
37 },
38 Closed {
39 resource: &'static str,
40 },
41 InvalidFieldKey {
42 key: String,
43 },
44 InvalidHashLength {
45 expected: usize,
46 actual: usize,
47 },
48 NulByte {
49 argument: &'static str,
50 },
51 Utf8Error {
52 operation: &'static str,
53 },
54}
55
56impl fmt::Display for CompressionError {
57 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
58 match self {
59 Self::BufferOperationFailed {
60 operation,
61 algorithm,
62 input_len,
63 output_capacity,
64 } => write!(
65 f,
66 "{operation} failed for {algorithm:?} (input_len={input_len}, output_capacity={output_capacity})"
67 ),
68 Self::StreamInitFailed {
69 operation,
70 algorithm,
71 } => write!(f, "{operation} failed for {algorithm:?}"),
72 Self::StreamProcessFailed {
73 operation,
74 algorithm,
75 status,
76 } => write!(
77 f,
78 "{operation} failed for {algorithm:?} (status={status})"
79 ),
80 Self::StreamStalled {
81 operation,
82 algorithm,
83 } => write!(
84 f,
85 "{operation} made no progress for {algorithm:?}; the input may be truncated or corrupt"
86 ),
87 Self::StreamFinished {
88 operation,
89 algorithm,
90 } => write!(f, "{operation} called after the {algorithm:?} stream already finished"),
91 Self::OperationFailed { operation, code } => {
92 if *code < 0 {
93 let os_code = -*code;
94 write!(
95 f,
96 "{operation} failed with {code} ({})",
97 std::io::Error::from_raw_os_error(os_code)
98 )
99 } else {
100 write!(f, "{operation} failed with {code}")
101 }
102 }
103 Self::NullHandle { operation } => write!(f, "{operation} returned a null handle"),
104 Self::Closed { resource } => write!(f, "{resource} is already closed"),
105 Self::InvalidFieldKey { key } => write!(f, "invalid AppleArchive field key: {key:?}"),
106 Self::InvalidHashLength { expected, actual } => {
107 write!(f, "invalid hash length: expected {expected} bytes, got {actual}")
108 }
109 Self::NulByte { argument } => write!(f, "{argument} contains an interior NUL byte"),
110 Self::Utf8Error { operation } => write!(f, "{operation} returned data that is not valid UTF-8"),
111 }
112 }
113}
114
115impl Error for CompressionError {}