archive_reader/
error.rs

1use crate::libarchive;
2use std::ffi::CStr;
3
4#[derive(thiserror::Error, Debug)]
5pub enum Error {
6    #[error("IO error: {0:?}")]
7    Io(#[from] std::io::Error),
8    /// `Extraction` error is a wrapper for errors generated by libarchive.
9    #[error("Extraction error: {0}")]
10    Extraction(String),
11    /// `PathNotUft8` error happens when passing in a path which is not UTF8 encoded.
12    /// Archive-reader relies on UTF8 encoded path to load archives.
13    #[error("Archive path cannot be converted to utf8")]
14    PathNotUtf8,
15    /// `Encoding` error happens when the giving decoding function failed to decode
16    /// the entry name.
17    #[error("Entry name cannot be decoded with given encoding")]
18    Encoding,
19    /// Unspecified error
20    #[error("Unknown error happened")]
21    Unknown,
22}
23
24pub type Result<T, E = Error> = std::result::Result<T, E>;
25
26pub(crate) fn analyze_result(
27    result: std::os::raw::c_int,
28    handle: *mut libarchive::archive,
29) -> Result<()> {
30    match result {
31        libarchive::ARCHIVE_OK | libarchive::ARCHIVE_WARN => Ok(()),
32        _ => unsafe {
33            let error_string = libarchive::archive_error_string(handle);
34            if !error_string.is_null() {
35                return Err(Error::Extraction(
36                    CStr::from_ptr(error_string).to_string_lossy().to_string(),
37                ));
38            }
39            let error_code = libarchive::archive_errno(handle);
40            if error_code != 0 {
41                Err(std::io::Error::from_raw_os_error(error_code).into())
42            } else {
43                Err(Error::Unknown)
44            }
45        },
46    }
47}
48
49pub(crate) fn path_does_not_exist<S: Into<String>>(message: S) -> Error {
50    Error::Io(std::io::Error::new(
51        std::io::ErrorKind::NotFound,
52        message.into(),
53    ))
54}
55
56pub(crate) fn invalid_data<S: Into<String>>(message: S) -> Error {
57    Error::Io(std::io::Error::new(
58        std::io::ErrorKind::InvalidData,
59        message.into(),
60    ))
61}