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
use crate::format::*;
use nom::{bytes::streaming::take, combinator::map};
use pretty_hex::PrettyHex;
use std::fmt;

/// A raw zip string, with no specific encoding.
///
/// This is used while parsing a zip archive's central directory,
/// before we know what encoding is used.
#[derive(Clone)]
pub struct ZipString(pub Vec<u8>);

impl<'a> From<&'a [u8]> for ZipString {
    fn from(slice: &'a [u8]) -> Self {
        Self(slice.into())
    }
}

impl fmt::Debug for ZipString {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match std::str::from_utf8(&self.0) {
            Ok(s) => write!(f, "{:?}", s),
            Err(_) => write!(f, "[non-utf8 string: {}]", self.0.hex_dump()),
        }
    }
}

impl ZipString {
    pub(crate) fn parser<'a, C>(count: C) -> impl FnMut(&'a [u8]) -> parse::Result<'a, Self>
    where
        C: nom::ToUsize,
    {
        map(take(count.to_usize()), |slice: &'a [u8]| {
            ZipString(slice.into())
        })
    }

    pub(crate) fn into_option(self) -> Option<ZipString> {
        if !self.0.is_empty() {
            Some(self)
        } else {
            None
        }
    }
}

/// A raw u8 slice, with no specific structure.
///
/// This is used while parsing a zip archive, when we want
/// to retain an owned slice to be parsed later.
#[derive(Clone)]
pub struct ZipBytes(pub Vec<u8>);

impl fmt::Debug for ZipBytes {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        const MAX_SHOWN_SIZE: usize = 10;
        let data = &self.0[..];
        let (slice, extra) = if data.len() > MAX_SHOWN_SIZE {
            (&self.0[..MAX_SHOWN_SIZE], Some(data.len() - MAX_SHOWN_SIZE))
        } else {
            (&self.0[..], None)
        };
        write!(f, "{}", slice.hex_dump())?;
        if let Some(extra) = extra {
            write!(f, " (+ {} bytes)", extra)?;
        }
        Ok(())
    }
}

impl ZipBytes {
    pub(crate) fn parser<'a, C>(count: C) -> impl FnMut(&'a [u8]) -> parse::Result<'a, Self>
    where
        C: nom::ToUsize,
    {
        map(take(count.to_usize()), |slice: &'a [u8]| {
            ZipBytes(slice.into())
        })
    }
}