PSArc_lib/archive/
compression_type.rs

1use crate::traits::{ConvertAsBytes, Parsable};
2use anyhow::anyhow;
3
4const LZMA_COMPRESSION: &str = "lzma";
5const ZLIB_COMPRESSION: &str = "zlib";
6
7/// **PSArchiveCompression** is the type of compression that the Playstation Archive file has
8#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
9#[derive(Debug, Clone, PartialEq, Eq)]
10pub enum PSArchiveCompression {
11    /// LZMA Compression type
12    LZMA,
13    /// ZLIB Compression type
14    ZLIB,
15    /// Error parsing compression type
16    ERROR,
17}
18
19/// Should parse 4 bytes, any more or less will result in an error
20impl Parsable for PSArchiveCompression {
21    type Error = anyhow::Error;
22    fn parse(bytes: impl ConvertAsBytes) -> Result<Self, Self::Error>
23    where
24        Self: Sized,
25    {
26        let bytes = bytes.convert_as_bytes();
27        if LZMA_COMPRESSION.convert_as_bytes() == bytes {
28            return Ok(Self::LZMA);
29        } else if ZLIB_COMPRESSION.convert_as_bytes() == bytes {
30            return Ok(Self::ZLIB);
31        }
32        return Err(anyhow!("Invalid compression type"));
33    }
34}
35
36impl Default for PSArchiveCompression {
37    fn default() -> Self {
38        return Self::ERROR;
39    }
40}
41
42impl std::fmt::Display for PSArchiveCompression {
43    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
44        match self {
45            Self::LZMA => {
46                write!(f, "lzma")
47            }
48            Self::ZLIB => {
49                write!(f, "zlib")
50            }
51            Self::ERROR => {
52                write!(f, "Error parsing Archive Compression")
53            }
54        }
55    }
56}
57
58#[cfg(test)]
59#[doc(hidden)]
60mod test {
61    use super::PSArchiveCompression;
62    use crate::prelude::*;
63
64    #[test]
65    fn test_compression_parsing_lzma() {
66        let bytes = "lzma".as_bytes();
67        let result = PSArchiveCompression::parse(bytes);
68        assert_eq!(result.is_ok(), true);
69        let result = result.unwrap();
70        assert_eq!(result, PSArchiveCompression::LZMA);
71    }
72
73    #[test]
74    fn test_compression_parsing_zlib() {
75        let bytes = "zlib".as_bytes();
76        let result = PSArchiveCompression::parse(bytes);
77        assert_eq!(result.is_ok(), true);
78        let result = result.unwrap();
79        assert_eq!(result, PSArchiveCompression::ZLIB);
80    }
81
82    #[test]
83    fn test_compression_parsing_error() {
84        let bytes = "nope".as_bytes();
85        let result = PSArchiveCompression::parse(bytes);
86        assert_eq!(result.is_ok(), false);
87    }
88
89    #[test]
90    fn test_compression_display() {
91        let bytes = "lzma".as_bytes();
92        let result = PSArchiveCompression::parse(bytes).unwrap();
93        assert_eq!(format!("{}", result), "lzma");
94    }
95}