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
//! Data structures used to read the prelude of a compressed file,
//! i.e. the definitions of additional dictionaries.

use entropy::rw::*;
use entropy::util::*;
use util::PosRead;
use TokenReaderError;

use bytes::varnum::ReadVarNum;

use std::io::Read;

/// A name read from the prelude.
///
/// It may be either a section name or a stream name.
#[derive(Debug)]
pub enum Name<T> {
    /// The name of a stream.
    Stream(T),

    /// The name of a section.
    Section(T),

    /// No name has been read yet.
    Nothing,
}

/// Decode a section of compressed streams into
/// sequences of names and bytes.
///
/// We expect the following binary structure:
/// ```md
/// - `[[section1]]`
/// - `[stream1]`
/// - compression_format (at the time of this writing, only `brotli;` is accepted)
/// - stream_length (varnum)
/// - stream_content ([u8; stream_length])
/// - `[stream2]`
/// - ...
/// - `[[section2]]`
/// ```
///
/// This decoder accept an input immediately **after** `[[section1]]` (i.e. the bytes `b"[[section1]]"`
/// must already have been consumed) and stops parsing immediately **after** `[[section2]]` (i.e.
/// it consumes the bytes `b"[[section2]]"`).
pub struct SectionDecoder<T>
where
    T: Read,
{
    /// The latest name read.
    ///
    /// This may be the name of a section or a stream.
    name: Name<NameData>,

    /// The input from which data will be read.
    input: T,

    /// The next pending char.
    next_char: [u8; 1],
}
impl<T> SectionDecoder<T>
where
    T: Read,
{
    /// Create a new SectionDecoder to parse a given input.
    pub fn new(input: T) -> Self {
        Self {
            name: Name::Nothing,
            input,
            next_char: [b'?'], // Arbitrary char.
        }
    }

    /// The latest name read. This is either the name of a stream
    /// or the name of the next section.
    ///
    /// This method returns
    ///
    /// - `Name::Nothing` if we have not encountered a name yet;
    /// - `Name::Stream(&'foobar')` if the latest name we have encountered is `[foobar]`
    ///    (single-brackets indicate a stream name)
    /// - `Name::Section(&'snafu')` if the latest name we have encountered is `[[snafu]]`
    ///    (double-brackets indicate a section name).
    pub fn name(&self) -> Name<&[u8]> {
        match self.name {
            Name::Nothing => Name::Nothing,
            Name::Stream(ref s) => Name::Stream(s.as_slice()),
            Name::Section(ref s) => Name::Section(s.as_slice()),
        }
    }

    /// Finalize this SectionReader and recover the input.
    pub fn into_input(self) -> T {
        self.input
    }

    /// Continue reading a name.
    ///
    /// This method is designed to be called from `read_stream`, after `read_stream`
    /// has read the `[` that precedes the name.
    fn read_name(&mut self) -> Result<NameData, TokenReaderError> {
        if self.next_char[0] == b'[' {
            self.input
                .read_exact(&mut self.next_char)
                .map_err(TokenReaderError::ReadError)?;
        }
        let mut name = NameData::new();
        while self.next_char[0] != b']' && name.len() < NAME_MAX_LEN {
            name.push(self.next_char[0]);
            self.input
                .read_exact(&mut self.next_char)
                .map_err(TokenReaderError::ReadError)?;
        }
        Ok(name)
    }

    /// Read the next stream.
    ///
    /// A stream starts with a name `[foo_bar]`, followed by a number of compressed
    /// bytes, followed by the actual bytes. In case of success, this returns the
    /// buffer containing the decompressed bytes. To access the name of the stream,
    /// use `self.name()`.
    fn read_stream(&mut self) -> Result<Option<Vec<u8>>, TokenReaderError> {
        debug!(target: "read", "SectionDecoder::read_stream");
        self.input
            .expect(b"[")
            .map_err(|e| TokenReaderError::ReadError(e))?;

        self.input
            .read_exact(&mut self.next_char)
            .map_err(TokenReaderError::ReadError)?;

        if self.next_char[0] == b'[' {
            debug!(target: "read", "SectionDecoder::read_stream it's a [[");
            // `[[` means that we have ended the current section. Fetch the next name, but we're done.
            let section_name = self.read_name()?;
            debug!(target: "read", "SectionDecoder::read_stream the next section is {:?}",
                std::str::from_utf8(&section_name));
            self.name = Name::Section(section_name);
            self.input
                .expect(b"]")
                .map_err(TokenReaderError::ReadError)?;
            return Ok(None);
        } else {
            // Find the name of the current stream.
            self.name = Name::Stream(self.read_name()?);
        }

        debug!(target: "read", "SectionDecoder::read_stream reading compression format");
        // Read the compression format.
        self.input
            .expect(FORMAT_BROTLI) // FIXME: Extend to other formats.
            .map_err(TokenReaderError::ReadError)?;

        debug!(target: "read", "SectionDecoder::read_stream reading byte length");
        // Read the byte length.
        let byte_len = self
            .input
            .read_varnum()
            .map_err(TokenReaderError::ReadError)? as usize;

        debug!(target: "read", "SectionDecoder::read_stream preparing to decompress {} bytes", byte_len);

        // Decompress slice.
        let mut result = Vec::new();
        let mut slice = PosRead::new(self.input.by_ref().take(byte_len as u64));
        brotli::BrotliDecompress(&mut slice, &mut result).map_err(TokenReaderError::ReadError)?;

        // Ensure that all bytes have been read.
        if slice.pos() != byte_len {
            return Err(TokenReaderError::BadLength {
                expected: byte_len,
                got: slice.pos(),
            });
        }

        debug!(target: "read", "SectionDecoder::read_stream I have decompressed {} bytes into {} bytes",
            byte_len,
            result.len());
        Ok(Some(result))
    }
}

impl<'a, T> Iterator for &'a mut SectionDecoder<T>
where
    T: Read,
{
    type Item = Result<(NameData, Vec<u8>), TokenReaderError>;
    /// Read the next stream.
    ///
    /// If there is no stream left in this section, this returns `None`.
    /// In such a case, use `name()` to get the name of the next
    /// section.
    fn next(&mut self) -> Option<Self::Item> {
        match self.read_stream() {
            Ok(Some(buf)) => match self.name {
                Name::Stream(ref stream) => Some(Ok((stream.clone(), buf))),
                ref other => panic!("SectionDecoder: Unexpected state: {:?}", other),
            },
            Ok(None) => None,
            Err(err) => Some(Err(err)),
        }
    }
}