Skip to main content

alpm_mtree/
utils.rs

1//! File handling integration.
2
3use std::io::Read;
4
5use flate2::read::GzDecoder;
6
7use crate::Error;
8
9/// Two magic bytes that occur at the beginning of gzip files and can be used to detect whether a
10/// file is gzip compressed.
11/// Spec: <https://datatracker.ietf.org/doc/html/rfc1952#page-6>
12pub const GZIP_MAGIC_NUMBER: [u8; 2] = [0x1f, 0x8b];
13
14/// Checks whether the contents of a byte `buffer` is considered to be gzip compressed.
15///
16/// Detects whether `buffer` contains gzip compressed data by checking if it is longer than two
17/// bytes and whether the first two bytes are the [`GZIP_MAGIC_NUMBER`].
18pub fn data_is_gzip(buffer: &[u8]) -> bool {
19    if let (Some(first), Some(second)) = (buffer.first().cloned(), buffer.get(1).cloned())
20        && [first, second] == GZIP_MAGIC_NUMBER
21    {
22        true
23    } else {
24        false
25    }
26}
27
28/// Creates a [`String`] from a byte vector which may be gzip compressed.
29///
30/// If `buffer` contains gzip compressed data, it decompressed before converting it into a
31/// `String`.
32///
33/// # Errors
34///
35/// Returns an error if
36/// - `buffer` contains invalid gzip compressed data
37/// - or `buffer` can not be converted to `String`.
38pub fn mtree_buffer_to_string(buffer: Vec<u8>) -> Result<String, Error> {
39    if data_is_gzip(buffer.as_slice()) {
40        let mut decoder = GzDecoder::new(buffer.as_slice());
41
42        let mut content = String::new();
43        decoder
44            .read_to_string(&mut content)
45            .map_err(Error::InvalidGzip)?;
46        Ok(content)
47    } else {
48        Ok(String::from_utf8(buffer)?)
49    }
50}