forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiBcbbd6e2Tahinli2 months ago2369 commits

lib.rs134 lines, 5.7 KiBHistoryRawDownload
1//! Compatibility shim carrying the `miniz_oxide` name and version, over
2//! [`ec_inflate`].
3//!
4//! Only the surface a caller in this family actually consumes is here — edith's
5//! Matroska `ContentEncodings` path uses exactly
6//! [`inflate::decompress_to_vec_zlib_with_limit`] and the `Display` of the error
7//! it returns. Field names, statuses and message strings match miniz_oxide
8//! 0.8.9 so a `[patch.crates-io]` swap needs no source change; anything else the
9//! upstream crate exposes is deliberately absent, so a new use shows up as a
10//! compile error rather than as silently different behaviour.
11
12#![forbid(unsafe_code)]
13#![warn(missing_docs)]
14
15/// Decompression, as `miniz_oxide::inflate`.
16pub mod inflate {
17 use ec_inflate::Error;
18
19 /// Return status codes, as miniz_oxide spells them.
20 #[repr(i8)]
21 #[derive(Copy, Clone, Debug, Hash, PartialEq, Eq)]
22 pub enum TINFLStatus {
23 /// More input was expected but the caller said there is no more.
24 FailedCannotMakeProgress = -4,
25 /// The output buffer is an invalid size.
26 BadParam = -3,
27 /// Decompression went fine but the Adler-32 did not match.
28 Adler32Mismatch = -2,
29 /// Failed to decompress due to invalid data.
30 Failed = -1,
31 /// Finished decompression without issues.
32 Done = 0,
33 /// The decompressor needs more input data to continue.
34 NeedsMoreInput = 1,
35 /// There is still pending data that did not fit in the output buffer.
36 HasMoreOutput = 2,
37 }
38
39 /// Failure of a `decompress_to_vec*` call, with the data decoded so far.
40 #[derive(Debug)]
41 pub struct DecompressError {
42 /// Decompressor status on failure.
43 pub status: TINFLStatus,
44 /// The currently decompressed data, if any.
45 pub output: Vec<u8>,
46 }
47
48 impl core::fmt::Display for DecompressError {
49 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
50 f.write_str(match self.status {
51 TINFLStatus::FailedCannotMakeProgress => "Truncated input stream",
52 TINFLStatus::BadParam => "Invalid output buffer size",
53 TINFLStatus::Adler32Mismatch => "Adler32 checksum mismatch",
54 TINFLStatus::Failed => "Invalid input data",
55 TINFLStatus::Done => "",
56 TINFLStatus::NeedsMoreInput => "Truncated input stream",
57 TINFLStatus::HasMoreOutput => "Output size exceeded the specified limit",
58 })
59 }
60 }
61
62 impl std::error::Error for DecompressError {}
63
64 /// Decompress zlib-wrapped data, growing the output to at most `max_size`.
65 ///
66 /// Over the limit the error carries [`TINFLStatus::HasMoreOutput`] and the
67 /// bytes decompressed so far, as upstream does.
68 pub fn decompress_to_vec_zlib_with_limit(
69 input: &[u8],
70 max_size: usize,
71 ) -> Result<Vec<u8>, DecompressError> {
72 let mut output = Vec::new();
73 match ec_inflate::inflate_into(input, &mut output, max_size, ec_inflate::Format::Zlib) {
74 Ok(()) => Ok(output),
75 Err(error) => Err(DecompressError {
76 status: match error {
77 Error::Truncated => TINFLStatus::FailedCannotMakeProgress,
78 Error::LimitExceeded { .. } => TINFLStatus::HasMoreOutput,
79 Error::Adler32Mismatch { .. } => TINFLStatus::Adler32Mismatch,
80 Error::Corrupt { .. } | Error::Unsupported { .. } => TINFLStatus::Failed,
81 },
82 output,
83 }),
84 }
85 }
86
87 #[cfg(test)]
88 mod tests {
89 use super::*;
90
91 /// `zlib.compress(b"edith reads this out of a Matroska ContentEncodings block" * 4, 9)`.
92 const STREAM: [u8; 66] = [
93 0x78, 0xda, 0xd5, 0xcb, 0xc1, 0x0d, 0x80, 0x30, 0x0c, 0x03, 0xc0, 0x55, 0xbc, 0x0b,
94 0xe2, 0xc9, 0x10, 0xa1, 0x09, 0xb4, 0x2a, 0x8a, 0xa5, 0xc6, 0xec, 0xcf, 0x1c, 0xdc,
95 0xff, 0xc2, 0x87, 0x3a, 0x56, 0x98, 0x17, 0xd4, 0x47, 0x81, 0xaf, 0xc0, 0x0b, 0x86,
96 0xc3, 0xb4, 0x58, 0xd3, 0xb0, 0x31, 0x15, 0xa9, 0x3d, 0x1b, 0x7d, 0xe4, 0x5d, 0x38,
97 0x1f, 0xb6, 0x19, 0xff, 0x89, 0x1f, 0xb5, 0xdd, 0x54, 0x95,
98 ];
99 const PLAIN: &[u8] = b"edith reads this out of a Matroska ContentEncodings block";
100
101 /// The call site: engine/src/demux.rs, `Unpack::Zlib`.
102 #[test]
103 fn decompresses_under_the_limit() {
104 let out = decompress_to_vec_zlib_with_limit(&STREAM, 64 << 20).unwrap();
105 assert_eq!(out.len(), PLAIN.len() * 4);
106 assert_eq!(&out[..PLAIN.len()], PLAIN);
107 }
108
109 #[test]
110 fn over_the_limit_reports_has_more_output_with_partial_data() {
111 let error = decompress_to_vec_zlib_with_limit(&STREAM, 64).unwrap_err();
112 assert_eq!(error.status, TINFLStatus::HasMoreOutput);
113 assert!(error.output.len() <= 64);
114 assert_eq!(
115 error.to_string(),
116 "Output size exceeded the specified limit"
117 );
118 }
119
120 #[test]
121 fn a_broken_stream_reports_its_status() {
122 let mut broken = STREAM;
123 let last = broken.len() - 1;
124 broken[last] ^= 0xff;
125 let error = decompress_to_vec_zlib_with_limit(&broken, 64 << 20).unwrap_err();
126 assert_eq!(error.status, TINFLStatus::Adler32Mismatch);
127 assert_eq!(error.to_string(), "Adler32 checksum mismatch");
128
129 let error = decompress_to_vec_zlib_with_limit(&STREAM[..20], 64 << 20).unwrap_err();
130 assert_eq!(error.status, TINFLStatus::FailedCannotMakeProgress);
131 assert_eq!(error.to_string(), "Truncated input stream");
132 }
133 }
134}