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.
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.
11 //! Utility implementations of Reader and Writer
16 use slice::bytes::MutableByteVector;
18 /// Wraps a `Reader`, limiting the number of bytes that can be read from it.
20 pub struct LimitReader<R> {
25 impl<R: Reader> LimitReader<R> {
26 /// Creates a new `LimitReader`
27 pub fn new(r: R, limit: uint) -> LimitReader<R> {
28 LimitReader { limit: limit, inner: r }
31 /// Consumes the `LimitReader`, returning the underlying `Reader`.
32 pub fn into_inner(self) -> R { self.inner }
34 /// Returns the number of bytes that can be read before the `LimitReader`
39 /// The reader may reach EOF after reading fewer bytes than indicated by
40 /// this method if the underlying reader reaches EOF.
41 pub fn limit(&self) -> uint { self.limit }
44 impl<R: Reader> Reader for LimitReader<R> {
45 fn read(&mut self, buf: &mut [u8]) -> io::IoResult<uint> {
47 return Err(io::standard_error(io::EndOfFile));
50 let len = cmp::min(self.limit, buf.len());
51 let res = self.inner.read(buf.slice_to_mut(len));
53 Ok(len) => self.limit -= len,
60 impl<R: Buffer> Buffer for LimitReader<R> {
61 fn fill_buf<'a>(&'a mut self) -> io::IoResult<&'a [u8]> {
62 let amt = try!(self.inner.fill_buf());
63 let buf = &amt[0..cmp::min(amt.len(), self.limit)];
65 Err(io::standard_error(io::EndOfFile))
71 fn consume(&mut self, amt: uint) {
72 // Don't let callers reset the limit by passing an overlarge value
73 let amt = cmp::min(amt, self.limit);
75 self.inner.consume(amt);
80 /// A `Writer` which ignores bytes written to it, like /dev/null.
82 pub struct NullWriter;
84 impl Writer for NullWriter {
86 fn write(&mut self, _buf: &[u8]) -> io::IoResult<()> { Ok(()) }
89 /// A `Reader` which returns an infinite stream of 0 bytes, like /dev/zero.
91 pub struct ZeroReader;
93 impl Reader for ZeroReader {
95 fn read(&mut self, buf: &mut [u8]) -> io::IoResult<uint> {
101 impl Buffer for ZeroReader {
102 fn fill_buf<'a>(&'a mut self) -> io::IoResult<&'a [u8]> {
103 static DATA: [u8; 64] = [0; 64];
107 fn consume(&mut self, _amt: uint) {}
110 /// A `Reader` which is always at EOF, like /dev/null.
111 #[derive(Copy, Show)]
112 pub struct NullReader;
114 impl Reader for NullReader {
116 fn read(&mut self, _buf: &mut [u8]) -> io::IoResult<uint> {
117 Err(io::standard_error(io::EndOfFile))
121 impl Buffer for NullReader {
122 fn fill_buf<'a>(&'a mut self) -> io::IoResult<&'a [u8]> {
123 Err(io::standard_error(io::EndOfFile))
125 fn consume(&mut self, _amt: uint) {}
128 /// A `Writer` which multiplexes writes to a set of `Writer`s.
130 /// The `Writer`s are delegated to in order. If any `Writer` returns an error,
131 /// that error is returned immediately and remaining `Writer`s are not called.
133 pub struct MultiWriter<W> {
137 impl<W> MultiWriter<W> where W: Writer {
138 /// Creates a new `MultiWriter`
139 pub fn new(writers: Vec<W>) -> MultiWriter<W> {
140 MultiWriter { writers: writers }
144 impl<W> Writer for MultiWriter<W> where W: Writer {
146 fn write(&mut self, buf: &[u8]) -> io::IoResult<()> {
147 for writer in self.writers.iter_mut() {
148 try!(writer.write(buf));
154 fn flush(&mut self) -> io::IoResult<()> {
155 for writer in self.writers.iter_mut() {
156 try!(writer.flush());
162 /// A `Reader` which chains input from multiple `Reader`s, reading each to
163 /// completion before moving onto the next.
164 #[derive(Clone, Show)]
165 pub struct ChainedReader<I, R> {
167 cur_reader: Option<R>,
170 impl<R: Reader, I: Iterator<Item=R>> ChainedReader<I, R> {
171 /// Creates a new `ChainedReader`
172 pub fn new(mut readers: I) -> ChainedReader<I, R> {
173 let r = readers.next();
174 ChainedReader { readers: readers, cur_reader: r }
178 impl<R: Reader, I: Iterator<Item=R>> Reader for ChainedReader<I, R> {
179 fn read(&mut self, buf: &mut [u8]) -> io::IoResult<uint> {
181 let err = match self.cur_reader {
184 Ok(len) => return Ok(len),
185 Err(ref e) if e.kind == io::EndOfFile => None,
191 self.cur_reader = self.readers.next();
193 Some(e) => return Err(e),
197 Err(io::standard_error(io::EndOfFile))
201 /// A `Reader` which forwards input from another `Reader`, passing it along to
202 /// a `Writer` as well. Similar to the `tee(1)` command.
204 pub struct TeeReader<R, W> {
209 impl<R: Reader, W: Writer> TeeReader<R, W> {
210 /// Creates a new `TeeReader`
211 pub fn new(r: R, w: W) -> TeeReader<R, W> {
212 TeeReader { reader: r, writer: w }
215 /// Consumes the `TeeReader`, returning the underlying `Reader` and
217 pub fn into_inner(self) -> (R, W) {
218 let TeeReader { reader, writer } = self;
223 impl<R: Reader, W: Writer> Reader for TeeReader<R, W> {
224 fn read(&mut self, buf: &mut [u8]) -> io::IoResult<uint> {
225 self.reader.read(buf).and_then(|len| {
226 self.writer.write(&mut buf[0..len]).map(|()| len)
231 /// Copies all data from a `Reader` to a `Writer`.
232 pub fn copy<R: Reader, W: Writer>(r: &mut R, w: &mut W) -> io::IoResult<()> {
233 let mut buf = [0; super::DEFAULT_BUF_SIZE];
235 let len = match r.read(&mut buf) {
237 Err(ref e) if e.kind == io::EndOfFile => return Ok(()),
238 Err(e) => return Err(e),
240 try!(w.write(&buf[0..len]));
244 /// An adaptor converting an `Iterator<u8>` to a `Reader`.
245 #[derive(Clone, Show)]
246 pub struct IterReader<T> {
250 impl<T: Iterator<Item=u8>> IterReader<T> {
251 /// Creates a new `IterReader` which will read from the specified
253 pub fn new(iter: T) -> IterReader<T> {
254 IterReader { iter: iter }
258 impl<T: Iterator<Item=u8>> Reader for IterReader<T> {
260 fn read(&mut self, buf: &mut [u8]) -> io::IoResult<uint> {
262 for (slot, elt) in buf.iter_mut().zip(self.iter.by_ref()) {
266 if len == 0 && buf.len() != 0 {
267 Err(io::standard_error(io::EndOfFile))
278 use io::{MemReader, ByRefReader};
283 fn test_limit_reader_unlimited() {
284 let mut r = MemReader::new(vec!(0, 1, 2));
286 let mut r = LimitReader::new(r.by_ref(), 4);
287 assert_eq!(vec!(0, 1, 2), r.read_to_end().unwrap());
292 fn test_limit_reader_limited() {
293 let mut r = MemReader::new(vec!(0, 1, 2));
295 let mut r = LimitReader::new(r.by_ref(), 2);
296 assert_eq!(vec!(0, 1), r.read_to_end().unwrap());
298 assert_eq!(vec!(2), r.read_to_end().unwrap());
302 fn test_limit_reader_limit() {
303 let r = MemReader::new(vec!(0, 1, 2));
304 let mut r = LimitReader::new(r, 3);
305 assert_eq!(3, r.limit());
306 assert_eq!(0, r.read_byte().unwrap());
307 assert_eq!(2, r.limit());
308 assert_eq!(vec!(1, 2), r.read_to_end().unwrap());
309 assert_eq!(0, r.limit());
313 fn test_limit_reader_overlong_consume() {
314 let mut r = MemReader::new(vec![0, 1, 2, 3, 4, 5]);
315 let mut r = LimitReader::new(r.by_ref(), 1);
317 assert_eq!(vec![], r.read_to_end().unwrap());
321 fn test_null_writer() {
322 let mut s = NullWriter;
323 let buf = vec![0, 0, 0];
324 s.write(buf.as_slice()).unwrap();
329 fn test_zero_reader() {
330 let mut s = ZeroReader;
331 let mut buf = vec![1, 2, 3];
332 assert_eq!(s.read(buf.as_mut_slice()), Ok(3));
333 assert_eq!(vec![0, 0, 0], buf);
337 fn test_null_reader() {
338 let mut r = NullReader;
339 let mut buf = vec![0];
340 assert!(r.read(buf.as_mut_slice()).is_err());
344 fn test_multi_writer() {
345 static mut writes: uint = 0;
346 static mut flushes: uint = 0;
349 impl Writer for TestWriter {
350 fn write(&mut self, _buf: &[u8]) -> io::IoResult<()> {
351 unsafe { writes += 1 }
355 fn flush(&mut self) -> io::IoResult<()> {
356 unsafe { flushes += 1 }
361 let mut multi = MultiWriter::new(vec!(box TestWriter as Box<Writer>,
362 box TestWriter as Box<Writer>));
363 multi.write(&[1, 2, 3]).unwrap();
364 assert_eq!(2, unsafe { writes });
365 assert_eq!(0, unsafe { flushes });
366 multi.flush().unwrap();
367 assert_eq!(2, unsafe { writes });
368 assert_eq!(2, unsafe { flushes });
372 fn test_chained_reader() {
373 let rs = vec!(MemReader::new(vec!(0, 1)), MemReader::new(vec!()),
374 MemReader::new(vec!(2, 3)));
375 let mut r = ChainedReader::new(rs.into_iter());
376 assert_eq!(vec!(0, 1, 2, 3), r.read_to_end().unwrap());
380 fn test_tee_reader() {
381 let mut r = TeeReader::new(MemReader::new(vec!(0, 1, 2)),
383 assert_eq!(vec!(0, 1, 2), r.read_to_end().unwrap());
384 let (_, w) = r.into_inner();
385 assert_eq!(vec!(0, 1, 2), w);
390 let mut r = MemReader::new(vec!(0, 1, 2, 3, 4));
391 let mut w = Vec::new();
392 copy(&mut r, &mut w).unwrap();
393 assert_eq!(vec!(0, 1, 2, 3, 4), w);
397 fn limit_reader_buffer() {
398 let r = &mut b"0123456789\n0123456789\n";
400 let mut r = LimitReader::new(r.by_ref(), 3);
401 assert_eq!(r.read_line(), Ok("012".to_string()));
402 assert_eq!(r.limit(), 0);
403 assert_eq!(r.read_line().err().unwrap().kind, io::EndOfFile);
406 let mut r = LimitReader::new(r.by_ref(), 9);
407 assert_eq!(r.read_line(), Ok("3456789\n".to_string()));
408 assert_eq!(r.limit(), 1);
409 assert_eq!(r.read_line(), Ok("0".to_string()));
412 let mut r = LimitReader::new(r.by_ref(), 100);
413 assert_eq!(r.read_char(), Ok('1'));
414 assert_eq!(r.limit(), 99);
415 assert_eq!(r.read_line(), Ok("23456789\n".to_string()));
420 fn test_iter_reader() {
421 let mut r = IterReader::new(range(0u8, 8));
422 let mut buf = [0, 0, 0];
423 let len = r.read(&mut buf).unwrap();
425 assert!(buf == [0, 1, 2]);
427 let len = r.read(&mut buf).unwrap();
429 assert!(buf == [3, 4, 5]);
431 let len = r.read(&mut buf).unwrap();
433 assert!(buf == [6, 7, 5]);
435 assert_eq!(r.read(&mut buf).unwrap_err().kind, io::EndOfFile);
439 fn iter_reader_zero_length() {
440 let mut r = IterReader::new(range(0u8, 8));
442 assert_eq!(Ok(0), r.read(&mut buf));