summaryrefslogtreecommitdiffstats
path: root/src/buffered_reader/buffered_reader.rs
blob: ebcb4dc952a4abeeb65665a184721323a56cf1a0 (plain)
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
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
use std;
use std::str;
use std::io;
use std::io::{Error,ErrorKind};
use std::cmp;
use std::fmt;

mod generic;
mod memory;
mod limitor;
mod partial_body;
mod decompress;

pub use self::generic::BufferedReaderGeneric;
pub use self::memory::BufferedReaderMemory;
pub use self::limitor::BufferedReaderLimitor;
pub use self::partial_body::BufferedReaderPartialBodyFilter;
pub use self::decompress::BufferedReaderDeflate;
pub use self::decompress::BufferedReaderZlib;
pub use self::decompress::BufferedReaderBzip;

// The default buffer size.
const DEFAULT_BUF_SIZE: usize = 8 * 1024;

/// A `BufferedReader` is a type of `Read`er that has an internal
/// buffer, and allows working directly from that buffer.  Like a
/// `BufRead`er, the internal buffer amortizes system calls.  And,
/// like a `BufRead`, a `BufferedReader` exposes the internal buffer
/// so that a user can work with the data in place rather than having
/// to first copy it to a local buffer.  However, unlike `BufRead`,
/// `BufferedReader` allows the caller to ensure that the internal
/// buffer has a certain amount of data.
pub trait BufferedReader : io::Read + fmt::Debug {
    /// Return the data in the internal buffer.  Normally, the
    /// returned buffer will contain *at least* `amount` bytes worth
    /// of data.  Less data may be returned if the end of the file is
    /// reached or an error occurs.  In these cases, any remaining
    /// data is returned.  Note: the error is not discarded, but will
    /// be returned when data is called and the internal buffer is
    /// empty.
    ///
    /// This function does not advance the cursor.  Thus, multiple
    /// calls will return the same data.  To advance the cursor, use
    /// `consume`.
    fn data(&mut self, amount: usize) -> Result<&[u8], io::Error>;

    /// Like `data`, but returns an error if there is not at least
    /// `amount` bytes available.
    fn data_hard(&mut self, amount: usize) -> Result<&[u8], io::Error> {
        let result = self.data(amount);
        if let Ok(buffer) = result {
            if buffer.len() < amount {
                return Err(Error::new(ErrorKind::UnexpectedEof, "unepxected EOF"));
            }
        }
        return result;
    }

    /// Return all of the data until EOF.  Like `data`, this does not
    /// actually consume the data that is read.
    ///
    /// In general, you shouldn't use this function as it can cause an
    /// enormous amount of buffering.  But, if you know that the
    /// amount of data is limited, this is acceptable.
    fn data_eof(&mut self) -> Result<&[u8], io::Error> {
        // Don't just read std::usize::MAX bytes at once.  The
        // implementation might try to actually allocate a buffer that
        // large!  Instead, try with increasingly larger buffers until
        // the read is (strictly) shorter than the specified size.
        let mut s = DEFAULT_BUF_SIZE;
        while s < std::usize::MAX {
            match self.data(s) {
                Ok(ref buffer) =>
                    if buffer.len() < s {
                        // We really want to do
                        //
                        //   return Ok(buffer);
                        //
                        // But, the borrower checker won't let us:
                        //
                        //  error[E0499]: cannot borrow `*self` as
                        //  mutable more than once at a time.
                        //
                        // Instead, we break out of the loop, and then
                        // call self.data(s) again.  This extra call
                        // shouldn't have any significant cost,
                        // because the buffer should already be
                        // prepared.
                        break;
                    } else {
                        s *= 2;
                    },
                Err(err) =>
                    return Err(err),
            }
        }
        return self.data(s);
    }

    /// Mark the first `amount` bytes of the internal buffer as
    /// consumed.  It is an error to call this function without having
    /// first successfully called `data` (or a related function) to
    /// buffer `amount` bytes.
    ///
    /// This function returns the data that has been consumed.
    fn consume(&mut self, amount: usize) -> &[u8];

    /// This is a convenient function that effectively combines data()
    /// and consume().
    fn data_consume(&mut self, amount: usize)
                    -> Result<&[u8], std::io::Error>;


    // This is a convenient function that effectively combines
    // data_hard() and consume().
    fn data_consume_hard(&mut self, amount: usize) -> Result<&[u8], io::Error>;

    /// A convenience function for reading a 16-bit unsigned integer
    /// in big endian format.
    fn read_be_u16(&mut self) -> Result<u16, std::io::Error> {
        let input = self.data_consume_hard(2)?;
        return Ok(((input[0] as u16) << 8) + (input[1] as u16));
    }

    /// A convenience function for reading a 32-bit unsigned integer
    /// in big endian format.
    fn read_be_u32(&mut self) -> Result<u32, std::io::Error> {
        let input = self.data_consume_hard(4)?;
        return Ok(((input[0] as u32) << 24) + ((input[1] as u32) << 16)
                  + ((input[2] as u32) << 8) + (input[3] as u32));
    }

    /// Reads and consumes `amount` bytes, and returns them in a
    /// caller owned buffer.  Implementations may optimize this to
    /// avoid a copy.
    fn steal(&mut self, amount: usize) -> Result<Vec<u8>, std::io::Error> {
        let mut data = self.data_consume_hard(amount)?;
        assert!(data.len() >= amount);
        if data.len() > amount {
            data = &data[..amount];
        }
        return Ok(data.to_vec());
    }

    /// Like steal, but instead of stealing a fixed number of bytes,
    /// it steals all of the data it can.
    fn steal_eof(&mut self) -> Result<Vec<u8>, std::io::Error> {
        let len = self.data_eof()?.len();
        let data = self.steal(len)?;
        return Ok(data);
    }

    fn into_inner<'a>(self: Box<Self>) -> Option<Box<BufferedReader + 'a>>
        where Self: 'a;
}

/// This function implements the `std::io::Read::read` method in terms
/// of the `data_consume` method.  We can't use the `io::std::Read`
/// interface, because the `BufferedReader` may have buffered some
/// data internally (in which case a read will not return the buffered
/// data, but the following data).  This implementation is generic.
/// When deriving a `BufferedReader`, you can include the following:
///
/// ```text
/// impl<'a, T: BufferedReader> std::io::Read for BufferedReaderXXX<'a, T> {
///     fn read(&mut self, buf: &mut [u8]) -> Result<usize, std::io::Error> {
///         return buffered_reader_generic_read_impl(self, buf);
///     }
/// }
/// ```
///
/// It would be nice if we could do:
///
/// ```text
/// impl <T: BufferedReader> std::io::Read for T { ... }
/// ```
///
/// but, alas, Rust doesn't like that ("error[E0119]: conflicting
/// implementations of trait `std::io::Read` for type `&mut _`").
fn buffered_reader_generic_read_impl<T: BufferedReader>
    (bio: &mut T, buf: &mut [u8]) -> Result<usize, io::Error> {
    match bio.data_consume(buf.len()) {
        Ok(inner) => {
            let amount = cmp::min(buf.len(), inner.len());
            buf[0..amount].copy_from_slice(&inner[0