1 // Copyright 2014 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 #![allow(missing_copy_implementations)]
14 use io::{self, Read, Write, ErrorKind, BufRead};
16 /// Copies the entire contents of a reader into a writer.
18 /// This function will continuously read data from `reader` and then
19 /// write it into `writer` in a streaming fashion until `reader`
22 /// On success, the total number of bytes that were copied from
23 /// `reader` to `writer` is returned.
27 /// This function will return an error immediately if any call to `read` or
28 /// `write` returns an error. All instances of `ErrorKind::Interrupted` are
29 /// handled by this function and the underlying operation is retried.
36 /// # fn foo() -> io::Result<()> {
37 /// let mut reader: &[u8] = b"hello";
38 /// let mut writer: Vec<u8> = vec![];
40 /// io::copy(&mut reader, &mut writer)?;
42 /// assert_eq!(reader, &writer[..]);
46 #[stable(feature = "rust1", since = "1.0.0")]
47 pub fn copy<R: ?Sized, W: ?Sized>(reader: &mut R, writer: &mut W) -> io::Result<u64>
48 where R: Read, W: Write
50 let mut buf = [0; super::DEFAULT_BUF_SIZE];
53 let len = match reader.read(&mut buf) {
54 Ok(0) => return Ok(written),
56 Err(ref e) if e.kind() == ErrorKind::Interrupted => continue,
57 Err(e) => return Err(e),
59 writer.write_all(&buf[..len])?;
60 written += len as u64;
64 /// A reader which is always at EOF.
66 /// This struct is generally created by calling [`empty`][empty]. Please see
67 /// the documentation of `empty()` for more details.
69 /// [empty]: fn.empty.html
70 #[stable(feature = "rust1", since = "1.0.0")]
71 pub struct Empty { _priv: () }
73 /// Constructs a new handle to an empty reader.
75 /// All reads from the returned reader will return `Ok(0)`.
79 /// A slightly sad example of not reading anything into a buffer:
82 /// use std::io::{self, Read};
84 /// let mut buffer = String::new();
85 /// io::empty().read_to_string(&mut buffer).unwrap();
86 /// assert!(buffer.is_empty());
88 #[stable(feature = "rust1", since = "1.0.0")]
89 pub fn empty() -> Empty { Empty { _priv: () } }
91 #[stable(feature = "rust1", since = "1.0.0")]
93 fn read(&mut self, _buf: &mut [u8]) -> io::Result<usize> { Ok(0) }
95 #[stable(feature = "rust1", since = "1.0.0")]
96 impl BufRead for Empty {
97 fn fill_buf(&mut self) -> io::Result<&[u8]> { Ok(&[]) }
98 fn consume(&mut self, _n: usize) {}
101 #[stable(feature = "std_debug", since = "1.16.0")]
102 impl fmt::Debug for Empty {
103 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
104 f.pad("Empty { .. }")
108 /// A reader which yields one byte over and over and over and over and over and...
110 /// This struct is generally created by calling [`repeat`][repeat]. Please
111 /// see the documentation of `repeat()` for more details.
113 /// [repeat]: fn.repeat.html
114 #[stable(feature = "rust1", since = "1.0.0")]
115 pub struct Repeat { byte: u8 }
117 /// Creates an instance of a reader that infinitely repeats one byte.
119 /// All reads from this reader will succeed by filling the specified buffer with
125 /// use std::io::{self, Read};
127 /// let mut buffer = [0; 3];
128 /// io::repeat(0b101).read_exact(&mut buffer).unwrap();
129 /// assert_eq!(buffer, [0b101, 0b101, 0b101]);
131 #[stable(feature = "rust1", since = "1.0.0")]
132 pub fn repeat(byte: u8) -> Repeat { Repeat { byte: byte } }
134 #[stable(feature = "rust1", since = "1.0.0")]
135 impl Read for Repeat {
136 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
137 for slot in &mut *buf {
144 #[stable(feature = "std_debug", since = "1.16.0")]
145 impl fmt::Debug for Repeat {
146 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
147 f.pad("Repeat { .. }")
151 /// A writer which will move data into the void.
153 /// This struct is generally created by calling [`sink`][sink]. Please
154 /// see the documentation of `sink()` for more details.
156 /// [sink]: fn.sink.html
157 #[stable(feature = "rust1", since = "1.0.0")]
158 pub struct Sink { _priv: () }
160 /// Creates an instance of a writer which will successfully consume all data.
162 /// All calls to `write` on the returned instance will return `Ok(buf.len())`
163 /// and the contents of the buffer will not be inspected.
168 /// use std::io::{self, Write};
170 /// let buffer = vec![1, 2, 3, 5, 8];
171 /// let num_bytes = io::sink().write(&buffer).unwrap();
172 /// assert_eq!(num_bytes, 5);
174 #[stable(feature = "rust1", since = "1.0.0")]
175 pub fn sink() -> Sink { Sink { _priv: () } }
177 #[stable(feature = "rust1", since = "1.0.0")]
178 impl Write for Sink {
179 fn write(&mut self, buf: &[u8]) -> io::Result<usize> { Ok(buf.len()) }
180 fn flush(&mut self) -> io::Result<()> { Ok(()) }
183 #[stable(feature = "std_debug", since = "1.16.0")]
184 impl fmt::Debug for Sink {
185 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
193 use io::{copy, sink, empty, repeat};
197 let mut r = repeat(0).take(4);
199 assert_eq!(copy(&mut r, &mut w).unwrap(), 4);
201 let mut r = repeat(0).take(1 << 17);
202 assert_eq!(copy(&mut r as &mut Read, &mut w as &mut Write).unwrap(), 1 << 17);
208 assert_eq!(s.write(&[]).unwrap(), 0);
209 assert_eq!(s.write(&[0]).unwrap(), 1);
210 assert_eq!(s.write(&[0; 1024]).unwrap(), 1024);
211 assert_eq!(s.by_ref().write(&[0; 1024]).unwrap(), 1024);
217 assert_eq!(e.read(&mut []).unwrap(), 0);
218 assert_eq!(e.read(&mut [0]).unwrap(), 0);
219 assert_eq!(e.read(&mut [0; 1024]).unwrap(), 0);
220 assert_eq!(e.by_ref().read(&mut [0; 1024]).unwrap(), 0);
224 fn repeat_repeats() {
225 let mut r = repeat(4);
226 let mut b = [0; 1024];
227 assert_eq!(r.read(&mut b).unwrap(), 1024);
228 assert!(b.iter().all(|b| *b == 4));
232 fn take_some_bytes() {
233 assert_eq!(repeat(4).take(100).bytes().count(), 100);
234 assert_eq!(repeat(4).take(100).bytes().next().unwrap().unwrap(), 4);
235 assert_eq!(repeat(1).take(10).chain(repeat(2).take(10)).bytes().count(), 20);