Skip to main content

asset_io/
transfer.rs

1// Copyright 2026 Adobe. All rights reserved.
2// This file is licensed to you under the Apache License,
3// Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
4// or the MIT license (http://opensource.org/licenses/MIT),
5// at your option.
6
7// Unless required by applicable law or agreed to in writing,
8// this software is distributed on an "AS IS" BASIS, WITHOUT
9// WARRANTIES OR REPRESENTATIONS OF ANY KIND, either express or
10// implied. See the LICENSE-MIT and LICENSE-APACHE files for the
11// specific language governing permissions and limitations under
12// each license.
13
14//! Transfer encodings: how a container wraps the bytes it stores for an item
15//! (base64 text, a Flate stream), as opposed to the [`Encoding`](crate::Encoding)
16//! of the content itself.
17//!
18//! The core always identifies a transfer encoding; decoding a compressed one needs
19//! the `flate` or `brotli` feature.
20//!
21//! [`TransferEncoding::decode`] and [`TransferEncoding::encode`] convert between
22//! what is stored (what [`Structure::read_item`](crate::Structure::read_item)
23//! returns, and what a hash covers) and the content
24//! ([`Structure::read_content`](crate::Structure::read_content)). The helpers here
25//! are also what handlers use for the same wrappings elsewhere in a file.
26
27use std::borrow::Cow;
28
29use crate::{Error, Result};
30
31/// Largest content a compressed item may decode to (64 MiB).
32pub const MAX_DECODED_LEN: usize = 64 * 1024 * 1024;
33
34/// Longest native label kept for an [`Unknown`](TransferEncoding::Unknown) encoding.
35pub const MAX_LABEL_LEN: usize = 255;
36
37/// How the bytes stored for an item wrap its content.
38///
39/// The core always identifies the wrapping, even when it cannot undo it: the
40/// decoders are optional features (`flate` for [`Zlib`](Self::Zlib),
41/// [`Deflate`](Self::Deflate) and [`Gzip`](Self::Gzip); `brotli` for
42/// [`Brotli`](Self::Brotli)).
43#[derive(Debug, Clone, PartialEq, Eq, Hash, Default)]
44#[non_exhaustive]
45pub enum TransferEncoding {
46    /// Stored as is.
47    #[default]
48    Identity,
49    /// Standard base64 (RFC 4648 alphabet, with padding), as SVG stores a manifest.
50    /// Whitespace is ignored when decoding.
51    Base64,
52    /// A zlib stream (RFC 1950), as PDF `FlateDecode` stores a stream, optionally
53    /// followed by PNG predictor rows of this many 8-bit single-component columns
54    /// (PDF `Predictor` 10 to 15).
55    Zlib {
56        /// Columns per PNG predictor row, or `None` when there is no predictor.
57        png_predictor_columns: Option<u32>,
58    },
59    /// A raw deflate stream (RFC 1951). Decoding also accepts a zlib-wrapped stream,
60    /// recognised by a valid zlib header, since some writers label zlib data
61    /// `deflate`.
62    Deflate,
63    /// A gzip stream (RFC 1952).
64    Gzip,
65    /// A Brotli stream (RFC 7932).
66    Brotli,
67    /// An encoding the core does not know, with the label the format gave it
68    /// (printable ASCII, at most [`MAX_LABEL_LEN`] bytes).
69    Unknown(Cow<'static, str>),
70}
71
72impl TransferEncoding {
73    /// An [`Unknown`](Self::Unknown) encoding labelled `label`, or `None` if the label
74    /// is empty, longer than [`MAX_LABEL_LEN`] or not printable ASCII.
75    pub fn unknown(label: &str) -> Option<Self> {
76        let ok = !label.is_empty()
77            && label.len() <= MAX_LABEL_LEN
78            && label.bytes().all(|c| (0x20..0x7f).contains(&c));
79        ok.then(|| Self::Unknown(Cow::Owned(label.to_owned())))
80    }
81
82    /// `"identity"`, `"base64"`, `"zlib"`, `"deflate"`, `"gzip"`, `"brotli"` or
83    /// `"unknown"`.
84    pub fn as_str(&self) -> &'static str {
85        match self {
86            Self::Identity => "identity",
87            Self::Base64 => "base64",
88            Self::Zlib { .. } => "zlib",
89            Self::Deflate => "deflate",
90            Self::Gzip => "gzip",
91            Self::Brotli => "brotli",
92            Self::Unknown(_) => "unknown",
93        }
94    }
95
96    /// The native label of an [`Unknown`](Self::Unknown) encoding.
97    pub fn unknown_name(&self) -> Option<&str> {
98        match self {
99            Self::Unknown(name) => Some(name),
100            _ => None,
101        }
102    }
103
104    /// The content of `stored` bytes. Decompressed content is bounded by
105    /// [`MAX_DECODED_LEN`]. An encoding whose decoder is not built in (see the type's
106    /// documentation), and an [`Unknown`](Self::Unknown) one, is
107    /// [`Error::UnsupportedFeature`].
108    pub fn decode(&self, stored: Vec<u8>) -> Result<Vec<u8>> {
109        let missing = match self {
110            Self::Zlib { .. } if !cfg!(feature = "flate") => {
111                Some("zlib decoding (enable the `flate` feature)")
112            }
113            Self::Deflate if !cfg!(feature = "flate") => {
114                Some("deflate decoding (enable the `flate` feature)")
115            }
116            Self::Gzip if !cfg!(feature = "flate") => {
117                Some("gzip decoding (enable the `flate` feature)")
118            }
119            Self::Brotli if !cfg!(feature = "brotli") => {
120                Some("Brotli decoding (enable the `brotli` feature)")
121            }
122            _ => None,
123        };
124        if let Some(missing) = missing {
125            return Err(Error::UnsupportedFeature(missing));
126        }
127        match self {
128            Self::Identity => Ok(stored),
129            Self::Base64 => base64_decode(&stored),
130            Self::Zlib {
131                png_predictor_columns,
132            } => {
133                let data = inflate(&stored, MAX_DECODED_LEN, None)?;
134                match png_predictor_columns {
135                    Some(columns) => undo_png_predictor(data, *columns),
136                    None => Ok(data),
137                }
138            }
139            Self::Deflate if is_zlib(&stored) => inflate(&stored, MAX_DECODED_LEN, None),
140            Self::Deflate => inflate_raw(&stored, MAX_DECODED_LEN),
141            Self::Gzip => gunzip(&stored, MAX_DECODED_LEN),
142            Self::Brotli => unbrotli(&stored, MAX_DECODED_LEN),
143            Self::Unknown(_) => Err(Error::UnsupportedFeature(
144                "decoding an unknown transfer encoding",
145            )),
146        }
147    }
148
149    /// At most the first `n` bytes of the content, decoding only as much of
150    /// `stored` as that needs. `stored` may be a prefix of what is stored. Fewer
151    /// bytes are returned when the content is shorter. Errors as
152    /// [`decode`](Self::decode) does.
153    pub fn decode_prefix(&self, stored: &[u8], n: usize) -> Result<Vec<u8>> {
154        match self {
155            Self::Identity => Ok(stored[..stored.len().min(n)].to_vec()),
156            Self::Base64 => {
157                let chars: Vec<u8> = stored
158                    .iter()
159                    .copied()
160                    .filter(|c| !c.is_ascii_whitespace())
161                    .take(n.div_ceil(3) * 4)
162                    .collect();
163                let whole = chars.len() / 4 * 4;
164                let mut out = base64_decode(&chars[..whole])?;
165                out.truncate(n);
166                Ok(out)
167            }
168            Self::Zlib {
169                png_predictor_columns: Some(columns),
170            } => {
171                let columns = (*columns).max(1) as usize;
172                let rows = n.div_ceil(columns);
173                let mut data = stream_prefix(self, stored, rows * (columns + 1))?;
174                data.truncate(data.len() / (columns + 1) * (columns + 1));
175                let mut out = undo_png_predictor(data, columns as u32)?;
176                out.truncate(n);
177                Ok(out)
178            }
179            Self::Unknown(_) => Err(Error::UnsupportedFeature(
180                "decoding an unknown transfer encoding",
181            )),
182            _ => stream_prefix(self, stored, n),
183        }
184    }
185
186    /// The bytes to store for `content`. Only [`Identity`](Self::Identity) and
187    /// [`Base64`](Self::Base64) can be written; anything else is
188    /// [`Error::UnsupportedFeature`].
189    pub fn encode<'a>(&self, content: &'a [u8]) -> Result<Cow<'a, [u8]>> {
190        match self {
191            Self::Identity => Ok(Cow::Borrowed(content)),
192            Self::Base64 => Ok(Cow::Owned(base64_encode(content))),
193            _ => Err(Error::UnsupportedFeature(
194                "encoding a compressed transfer encoding",
195            )),
196        }
197    }
198}
199
200impl std::fmt::Display for TransferEncoding {
201    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
202        match self {
203            Self::Unknown(name) => write!(f, "unknown ({name})"),
204            other => f.write_str(other.as_str()),
205        }
206    }
207}
208
209/// Whether `data` starts with a valid zlib header: deflate method, a window of at
210/// most 32 KiB, and a header checksum that holds.
211fn is_zlib(data: &[u8]) -> bool {
212    match data {
213        [cmf, flg, ..] => {
214            cmf & 0x0f == 8 && cmf >> 4 <= 7 && (u16::from(*cmf) * 256 + u16::from(*flg)) % 31 == 0
215        }
216        _ => false,
217    }
218}
219
220const ALPHABET: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
221
222/// Standard base64 with padding.
223pub fn base64_encode(data: &[u8]) -> Vec<u8> {
224    let mut out = Vec::with_capacity(data.len().div_ceil(3) * 4);
225    for chunk in data.chunks(3) {
226        let n = chunk
227            .iter()
228            .enumerate()
229            .fold(0u32, |n, (i, &b)| n | (b as u32) << (16 - 8 * i));
230        for i in 0..4 {
231            if i <= chunk.len() {
232                out.push(ALPHABET[(n >> (18 - 6 * i) & 63) as usize]);
233            } else {
234                out.push(b'=');
235            }
236        }
237    }
238    out
239}
240
241/// Decode standard base64 with padding, ignoring whitespace (which an XML text
242/// may have).
243pub fn base64_decode(text: &[u8]) -> Result<Vec<u8>> {
244    let bad = |why: &str| Error::InvalidFormat(format!("not base64: {why}"));
245    let mut out = Vec::with_capacity(text.len() / 4 * 3);
246    let (mut n, mut bits, mut pad) = (0u32, 0, 0);
247    for &c in text.iter().filter(|c| !c.is_ascii_whitespace()) {
248        let v = match c {
249            b'A'..=b'Z' => c - b'A',
250            b'a'..=b'z' => c - b'a' + 26,
251            b'0'..=b'9' => c - b'0' + 52,
252            b'+' => 62,
253            b'/' => 63,
254            b'=' => {
255                pad += 1;
256                continue;
257            }
258            _ => return Err(bad("an invalid character")),
259        };
260        if pad > 0 {
261            return Err(bad("data after padding"));
262        }
263        n = n << 6 | v as u32;
264        bits += 6;
265        if bits == 24 {
266            out.extend_from_slice(&n.to_be_bytes()[1..]);
267            (n, bits) = (0, 0);
268        }
269    }
270    match (bits, pad) {
271        (0, 0) => {}
272        (12, 2) => out.push((n >> 4) as u8),
273        (18, 1) => out.extend_from_slice(&[(n >> 10) as u8, (n >> 2) as u8]),
274        _ => return Err(bad("the length or padding is wrong")),
275    }
276    Ok(out)
277}
278
279fn flate_error(message: &str) -> Error {
280    Error::InvalidFormat(format!("Flate: {message}"))
281}
282
283/// Inflate zlib data, which must be all of `input`, to at most `limit` bytes.
284///
285/// `sync_flush_size`: some producers end a stream with a sync flush instead of a
286/// finished zlib stream (PDF cross-reference streams). That is accepted, only for
287/// data that ends in the flush marker and decodes to exactly this size.
288///
289/// Needs the `flate` feature; without it this is [`Error::UnsupportedFeature`].
290pub fn inflate(input: &[u8], limit: usize, sync_flush_size: Option<usize>) -> Result<Vec<u8>> {
291    inflate_with(input, limit, sync_flush_size, true)
292}
293
294/// Inflate a raw deflate stream (no zlib header), which must be all of `input`.
295fn inflate_raw(input: &[u8], limit: usize) -> Result<Vec<u8>> {
296    inflate_with(input, limit, None, false)
297}
298
299#[cfg(feature = "flate")]
300fn inflate_with(
301    input: &[u8],
302    limit: usize,
303    sync_flush_size: Option<usize>,
304    zlib: bool,
305) -> Result<Vec<u8>> {
306    use flate2::{Decompress, FlushDecompress, Status};
307    let mut decoder = Decompress::new(zlib);
308    let mut output = Vec::new();
309    let mut buffer = [0u8; 8192];
310    let mut used = 0usize;
311    loop {
312        let (before_in, before_out) = (decoder.total_in(), decoder.total_out());
313        let status = decoder
314            .decompress(&input[used..], &mut buffer, FlushDecompress::None)
315            .map_err(|_| flate_error("invalid Flate stream or checksum"))?;
316        let consumed = (decoder.total_in() - before_in) as usize;
317        let produced = (decoder.total_out() - before_out) as usize;
318        used += consumed;
319        if output.len().checked_add(produced).is_none_or(|n| n > limit) {
320            return Err(flate_error("decoded stream size limit exceeded"));
321        }
322        output.extend_from_slice(&buffer[..produced]);
323        if status == Status::StreamEnd {
324            if used != input.len() {
325                return Err(flate_error("trailing data in Flate stream"));
326            }
327            return Ok(output);
328        }
329        if consumed == 0 && produced == 0 {
330            if used == input.len()
331                && input.ends_with(&[0, 0, 0xff, 0xff])
332                && sync_flush_size == Some(output.len())
333            {
334                return Ok(output);
335            }
336            return Err(flate_error(if used == input.len() {
337                "incomplete Flate stream"
338            } else {
339                "Flate decoder made no progress"
340            }));
341        }
342    }
343}
344
345#[cfg(not(feature = "flate"))]
346fn inflate_with(_: &[u8], _: usize, _: Option<usize>, _: bool) -> Result<Vec<u8>> {
347    Err(Error::UnsupportedFeature(
348        "Flate decoding (enable the `flate` feature)",
349    ))
350}
351
352/// The first `n` bytes a streaming decoder gives for `stored`; a stream that ends
353/// early (or a truncated `stored`) gives what was decoded before the end.
354#[cfg(any(feature = "flate", feature = "brotli"))]
355fn stream_prefix(encoding: &TransferEncoding, stored: &[u8], n: usize) -> Result<Vec<u8>> {
356    use std::io::Read;
357    let reader: Box<dyn Read + '_> = match encoding {
358        #[cfg(feature = "flate")]
359        TransferEncoding::Zlib { .. } => Box::new(flate2::read::ZlibDecoder::new(stored)),
360        #[cfg(feature = "flate")]
361        TransferEncoding::Deflate if is_zlib(stored) => {
362            Box::new(flate2::read::ZlibDecoder::new(stored))
363        }
364        #[cfg(feature = "flate")]
365        TransferEncoding::Deflate => Box::new(flate2::read::DeflateDecoder::new(stored)),
366        #[cfg(feature = "flate")]
367        TransferEncoding::Gzip => Box::new(flate2::read::GzDecoder::new(stored)),
368        #[cfg(feature = "brotli")]
369        TransferEncoding::Brotli => Box::new(brotli_decompressor::Decompressor::new(stored, 4096)),
370        other => return missing_decoder(other),
371    };
372    let mut out = vec![0u8; n];
373    let mut filled = 0;
374    let mut reader = reader;
375    while filled < n {
376        match reader.read(&mut out[filled..]) {
377            Ok(0) => break,
378            Ok(k) => filled += k,
379            Err(e) if e.kind() == std::io::ErrorKind::UnexpectedEof && filled > 0 => break,
380            Err(e) => return Err(Error::InvalidFormat(format!("{}: {e}", encoding.as_str()))),
381        }
382    }
383    out.truncate(filled);
384    Ok(out)
385}
386
387#[cfg(not(any(feature = "flate", feature = "brotli")))]
388fn stream_prefix(encoding: &TransferEncoding, _: &[u8], _: usize) -> Result<Vec<u8>> {
389    missing_decoder(encoding)
390}
391
392fn missing_decoder(encoding: &TransferEncoding) -> Result<Vec<u8>> {
393    // `decode` names the feature to enable; reuse its message.
394    match encoding.decode(Vec::new()) {
395        Err(e @ Error::UnsupportedFeature(_)) => Err(e),
396        _ => Err(Error::UnsupportedFeature("decoder not built in")),
397    }
398}
399
400/// Read all of `reader`, failing above `limit` bytes.
401#[cfg(any(feature = "flate", feature = "brotli"))]
402fn read_bounded(reader: impl std::io::Read, limit: usize, what: &str) -> Result<Vec<u8>> {
403    use std::io::Read;
404    let mut out = Vec::new();
405    reader
406        .take(limit as u64 + 1)
407        .read_to_end(&mut out)
408        .map_err(|e| Error::InvalidFormat(format!("{what}: {e}")))?;
409    if out.len() > limit {
410        return Err(Error::InvalidFormat(format!(
411            "{what}: decoded size limit exceeded"
412        )));
413    }
414    Ok(out)
415}
416
417#[cfg(feature = "flate")]
418fn gunzip(input: &[u8], limit: usize) -> Result<Vec<u8>> {
419    read_bounded(flate2::read::GzDecoder::new(input), limit, "gzip")
420}
421
422#[cfg(not(feature = "flate"))]
423fn gunzip(_: &[u8], _: usize) -> Result<Vec<u8>> {
424    Err(Error::UnsupportedFeature(
425        "gzip decoding (enable the `flate` feature)",
426    ))
427}
428
429#[cfg(feature = "brotli")]
430fn unbrotli(input: &[u8], limit: usize) -> Result<Vec<u8>> {
431    read_bounded(
432        brotli_decompressor::Decompressor::new(input, 4096),
433        limit,
434        "Brotli",
435    )
436}
437
438#[cfg(not(feature = "brotli"))]
439fn unbrotli(_: &[u8], _: usize) -> Result<Vec<u8>> {
440    Err(Error::UnsupportedFeature(
441        "Brotli decoding (enable the `brotli` feature)",
442    ))
443}
444
445/// Undo PNG predictors (filter types 0 to 4, one per row) over rows of `columns`
446/// 8-bit single-component samples, each row led by its filter byte.
447pub fn undo_png_predictor(mut data: Vec<u8>, columns: u32) -> Result<Vec<u8>> {
448    let columns = columns as usize;
449    if columns == 0 {
450        return Err(flate_error("PNG predictor rows have no columns"));
451    }
452    let stride = columns + 1;
453    if !data.chunks_exact(stride).remainder().is_empty() {
454        return Err(flate_error("incomplete PNG predictor row"));
455    }
456    let rows = data.len() / stride;
457    for row in 0..rows {
458        let source = row * stride;
459        let target = row * columns;
460        let filter = data[source];
461        if filter > 4 {
462            return Err(flate_error("invalid PNG predictor filter"));
463        }
464        data.copy_within(source + 1..source + stride, target);
465        for column in 0..columns {
466            let left = if column == 0 {
467                0
468            } else {
469                data[target + column - 1]
470            };
471            let above = if row == 0 {
472                0
473            } else {
474                data[target - columns + column]
475            };
476            let upper_left = if row == 0 || column == 0 {
477                0
478            } else {
479                data[target - columns + column - 1]
480            };
481            let prediction = match filter {
482                0 => 0,
483                1 => left,
484                2 => above,
485                3 => ((u16::from(left) + u16::from(above)) / 2) as u8,
486                4 => {
487                    let p = i32::from(left) + i32::from(above) - i32::from(upper_left);
488                    let distances = [
489                        (p - i32::from(left)).abs(),
490                        (p - i32::from(above)).abs(),
491                        (p - i32::from(upper_left)).abs(),
492                    ];
493                    if distances[0] <= distances[1] && distances[0] <= distances[2] {
494                        left
495                    } else if distances[1] <= distances[2] {
496                        above
497                    } else {
498                        upper_left
499                    }
500                }
501                _ => unreachable!("filter was checked above"),
502            };
503            data[target + column] = data[target + column].wrapping_add(prediction);
504        }
505    }
506    data.truncate(rows * columns);
507    Ok(data)
508}
509
510#[cfg(test)]
511mod tests {
512    use super::*;
513    use crate::testing::brotli_stored;
514
515    #[test]
516    fn base64_round_trips_every_length() {
517        for n in 0..40usize {
518            let data: Vec<u8> = (0..n as u8).map(|b| b.wrapping_mul(37)).collect();
519            assert_eq!(base64_decode(&base64_encode(&data)).unwrap(), data);
520            let t = TransferEncoding::Base64;
521            assert_eq!(
522                t.decode(t.encode(&data).unwrap().into_owned()).unwrap(),
523                data
524            );
525        }
526        assert_eq!(base64_encode(b"Man"), b"TWFu");
527        assert_eq!(base64_encode(b"Ma"), b"TWE=");
528        assert_eq!(base64_encode(b"M"), b"TQ==");
529    }
530
531    #[test]
532    fn base64_rejects_what_is_not_base64() {
533        for bad in [&b"TWE"[..], b"TW=u", b"T!Fu", b"TQ==TQ==", b"TQ="] {
534            assert!(
535                base64_decode(bad).is_err(),
536                "{:?}",
537                String::from_utf8_lossy(bad)
538            );
539        }
540        assert_eq!(base64_decode(b" TW\nFu ").unwrap(), b"Man");
541    }
542
543    #[test]
544    fn identity_is_unchanged_and_compressed_encodings_do_not_encode() {
545        let t = TransferEncoding::default();
546        assert_eq!(t, TransferEncoding::Identity);
547        assert_eq!(t.decode(b"abc".to_vec()).unwrap(), b"abc");
548        assert!(matches!(t.encode(b"abc").unwrap(), Cow::Borrowed(b"abc")));
549        for t in [
550            TransferEncoding::Zlib {
551                png_predictor_columns: None,
552            },
553            TransferEncoding::Deflate,
554            TransferEncoding::Gzip,
555            TransferEncoding::Brotli,
556            TransferEncoding::unknown("x-lzma").unwrap(),
557        ] {
558            assert!(matches!(
559                t.encode(b"abc"),
560                Err(Error::UnsupportedFeature(_))
561            ));
562        }
563    }
564
565    #[test]
566    fn names_and_unknown_labels() {
567        let names: Vec<_> = [
568            TransferEncoding::Identity,
569            TransferEncoding::Base64,
570            TransferEncoding::Zlib {
571                png_predictor_columns: Some(3),
572            },
573            TransferEncoding::Deflate,
574            TransferEncoding::Gzip,
575            TransferEncoding::Brotli,
576            TransferEncoding::unknown("x-lzma").unwrap(),
577        ]
578        .iter()
579        .map(|t| t.as_str())
580        .collect();
581        assert_eq!(
582            names,
583            ["identity", "base64", "zlib", "deflate", "gzip", "brotli", "unknown"]
584        );
585        let u = TransferEncoding::unknown("x-lzma").unwrap();
586        assert_eq!(u.unknown_name(), Some("x-lzma"));
587        assert_eq!(u.to_string(), "unknown (x-lzma)");
588        assert!(matches!(
589            u.decode(vec![1]),
590            Err(Error::UnsupportedFeature(_))
591        ));
592        assert!(TransferEncoding::unknown("").is_none());
593        assert!(TransferEncoding::unknown("a\u{1}b").is_none());
594        assert!(TransferEncoding::unknown(&"a".repeat(256)).is_none());
595        assert!(TransferEncoding::unknown(&"a".repeat(255)).is_some());
596    }
597
598    #[test]
599    fn zlib_headers_are_recognised() {
600        assert!(is_zlib(&[0x78, 0x9c]));
601        assert!(is_zlib(&[0x78, 0x01]));
602        assert!(!is_zlib(&[0x78, 0x9d]), "bad check bits");
603        assert!(!is_zlib(&[0x88, 0x1d]), "window too large");
604        assert!(!is_zlib(&[0x79, 0x9c]), "not deflate");
605        assert!(!is_zlib(&[0x78]));
606    }
607
608    #[cfg(feature = "brotli")]
609    #[test]
610    fn brotli_decodes_and_is_bounded() {
611        let data = b"<x:xmpmeta/>".repeat(10);
612        let stored = brotli_stored(&data);
613        assert_eq!(
614            TransferEncoding::Brotli.decode(stored.clone()).unwrap(),
615            data
616        );
617        assert!(unbrotli(&stored, data.len() - 1).is_err());
618        assert!(TransferEncoding::Brotli.decode(vec![0xff; 8]).is_err());
619    }
620
621    #[cfg(not(feature = "brotli"))]
622    #[test]
623    fn brotli_needs_the_feature() {
624        assert!(matches!(
625            TransferEncoding::Brotli.decode(brotli_stored(b"abc")),
626            Err(Error::UnsupportedFeature(m)) if m.contains("Brotli")
627        ));
628    }
629
630    #[test]
631    fn a_png_predictor_is_undone() {
632        // Two rows of three samples: "Sub" then "Up".
633        let encoded = vec![1, 10, 1, 1, 2, 5, 5, 5];
634        assert_eq!(
635            undo_png_predictor(encoded, 3).unwrap(),
636            [10, 11, 12, 15, 16, 17]
637        );
638        assert!(undo_png_predictor(vec![0; 5], 3).is_err(), "partial row");
639        assert!(
640            undo_png_predictor(vec![9, 0, 0, 0], 3).is_err(),
641            "bad filter"
642        );
643        assert!(undo_png_predictor(vec![0], 0).is_err(), "no columns");
644    }
645
646    #[cfg(not(feature = "flate"))]
647    #[test]
648    fn flate_needs_the_feature() {
649        for (t, name) in [
650            (
651                TransferEncoding::Zlib {
652                    png_predictor_columns: None,
653                },
654                "zlib",
655            ),
656            (TransferEncoding::Deflate, "deflate"),
657            (TransferEncoding::Gzip, "gzip"),
658        ] {
659            assert!(matches!(
660                t.decode(vec![0x78, 0x9c]),
661                Err(Error::UnsupportedFeature(m)) if m.contains(name)
662            ));
663        }
664    }
665
666    #[cfg(feature = "flate")]
667    mod flate {
668        use std::io::Write;
669
670        use flate2::{write::ZlibEncoder, Compression};
671
672        use super::*;
673
674        fn deflate(data: &[u8]) -> Vec<u8> {
675            let mut e = ZlibEncoder::new(Vec::new(), Compression::default());
676            e.write_all(data).unwrap();
677            e.finish().unwrap()
678        }
679
680        #[test]
681        fn inflates_and_enforces_the_limit_and_the_end() {
682            let data = vec![7u8; 10_000];
683            let z = deflate(&data);
684            assert_eq!(inflate(&z, 10_000, None).unwrap(), data);
685            assert!(inflate(&z, 9_999, None).is_err(), "over the limit");
686            let mut trailing = z.clone();
687            trailing.push(0);
688            assert!(inflate(&trailing, 10_000, None).is_err());
689            assert!(
690                inflate(&z[..z.len() - 2], 10_000, None).is_err(),
691                "cut short"
692            );
693            let mut bad = z.clone();
694            let last = bad.len() - 1;
695            bad[last] ^= 1;
696            assert!(inflate(&bad, 10_000, None).is_err(), "checksum");
697        }
698
699        #[test]
700        fn decodes_with_and_without_a_predictor() {
701            let plain = TransferEncoding::Zlib {
702                png_predictor_columns: None,
703            };
704            assert_eq!(plain.decode(deflate(b"hello")).unwrap(), b"hello");
705            let predicted = TransferEncoding::Zlib {
706                png_predictor_columns: Some(3),
707            };
708            let rows = deflate(&[1, 10, 1, 1, 2, 5, 5, 5]);
709            assert_eq!(predicted.decode(rows).unwrap(), [10, 11, 12, 15, 16, 17]);
710            assert!(plain.decode(b"not zlib".to_vec()).is_err());
711        }
712
713        #[test]
714        fn deflate_accepts_raw_and_zlib_wrapped_streams_and_gzip_decodes() {
715            use flate2::write::{DeflateEncoder, GzEncoder};
716            let data = b"<x:xmpmeta>compressed</x:xmpmeta>".repeat(20);
717            let mut raw = DeflateEncoder::new(Vec::new(), Compression::default());
718            raw.write_all(&data).unwrap();
719            let raw = raw.finish().unwrap();
720            assert!(!is_zlib(&raw));
721            for stored in [raw, deflate(&data)] {
722                assert_eq!(TransferEncoding::Deflate.decode(stored).unwrap(), data);
723            }
724            let mut gz = GzEncoder::new(Vec::new(), Compression::default());
725            gz.write_all(&data).unwrap();
726            let gz = gz.finish().unwrap();
727            assert_eq!(TransferEncoding::Gzip.decode(gz.clone()).unwrap(), data);
728            assert!(gunzip(&gz, data.len() - 1).is_err(), "over the limit");
729            assert!(TransferEncoding::Gzip.decode(b"not gzip".to_vec()).is_err());
730        }
731
732        #[test]
733        fn a_prefix_decodes_only_what_it_needs() {
734            let data: Vec<u8> = (0..20_000u32).map(|i| (i * 7 % 251) as u8).collect();
735            let z = deflate(&data);
736            let plain = TransferEncoding::Zlib {
737                png_predictor_columns: None,
738            };
739            // A cut-short stream still gives its head.
740            assert_eq!(
741                plain.decode_prefix(&z[..z.len() / 2], 32).unwrap(),
742                data[..32]
743            );
744            assert_eq!(
745                TransferEncoding::Deflate.decode_prefix(&z, 5).unwrap(),
746                data[..5]
747            );
748            let predicted = TransferEncoding::Zlib {
749                png_predictor_columns: Some(3),
750            };
751            let rows = deflate(&[1, 10, 1, 1, 2, 5, 5, 5]);
752            assert_eq!(predicted.decode_prefix(&rows, 4).unwrap(), [10, 11, 12, 15]);
753            assert_eq!(plain.decode_prefix(&deflate(b"ab"), 32).unwrap(), b"ab");
754            assert!(plain.decode_prefix(b"not zlib", 32).is_err());
755        }
756    }
757
758    #[test]
759    fn a_base64_prefix_decodes_only_its_head() {
760        let data: Vec<u8> = (0..100u8).collect();
761        let mut text = base64_encode(&data);
762        text.insert(10, b'\n');
763        let tail = text.len() - 3;
764        text[tail] = b'!'; // damage beyond the head is not read
765        assert_eq!(
766            TransferEncoding::Base64.decode_prefix(&text, 32).unwrap(),
767            data[..32]
768        );
769        assert_eq!(
770            TransferEncoding::Identity.decode_prefix(&data, 4).unwrap(),
771            data[..4]
772        );
773        assert!(TransferEncoding::Base64.decode_prefix(b"!!!!", 3).is_err());
774        assert!(matches!(
775            TransferEncoding::unknown("x-custom")
776                .unwrap()
777                .decode_prefix(b"abc", 3),
778            Err(Error::UnsupportedFeature(_))
779        ));
780    }
781}