| 1 | mod api; |
| 2 | |
| 3 | use crate::{ |
| 4 | common::{DEFAULT_BUF_SIZE, DICTIONARY_SIZE}, |
| 5 | lz4, Error, ErrorKind, Result, |
| 6 | }; |
| 7 | use api::{CompressionContext, DecompressionContext}; |
| 8 | use std::{borrow::Cow, cmp, collections::LinkedList, pin::Pin}; |
| 9 | |
| 10 | /// Streaming LZ4 compressor. |
| 11 | /// |
| 12 | /// # Example |
| 13 | /// |
| 14 | /// ``` |
| 15 | /// use lzzzz::lz4; |
| 16 | /// |
| 17 | /// let data = b"The quick brown fox jumps over the lazy dog."; |
| 18 | /// let mut buf = [0u8; 256]; |
| 19 | /// |
| 20 | /// // The slice should have enough capacity. |
| 21 | /// assert!(buf.len() >= lz4::max_compressed_size(data.len())); |
| 22 | /// |
| 23 | /// let mut comp = lz4::Compressor::new()?; |
| 24 | /// let len = comp.next(data, &mut buf, lz4::ACC_LEVEL_DEFAULT)?; |
| 25 | /// let compressed = &buf[..len]; |
| 26 | /// |
| 27 | /// # let mut buf = [0u8; 256]; |
| 28 | /// # let len = lz4::decompress(compressed, &mut buf[..data.len()])?; |
| 29 | /// # assert_eq!(&buf[..len], &data[..]); |
| 30 | /// # Ok::<(), std::io::Error>(()) |
| 31 | /// ``` |
| 32 | pub struct Compressor<'a> { |
| 33 | ctx: CompressionContext, |
| 34 | dict: Pin<Cow<'a, [u8]>>, |
| 35 | safe_buf: Vec<u8>, |
| 36 | } |
| 37 | |
| 38 | impl<'a> Compressor<'a> { |
| 39 | /// Creates a new `Compressor`. |
| 40 | pub fn new() -> Result<Self> { |
| 41 | Ok(Self { |
| 42 | ctx: CompressionContext::new()?, |
| 43 | dict: Pin::new(Cow::Borrowed(&[])), |
| 44 | safe_buf: Vec::new(), |
| 45 | }) |
| 46 | } |
| 47 | |
| 48 | /// Creates a new `Compressor` with a dictionary. |
| 49 | pub fn with_dict<D>(dict: D) -> Result<Self> |
| 50 | where |
| 51 | D: Into<Cow<'a, [u8]>>, |
| 52 | { |
| 53 | let mut comp = Self { |
| 54 | dict: Pin::new(dict.into()), |
| 55 | ..Self::new()? |
| 56 | }; |
| 57 | comp.ctx.load_dict(&comp.dict); |
| 58 | Ok(comp) |
| 59 | } |
| 60 | |
| 61 | /// Creates a new `Compressor` with a dictionary. |
| 62 | /// This variant which consumes more initialization time to better reference the dictionary, |
| 63 | /// resulting in slightly improved compression ratios at expense of time. |
| 64 | pub fn with_dict_slow<D>(dict: D) -> Result<Self> |
| 65 | where |
| 66 | D: Into<Cow<'a, [u8]>>, |
| 67 | { |
| 68 | let mut comp = Self { |
| 69 | dict: Pin::new(dict.into()), |
| 70 | ..Self::new()? |
| 71 | }; |
| 72 | comp.ctx.load_dict_slow(&comp.dict); |
| 73 | Ok(comp) |
| 74 | } |
| 75 | |
| 76 | /// Performs LZ4 streaming compression. |
| 77 | /// |
| 78 | /// Returns the number of bytes written into the destination buffer. |
| 79 | pub fn next(&mut self, src: &[u8], dst: &mut [u8], acc: i32) -> Result<usize> { |
| 80 | self.next_to_ptr(src, dst.as_mut_ptr(), dst.len(), acc) |
| 81 | } |
| 82 | |
| 83 | fn next_to_ptr(&mut self, src: &[u8], dst: *mut u8, dst_len: usize, acc: i32) -> Result<usize> { |
| 84 | let is_empty = src.is_empty() && dst_len == 0; |
| 85 | let dst_len = self.ctx.next(src, dst, dst_len, acc); |
| 86 | |
| 87 | self.save_dict(); |
| 88 | |
| 89 | if dst_len > 0 { |
| 90 | Ok(dst_len) |
| 91 | } else if is_empty { |
| 92 | Ok(0) |
| 93 | } else { |
| 94 | Err(Error::new(ErrorKind::CompressionFailed)) |
| 95 | } |
| 96 | } |
| 97 | |
| 98 | /// Appends compressed data to `Vec<u8>`. |
| 99 | /// |
| 100 | /// Returns the number of bytes appended to the given `Vec<u8>`. |
| 101 | pub fn next_to_vec(&mut self, src: &[u8], dst: &mut Vec<u8>, acc: i32) -> Result<usize> { |
| 102 | let orig_len = dst.len(); |
| 103 | dst.reserve(lz4::max_compressed_size(src.len())); |
| 104 | #[allow(unsafe_code)] |
| 105 | unsafe { |
| 106 | let result = self.next_to_ptr( |
| 107 | src, |
| 108 | dst.as_mut_ptr().add(orig_len), |
| 109 | dst.capacity() - orig_len, |
| 110 | acc, |
| 111 | ); |
| 112 | dst.set_len(orig_len + result.as_ref().unwrap_or(&0)); |
| 113 | result |
| 114 | } |
| 115 | } |
| 116 | |
| 117 | fn save_dict(&mut self) { |
| 118 | self.safe_buf.resize(DICTIONARY_SIZE, 0); |
| 119 | self.ctx.save_dict(&mut self.safe_buf); |
| 120 | } |
| 121 | |
| 122 | /// Attaches a dictionary stream for efficient dictionary reuse. |
| 123 | /// |
| 124 | /// This allows efficient re-use of a static dictionary multiple times by referencing |
| 125 | /// the dictionary stream in-place rather than copying it. |
| 126 | /// |
| 127 | /// # Arguments |
| 128 | /// |
| 129 | /// * `dict_stream` - The dictionary stream to attach, or None to unset any existing dictionary |
| 130 | /// |
| 131 | /// # Notes |
| 132 | /// |
| 133 | /// - The dictionary stream must have been prepared using `with_dict()` or `with_dict_slow()` |
| 134 | /// - The dictionary will only remain attached through the first compression call |
| 135 | /// - The dictionary stream (and its source buffer) must remain valid through the compression session |
| 136 | /// |
| 137 | /// # Example |
| 138 | /// |
| 139 | /// ``` |
| 140 | /// use lzzzz::lz4; |
| 141 | /// |
| 142 | /// let dict_data = b"some dictionary data"; |
| 143 | /// let data = b"data to compress"; |
| 144 | /// |
| 145 | /// // Create dictionary stream |
| 146 | /// let mut dict_comp = lz4::Compressor::with_dict(dict_data)?; |
| 147 | /// |
| 148 | /// // Create working stream and attach dictionary |
| 149 | /// let mut comp = lz4::Compressor::new()?; |
| 150 | /// comp.attach_dict(Some(&mut dict_comp)); |
| 151 | /// |
| 152 | /// // Compress data using the attached dictionary |
| 153 | /// let mut buf = [0u8; 256]; |
| 154 | /// let len = comp.next(data, &mut buf, lz4::ACC_LEVEL_DEFAULT)?; |
| 155 | /// # Ok::<(), std::io::Error>(()) |
| 156 | /// ``` |
| 157 | pub fn attach_dict(&mut self, dict_stream: Option<&mut Compressor<'a>>) { |
| 158 | if let Some(dict) = dict_stream { |
| 159 | self.ctx.attach_dict(Some(&mut dict.ctx)); |
| 160 | } else { |
| 161 | self.ctx.attach_dict(None); |
| 162 | } |
| 163 | } |
| 164 | } |
| 165 | |
| 166 | /// Streaming LZ4 decompressor. |
| 167 | /// |
| 168 | /// # Example |
| 169 | /// |
| 170 | /// ``` |
| 171 | /// use lzzzz::lz4; |
| 172 | /// |
| 173 | /// const ORIGINAL_SIZE: usize = 44; |
| 174 | /// const COMPRESSED_DATA: &str = |
| 175 | /// "8B1UaGUgcXVpY2sgYnJvd24gZm94IGp1bXBzIG92ZXIgdGhlIGxhenkgZG9nLg=="; |
| 176 | /// |
| 177 | /// let data = base64::decode(COMPRESSED_DATA).unwrap(); |
| 178 | /// |
| 179 | /// let mut decomp = lz4::Decompressor::new()?; |
| 180 | /// let result = decomp.next(&data[..], ORIGINAL_SIZE)?; |
| 181 | /// |
| 182 | /// assert_eq!(result, &b"The quick brown fox jumps over the lazy dog."[..]); |
| 183 | /// # Ok::<(), std::io::Error>(()) |
| 184 | /// ``` |
| 185 | pub struct Decompressor<'a> { |
| 186 | ctx: DecompressionContext, |
| 187 | cache: LinkedList<Vec<u8>>, |
| 188 | cache_len: usize, |
| 189 | last_len: usize, |
| 190 | dict: Pin<Cow<'a, [u8]>>, |
| 191 | } |
| 192 | |
| 193 | impl<'a> Decompressor<'a> { |
| 194 | /// Creates a new `Decompressor`. |
| 195 | pub fn new() -> Result<Self> { |
| 196 | Ok(Self { |
| 197 | ctx: DecompressionContext::new()?, |
| 198 | cache: LinkedList::new(), |
| 199 | cache_len: 0, |
| 200 | last_len: 0, |
| 201 | dict: Pin::new(Cow::Borrowed(&[])), |
| 202 | }) |
| 203 | } |
| 204 | |
| 205 | /// Creates a new `Decompressor` with a dictionary. |
| 206 | pub fn with_dict<D>(dict: D) -> Result<Self> |
| 207 | where |
| 208 | D: Into<Cow<'a, [u8]>>, |
| 209 | { |
| 210 | let mut decomp = Self { |
| 211 | dict: Pin::new(dict.into()), |
| 212 | ..Self::new()? |
| 213 | }; |
| 214 | decomp.ctx.reset(&decomp.dict)?; |
| 215 | Ok(decomp) |
| 216 | } |
| 217 | |
| 218 | /// Decompresses an LZ4 block. |
| 219 | pub fn next(&mut self, src: &[u8], original_size: usize) -> Result<&[u8]> { |
| 220 | if self |
| 221 | .cache |
| 222 | .back() |
| 223 | .map(|v| v.capacity() - v.len()) |
| 224 | .filter(|n| *n >= original_size) |
| 225 | .is_none() |
| 226 | { |
| 227 | self.cache.push_back(Vec::with_capacity(cmp::max( |
| 228 | original_size, |
| 229 | DEFAULT_BUF_SIZE, |
| 230 | ))); |
| 231 | } |
| 232 | |
| 233 | let back = self.cache.back_mut().unwrap(); |
| 234 | let orig_len = back.len(); |
| 235 | |
| 236 | #[allow(unsafe_code)] |
| 237 | unsafe { |
| 238 | let dst_len = self.ctx.decompress( |
| 239 | src, |
| 240 | back.as_mut_ptr().add(orig_len), |
| 241 | back.capacity() - orig_len, |
| 242 | )?; |
| 243 | back.set_len(orig_len + dst_len); |
| 244 | self.cache_len += dst_len; |
| 245 | } |
| 246 | self.last_len = original_size; |
| 247 | |
| 248 | while let Some(len) = self |
| 249 | .cache |
| 250 | .front() |
| 251 | .map(Vec::len) |
| 252 | .filter(|n| self.cache_len - n >= DICTIONARY_SIZE) |
| 253 | { |
| 254 | self.cache.pop_front(); |
| 255 | self.cache_len -= len; |
| 256 | } |
| 257 | Ok(self.data()) |
| 258 | } |
| 259 | |
| 260 | fn data(&self) -> &[u8] { |
| 261 | if let Some(back) = self.cache.back() { |
| 262 | let offset = back.len() - self.last_len; |
| 263 | &back[offset..] |
| 264 | } else { |
| 265 | &[] |
| 266 | } |
| 267 | } |
| 268 | } |