1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
use core::{ffi::c_uint, mem::MaybeUninit};
use crate::deflate::DeflateConfig;
use crate::inflate::InflateConfig;
use crate::ReturnCode;
pub use crate::{DeflateFlush, InflateFlush};
/// Possible status results of compressing some data or successfully
/// decompressing a block of data.
#[derive(Copy, Clone, PartialEq, Eq, Debug)]
pub enum Status {
/// Indicates success.
///
/// Means that more input may be needed but isn't available
/// and/or there's more output to be written but the output buffer is full.
Ok,
/// Indicates that forward progress is not possible due to input or output
/// buffers being empty.
///
/// For compression it means the input buffer needs some more data or the
/// output buffer needs to be freed up before trying again.
///
/// For decompression this means that more input is needed to continue or
/// the output buffer isn't large enough to contain the result. The function
/// can be called again after fixing both.
BufError,
/// Indicates that all input has been consumed and all output bytes have
/// been written. Decompression/compression should not be called again.
///
/// For decompression with zlib streams the adler-32 of the decompressed
/// data has also been verified.
StreamEnd,
}
/// Errors that can occur when decompressing.
#[derive(Copy, Clone, PartialEq, Eq, Debug)]
#[repr(i32)]
pub enum InflateError {
/// Decompressing this input requires a dictionary.
NeedDict { dict_id: u32 } = 2,
/// The [`Inflate`] is in an inconsistent state, most likely
/// due to an invalid configuration parameter.
StreamError = -2,
/// The input is not a valid deflate stream.
DataError = -3,
/// A memory allocation failed.
MemError = -4,
}
impl From<InflateError> for ReturnCode {
fn from(value: InflateError) -> Self {
match value {
InflateError::NeedDict { .. } => ReturnCode::NeedDict,
InflateError::StreamError => ReturnCode::StreamError,
InflateError::DataError => ReturnCode::DataError,
InflateError::MemError => ReturnCode::MemError,
}
}
}
impl InflateError {
pub fn as_str(self) -> &'static str {
ReturnCode::from(self).error_message_str()
}
}
/// The state that is used to decompress an input.
pub struct Inflate {
// A `z_stream` rather than an `InflateStream`, because the latter holds a `&mut State`. That
// reference is protected while an `Inflate` is passed by value, which makes the deallocation
// in `inflate::end` undefined behavior. A raw pointer is not retagged, so no protector exists.
inner: crate::c_api::z_stream,
total_in: u64,
total_out: u64,
}
// SAFETY: `Inflate` exclusively owns its state and uses a thread-safe default allocator.
// Input/output buffers are only accessed during calls borrowing them.
unsafe impl Send for Inflate {}
// SAFETY: Shared access only reads counters and a static error message. Mutating or freeing
// the state requires exclusive access through `&mut self`.
unsafe impl Sync for Inflate {}
impl Inflate {
fn stream(&mut self) -> &mut crate::inflate::InflateStream<'static> {
// SAFETY: `Inflate::new` initialized `self.inner` with `inflate::init`.
unsafe { crate::inflate::InflateStream::from_stream_mut(&mut self.inner) }.unwrap()
}
/// The amount of bytes consumed from the input so far.
pub fn total_in(&self) -> u64 {
self.total_in
}
/// The amount of decompressed bytes that have been written to the output thus far.
pub fn total_out(&self) -> u64 {
self.total_out
}
/// The error message if the previous operation failed.
pub fn error_message(&self) -> Option<&'static str> {
if self.inner.msg.is_null() {
None
} else {
unsafe { core::ffi::CStr::from_ptr(self.inner.msg).to_str() }.ok()
}
}
/// Create a new instance. This function allocates, and so it is recommended to re-use this
/// state when possible, using [`Inflate::reset`] as needed.
///
/// This function will:
///
/// - decode a raw deflate stream when `expect_header = false` and `window_bits` is in the
/// range `8..=15`
/// - decode a zlib header followed by a deflate stream when `expect_header = true` and
/// `window_bits` is in the range `8..=15`
/// - decode a gzip header followed by a deflate stream when `expect_header = true` and
/// `window_bits` is in the range `16 + 8..=16 + 15`
/// - decode either a zlib or a gzip header, followed by a deflate stream when
/// `expect_header = true` and `window_bits` is in the range `32 + 8..=32 + 15`
///
/// `window_bits` can also be 0 to request that inflate use the window size in the
/// zlib header of the compressed stream when using zlib.
///
/// Note that when deflating a value of `window_bits = 8` is silently converted to
/// `window_bits = 9` in most zlib implementations, and hence should be inflated using
/// `window_bits = 9`.
///
/// # Panics
///
/// This function may panic when the `window_bits` and `expect_header` have values not listed above.
pub fn new(expect_header: bool, window_bits: u8) -> Self {
let config = InflateConfig {
window_bits: if expect_header {
i32::from(window_bits)
} else {
-i32::from(window_bits)
},
};
let mut inner = crate::c_api::z_stream::default();
let ret = crate::inflate::init(&mut inner, config);
assert_eq!(ret, ReturnCode::Ok);
Self {
inner,
total_in: 0,
total_out: 0,
}
}
/// Reset the state to allow handling a new stream.
pub fn reset(&mut self, zlib_header: bool) {
let mut config = InflateConfig::default();
if !zlib_header {
config.window_bits = -config.window_bits;
}
self.total_in = 0;
self.total_out = 0;
crate::inflate::reset_with_config(self.stream(), config);
}
/// Decompress `input` and write all decompressed bytes into `output`,
/// with `flush` defining some details about this.
pub fn decompress(
&mut self,
input: &[u8],
output: &mut [u8],
flush: InflateFlush,
) -> Result<Status, InflateError> {
self.decompress_uninit(
input,
unsafe { &mut *(output as *mut _ as *mut [MaybeUninit<u8>]) },
flush,
)
}
/// Decompress `input` and write all decompressed bytes into a potentially uninitialized `output`,
/// with `flush` defining some details about this.
pub fn decompress_uninit(
&mut self,
input: &[u8],
output: &mut [MaybeUninit<u8>],
flush: InflateFlush,
) -> Result<Status, InflateError> {
// Limit the length of the input and output to the maximum value of a c_uint. For larger
// inputs, this will either complete or signal that more input and output is needed. The
// caller should be able to handle this regardless.
self.inner.avail_in = Ord::min(input.len(), c_uint::MAX as usize) as c_uint;
self.inner.avail_out = Ord::min(output.len(), c_uint::MAX as usize) as c_uint;
// This cast_mut is unfortunate, that is just how the types are.
self.inner.next_in = input.as_ptr().cast_mut();
self.inner.next_out = output.as_mut_ptr().cast();
let start_in = self.inner.next_in;
let start_out = self.inner.next_out;
// SAFETY: the inflate state was properly initialized.
let ret = unsafe { crate::inflate::inflate(self.stream(), flush) };
self.total_in += (self.inner.next_in as usize - start_in as usize) as u64;
self.total_out += (self.inner.next_out as usize - start_out as usize) as u64;
match ret {
ReturnCode::Ok => Ok(Status::Ok),
ReturnCode::StreamEnd => Ok(Status::StreamEnd),
ReturnCode::NeedDict => Err(InflateError::NeedDict {
dict_id: self.inner.adler as u32,
}),
ReturnCode::ErrNo => unreachable!("the rust API does not use files"),
ReturnCode::StreamError => Err(InflateError::StreamError),
ReturnCode::DataError => Err(InflateError::DataError),
ReturnCode::MemError => Err(InflateError::MemError),
ReturnCode::BufError => Ok(Status::BufError),
ReturnCode::VersionError => unreachable!("the rust API does not use the version"),
}
}
/// Decompress `input`, appending the output to `output` (house delta, rusty_zlib).
///
/// Writes into the vector's spare capacity, `output.capacity() - output.len()` bytes, and
/// extends its length by the number of bytes produced. It never reallocates; reserve
/// capacity first. The semantics match flate2's `Decompress::decompress_vec`. The
/// uninitialised-memory handling stays inside this crate, so callers that forbid `unsafe` get
/// it without zero-filling the buffer first.
#[cfg(any(feature = "rust-allocator", feature = "c-allocator"))]
pub fn decompress_vec(
&mut self,
input: &[u8],
output: &mut alloc::vec::Vec<u8>,
flush: InflateFlush,
) -> Result<Status, InflateError> {
let len = output.len();
let before = self.total_out;
let result = self.decompress_uninit(input, output.spare_capacity_mut(), flush);
let written = (self.total_out - before) as usize;
// SAFETY: inflate initialised exactly the first `written` bytes of the spare capacity
// (`total_out` advanced by the bytes it wrote through `next_out`), and `written` is at
// most the spare capacity it was given. This holds on error too: those bytes were written.
unsafe { output.set_len(len + written) };
result
}
/// Turn checksum validation (Adler-32 for zlib, CRC-32 for gzip) on or off for this stream
/// (house delta, rusty_zlib). On by default. Turning it off matches libpng's and fdeflate's
/// `ignore_adler32`. Header and data errors are still reported.
pub fn set_validate_checksum(&mut self, validate: bool) {
let _ = crate::inflate::validate(self.stream(), validate);
}
pub fn set_dictionary(&mut self, dictionary: &[u8]) -> Result<u32, InflateError> {
match crate::inflate::set_dictionary(self.stream(), dictionary) {
ReturnCode::Ok => Ok(self.inner.adler as u32),
ReturnCode::StreamError => Err(InflateError::StreamError),
ReturnCode::DataError => Err(InflateError::DataError),
other => unreachable!("set_dictionary does not return {other:?}"),
}
}
}
impl Drop for Inflate {
fn drop(&mut self) {
let _ = crate::inflate::end(self.stream());
}
}
/// Errors that can occur when compressing.
#[derive(Copy, Clone, PartialEq, Eq, Debug)]
pub enum DeflateError {
/// The [`Deflate`] is in an inconsistent state, most likely
/// due to an invalid configuration parameter.
StreamError = -2,
/// The input is not a valid deflate stream.
DataError = -3,
/// A memory allocation failed.
MemError = -4,
}
impl From<DeflateError> for ReturnCode {
fn from(value: DeflateError) -> Self {
match value {
DeflateError::StreamError => ReturnCode::StreamError,
DeflateError::DataError => ReturnCode::DataError,
DeflateError::MemError => ReturnCode::MemError,
}
}
}
impl DeflateError {
pub fn as_str(self) -> &'static str {
ReturnCode::from(self).error_message_str()
}
}
impl From<ReturnCode> for Result<Status, DeflateError> {
fn from(value: ReturnCode) -> Self {
match value {
ReturnCode::Ok => Ok(Status::Ok),
ReturnCode::StreamEnd => Ok(Status::StreamEnd),
ReturnCode::NeedDict => unreachable!("compression does not use dictionary"),
ReturnCode::ErrNo => unreachable!("the rust API does not use files"),
ReturnCode::StreamError => Err(DeflateError::StreamError),
ReturnCode::DataError => Err(DeflateError::DataError),
ReturnCode::MemError => Err(DeflateError::MemError),
ReturnCode::BufError => Ok(Status::BufError),
ReturnCode::VersionError => unreachable!("the rust API does not use the version"),
}
}
}
/// The state that is used to compress an input.
pub struct Deflate {
// See the note on `Inflate::inner`.
inner: crate::c_api::z_stream,
total_in: u64,
total_out: u64,
}
// SAFETY: `Deflate` exclusively owns its state and uses a thread-safe default allocator.
// Input/output buffers are only accessed during calls borrowing them.
unsafe impl Send for Deflate {}
// SAFETY: Shared access only reads counters and a static error message. Mutating or freeing
// the state requires exclusive access through `&mut self`.
unsafe impl Sync for Deflate {}
impl Deflate {
fn stream(&mut self) -> &mut crate::deflate::DeflateStream<'static> {
// SAFETY: `Deflate::new` initialized `self.inner` with `deflate::init`.
unsafe { crate::deflate::DeflateStream::from_stream_mut(&mut self.inner) }.unwrap()
}
/// The number of bytes that were read from the input.
pub fn total_in(&self) -> u64 {
self.total_in
}
/// The number of compressed bytes that were written to the output.
pub fn total_out(&self) -> u64 {
self.total_out
}
/// The error message if the previous operation failed.
pub fn error_message(&self) -> Option<&'static str> {
if self.inner.msg.is_null() {
None
} else {
unsafe { core::ffi::CStr::from_ptr(self.inner.msg).to_str() }.ok()
}
}
/// Create a new instance - this allocates so should be done with care.
///
/// The `window_bits` must be in the range `8..=15`, with `15` being most common.
pub fn new(level: i32, zlib_header: bool, window_bits: u8) -> Self {
let config = DeflateConfig {
window_bits: if zlib_header {
i32::from(window_bits)
} else {
-i32::from(window_bits)
},
level,
..DeflateConfig::default()
};
Self::new_with_config(config)
}
/// Create a new instance with the provided [`DeflateConfig`].
///
/// In most cases it is recommended to use the standard [`Deflate::new`] constructor unless
/// tweaking `mem_level` or `strategy` is desired.
///
/// This allocates, so should be done with care.
pub fn new_with_config(config: DeflateConfig) -> Self {
let mut inner = crate::c_api::z_stream::default();
let ret = crate::deflate::init(&mut inner, config);
assert_eq!(ret, ReturnCode::Ok);
Self {
inner,
total_in: 0,
total_out: 0,
}
}
/// Prepare the instance for a new stream.
pub fn reset(&mut self) {
self.total_in = 0;
self.total_out = 0;
crate::deflate::reset(self.stream());
}
/// Compress `input` and write compressed bytes to `output`,
/// with `flush` controlling additional characteristics.
pub fn compress(
&mut self,
input: &[u8],
output: &mut [u8],
flush: DeflateFlush,
) -> Result<Status, DeflateError> {
self.compress_uninit(
input,
unsafe { &mut *(output as *mut _ as *mut [MaybeUninit<u8>]) },
flush,
)
}
/// Compress `input` and write compressed bytes to a potentially uninitialized `output`,
/// with `flush` controlling additional characteristics.
pub fn compress_uninit(
&mut self,
input: &[u8],
output: &mut [MaybeUninit<u8>],
flush: DeflateFlush,
) -> Result<Status, DeflateError> {
// Limit the length of the input and output to the maximum value of a c_uint. For larger
// inputs, this will either complete or signal that more input and output is needed. The
// caller should be able to handle this regardless.
self.inner.avail_in = Ord::min(input.len(), c_uint::MAX as usize) as c_uint;
self.inner.avail_out = Ord::min(output.len(), c_uint::MAX as usize) as c_uint;
// This cast_mut is unfortunate, that is just how the types are.
self.inner.next_in = input.as_ptr().cast_mut();
self.inner.next_out = output.as_mut_ptr().cast();
let start_in = self.inner.next_in;
let start_out = self.inner.next_out;
let ret = crate::deflate::deflate(self.stream(), flush).into();
self.total_in += (self.inner.next_in as usize - start_in as usize) as u64;
self.total_out += (self.inner.next_out as usize - start_out as usize) as u64;
// Clear these pointers so there can be no use after free.
self.inner.next_in = core::ptr::null_mut();
self.inner.next_out = core::ptr::null_mut();
self.inner.avail_in = 0;
self.inner.avail_out = 0;
ret
}
/// Compress `input`, appending the output to `output` (house delta, rusty_zlib).
///
/// Writes into the vector's spare capacity and extends its length by the bytes produced. It
/// never reallocates. The semantics match flate2's `Compress::compress_vec`.
#[cfg(any(feature = "rust-allocator", feature = "c-allocator"))]
pub fn compress_vec(
&mut self,
input: &[u8],
output: &mut alloc::vec::Vec<u8>,
flush: DeflateFlush,
) -> Result<Status, DeflateError> {
let len = output.len();
let before = self.total_out;
let result = self.compress_uninit(input, output.spare_capacity_mut(), flush);
let written = (self.total_out - before) as usize;
// SAFETY: deflate initialised exactly the first `written` bytes of the spare capacity.
unsafe { output.set_len(len + written) };
result
}
/// Specifies the compression dictionary to use.
///
/// Returns the Adler-32 checksum of the dictionary.
pub fn set_dictionary(&mut self, dictionary: &[u8]) -> Result<u32, DeflateError> {
match crate::deflate::set_dictionary(self.stream(), dictionary) {
ReturnCode::Ok => Ok(self.inner.adler as u32),
ReturnCode::StreamError => Err(DeflateError::StreamError),
other => unreachable!("set_dictionary does not return {other:?}"),
}
}
/// Dynamically updates the compression level.
///
/// This can be used to switch between compression levels for different
/// kinds of data, or it can be used in conjunction with a call to [`Deflate::reset`]
/// to reuse the compressor.
///
/// This may return an error if there wasn't enough output space to complete
/// the compression of the available input data before changing the
/// compression level. Flushing the stream before calling this method
/// ensures that the function will succeed on the first call.
pub fn set_level(&mut self, level: i32) -> Result<Status, DeflateError> {
// Clear the input pointer so there can be no use after free. Keep a
// non-null empty output buffer: `deflate` (called by `params` to flush
// remaining output with the previous compression level) rejects a null
// `next_out` with StreamError before it can report BufError for
// `avail_out == 0`, which is what C callers pass when changing levels
// after a flush.
self.inner.next_in = core::ptr::null_mut();
// FIXME: Use core::ptr::dangling_mut() once MSRV is raised beyond 1.84
self.inner.next_out = core::ptr::NonNull::dangling().as_ptr();
self.inner.avail_in = 0;
self.inner.avail_out = 0;
let rc = crate::deflate::params(self.stream(), level, Default::default());
// Actually clear the output pointer as well, so that any attempt to
// use it will fail with an error
self.inner.next_out = core::ptr::null_mut();
match rc {
ReturnCode::Ok => Ok(Status::Ok),
ReturnCode::StreamError => Err(DeflateError::StreamError),
ReturnCode::BufError => Ok(Status::BufError),
other => unreachable!("set_level does not return {other:?}"),
}
}
}
impl Drop for Deflate {
fn drop(&mut self) {
let _ = crate::deflate::end(self.stream());
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn send_sync() {
fn assert_send_sync<T: Send + Sync>() {}
assert_send_sync::<Inflate>();
assert_send_sync::<Deflate>();
}
#[test]
fn vec_append_round_trip_in_small_steps() {
// Data large enough for several blocks, fed through 7-byte capacity steps so every
// resume path is used; the Vec APIs must append and never touch existing bytes.
let data: Vec<u8> = (0..200_000u32)
.map(|i| (i * 7 % 251) as u8 ^ (i >> 9) as u8)
.collect();
let mut d = Deflate::new(6, true, 15);
let mut z = b"prefix".to_vec();
let mut consumed = 0;
loop {
z.reserve(7);
let before = d.total_in() as usize;
let st = d
.compress_vec(&data[consumed..], &mut z, DeflateFlush::Finish)
.unwrap();
consumed += d.total_in() as usize - before;
if st == Status::StreamEnd {
break;
}
}
assert_eq!(&z[..6], b"prefix");
assert_eq!(z.len() - 6, d.total_out() as usize);
// The same 7-byte stepping through the slice API must give the same bytes.
let mut d2 = Deflate::new(6, true, 15);
let mut via_slice = Vec::new();
let mut consumed = 0;
loop {
let mut step = [0u8; 7];
let (bi, bo) = (d2.total_in() as usize, d2.total_out() as usize);
let st = d2
.compress(&data[consumed..], &mut step, DeflateFlush::Finish)
.unwrap();
consumed += d2.total_in() as usize - bi;
via_slice.extend_from_slice(&step[..d2.total_out() as usize - bo]);
if st == Status::StreamEnd {
break;
}
}
assert!(z[6..] == via_slice[..], "same bytes as the slice API");
let mut inf = Inflate::new(true, 15);
let mut out = b"keep".to_vec();
let mut used = 6;
loop {
out.reserve(7);
let before = inf.total_in() as usize;
let st = inf
.decompress_vec(&z[used..], &mut out, InflateFlush::NoFlush)
.unwrap();
used += inf.total_in() as usize - before;
if st == Status::StreamEnd {
break;
}
}
assert_eq!(&out[..4], b"keep");
assert!(out[4..] == data[..]);
}
#[test]
fn vec_append_with_no_spare_capacity_writes_nothing() {
let z = compress(INPUT);
let mut inf = Inflate::new(true, 15);
let mut out = Vec::new();
out.shrink_to_fit();
let st = inf
.decompress_vec(&z, &mut out, InflateFlush::NoFlush)
.unwrap();
assert!(out.is_empty());
assert_ne!(st, Status::StreamEnd);
}
#[test]
fn checksum_validation_can_be_turned_off() {
let mut z = compress(INPUT);
let last = z.len() - 1;
z[last] ^= 0xff; // corrupt the Adler-32 trailer
let mut out = Vec::with_capacity(256);
assert!(Inflate::new(true, 15)
.decompress_vec(&z, &mut out, InflateFlush::Finish)
.is_err());
let mut inf = Inflate::new(true, 15);
inf.set_validate_checksum(false);
out.clear();
assert_eq!(
inf.decompress_vec(&z, &mut out, InflateFlush::Finish)
.unwrap(),
Status::StreamEnd
);
assert_eq!(out, INPUT);
}
const INPUT: &[u8] = b"scatter scatter scatter, gather gather gather, scatter gather";
fn compress(input: &[u8]) -> Vec<u8> {
let mut deflate = Deflate::new(6, true, 15);
let mut output = vec![0u8; 256];
let status = deflate
.compress(input, &mut output, DeflateFlush::Finish)
.unwrap();
assert_eq!(status, Status::StreamEnd);
output.truncate(deflate.total_out() as usize);
output
}
fn decompress(input: &[u8]) -> Vec<u8> {
let mut inflate = Inflate::new(true, 15);
let mut output = vec![0u8; 256];
let status = inflate
.decompress(input, &mut output, InflateFlush::Finish)
.unwrap();
assert_eq!(status, Status::StreamEnd);
output.truncate(inflate.total_out() as usize);
output
}
#[test]
fn round_trip() {
assert_eq!(decompress(&compress(INPUT)), INPUT);
}
#[test]
fn reuse_after_reset() {
let compressed = compress(INPUT);
let mut inflate = Inflate::new(true, 15);
let mut output = vec![0u8; 256];
for _ in 0..2 {
inflate.reset(true);
let status = inflate
.decompress(&compressed, &mut output, InflateFlush::Finish)
.unwrap();
assert_eq!(status, Status::StreamEnd);
assert_eq!(&output[..inflate.total_out() as usize], INPUT);
}
}
#[test]
fn reuse_after_error() {
let mut compressed = compress(INPUT);
let last = compressed.len() - 1;
compressed[last] ^= 0xff;
let mut inflate = Inflate::new(true, 15);
let mut output = vec![0u8; 256];
assert!(inflate
.decompress(&compressed, &mut output, InflateFlush::Finish)
.is_err());
inflate.reset(true);
let compressed = compress(INPUT);
let status = inflate
.decompress(&compressed, &mut output, InflateFlush::Finish)
.unwrap();
assert_eq!(status, Status::StreamEnd);
assert_eq!(&output[..inflate.total_out() as usize], INPUT);
}
/// The state now lives behind a raw pointer, so moving the value must not invalidate it.
#[test]
fn usable_after_being_moved() {
let mut boxed = Box::new(Inflate::new(true, 15));
let mut output = vec![0u8; 256];
let inflate = &mut *boxed;
let compressed = compress(INPUT);
let status = inflate
.decompress(&compressed, &mut output, InflateFlush::Finish)
.unwrap();
assert_eq!(status, Status::StreamEnd);
assert_eq!(&output[..inflate.total_out() as usize], INPUT);
}
/// Passing a value to a function by value retags the references reachable from it and
/// protects them for the duration of the call. Storing the state as a `&mut State` meant the
/// drop glue then freed the allocation that protected reference points into, which miri
/// rejects under both Stacked Borrows and Tree Borrows.
#[test]
fn drop_by_value() {
drop(Inflate::new(true, 15));
drop(Deflate::new(6, true, 15));
}
/// The retag is recursive, so burying the value in a field does not avoid the protector.
#[test]
fn drop_nested_by_value() {
struct Wrapper {
_inflate: Option<Inflate>,
_deflate: Box<Deflate>,
}
drop(Wrapper {
_inflate: Some(Inflate::new(true, 15)),
_deflate: Box::new(Deflate::new(6, true, 15)),
});
}
/// A value that has been used still has to survive the same drop.
#[test]
fn drop_by_value_after_use() {
let mut inflate = Inflate::new(true, 15);
let mut output = vec![0u8; 256];
inflate
.decompress(&compress(INPUT), &mut output, InflateFlush::Finish)
.unwrap();
drop(inflate);
}
/// The other drop shapes never created a protector, and must stay that way.
#[test]
fn drop_without_being_passed_by_value() {
let _scope_end = Inflate::new(true, 15);
let mut vec = vec![Inflate::new(true, 15)];
vec.clear();
let mut option = Some(Deflate::new(6, true, 15));
let _ = option.take();
}
#[test]
fn set_level_after_sync_flush_changes_deflate_function() {
let input = vec![b'a'; 128];
let mut out = vec![0u8; 512];
let mut d = Deflate::new(1, true, 15);
d.compress(&input, &mut out, DeflateFlush::SyncFlush)
.unwrap();
assert_eq!(d.set_level(9), Ok(Status::Ok));
}
#[test]
fn set_level_without_flush_reports_buf_error() {
let input = vec![b'a'; 128];
let mut out = vec![0u8; 512];
let mut d = Deflate::new(1, true, 15);
d.compress(&input, &mut out, DeflateFlush::NoFlush).unwrap();
assert_eq!(d.set_level(9), Ok(Status::BufError));
}
}