1use crate::{Algorithm, Compression, Error};
4
5#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
39pub struct Xz;
40
41impl Xz {
42 pub const fn new() -> Self {
46 Xz
47 }
48
49 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 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 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}