Skip to main content

utopia_compression/
xz.rs

1//! XZ.
2
3use crate::{Algorithm, Compression, Error};
4
5/// XZ: LZMA2 at preset 5 in an `.xz` container with a CRC64 check.
6///
7/// The settings are those of PHP's ext-xz `xzencode()` (its default
8/// `xz.compression_level` of 5); decompressing reads concatenated `.xz`
9/// streams.
10///
11/// ```
12/// use utopia_compression::{Algorithm, Xz};
13///
14/// let xz = Xz::new();
15/// match xz.compress(b"This is a demo string") {
16///     Ok(body) => assert_eq!(xz.decompress(&body)?, b"This is a demo string"),
17///     // Built without the `xz` feature.
18///     Err(e) => assert_eq!(e.php_class(), "Error"),
19/// }
20/// # Ok::<(), utopia_compression::Error>(())
21/// ```
22///
23/// ```php
24/// use Utopia\Compression\Algorithms\XZ;
25///
26/// $xz = new XZ();
27/// if (XZ::isSupported()) {
28///     echo $xz->decompress($xz->compress('This is a demo string')), "\n"; // This is a demo string
29/// }
30/// ```
31///
32/// Requires the `xz` feature, which is off by default: without it, as in
33/// PHP without ext-xz, `compress()` and `decompress()` fail with
34/// [`Error::Unsupported`]. Output is not compared with PHP's: the PHP image
35/// the conversion is checked against has no ext-xz.
36///
37/// PHP: `Utopia\Compression\Algorithms\XZ`.
38#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
39pub struct Xz;
40
41impl Xz {
42    /// XZ at preset 5.
43    ///
44    /// PHP: `new XZ()`.
45    pub const fn new() -> Self {
46        Xz
47    }
48
49    /// Whether this build has XZ (the `xz` feature).
50    ///
51    /// PHP: `XZ::isSupported()`, whether `xzencode()` exists.
52    pub const fn is_supported() -> bool {
53        cfg!(feature = "xz")
54    }
55}
56
57impl Algorithm for Xz {
58    fn name(&self) -> &str {
59        Compression::XZ
60    }
61
62    fn compress(&self, data: &[u8]) -> Result<Vec<u8>, Error> {
63        imp::compress(data)
64    }
65
66    fn decompress(&self, data: &[u8]) -> Result<Vec<u8>, Error> {
67        imp::decompress(data)
68    }
69
70    fn supported(&self) -> bool {
71        Self::is_supported()
72    }
73}
74
75#[cfg(feature = "xz")]
76mod imp {
77    use std::io::{Read, Write};
78
79    use lzma_rust2::{XzOptions, XzReader, XzWriter};
80
81    use crate::Error;
82
83    /// `xz.compression_level`'s default.
84    const PRESET: u32 = 5;
85
86    pub(super) fn compress(data: &[u8]) -> Result<Vec<u8>, Error> {
87        let fail = |e: std::io::Error| Error::Codec(format!("xzencode(): {e}"));
88        let mut writer =
89            XzWriter::new(Vec::with_capacity(data.len() / 2 + 64), XzOptions::with_preset(PRESET)).map_err(fail)?;
90        writer.write_all(data).map_err(fail)?;
91        writer.finish().map_err(fail)
92    }
93
94    /// PHP's `xzdecode()` returns `false` without a warning on invalid data;
95    /// the message here is Rust's own.
96    pub(super) fn decompress(data: &[u8]) -> Result<Vec<u8>, Error> {
97        if data.is_empty() {
98            return Err(Error::Codec("xzdecode(): empty input".into()));
99        }
100        let mut out = Vec::new();
101        XzReader::new(data, true).read_to_end(&mut out).map_err(|e| Error::Codec(format!("xzdecode(): {e}")))?;
102        Ok(out)
103    }
104}
105
106#[cfg(not(feature = "xz"))]
107mod imp {
108    use crate::Error;
109
110    pub(super) fn compress(_: &[u8]) -> Result<Vec<u8>, Error> {
111        Err(Error::undefined("xzencode"))
112    }
113
114    pub(super) fn decompress(_: &[u8]) -> Result<Vec<u8>, Error> {
115        Err(Error::undefined("xzdecode"))
116    }
117}
118
119#[cfg(test)]
120mod tests {
121    use super::*;
122
123    #[cfg(feature = "xz")]
124    #[test]
125    fn round_trips() {
126        let xz = Xz::new();
127        for data in [&b""[..], b"This is a demo string", &b"Lorem ipsum dolor sit amet ".repeat(5000)] {
128            let compressed = xz.compress(data).unwrap();
129            assert_eq!(&compressed[..6], b"\xfd7zXZ\x00");
130            assert_eq!(xz.decompress(&compressed).unwrap(), data);
131        }
132        assert!(xz.compress(&b"Lorem ipsum ".repeat(5000)).unwrap().len() < 1000);
133        assert!(matches!(xz.decompress(b"garbage"), Err(Error::Codec(_))));
134    }
135
136    #[cfg(not(feature = "xz"))]
137    #[test]
138    fn unsupported() {
139        assert!(!Xz::is_supported());
140        assert_eq!(
141            Xz::new().compress(b"x"),
142            Err(Error::Unsupported("Call to undefined function Utopia\\Compression\\Algorithms\\xzencode()".into()))
143        );
144    }
145}