1use crate::{Algorithm, Compression, Error, Sink};
4
5#[derive(Debug, Clone, Copy, PartialEq, Eq)]
32pub struct Zstd {
33 level: i64,
34}
35
36impl Default for Zstd {
37 fn default() -> Self {
38 Self::new()
39 }
40}
41
42impl Zstd {
43 pub const fn new() -> Self {
47 Zstd { level: 3 }
48 }
49
50 pub const fn with_level(level: i64) -> Self {
55 Zstd { level }
56 }
57
58 pub const fn level(&self) -> i64 {
62 self.level
63 }
64
65 pub fn set_level(&mut self, level: i64) -> Result<(), Error> {
69 if !(1..=22).contains(&level) {
70 return Err(Error::InvalidArgument("Level must be between 1 and 22".into()));
71 }
72 self.level = level;
73 Ok(())
74 }
75
76 pub const fn is_supported() -> bool {
80 cfg!(feature = "zstd")
81 }
82
83 pub fn compress_into<S: Sink + ?Sized>(&self, data: &[u8], out: &mut S) -> Result<(), Error> {
85 imp::compress(data, self.level, out)
86 }
87
88 pub fn decompress_into<S: Sink + ?Sized>(&self, data: &[u8], out: &mut S) -> Result<(), Error> {
90 imp::decompress(data, out)
91 }
92}
93
94impl Algorithm for Zstd {
95 fn name(&self) -> &str {
96 Compression::ZSTD
97 }
98
99 fn compress(&self, data: &[u8]) -> Result<Vec<u8>, Error> {
100 let mut out = Vec::new();
101 self.compress_into(data, &mut out)?;
102 Ok(out)
103 }
104
105 fn decompress(&self, data: &[u8]) -> Result<Vec<u8>, Error> {
106 let mut out = Vec::new();
107 self.decompress_into(data, &mut out)?;
108 Ok(out)
109 }
110
111 fn supported(&self) -> bool {
112 Self::is_supported()
113 }
114}
115
116#[cfg(feature = "zstd")]
117mod imp {
118 use std::ffi::{CStr, c_void};
127
128 use zstd_safe::zstd_sys as z;
129
130 use crate::sink::spare;
131 use crate::{Allocator, Error, Sink};
132
133 fn codec(function: &str, code: usize) -> Error {
134 let name = unsafe { CStr::from_ptr(z::ZSTD_getErrorName(code)) };
136 Error::Codec(format!("{function}(): {}", name.to_string_lossy()))
137 }
138
139 fn is_error(code: usize) -> bool {
140 unsafe { z::ZSTD_isError(code) != 0 }
142 }
143
144 fn custom(allocator: Option<Allocator>) -> Option<z::ZSTD_customMem> {
146 allocator.map(|allocator| z::ZSTD_customMem {
147 customAlloc: Some(allocator.alloc as unsafe extern "C" fn(*mut c_void, usize) -> *mut c_void),
148 customFree: Some(allocator.free as unsafe extern "C" fn(*mut c_void, *mut c_void)),
149 opaque: allocator.opaque,
150 })
151 }
152
153 struct CCtx(*mut z::ZSTD_CCtx);
155
156 impl CCtx {
157 fn new(allocator: Option<Allocator>) -> Option<Self> {
159 let cctx = unsafe {
161 match custom(allocator) {
162 Some(memory) => z::ZSTD_createCCtx_advanced(memory),
163 None => z::ZSTD_createCCtx(),
164 }
165 };
166 (!cctx.is_null()).then_some(CCtx(cctx))
167 }
168 }
169
170 impl Drop for CCtx {
171 fn drop(&mut self) {
172 unsafe { z::ZSTD_freeCCtx(self.0) };
174 }
175 }
176
177 struct DCtx(*mut z::ZSTD_DCtx);
179
180 impl DCtx {
181 fn new(allocator: Option<Allocator>) -> Option<Self> {
183 let dctx = unsafe {
185 match custom(allocator) {
186 Some(memory) => z::ZSTD_createDCtx_advanced(memory),
187 None => z::ZSTD_createDCtx(),
188 }
189 };
190 (!dctx.is_null()).then_some(DCtx(dctx))
191 }
192 }
193
194 impl Drop for DCtx {
195 fn drop(&mut self) {
196 unsafe { z::ZSTD_freeDCtx(self.0) };
198 }
199 }
200
201 fn room<S: Sink + ?Sized>(out: &mut S, window: usize) -> bool {
203 let (len, capacity) = (out.len(), out.capacity());
204 len + window <= capacity || out.grow((len + window).max(capacity + capacity / 2))
205 }
206
207 pub(super) fn compress<S: Sink + ?Sized>(data: &[u8], level: i64, out: &mut S) -> Result<(), Error> {
214 let (max, bound, window) =
216 unsafe { (z::ZSTD_maxCLevel(), z::ZSTD_compressBound(data.len()), z::ZSTD_CStreamOutSize()) };
217 if level > i64::from(max) {
218 return Err(Error::Codec(format!(
219 "zstd_compress(): compression level ({level}) must be within 1..{max} or smaller then 0"
220 )));
221 }
222 let window = window.min(bound);
223 let fail = || Error::Codec("zstd_compress(): insufficient memory".into());
224 out.reserve(out.len() + bound + window);
225 let cctx = CCtx::new(out.allocator())
226 .ok_or_else(|| Error::Codec("zstd_compress(): failed to create compress context".into()))?;
227 unsafe {
230 z::ZSTD_CCtx_reset(cctx.0, z::ZSTD_ResetDirective::ZSTD_reset_session_only);
231 z::ZSTD_CCtx_setParameter(cctx.0, z::ZSTD_cParameter::ZSTD_c_compressionLevel, level as i32);
232 }
233 let mut input = z::ZSTD_inBuffer { src: data.as_ptr().cast(), size: data.len(), pos: 0 };
234 loop {
235 if !room(out, window) {
236 return Err(fail());
237 }
238 let (at, _) = spare(out);
239 let mut output = z::ZSTD_outBuffer { dst: at.cast(), size: window, pos: 0 };
240 let remaining = unsafe {
243 z::ZSTD_compressStream2(cctx.0, &raw mut output, &raw mut input, z::ZSTD_EndDirective::ZSTD_e_end)
244 };
245 if is_error(remaining) {
246 return Err(codec("zstd_compress", remaining));
247 }
248 unsafe { out.set_len(out.len() + output.pos) };
250 if remaining == 0 {
251 return Ok(());
252 }
253 }
254 }
255
256 pub(super) fn decompress<S: Sink + ?Sized>(data: &[u8], out: &mut S) -> Result<(), Error> {
260 let not_zstd = || Error::Codec("zstd_uncompress(): it was not compressed by zstd".into());
261 if let Some(magic) = data.first_chunk::<4>()
264 && matches!(u32::from_le_bytes(*magic), 0x1EB5_2FFD | 0xFD2F_B522..=0xFD2F_B524)
265 {
266 return Err(not_zstd());
267 }
268 let size = unsafe { z::ZSTD_getFrameContentSize(data.as_ptr().cast(), data.len()) };
270 let chunk = unsafe { z::ZSTD_DStreamOutSize() };
272 let mut window = match size {
273 size if size == z::ZSTD_CONTENTSIZE_ERROR as u64 => return Err(not_zstd()),
274 size if size == z::ZSTD_CONTENTSIZE_UNKNOWN as u64 => chunk,
275 size => usize::try_from(size).unwrap_or(usize::MAX),
277 };
278 let fail = || Error::Codec("zstd_uncompress(): insufficient memory".into());
279 if !out.grow(out.len().saturating_add(window)) {
282 return Err(fail());
283 }
284 let dctx = DCtx::new(out.allocator())
285 .ok_or_else(|| Error::Codec("zstd_uncompress(): failed to prepare uncompression".into()))?;
286 unsafe { z::ZSTD_DCtx_reset(dctx.0, z::ZSTD_ResetDirective::ZSTD_reset_session_only) };
288 let mut input = z::ZSTD_inBuffer { src: data.as_ptr().cast(), size: data.len(), pos: 0 };
289 let mut filled = 0;
290 while input.pos < input.size {
291 if filled == window {
292 window += chunk;
293 }
294 if !room(out, window) {
295 return Err(fail());
296 }
297 let (at, _) = spare(out);
298 let mut output = z::ZSTD_outBuffer { dst: at.cast(), size: window, pos: 0 };
299 let hint = unsafe { z::ZSTD_decompressStream(dctx.0, &raw mut output, &raw mut input) };
302 if is_error(hint) {
303 return Err(codec("zstd_uncompress", hint));
304 }
305 filled = output.pos;
306 unsafe { out.set_len(out.len() + filled) };
308 if hint == 0 {
309 break;
310 }
311 }
312 Ok(())
313 }
314}
315
316#[cfg(not(feature = "zstd"))]
317mod imp {
318 use crate::{Error, Sink};
319
320 pub(super) fn compress<S: Sink + ?Sized>(_: &[u8], _: i64, _: &mut S) -> Result<(), Error> {
321 Err(Error::undefined("zstd_compress"))
322 }
323
324 pub(super) fn decompress<S: Sink + ?Sized>(_: &[u8], _: &mut S) -> Result<(), Error> {
325 Err(Error::undefined("zstd_uncompress"))
326 }
327}
328
329#[cfg(all(test, feature = "zstd"))]
330mod tests {
331 use super::*;
332
333 #[test]
334 fn levels() {
335 let mut zstd = Zstd::new();
336 assert_eq!(zstd.set_level(0), Err(Error::InvalidArgument("Level must be between 1 and 22".into())));
337 let data = b"Lorem ipsum dolor sit amet ".repeat(500);
338 for level in [-5, -1, 0, 1, 3, 9, 19, 22] {
339 let zstd = Zstd::with_level(level);
340 assert_eq!(zstd.decompress(&zstd.compress(&data).unwrap()).unwrap(), data);
341 }
342 assert_eq!(
343 Zstd::with_level(23).compress(b"x"),
344 Err(Error::Codec("zstd_compress(): compression level (23) must be within 1..22 or smaller then 0".into()))
345 );
346 }
347
348 #[test]
349 fn known_output() {
350 assert_eq!(
351 Zstd::new().compress(b"This is a demo string").unwrap(),
352 b"\x28\xb5\x2f\xfd\x20\x15\xa9\x00\x00This is a demo string"
353 );
354 }
355
356 #[test]
357 fn large_input_in_blocks() {
358 let data: Vec<u8> = (0..1_000_000u32).map(|i| (i.wrapping_mul(2_654_435_761) >> 27) as u8).collect();
360 let first = Zstd::new().compress(&data).unwrap();
361 assert_eq!(Zstd::new().compress(&data).unwrap(), first);
362 assert_eq!(Zstd::new().decompress(&first).unwrap(), data);
363 }
364
365 #[test]
366 fn truncated_and_invalid() {
367 let data = b"Lorem ipsum dolor sit amet ".repeat(5000);
368 let body = Zstd::new().compress(&data).unwrap();
369 let partial = Zstd::new().decompress(&body[..body.len() / 2]).unwrap();
371 assert!(data.starts_with(&partial));
372 let not_zstd = Err(Error::Codec("zstd_uncompress(): it was not compressed by zstd".into()));
373 assert_eq!(Zstd::new().decompress(b""), not_zstd);
374 assert_eq!(Zstd::new().decompress(b"garbage"), not_zstd);
375 }
376}