Debian Codegraph @

src/lz4_hc/stream/mod.rs

raw symbols SCIP
1 mod api;
2
3 use crate::{common::DICTIONARY_SIZE, lz4, lz4_hc::FavorDecSpeed, Result};
4 use api::CompressionContext;
5 use std::{borrow::Cow, cmp, io::Cursor, pin::Pin};
6
7 /// Streaming LZ4_HC compressor.
8 ///
9 /// # Example
10 ///
11 /// ```
12 /// use lzzzz::{lz4, lz4_hc};
13 ///
14 /// let data = b"The quick brown fox jumps over the lazy dog.";
15 /// let mut buf = [0u8; 256];
16 ///
17 /// // The slice should have enough capacity.
18 /// assert!(buf.len() >= lz4::max_compressed_size(data.len()));
19 ///
20 /// let mut comp = lz4_hc::Compressor::new()?;
21 /// let len = comp.next(data, &mut buf)?;
22 /// let compressed = &buf[..len];
23 ///
24 /// # let mut buf = [0u8; 256];
25 /// # let len = lz4::decompress(compressed, &mut buf[..data.len()])?;
26 /// # assert_eq!(&buf[..len], &data[..]);
27 /// # Ok::<(), std::io::Error>(())
28 /// ```
29 pub struct Compressor<'a> {
30 ctx: CompressionContext,
31 dict: Pin<Cow<'a, [u8]>>,
32 safe_buf: Vec<u8>,
33 }
34
35 impl<'a> Compressor<'a> {
36 /// Creates a new `Compressor`.
37 pub fn new() -> Result<Self> {
38 Ok(Self {
39 ctx: CompressionContext::new()?,
40 dict: Pin::new(Cow::Borrowed(&[])),
41 safe_buf: Vec::new(),
42 })
43 }
44
45 /// Creates a new `Compressor` with a dictionary.
46 pub fn with_dict<D>(dict: D, compression_level: i32) -> Result<Self>
47 where
48 D: Into<Cow<'a, [u8]>>,
49 {
50 // Note(sewer56).
51 // The LZ4 documentation states the following:
52 // - In order for LZ4_loadDictHC() to create the correct data structure,
53 // it is essential to set the compression level _before_ loading the dictionary.
54 // Therefore this API requires a `compression_level`.
55
56 let mut comp = Self {
57 dict: Pin::new(dict.into()),
58 ..Self::new()?
59 };
60
61 comp.ctx.set_compression_level(compression_level);
62 comp.ctx.load_dict(&comp.dict);
63 Ok(comp)
64 }
65
66 /// Sets the compression level.
67 pub fn set_compression_level(&mut self, level: i32) {
68 self.ctx.set_compression_level(level);
69 }
70
71 /// Sets the decompression speed mode flag.
72 pub fn set_favor_dec_speed(&mut self, dec_speed: FavorDecSpeed) {
73 self.ctx
74 .set_favor_dec_speed(dec_speed == FavorDecSpeed::Enabled);
75 }
76
77 /// Performs LZ4_HC streaming compression.
78 ///
79 /// Returns the number of bytes written into the destination buffer.
80 pub fn next(&mut self, src: &[u8], dst: &mut [u8]) -> Result<usize> {
81 self.next_to_ptr(src, dst.as_mut_ptr(), dst.len())
82 }
83
84 fn next_to_ptr(&mut self, src: &[u8], dst: *mut u8, dst_len: usize) -> Result<usize> {
85 let result = self.ctx.next(src, dst, dst_len)?;
86 self.save_dict();
87 Ok(result)
88 }
89
90 /// Performs LZ4_HC streaming compression to fill `dst`.
91 ///
92 /// This function either compresses the entire `src` buffer into `dst` if it's
93 /// large enough, or will fill `dst` with as much data as possible from `src`.
94 ///
95 /// Returns a pair `(read, wrote)` giving the number of bytes read from `src`
96 /// and the number of bytes written to `dst`.
97 ///
98 /// # Example
99 ///
100 /// ```
101 /// use lzzzz::{lz4, lz4_hc};
102 ///
103 /// let data = b"The quick brown fox jumps over the lazy dog.";
104 ///
105 /// let mut smallbuf = [0u8; 32];
106 /// assert!(smallbuf.len() < lz4::max_compressed_size(data.len()));
107 ///
108 /// let mut comp = lz4_hc::Compressor::new()?;
109 /// let (read, wrote) = comp.next_fill(data, &mut smallbuf)?;
110 /// let remaining_data = &data[read..];
111 ///
112 /// # let mut buf = [0u8; 256];
113 /// # let len = lz4::decompress(&smallbuf, &mut buf)?;
114 /// # assert_eq!(&buf[..len], &data[..read]);
115 /// # Ok::<(), std::io::Error>(())
116 /// ```
117 pub fn next_fill(&mut self, src: &[u8], dst: &mut [u8]) -> Result<(usize, usize)> {
118 let (src_len, dst_len) = self.ctx.next_partial(src, dst)?;
119 self.save_dict();
120 Ok((src_len, dst_len))
121 }
122
123 /// Compresses data until the destination slice fills up.
124 ///
125 /// Returns the number of bytes written into the destination buffer.
126 #[deprecated(since = "1.1.0", note = "Use next_fill instead.")]
127 pub fn next_partial<T>(&mut self, src: &mut Cursor<T>, dst: &mut [u8]) -> Result<usize>
128 where
129 T: AsRef<[u8]>,
130 {
131 let src_ref = src.get_ref().as_ref();
132 let pos = cmp::min(src_ref.len(), src.position() as usize);
133 let src_ref = &src_ref[pos..];
134 let (src_len, dst_len) = self.ctx.next_partial(src_ref, dst)?;
135 src.set_position(src.position() + src_len as u64);
136 self.save_dict();
137 Ok(dst_len)
138 }
139
140 /// Appends a compressed frame to `Vec<u8>`.
141 ///
142 /// Returns the number of bytes appended to the given `Vec<u8>`.
143 pub fn next_to_vec(&mut self, src: &[u8], dst: &mut Vec<u8>) -> Result<usize> {
144 let orig_len = dst.len();
145 dst.reserve(lz4::max_compressed_size(src.len()));
146 #[allow(unsafe_code)]
147 unsafe {
148 let result = self.next_to_ptr(
149 src,
150 dst.as_mut_ptr().add(orig_len),
151 dst.capacity() - orig_len,
152 );
153 dst.set_len(orig_len + result.as_ref().unwrap_or(&0));
154 result
155 }
156 }
157
158 fn save_dict(&mut self) {
159 self.safe_buf.resize(DICTIONARY_SIZE, 0);
160 self.ctx.save_dict(&mut self.safe_buf);
161 }
162
163 /// Attaches a dictionary stream for efficient dictionary reuse.
164 ///
165 /// This allows efficient re-use of a static dictionary multiple times by referencing
166 /// the dictionary stream in-place rather than copying it.
167 ///
168 /// # Arguments
169 ///
170 /// * `dict_stream` - The dictionary stream to attach, or None to unset any existing dictionary
171 /// * `compression_level` - The compression level to use (CLEVEL_MIN to CLEVEL_MAX)
172 ///
173 /// # Notes
174 ///
175 /// - The dictionary stream must have been prepared using `with_dict()`
176 /// - The dictionary will only remain attached through the first compression call
177 /// - The dictionary stream (and its source buffer) must remain valid through the compression session
178 ///
179 /// # Example
180 ///
181 /// ```
182 /// use lzzzz::lz4_hc;
183 ///
184 /// let dict_data = b"dictionary data";
185 /// let data = b"data to compress";
186 ///
187 /// // Create dictionary stream
188 /// let dict_comp = lz4_hc::Compressor::with_dict(dict_data, lz4_hc::CLEVEL_DEFAULT)?;
189 ///
190 /// // Create working stream and attach dictionary
191 /// let mut comp = lz4_hc::Compressor::new()?;
192 /// comp.attach_dict(Some(&dict_comp), lz4_hc::CLEVEL_DEFAULT);
193 ///
194 /// // Compress data using the attached dictionary
195 /// let mut buf = [0u8; 256];
196 /// let len = comp.next(data, &mut buf)?;
197 /// # Ok::<(), std::io::Error>(())
198 /// ```
199 pub fn attach_dict(&mut self, dict_stream: Option<&Compressor<'a>>, compression_level: i32) {
200 if let Some(dict) = dict_stream {
201 self.ctx.attach_dict(Some(&dict.ctx), compression_level);
202 } else {
203 self.ctx.attach_dict(None, compression_level);
204 }
205 }
206 }