1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
use std::{borrow::Cow, fmt::Display};
#[derive(Debug)]
pub enum Error {
    BadSignature([u8; 6]),
    UnsupportedVersion { major: u8, minor: u8 },
    ChecksumVerificationFailed,
    NextHeaderCrcMismatch,
    Io(std::io::Error, Cow<'static, str>),
    FileOpen(std::io::Error, String),
    Other(Cow<'static, str>),
    BadTerminatedStreamsInfo(u8),
    BadTerminatedUnpackInfo,
    BadTerminatedPackInfo(u8),
    BadTerminatedSubStreamsInfo,
    BadTerminatedheader(u8),

    ExternalUnsupported,
    UnsupportedCompressionMethod(String),
    MaxMemLimited { max_kb: usize, actaul_kb: usize },
    PasswordRequired,
    Unsupported(Cow<'static, str>),
    MaybeBadPassword(std::io::Error),
}

impl From<std::io::Error> for Error {
    fn from(value: std::io::Error) -> Self {
        Self::io(value)
    }
}

impl Error {
    #[inline]
    pub fn other<S: Into<Cow<'static, str>>>(s: S) -> Self {
        Self::Other(s.into())
    }
    #[inline]
    pub fn unsupported<S: Into<Cow<'static, str>>>(s: S) -> Self {
        Self::Unsupported(s.into())
    }

    #[inline]
    pub fn io(e: std::io::Error) -> Self {
        Self::io_msg(e, "")
    }
    #[inline]
    pub fn io_msg(e: std::io::Error, msg: impl Into<Cow<'static, str>>) -> Self {
        Self::Io(e, msg.into())
    }

    pub fn bad_password(e: std::io::Error, encryped: bool) -> Self {
        if encryped {
            Self::MaybeBadPassword(e)
        } else {
            Self::io(e)
        }
    }

    #[inline]
    pub(crate) fn file_open(e: std::io::Error, filename: impl Into<Cow<'static, str>>) -> Self {
        Self::Io(e, filename.into())
    }

    pub(crate) fn maybe_bad_password(self, encryped: bool) -> Self {
        if !encryped {
            return self;
        }
        match self {
            Self::Io(e, s) if s.is_empty() => Self::MaybeBadPassword(e),
            _ => self,
        }
    }
}

impl Display for Error {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        std::fmt::Debug::fmt(&self, f)
    }
}

impl std::error::Error for Error {}