lzma/lib.rs
1//! This crate provides a simple interface to liblzma. LZMA is more commonly known as XZ or 7zip,
2//! (as in, files with the `.xz` or `.7z` file extension). LZMA compression is fast and aggressive,
3//! compressing better than bzip2. liblzma implements the XZ variant, so it can read and write
4//! `.xz` files/streams.
5//!
6//! Two interfaces are provided. `LzmaReader`/`LzmaWriter` are generic Readers and Writers that
7//! can be composed with other `Read`/`Write` interfaces. For example, wrap them around a `File`
8//! and you can write data to a file while compressing it on the fly, or stream in an `xz` file
9//! from disk.
10//!
11//! `compress`/`decompress` are easy to use functions for simple use cases.
12//!
13//! See the `LzmaReader` and `LzmaWriter` documentation for further details on that interface.
14//! `compress` and `decompress` are documented here.
15//!
16//! # Examples
17//!
18//! ```
19//! let test_string = "Like tears in rain";
20//! let mut compressed = lzma::compress(test_string.as_bytes(), 6).unwrap();
21//! let decompressed = lzma::decompress(&mut compressed).unwrap();
22//! let decompressed_str = String::from_utf8(decompressed).unwrap();
23//!
24//! assert_eq!(test_string, decompressed_str);
25//! ```
26
27pub enum Direction {
28 Compress,
29 Decompress,
30}
31
32mod lzma_sys;
33mod lzma_stream_wrapper;
34pub mod reader;
35pub mod writer;
36pub mod error;
37
38use std::io::Read;
39pub use reader::LzmaReader;
40pub use writer::LzmaWriter;
41pub use error::LzmaError;
42
43
44pub const EXTREME_PRESET: u32 = 1 << 31;
45
46
47/// Compress `buf` and return the result.
48///
49/// preset is [0-9] and corresponds to xz's presets.
50/// Binary-or with EXTREME_PRESET for --extreme (e.g. 9 | EXTREME_PRESET).
51pub fn compress(buf: &[u8], preset: u32) -> Result<Vec<u8>, LzmaError> {
52 let mut output: Vec<u8> = Vec::new();
53
54 {
55 let mut reader = LzmaReader::new_compressor(buf, preset)?;
56
57 reader.read_to_end(&mut output)?;
58 }
59
60 Ok(output)
61}
62
63
64/// Decompress `buf` and return the result.
65pub fn decompress(buf: &[u8]) -> Result<Vec<u8>, LzmaError> {
66 let mut output: Vec<u8> = Vec::new();
67
68 {
69 let mut reader = LzmaReader::new_decompressor(buf)?;
70
71 reader.read_to_end(&mut output)?;
72 }
73
74 Ok(output)
75}