]> git.lizzy.rs Git - rust.git/blob - src/libstd/io/buffered.rs
check: Reword the warning to be more prescriptive
[rust.git] / src / libstd / io / buffered.rs
1 // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10 //
11 // ignore-lexer-test FIXME #15883
12
13 //! Buffering wrappers for I/O traits
14
15 use prelude::v1::*;
16 use io::prelude::*;
17
18 use cmp;
19 use error::{self, FromError};
20 use fmt;
21 use io::{self, Cursor, DEFAULT_BUF_SIZE, Error, ErrorKind};
22 use ptr;
23
24 /// Wraps a `Read` and buffers input from it
25 ///
26 /// It can be excessively inefficient to work directly with a `Read` instance.
27 /// For example, every call to `read` on `TcpStream` results in a system call.
28 /// A `BufReader` performs large, infrequent reads on the underlying `Read`
29 /// and maintains an in-memory buffer of the results.
30 #[stable(feature = "rust1", since = "1.0.0")]
31 pub struct BufReader<R> {
32     inner: R,
33     buf: Cursor<Vec<u8>>,
34 }
35
36 impl<R: Read> BufReader<R> {
37     /// Creates a new `BufReader` with a default buffer capacity
38     #[stable(feature = "rust1", since = "1.0.0")]
39     pub fn new(inner: R) -> BufReader<R> {
40         BufReader::with_capacity(DEFAULT_BUF_SIZE, inner)
41     }
42
43     /// Creates a new `BufReader` with the specified buffer capacity
44     #[stable(feature = "rust1", since = "1.0.0")]
45     pub fn with_capacity(cap: usize, inner: R) -> BufReader<R> {
46         BufReader {
47             inner: inner,
48             buf: Cursor::new(Vec::with_capacity(cap)),
49         }
50     }
51
52     /// Gets a reference to the underlying reader.
53     #[stable(feature = "rust1", since = "1.0.0")]
54     pub fn get_ref(&self) -> &R { &self.inner }
55
56     /// Gets a mutable reference to the underlying reader.
57     ///
58     /// # Warning
59     ///
60     /// It is inadvisable to directly read from the underlying reader.
61     #[stable(feature = "rust1", since = "1.0.0")]
62     pub fn get_mut(&mut self) -> &mut R { &mut self.inner }
63
64     /// Unwraps this `BufReader`, returning the underlying reader.
65     ///
66     /// Note that any leftover data in the internal buffer is lost.
67     #[stable(feature = "rust1", since = "1.0.0")]
68     pub fn into_inner(self) -> R { self.inner }
69 }
70
71 #[stable(feature = "rust1", since = "1.0.0")]
72 impl<R: Read> Read for BufReader<R> {
73     fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
74         // If we don't have any buffered data and we're doing a massive read
75         // (larger than our internal buffer), bypass our internal buffer
76         // entirely.
77         if self.buf.get_ref().len() == self.buf.position() as usize &&
78             buf.len() >= self.buf.get_ref().capacity() {
79             return self.inner.read(buf);
80         }
81         try!(self.fill_buf());
82         self.buf.read(buf)
83     }
84 }
85
86 #[stable(feature = "rust1", since = "1.0.0")]
87 impl<R: Read> BufRead for BufReader<R> {
88     fn fill_buf(&mut self) -> io::Result<&[u8]> {
89         // If we've reached the end of our internal buffer then we need to fetch
90         // some more data from the underlying reader.
91         if self.buf.position() as usize == self.buf.get_ref().len() {
92             self.buf.set_position(0);
93             let v = self.buf.get_mut();
94             v.truncate(0);
95             let inner = &mut self.inner;
96             try!(super::with_end_to_cap(v, |b| inner.read(b)));
97         }
98         self.buf.fill_buf()
99     }
100
101     fn consume(&mut self, amt: uint) {
102         self.buf.consume(amt)
103     }
104 }
105
106 #[stable(feature = "rust1", since = "1.0.0")]
107 impl<R> fmt::Debug for BufReader<R> where R: fmt::Debug {
108     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
109         write!(fmt, "BufReader {{ reader: {:?}, buffer: {}/{} }}",
110                self.inner, self.buf.position(), self.buf.get_ref().len())
111     }
112 }
113
114 /// Wraps a Writer and buffers output to it
115 ///
116 /// It can be excessively inefficient to work directly with a `Write`. For
117 /// example, every call to `write` on `TcpStream` results in a system call. A
118 /// `BufWriter` keeps an in memory buffer of data and writes it to the
119 /// underlying `Write` in large, infrequent batches.
120 ///
121 /// The buffer will be written out when the writer is dropped.
122 #[stable(feature = "rust1", since = "1.0.0")]
123 pub struct BufWriter<W: Write> {
124     inner: Option<W>,
125     buf: Vec<u8>,
126 }
127
128 /// An error returned by `into_inner` which combines an error that
129 /// happened while writing out the buffer, and the buffered writer object
130 /// which may be used to recover from the condition.
131 #[derive(Debug)]
132 #[stable(feature = "rust1", since = "1.0.0")]
133 pub struct IntoInnerError<W>(W, Error);
134
135 impl<W: Write> BufWriter<W> {
136     /// Creates a new `BufWriter` with a default buffer capacity
137     #[stable(feature = "rust1", since = "1.0.0")]
138     pub fn new(inner: W) -> BufWriter<W> {
139         BufWriter::with_capacity(DEFAULT_BUF_SIZE, inner)
140     }
141
142     /// Creates a new `BufWriter` with the specified buffer capacity
143     #[stable(feature = "rust1", since = "1.0.0")]
144     pub fn with_capacity(cap: usize, inner: W) -> BufWriter<W> {
145         BufWriter {
146             inner: Some(inner),
147             buf: Vec::with_capacity(cap),
148         }
149     }
150
151     fn flush_buf(&mut self) -> io::Result<()> {
152         let mut written = 0;
153         let len = self.buf.len();
154         let mut ret = Ok(());
155         while written < len {
156             match self.inner.as_mut().unwrap().write(&self.buf[written..]) {
157                 Ok(0) => {
158                     ret = Err(Error::new(ErrorKind::WriteZero,
159                                          "failed to write the buffered data", None));
160                     break;
161                 }
162                 Ok(n) => written += n,
163                 Err(ref e) if e.kind() == io::ErrorKind::Interrupted => {}
164                 Err(e) => { ret = Err(e); break }
165
166             }
167         }
168         if written > 0 {
169             // NB: would be better expressed as .remove(0..n) if it existed
170             unsafe {
171                 ptr::copy(self.buf.as_mut_ptr(),
172                           self.buf.as_ptr().offset(written as isize),
173                           len - written);
174             }
175         }
176         self.buf.truncate(len - written);
177         ret
178     }
179
180     /// Gets a reference to the underlying writer.
181     #[stable(feature = "rust1", since = "1.0.0")]
182     pub fn get_ref(&self) -> &W { self.inner.as_ref().unwrap() }
183
184     /// Gets a mutable reference to the underlying write.
185     ///
186     /// # Warning
187     ///
188     /// It is inadvisable to directly read from the underlying writer.
189     #[stable(feature = "rust1", since = "1.0.0")]
190     pub fn get_mut(&mut self) -> &mut W { self.inner.as_mut().unwrap() }
191
192     /// Unwraps this `BufWriter`, returning the underlying writer.
193     ///
194     /// The buffer is written out before returning the writer.
195     #[stable(feature = "rust1", since = "1.0.0")]
196     pub fn into_inner(mut self) -> Result<W, IntoInnerError<BufWriter<W>>> {
197         match self.flush_buf() {
198             Err(e) => Err(IntoInnerError(self, e)),
199             Ok(()) => Ok(self.inner.take().unwrap())
200         }
201     }
202 }
203
204 #[stable(feature = "rust1", since = "1.0.0")]
205 impl<W: Write> Write for BufWriter<W> {
206     fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
207         if self.buf.len() + buf.len() > self.buf.capacity() {
208             try!(self.flush_buf());
209         }
210         if buf.len() >= self.buf.capacity() {
211             self.inner.as_mut().unwrap().write(buf)
212         } else {
213             let amt = cmp::min(buf.len(), self.buf.capacity());
214             Write::write(&mut self.buf, &buf[..amt])
215         }
216     }
217     fn flush(&mut self) -> io::Result<()> {
218         self.flush_buf().and_then(|()| self.get_mut().flush())
219     }
220 }
221
222 #[stable(feature = "rust1", since = "1.0.0")]
223 impl<W: Write> fmt::Debug for BufWriter<W> where W: fmt::Debug {
224     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
225         write!(fmt, "BufWriter {{ writer: {:?}, buffer: {}/{} }}",
226                self.inner.as_ref().unwrap(), self.buf.len(), self.buf.capacity())
227     }
228 }
229
230 #[unsafe_destructor]
231 impl<W: Write> Drop for BufWriter<W> {
232     fn drop(&mut self) {
233         if self.inner.is_some() {
234             // dtors should not panic, so we ignore a failed flush
235             let _r = self.flush_buf();
236         }
237     }
238 }
239
240 impl<W> IntoInnerError<W> {
241     /// Returns the error which caused the call to `into_inner` to fail.
242     ///
243     /// This error was returned when attempting to write the internal buffer.
244     #[stable(feature = "rust1", since = "1.0.0")]
245     pub fn error(&self) -> &Error { &self.1 }
246
247     /// Returns the buffered writer instance which generated the error.
248     ///
249     /// The returned object can be used for error recovery, such as
250     /// re-inspecting the buffer.
251     #[stable(feature = "rust1", since = "1.0.0")]
252     pub fn into_inner(self) -> W { self.0 }
253 }
254
255 #[stable(feature = "rust1", since = "1.0.0")]
256 impl<W> FromError<IntoInnerError<W>> for Error {
257     fn from_error(iie: IntoInnerError<W>) -> Error { iie.1 }
258 }
259
260 #[stable(feature = "rust1", since = "1.0.0")]
261 impl<W: Send + fmt::Debug> error::Error for IntoInnerError<W> {
262     fn description(&self) -> &str {
263         error::Error::description(self.error())
264     }
265 }
266
267 #[stable(feature = "rust1", since = "1.0.0")]
268 impl<W> fmt::Display for IntoInnerError<W> {
269     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
270         self.error().fmt(f)
271     }
272 }
273
274 /// Wraps a Writer and buffers output to it, flushing whenever a newline
275 /// (`0x0a`, `'\n'`) is detected.
276 ///
277 /// The buffer will be written out when the writer is dropped.
278 #[stable(feature = "rust1", since = "1.0.0")]
279 pub struct LineWriter<W: Write> {
280     inner: BufWriter<W>,
281 }
282
283 impl<W: Write> LineWriter<W> {
284     /// Creates a new `LineWriter`
285     #[stable(feature = "rust1", since = "1.0.0")]
286     pub fn new(inner: W) -> LineWriter<W> {
287         // Lines typically aren't that long, don't use a giant buffer
288         LineWriter::with_capacity(1024, inner)
289     }
290
291     /// Creates a new `LineWriter` with a specified capacity for the internal
292     /// buffer.
293     #[stable(feature = "rust1", since = "1.0.0")]
294     pub fn with_capacity(cap: usize, inner: W) -> LineWriter<W> {
295         LineWriter { inner: BufWriter::with_capacity(cap, inner) }
296     }
297
298     /// Gets a reference to the underlying writer.
299     #[stable(feature = "rust1", since = "1.0.0")]
300     pub fn get_ref(&self) -> &W { self.inner.get_ref() }
301
302     /// Gets a mutable reference to the underlying writer.
303     ///
304     /// Caution must be taken when calling methods on the mutable reference
305     /// returned as extra writes could corrupt the output stream.
306     #[stable(feature = "rust1", since = "1.0.0")]
307     pub fn get_mut(&mut self) -> &mut W { self.inner.get_mut() }
308
309     /// Unwraps this `LineWriter`, returning the underlying writer.
310     ///
311     /// The internal buffer is written out before returning the writer.
312     #[stable(feature = "rust1", since = "1.0.0")]
313     pub fn into_inner(self) -> Result<W, IntoInnerError<LineWriter<W>>> {
314         self.inner.into_inner().map_err(|IntoInnerError(buf, e)| {
315             IntoInnerError(LineWriter { inner: buf }, e)
316         })
317     }
318 }
319
320 #[stable(feature = "rust1", since = "1.0.0")]
321 impl<W: Write> Write for LineWriter<W> {
322     fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
323         match buf.rposition_elem(&b'\n') {
324             Some(i) => {
325                 let n = try!(self.inner.write(&buf[..i + 1]));
326                 if n != i + 1 { return Ok(n) }
327                 try!(self.inner.flush());
328                 self.inner.write(&buf[i + 1..]).map(|i| n + i)
329             }
330             None => self.inner.write(buf),
331         }
332     }
333
334     fn flush(&mut self) -> io::Result<()> { self.inner.flush() }
335 }
336
337 #[stable(feature = "rust1", since = "1.0.0")]
338 impl<W: Write> fmt::Debug for LineWriter<W> where W: fmt::Debug {
339     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
340         write!(fmt, "LineWriter {{ writer: {:?}, buffer: {}/{} }}",
341                self.inner.inner, self.inner.buf.len(),
342                self.inner.buf.capacity())
343     }
344 }
345
346 struct InternalBufWriter<W: Write>(BufWriter<W>);
347
348 impl<W: Read + Write> InternalBufWriter<W> {
349     fn get_mut(&mut self) -> &mut BufWriter<W> {
350         let InternalBufWriter(ref mut w) = *self;
351         return w;
352     }
353 }
354
355 impl<W: Read + Write> Read for InternalBufWriter<W> {
356     fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
357         self.get_mut().inner.as_mut().unwrap().read(buf)
358     }
359 }
360
361 /// Wraps a Stream and buffers input and output to and from it.
362 ///
363 /// It can be excessively inefficient to work directly with a `Read+Write`. For
364 /// example, every call to `read` or `write` on `TcpStream` results in a system
365 /// call. A `BufStream` keeps in memory buffers of data, making large,
366 /// infrequent calls to `read` and `write` on the underlying `Read+Write`.
367 ///
368 /// The output buffer will be written out when this stream is dropped.
369 #[stable(feature = "rust1", since = "1.0.0")]
370 pub struct BufStream<S: Write> {
371     inner: BufReader<InternalBufWriter<S>>
372 }
373
374 impl<S: Read + Write> BufStream<S> {
375     /// Creates a new buffered stream with explicitly listed capacities for the
376     /// reader/writer buffer.
377     #[stable(feature = "rust1", since = "1.0.0")]
378     pub fn with_capacities(reader_cap: usize, writer_cap: usize, inner: S)
379                            -> BufStream<S> {
380         let writer = BufWriter::with_capacity(writer_cap, inner);
381         let internal_writer = InternalBufWriter(writer);
382         let reader = BufReader::with_capacity(reader_cap, internal_writer);
383         BufStream { inner: reader }
384     }
385
386     /// Creates a new buffered stream with the default reader/writer buffer
387     /// capacities.
388     #[stable(feature = "rust1", since = "1.0.0")]
389     pub fn new(inner: S) -> BufStream<S> {
390         BufStream::with_capacities(DEFAULT_BUF_SIZE, DEFAULT_BUF_SIZE, inner)
391     }
392
393     /// Gets a reference to the underlying stream.
394     #[stable(feature = "rust1", since = "1.0.0")]
395     pub fn get_ref(&self) -> &S {
396         let InternalBufWriter(ref w) = self.inner.inner;
397         w.get_ref()
398     }
399
400     /// Gets a mutable reference to the underlying stream.
401     ///
402     /// # Warning
403     ///
404     /// It is inadvisable to read directly from or write directly to the
405     /// underlying stream.
406     #[stable(feature = "rust1", since = "1.0.0")]
407     pub fn get_mut(&mut self) -> &mut S {
408         let InternalBufWriter(ref mut w) = self.inner.inner;
409         w.get_mut()
410     }
411
412     /// Unwraps this `BufStream`, returning the underlying stream.
413     ///
414     /// The internal write buffer is written out before returning the stream.
415     /// Any leftover data in the read buffer is lost.
416     #[stable(feature = "rust1", since = "1.0.0")]
417     pub fn into_inner(self) -> Result<S, IntoInnerError<BufStream<S>>> {
418         let BufReader { inner: InternalBufWriter(w), buf } = self.inner;
419         w.into_inner().map_err(|IntoInnerError(w, e)| {
420             IntoInnerError(BufStream {
421                 inner: BufReader { inner: InternalBufWriter(w), buf: buf },
422             }, e)
423         })
424     }
425 }
426
427 #[stable(feature = "rust1", since = "1.0.0")]
428 impl<S: Read + Write> BufRead for BufStream<S> {
429     fn fill_buf(&mut self) -> io::Result<&[u8]> { self.inner.fill_buf() }
430     fn consume(&mut self, amt: uint) { self.inner.consume(amt) }
431 }
432
433 #[stable(feature = "rust1", since = "1.0.0")]
434 impl<S: Read + Write> Read for BufStream<S> {
435     fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
436         self.inner.read(buf)
437     }
438 }
439
440 #[stable(feature = "rust1", since = "1.0.0")]
441 impl<S: Read + Write> Write for BufStream<S> {
442     fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
443         self.inner.inner.get_mut().write(buf)
444     }
445     fn flush(&mut self) -> io::Result<()> {
446         self.inner.inner.get_mut().flush()
447     }
448 }
449
450 #[stable(feature = "rust1", since = "1.0.0")]
451 impl<S: Write> fmt::Debug for BufStream<S> where S: fmt::Debug {
452     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
453         let reader = &self.inner;
454         let writer = &self.inner.inner.0;
455         write!(fmt, "BufStream {{ stream: {:?}, write_buffer: {}/{}, read_buffer: {}/{} }}",
456                writer.inner,
457                writer.buf.len(), writer.buf.capacity(),
458                reader.buf.position(), reader.buf.get_ref().len())
459     }
460 }
461
462 #[cfg(test)]
463 mod tests {
464     use prelude::v1::*;
465     use io::prelude::*;
466     use io::{self, BufReader, BufWriter, BufStream, Cursor, LineWriter};
467     use test;
468
469     /// A dummy reader intended at testing short-reads propagation.
470     pub struct ShortReader {
471         lengths: Vec<usize>,
472     }
473
474     impl Read for ShortReader {
475         fn read(&mut self, _: &mut [u8]) -> io::Result<usize> {
476             if self.lengths.is_empty() {
477                 Ok(0)
478             } else {
479                 Ok(self.lengths.remove(0))
480             }
481         }
482     }
483
484     #[test]
485     fn test_buffered_reader() {
486         let inner: &[u8] = &[5, 6, 7, 0, 1, 2, 3, 4];
487         let mut reader = BufReader::with_capacity(2, inner);
488
489         let mut buf = [0, 0, 0];
490         let nread = reader.read(&mut buf);
491         assert_eq!(Ok(3), nread);
492         let b: &[_] = &[5, 6, 7];
493         assert_eq!(buf, b);
494
495         let mut buf = [0, 0];
496         let nread = reader.read(&mut buf);
497         assert_eq!(Ok(2), nread);
498         let b: &[_] = &[0, 1];
499         assert_eq!(buf, b);
500
501         let mut buf = [0];
502         let nread = reader.read(&mut buf);
503         assert_eq!(Ok(1), nread);
504         let b: &[_] = &[2];
505         assert_eq!(buf, b);
506
507         let mut buf = [0, 0, 0];
508         let nread = reader.read(&mut buf);
509         assert_eq!(Ok(1), nread);
510         let b: &[_] = &[3, 0, 0];
511         assert_eq!(buf, b);
512
513         let nread = reader.read(&mut buf);
514         assert_eq!(Ok(1), nread);
515         let b: &[_] = &[4, 0, 0];
516         assert_eq!(buf, b);
517
518         assert_eq!(reader.read(&mut buf), Ok(0));
519     }
520
521     #[test]
522     fn test_buffered_writer() {
523         let inner = Vec::new();
524         let mut writer = BufWriter::with_capacity(2, inner);
525
526         writer.write(&[0, 1]).unwrap();
527         assert_eq!(*writer.get_ref(), [0, 1]);
528
529         writer.write(&[2]).unwrap();
530         assert_eq!(*writer.get_ref(), [0, 1]);
531
532         writer.write(&[3]).unwrap();
533         assert_eq!(*writer.get_ref(), [0, 1]);
534
535         writer.flush().unwrap();
536         assert_eq!(*writer.get_ref(), [0, 1, 2, 3]);
537
538         writer.write(&[4]).unwrap();
539         writer.write(&[5]).unwrap();
540         assert_eq!(*writer.get_ref(), [0, 1, 2, 3]);
541
542         writer.write(&[6]).unwrap();
543         assert_eq!(*writer.get_ref(), [0, 1, 2, 3, 4, 5]);
544
545         writer.write(&[7, 8]).unwrap();
546         assert_eq!(*writer.get_ref(), [0, 1, 2, 3, 4, 5, 6, 7, 8]);
547
548         writer.write(&[9, 10, 11]).unwrap();
549         assert_eq!(*writer.get_ref(), [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]);
550
551         writer.flush().unwrap();
552         assert_eq!(*writer.get_ref(), [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]);
553     }
554
555     #[test]
556     fn test_buffered_writer_inner_flushes() {
557         let mut w = BufWriter::with_capacity(3, Vec::new());
558         w.write(&[0, 1]).unwrap();
559         assert_eq!(*w.get_ref(), []);
560         let w = w.into_inner().unwrap();
561         assert_eq!(w, [0, 1]);
562     }
563
564     // This is just here to make sure that we don't infinite loop in the
565     // newtype struct autoderef weirdness
566     #[test]
567     fn test_buffered_stream() {
568         struct S;
569
570         impl Write for S {
571             fn write(&mut self, b: &[u8]) -> io::Result<usize> { Ok(b.len()) }
572             fn flush(&mut self) -> io::Result<()> { Ok(()) }
573         }
574
575         impl Read for S {
576             fn read(&mut self, _: &mut [u8]) -> io::Result<usize> { Ok(0) }
577         }
578
579         let mut stream = BufStream::new(S);
580         assert_eq!(stream.read(&mut [0; 10]), Ok(0));
581         stream.write(&[0; 10]).unwrap();
582         stream.flush().unwrap();
583     }
584
585     #[test]
586     fn test_read_until() {
587         let inner: &[u8] = &[0, 1, 2, 1, 0];
588         let mut reader = BufReader::with_capacity(2, inner);
589         let mut v = Vec::new();
590         reader.read_until(0, &mut v).unwrap();
591         assert_eq!(v, [0]);
592         v.truncate(0);
593         reader.read_until(2, &mut v).unwrap();
594         assert_eq!(v, [1, 2]);
595         v.truncate(0);
596         reader.read_until(1, &mut v).unwrap();
597         assert_eq!(v, [1]);
598         v.truncate(0);
599         reader.read_until(8, &mut v).unwrap();
600         assert_eq!(v, [0]);
601         v.truncate(0);
602         reader.read_until(9, &mut v).unwrap();
603         assert_eq!(v, []);
604     }
605
606     #[test]
607     fn test_line_buffer() {
608         let mut writer = LineWriter::new(Vec::new());
609         writer.write(&[0]).unwrap();
610         assert_eq!(*writer.get_ref(), []);
611         writer.write(&[1]).unwrap();
612         assert_eq!(*writer.get_ref(), []);
613         writer.flush().unwrap();
614         assert_eq!(*writer.get_ref(), [0, 1]);
615         writer.write(&[0, b'\n', 1, b'\n', 2]).unwrap();
616         assert_eq!(*writer.get_ref(), [0, 1, 0, b'\n', 1, b'\n']);
617         writer.flush().unwrap();
618         assert_eq!(*writer.get_ref(), [0, 1, 0, b'\n', 1, b'\n', 2]);
619         writer.write(&[3, b'\n']).unwrap();
620         assert_eq!(*writer.get_ref(), [0, 1, 0, b'\n', 1, b'\n', 2, 3, b'\n']);
621     }
622
623     #[test]
624     fn test_read_line() {
625         let in_buf: &[u8] = b"a\nb\nc";
626         let mut reader = BufReader::with_capacity(2, in_buf);
627         let mut s = String::new();
628         reader.read_line(&mut s).unwrap();
629         assert_eq!(s, "a\n");
630         s.truncate(0);
631         reader.read_line(&mut s).unwrap();
632         assert_eq!(s, "b\n");
633         s.truncate(0);
634         reader.read_line(&mut s).unwrap();
635         assert_eq!(s, "c");
636         s.truncate(0);
637         reader.read_line(&mut s).unwrap();
638         assert_eq!(s, "");
639     }
640
641     #[test]
642     fn test_lines() {
643         let in_buf: &[u8] = b"a\nb\nc";
644         let reader = BufReader::with_capacity(2, in_buf);
645         let mut it = reader.lines();
646         assert_eq!(it.next(), Some(Ok("a".to_string())));
647         assert_eq!(it.next(), Some(Ok("b".to_string())));
648         assert_eq!(it.next(), Some(Ok("c".to_string())));
649         assert_eq!(it.next(), None);
650     }
651
652     #[test]
653     fn test_short_reads() {
654         let inner = ShortReader{lengths: vec![0, 1, 2, 0, 1, 0]};
655         let mut reader = BufReader::new(inner);
656         let mut buf = [0, 0];
657         assert_eq!(reader.read(&mut buf), Ok(0));
658         assert_eq!(reader.read(&mut buf), Ok(1));
659         assert_eq!(reader.read(&mut buf), Ok(2));
660         assert_eq!(reader.read(&mut buf), Ok(0));
661         assert_eq!(reader.read(&mut buf), Ok(1));
662         assert_eq!(reader.read(&mut buf), Ok(0));
663         assert_eq!(reader.read(&mut buf), Ok(0));
664     }
665
666     #[test]
667     fn read_char_buffered() {
668         let buf = [195, 159];
669         let reader = BufReader::with_capacity(1, &buf[..]);
670         assert_eq!(reader.chars().next(), Some(Ok('ß')));
671     }
672
673     #[test]
674     fn test_chars() {
675         let buf = [195, 159, b'a'];
676         let reader = BufReader::with_capacity(1, &buf[..]);
677         let mut it = reader.chars();
678         assert_eq!(it.next(), Some(Ok('ß')));
679         assert_eq!(it.next(), Some(Ok('a')));
680         assert_eq!(it.next(), None);
681     }
682
683     #[test]
684     #[should_fail]
685     fn dont_panic_in_drop_on_panicked_flush() {
686         struct FailFlushWriter;
687
688         impl Write for FailFlushWriter {
689             fn write(&mut self, buf: &[u8]) -> io::Result<usize> { Ok(buf.len()) }
690             fn flush(&mut self) -> io::Result<()> {
691                 Err(io::Error::last_os_error())
692             }
693         }
694
695         let writer = FailFlushWriter;
696         let _writer = BufWriter::new(writer);
697
698         // If writer panics *again* due to the flush error then the process will
699         // abort.
700         panic!();
701     }
702
703     #[bench]
704     fn bench_buffered_reader(b: &mut test::Bencher) {
705         b.iter(|| {
706             BufReader::new(io::empty())
707         });
708     }
709
710     #[bench]
711     fn bench_buffered_writer(b: &mut test::Bencher) {
712         b.iter(|| {
713             BufWriter::new(io::sink())
714         });
715     }
716
717     #[bench]
718     fn bench_buffered_stream(b: &mut test::Bencher) {
719         let mut buf = Cursor::new(Vec::new());
720         b.iter(|| {
721             BufStream::new(&mut buf);
722         });
723     }
724 }