1use alloc::boxed::Box;
4use alloc::vec::Vec;
5
6use crate::block::{BLOCK_SIZE_MAX, BlockDecoder, Output, WILDCOPY_OVERLENGTH};
7use crate::dict::Dictionary;
8use crate::error::{Error, Result};
9use crate::frame::{self, FrameHeader};
10use crate::xxhash::Xxh64;
11
12pub struct Decompressor {
25 block: Box<BlockDecoder>,
26 dict: Option<Dictionary>,
27 dict_end: usize,
32}
33
34impl core::fmt::Debug for Decompressor {
35 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
36 f.debug_struct("Decompressor")
37 .field("dict", &self.dict)
38 .finish_non_exhaustive()
39 }
40}
41
42impl Default for Decompressor {
43 fn default() -> Self {
44 Self::new()
45 }
46}
47
48enum Sink<'a> {
50 Vec(&'a mut Vec<u8>),
51 Slice,
52}
53
54impl Decompressor {
55 pub fn new() -> Self {
57 Decompressor {
58 block: Box::new(BlockDecoder::new()),
59 dict: None,
60 dict_end: 0,
61 }
62 }
63
64 pub fn with_dictionary(dict: Dictionary) -> Self {
66 Decompressor {
67 block: Box::new(BlockDecoder::new()),
68 dict: Some(dict),
69 dict_end: 0,
70 }
71 }
72
73 pub fn set_dictionary(&mut self, dict: Option<Dictionary>) {
75 let same = matches!((&self.dict, &dict), (Some(a), Some(b)) if a.same(b));
77 if !same {
78 self.block.dict_changed();
79 }
80 self.dict = dict;
81 }
82
83 pub fn decompress(&mut self, src: &[u8]) -> Result<Vec<u8>> {
90 let mut v = Vec::new();
91 self.decompress_append(src, &mut v)?;
92 Ok(v)
93 }
94
95 pub fn decompress_append(&mut self, src: &[u8], dst: &mut Vec<u8>) -> Result<()> {
103 let mut out = Output {
104 ptr: dst.as_mut_ptr(),
105 cap: dst.capacity(),
106 pos: dst.len(),
107 };
108 let res = self.decode_frames(src, &mut out, &mut Sink::Vec(&mut *dst));
109 #[allow(unsafe_code)]
111 unsafe {
112 dst.set_len(out.pos)
113 };
114 res
115 }
116
117 pub fn decompress_to_slice(&mut self, src: &[u8], dst: &mut [u8]) -> Result<usize> {
125 let mut out = Output {
126 ptr: dst.as_mut_ptr(),
127 cap: dst.len(),
128 pos: 0,
129 };
130 self.decode_frames(src, &mut out, &mut Sink::Slice)?;
131 Ok(out.pos)
132 }
133
134 fn decode_frames(&mut self, src: &[u8], out: &mut Output, sink: &mut Sink<'_>) -> Result<()> {
135 let mut ip = 0;
136 while src.len() - ip >= frame::STARTING_INPUT_LENGTH {
137 let magic = frame::read_le32(src, ip);
138 if frame::is_skippable(magic) {
139 if src.len() - ip < 8 {
140 return Err(Error::Truncated);
141 }
142 let size = frame::read_le32(src, ip + 4) as usize;
143 if size > src.len() - ip - 8 {
144 return Err(Error::Truncated);
145 }
146 ip += 8 + size;
147 continue;
148 }
149 ip += self.decode_frame(&src[ip..], out, sink)?;
150 }
151 if ip != src.len() {
152 return Err(Error::Truncated);
153 }
154 Ok(())
155 }
156
157 fn decode_frame(&mut self, src: &[u8], out: &mut Output, sink: &mut Sink<'_>) -> Result<usize> {
159 if src.len() < frame::FRAME_HEADER_SIZE_MIN + frame::BLOCK_HEADER_SIZE {
160 return Err(Error::Truncated);
161 }
162 let fh = FrameHeader::parse(src)?;
163 let mut ip = fh.header_size;
164 if src.len() < ip + frame::BLOCK_HEADER_SIZE {
165 return Err(Error::Truncated);
166 }
167 let dict: &[u8] = match &self.dict {
168 Some(d) => {
169 if fh.dict_id != 0 && fh.dict_id != d.id() {
170 return Err(Error::DictionaryMismatch);
171 }
172 self.block.start_frame(d.entropy());
173 d.content()
174 }
175 None => {
176 if fh.dict_id != 0 {
177 return Err(Error::DictionaryMismatch);
178 }
179 self.block.start_frame(None);
180 &[]
181 }
182 };
183 let dict_ent = self.dict.as_ref().and_then(Dictionary::entropy);
184 let end = self
189 .dict
190 .as_ref()
191 .map_or(0, |d| d.content().as_ptr_range().end as usize);
192 self.block.dict_cold = end != 0 && end != core::mem::replace(&mut self.dict_end, end);
193 let block_max = fh.block_size_max();
194 let prefix = out.pos;
195
196 if let Sink::Vec(v) = sink {
197 if let Some(cs) = fh.content_size {
200 let bound = ((src.len() as u64 / 3) + 1).saturating_mul(BLOCK_SIZE_MAX as u64);
201 let want = cs.min(bound).saturating_add(WILDCOPY_OVERLENGTH as u64);
202 let want = usize::try_from(want).map_err(|_| Error::OutputTooLarge)?;
203 reserve(v, out, want)?;
204 }
205 }
206
207 let mut xxh = fh.has_checksum.then(Xxh64::new);
208 loop {
209 if src.len() - ip < frame::BLOCK_HEADER_SIZE {
210 return Err(Error::Truncated);
211 }
212 let bh = u32::from_le_bytes([src[ip], src[ip + 1], src[ip + 2], 0]);
213 ip += frame::BLOCK_HEADER_SIZE;
214 let last = bh & 1 != 0;
215 let btype = (bh >> 1) & 3;
216 let bsize = (bh >> 3) as usize;
217 let start = out.pos;
218 match btype {
219 0 => {
220 if bsize > src.len() - ip {
222 return Err(Error::Truncated);
223 }
224 if let Sink::Vec(v) = sink {
225 reserve(v, out, bsize + WILDCOPY_OVERLENGTH)?;
226 }
227 if bsize > out.cap - out.pos {
228 return Err(Error::OutputTooSmall);
229 }
230 #[allow(unsafe_code)]
232 unsafe {
233 core::ptr::copy_nonoverlapping(
234 src.as_ptr().add(ip),
235 out.ptr.add(out.pos),
236 bsize,
237 )
238 };
239 out.pos += bsize;
240 ip += bsize;
241 }
242 1 => {
243 if ip >= src.len() {
245 return Err(Error::Truncated);
246 }
247 if let Sink::Vec(v) = sink {
248 reserve(v, out, bsize + WILDCOPY_OVERLENGTH)?;
249 }
250 if bsize > out.cap - out.pos {
251 return Err(Error::OutputTooSmall);
252 }
253 #[allow(unsafe_code)]
255 unsafe {
256 core::ptr::write_bytes(out.ptr.add(out.pos), src[ip], bsize)
257 };
258 out.pos += bsize;
259 ip += 1;
260 }
261 2 => {
262 if bsize > src.len() - ip {
263 return Err(Error::Truncated);
264 }
265 if let Sink::Vec(v) = sink {
266 reserve(v, out, block_max + WILDCOPY_OVERLENGTH)?;
267 }
268 self.block.decode_block(
269 &src[ip..ip + bsize],
270 out,
271 prefix,
272 dict,
273 dict_ent,
274 block_max,
275 )?;
276 ip += bsize;
277 }
278 _ => return Err(Error::Corrupted),
279 }
280 if let Some(x) = &mut xxh {
281 #[allow(unsafe_code)]
283 let produced =
284 unsafe { core::slice::from_raw_parts(out.ptr.add(start), out.pos - start) };
285 x.update(produced);
286 }
287 if last {
288 break;
289 }
290 }
291 if let Some(cs) = fh.content_size
292 && (out.pos - prefix) as u64 != cs
293 {
294 return Err(Error::Corrupted);
295 }
296 if let Some(x) = xxh {
297 if src.len() - ip < 4 {
298 return Err(Error::Truncated);
299 }
300 if frame::read_le32(src, ip) != x.digest() as u32 {
301 return Err(Error::ChecksumMismatch);
302 }
303 ip += 4;
304 }
305 Ok(ip)
306 }
307}
308
309pub(crate) fn reserve(v: &mut Vec<u8>, out: &mut Output, extra: usize) -> Result<()> {
311 if out.cap - out.pos >= extra {
312 return Ok(());
313 }
314 #[allow(unsafe_code)]
316 unsafe {
317 v.set_len(out.pos)
318 };
319 v.try_reserve(extra).map_err(|_| Error::OutputTooLarge)?;
320 out.ptr = v.as_mut_ptr();
321 out.cap = v.capacity();
322 Ok(())
323}
324
325pub fn decompress(src: &[u8]) -> Result<Vec<u8>> {
338 with_cached(|d| d.decompress(src))
339}
340
341pub fn decompress_to_slice(src: &[u8], dst: &mut [u8]) -> Result<usize> {
348 with_cached(|d| d.decompress_to_slice(src, dst))
349}
350
351#[cfg(feature = "std")]
355fn with_cached<T>(f: impl FnOnce(&mut Decompressor) -> T) -> T {
356 use core::cell::Cell;
357 std::thread_local! {
358 static CACHED: Cell<Option<Box<Decompressor>>> = const { Cell::new(None) };
359 }
360 let mut d = CACHED
362 .with(Cell::take)
363 .unwrap_or_else(|| Box::new(Decompressor::new()));
364 let r = f(&mut d);
365 CACHED.with(|c| c.set(Some(d)));
366 r
367}
368
369#[cfg(not(feature = "std"))]
370fn with_cached<T>(f: impl FnOnce(&mut Decompressor) -> T) -> T {
371 f(&mut Decompressor::new())
372}
373
374pub fn content_size(src: &[u8]) -> Result<Option<u64>> {
381 Ok(FrameHeader::parse(src)?.content_size)
382}