1use std::borrow::Cow;
5
6use coip_format::Codec;
7
8use crate::error::{ReaderError, Result};
9
10#[inline]
12pub fn decompress<'a>(
13 codec: Codec,
14 input: &'a [u8],
15 size_hint: Option<usize>,
16) -> Result<Cow<'a, [u8]>> {
17 decompress_with_dict(codec, input, size_hint, None)
18}
19
20#[inline]
22pub fn decompress_with_dict<'a>(
23 codec: Codec,
24 input: &'a [u8],
25 size_hint: Option<usize>,
26 zstd_dict: Option<(u32, &[u8])>,
27) -> Result<Cow<'a, [u8]>> {
28 match codec {
29 Codec::None => Ok(Cow::Borrowed(input)),
30 Codec::Zstd => Ok(Cow::Owned(decompress_zstd(input, size_hint, zstd_dict)?)),
31 Codec::Lz4 => Ok(Cow::Owned(
32 lz4_flex::decompress_size_prepended(input)
33 .map_err(|e| ReaderError::Decompression(e.to_string()))?,
34 )),
35 other => Err(ReaderError::UnsupportedCodec(other)),
36 }
37}
38
39#[cfg(feature = "zstd-c")]
40#[inline]
41fn decompress_zstd(
42 input: &[u8],
43 size_hint: Option<usize>,
44 zstd_dict: Option<(u32, &[u8])>,
45) -> Result<Vec<u8>> {
46 use std::cell::RefCell;
47 use std::collections::HashMap;
48
49 struct ThreadDecomp {
50 plain: Option<zstd::bulk::Decompressor<'static>>,
51 by_dict: HashMap<u32, zstd::bulk::Decompressor<'static>>,
52 }
53
54 thread_local! {
55 static DECOMP: RefCell<ThreadDecomp> = RefCell::new(ThreadDecomp {
56 plain: None,
57 by_dict: HashMap::new(),
58 });
59 }
60
61 DECOMP.with(|cell| {
62 let mut td = cell.borrow_mut();
63 let cap = zstd::zstd_safe::get_frame_content_size(input)
64 .ok()
65 .flatten()
66 .and_then(|s| usize::try_from(s).ok())
67 .or(size_hint)
68 .unwrap_or_else(|| input.len().saturating_mul(8).max(256));
69
70 let decomp: &mut zstd::bulk::Decompressor<'static> = match zstd_dict {
71 None => {
72 if td.plain.is_none() {
73 td.plain = Some(
74 zstd::bulk::Decompressor::new()
75 .map_err(|e| ReaderError::Decompression(e.to_string()))?,
76 );
77 }
78 td.plain.as_mut().unwrap()
79 }
80 Some((dict_key, dict_bytes)) => {
81 if !td.by_dict.contains_key(&dict_key) {
82 let d = zstd::bulk::Decompressor::with_dictionary(dict_bytes)
83 .map_err(|e| ReaderError::Decompression(e.to_string()))?;
84 td.by_dict.insert(dict_key, d);
85 }
86 td.by_dict.get_mut(&dict_key).unwrap()
87 }
88 };
89
90 match decomp.decompress(input, cap.max(64)) {
91 Ok(buf) => Ok(buf),
92 Err(e) => match zstd_dict {
93 None => zstd::stream::decode_all(input)
94 .map_err(|e2| ReaderError::Decompression(e2.to_string())),
95 Some((_, dict_bytes)) => {
96 let mut dec = zstd::stream::Decoder::with_dictionary(input, dict_bytes)
97 .map_err(|_| ReaderError::Decompression(e.to_string()))?;
98 let mut out = Vec::with_capacity(cap);
99 std::io::Read::read_to_end(&mut dec, &mut out)
100 .map_err(|e2| ReaderError::Decompression(e2.to_string()))?;
101 Ok(out)
102 }
103 },
104 }
105 })
106}
107
108#[cfg(not(feature = "zstd-c"))]
109#[inline]
110fn decompress_zstd(
111 input: &[u8],
112 size_hint: Option<usize>,
113 zstd_dict: Option<(u32, &[u8])>,
114) -> Result<Vec<u8>> {
115 use std::cell::RefCell;
116 use std::collections::HashSet;
117
118 struct ThreadRuzstd {
119 decoder: ruzstd::decoding::FrameDecoder,
120 loaded_dicts: HashSet<u32>,
121 }
122
123 thread_local! {
124 static DECODER: RefCell<ThreadRuzstd> = RefCell::new(ThreadRuzstd {
125 decoder: ruzstd::decoding::FrameDecoder::new(),
126 loaded_dicts: HashSet::new(),
127 });
128 }
129
130 DECODER.with(|cell| {
131 let mut state = cell.borrow_mut();
132 if let Some((dict_key, dict_bytes)) = zstd_dict {
133 if !state.loaded_dicts.contains(&dict_key) {
134 let dict = ruzstd::decoding::Dictionary::decode_dict(dict_bytes)
135 .map_err(|e| ReaderError::Decompression(e.to_string()))?;
136 state
137 .decoder
138 .add_dict(dict)
139 .map_err(|e| ReaderError::Decompression(e.to_string()))?;
140 state.loaded_dicts.insert(dict_key);
141 }
142 }
143
144 let mut src = input;
145 state
146 .decoder
147 .reset(&mut src)
148 .map_err(|e| ReaderError::Decompression(e.to_string()))?;
149
150 let cs = state.decoder.content_size();
151 let cap = if cs > 0 {
152 usize::try_from(cs).unwrap_or(256)
153 } else {
154 size_hint.unwrap_or_else(|| input.len().saturating_mul(4).max(256))
155 };
156 let mut out = Vec::with_capacity(cap);
157
158 state
159 .decoder
160 .decode_blocks(&mut src, ruzstd::decoding::BlockDecodingStrategy::All)
161 .map_err(|e| ReaderError::Decompression(e.to_string()))?;
162
163 state
164 .decoder
165 .collect_to_writer(&mut out)
166 .map_err(|e| ReaderError::Decompression(e.to_string()))?;
167 Ok(out)
168 })
169}