Skip to main content

quichash_core/
error.rs

1//! Error handling for the reusable QuicHash core.
2// Provides comprehensive error types with context for all operations
3
4use std::fmt;
5use std::io;
6use std::path::PathBuf;
7
8/// Main error type for the hash utility
9/// Provides context-rich error messages with file paths and operations
10#[derive(Debug)]
11#[non_exhaustive]
12pub enum HashUtilityError {
13    /// A required file does not exist.
14    FileNotFound {
15        /// Missing file path.
16        path: PathBuf,
17    },
18    /// A required directory does not exist.
19    DirectoryNotFound {
20        /// Missing directory path.
21        path: PathBuf,
22    },
23    /// The process lacks permission for a filesystem operation.
24    PermissionDenied {
25        /// Path that could not be accessed.
26        path: PathBuf,
27        /// Operation attempted on the path.
28        operation: String,
29    },
30    /// Other input/output failure with operation context.
31    IoError {
32        /// Related path, when one is available.
33        path: Option<PathBuf>,
34        /// Operation being performed when the error occurred.
35        operation: String,
36        /// Original I/O error.
37        source: io::Error,
38    },
39
40    /// A string does not identify a supported algorithm.
41    UnsupportedAlgorithm {
42        /// Unrecognized algorithm name.
43        algorithm: String,
44    },
45    /// A known algorithm was disabled at compile time.
46    AlgorithmUnavailable {
47        /// Canonical algorithm name.
48        algorithm: String,
49        /// Cargo feature required to enable the algorithm.
50        feature: &'static str,
51    },
52    /// Digest text or bytes have an invalid value or length.
53    InvalidDigest {
54        /// Algorithm whose digest was being decoded.
55        algorithm: String,
56        /// Validation failure description.
57        reason: String,
58    },
59    /// A file could not be hashed.
60    HashComputationFailed {
61        /// File being hashed.
62        path: PathBuf,
63        /// Requested algorithm.
64        algorithm: String,
65        /// Underlying failure description.
66        reason: String,
67    },
68
69    /// Cooperative cancellation requested by an embedding application.
70    Cancelled,
71
72    /// A requested manifest database does not exist.
73    DatabaseNotFound {
74        /// Missing database path.
75        path: PathBuf,
76    },
77    /// A manifest line could not be parsed.
78    DatabaseParseError {
79        /// Manifest path.
80        path: PathBuf,
81        /// One-based line number.
82        line: usize,
83        /// Parsing failure description.
84        reason: String,
85    },
86    /// A manifest could not be written.
87    DatabaseWriteError {
88        /// Destination path.
89        path: PathBuf,
90        /// Write failure description.
91        reason: String,
92    },
93    /// A manifest contained no usable entries.
94    EmptyDatabase {
95        /// Empty manifest path.
96        path: PathBuf,
97    },
98
99    /// Verification could not be completed.
100    VerificationFailed {
101        /// Failure description.
102        reason: String,
103    },
104
105    /// An operation received an invalid combination of arguments.
106    InvalidArguments {
107        /// Argument validation message.
108        message: String,
109    },
110    /// A compatibility operation did not receive a required argument.
111    MissingRequiredArgument {
112        /// Name of the missing argument.
113        argument: String,
114    },
115
116    /// An algorithm benchmark failed.
117    BenchmarkFailed {
118        /// Algorithm being measured.
119        algorithm: String,
120        /// Benchmark failure description.
121        reason: String,
122    },
123}
124
125impl fmt::Display for HashUtilityError {
126    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
127        match self {
128            // File system errors
129            HashUtilityError::FileNotFound { path } => {
130                writeln!(f, "File not found: {}", path.display())?;
131                write!(
132                    f,
133                    "Suggestion: Check that the file path is correct and the file exists"
134                )
135            }
136            HashUtilityError::DirectoryNotFound { path } => {
137                writeln!(f, "Directory not found: {}", path.display())?;
138                write!(
139                    f,
140                    "Suggestion: Check that the directory path is correct and the directory exists"
141                )
142            }
143            HashUtilityError::PermissionDenied { path, operation } => {
144                writeln!(
145                    f,
146                    "Permission denied while {} file: {}",
147                    operation,
148                    path.display()
149                )?;
150                write!(
151                    f,
152                    "Suggestion: Check file permissions or run with appropriate privileges"
153                )
154            }
155            HashUtilityError::IoError {
156                path,
157                operation,
158                source,
159            } => {
160                if let Some(p) = path {
161                    writeln!(
162                        f,
163                        "I/O error while {} file {}: {}",
164                        operation,
165                        p.display(),
166                        source
167                    )?;
168                } else {
169                    writeln!(f, "I/O error while {}: {}", operation, source)?;
170                }
171                write!(f, "Suggestion: Check file permissions and disk space")
172            }
173
174            // Hash computation errors
175            HashUtilityError::UnsupportedAlgorithm { algorithm } => {
176                writeln!(f, "Unsupported hash algorithm: {}", algorithm)?;
177                write!(f, "Suggestion: Use --list to see available algorithms")
178            }
179            HashUtilityError::AlgorithmUnavailable { algorithm, feature } => {
180                writeln!(f, "Hash algorithm '{}' is not compiled in", algorithm)?;
181                write!(f, "Suggestion: Enable the '{}' Cargo feature", feature)
182            }
183            HashUtilityError::InvalidDigest { algorithm, reason } => {
184                write!(f, "Invalid {} digest: {}", algorithm, reason)
185            }
186            HashUtilityError::HashComputationFailed {
187                path,
188                algorithm,
189                reason,
190            } => {
191                writeln!(
192                    f,
193                    "Failed to compute {} hash for {}: {}",
194                    algorithm,
195                    path.display(),
196                    reason
197                )?;
198                write!(
199                    f,
200                    "Suggestion: Check that the file is readable and not corrupted"
201                )
202            }
203            HashUtilityError::Cancelled => write!(f, "Operation cancelled"),
204
205            // Database errors
206            HashUtilityError::DatabaseNotFound { path } => {
207                writeln!(f, "Hash database file not found: {}", path.display())?;
208                write!(
209                    f,
210                    "Suggestion: Create a database first using the 'scan' command"
211                )
212            }
213            HashUtilityError::DatabaseParseError { path, line, reason } => {
214                writeln!(
215                    f,
216                    "Error parsing database {} at line {}: {}",
217                    path.display(),
218                    line,
219                    reason
220                )?;
221                write!(
222                    f,
223                    "Suggestion: Check that the database file format is correct (hash  filepath)"
224                )
225            }
226            HashUtilityError::DatabaseWriteError { path, reason } => {
227                writeln!(
228                    f,
229                    "Failed to write to database {}: {}",
230                    path.display(),
231                    reason
232                )?;
233                write!(f, "Suggestion: Check disk space and write permissions")
234            }
235            HashUtilityError::EmptyDatabase { path } => {
236                writeln!(f, "Database file is empty: {}", path.display())?;
237                write!(
238                    f,
239                    "Suggestion: Ensure the database contains at least one hash entry"
240                )
241            }
242
243            // Verification errors
244            HashUtilityError::VerificationFailed { reason } => {
245                writeln!(f, "Verification failed: {}", reason)?;
246                write!(
247                    f,
248                    "Suggestion: Check that the database and directory paths are correct"
249                )
250            }
251
252            // CLI errors
253            HashUtilityError::InvalidArguments { message } => {
254                writeln!(f, "Invalid arguments: {}", message)?;
255                write!(f, "Suggestion: Run with --help to see usage information")
256            }
257            HashUtilityError::MissingRequiredArgument { argument } => {
258                writeln!(f, "Missing required argument: {}", argument)?;
259                write!(f, "Suggestion: Run with --help to see required arguments")
260            }
261
262            // Benchmark errors
263            HashUtilityError::BenchmarkFailed { algorithm, reason } => {
264                writeln!(f, "Benchmark failed for {}: {}", algorithm, reason)?;
265                write!(
266                    f,
267                    "Suggestion: Try running the benchmark again or with a smaller data size"
268                )
269            }
270        }
271    }
272}
273
274impl std::error::Error for HashUtilityError {
275    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
276        match self {
277            HashUtilityError::IoError { source, .. } => Some(source),
278            _ => None,
279        }
280    }
281}
282
283// Conversion from io::Error with context
284impl HashUtilityError {
285    /// Convert an [`io::Error`] while retaining operation and path context.
286    ///
287    /// `NotFound` and `PermissionDenied` errors are promoted to their more
288    /// specific variants when a path is supplied.
289    pub fn from_io_error(err: io::Error, operation: &str, path: Option<PathBuf>) -> Self {
290        // Check for specific error kinds and provide more specific errors
291        match err.kind() {
292            io::ErrorKind::NotFound => {
293                if let Some(p) = path {
294                    if operation.contains("directory") || operation.contains("scan") {
295                        HashUtilityError::DirectoryNotFound { path: p }
296                    } else {
297                        HashUtilityError::FileNotFound { path: p }
298                    }
299                } else {
300                    HashUtilityError::IoError {
301                        path: None,
302                        operation: operation.to_string(),
303                        source: err,
304                    }
305                }
306            }
307            io::ErrorKind::PermissionDenied => {
308                if let Some(p) = path {
309                    HashUtilityError::PermissionDenied {
310                        path: p,
311                        operation: operation.to_string(),
312                    }
313                } else {
314                    HashUtilityError::IoError {
315                        path: None,
316                        operation: operation.to_string(),
317                        source: err,
318                    }
319                }
320            }
321            _ => HashUtilityError::IoError {
322                path,
323                operation: operation.to_string(),
324                source: err,
325            },
326        }
327    }
328}
329
330// Default From implementation for io::Error (without context)
331impl From<io::Error> for HashUtilityError {
332    fn from(err: io::Error) -> Self {
333        HashUtilityError::from_io_error(err, "unknown operation", None)
334    }
335}