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, Initializer, Write, ErrorKind, BufRead};
17 /// Copies the entire contents of a reader into a writer.
19 /// This function will continuously read data from `reader` and then
20 /// write it into `writer` in a streaming fashion until `reader`
23 /// On success, the total number of bytes that were copied from
24 /// `reader` to `writer` is returned.
28 /// This function will return an error immediately if any call to `read` or
29 /// `write` returns an error. All instances of `ErrorKind::Interrupted` are
30 /// handled by this function and the underlying operation is retried.
37 /// fn main() -> io::Result<()> {
38 /// let mut reader: &[u8] = b"hello";
39 /// let mut writer: Vec<u8> = vec![];
41 /// io::copy(&mut reader, &mut writer)?;
43 /// assert_eq!(&b"hello"[..], &writer[..]);
47 #[stable(feature = "rust1", since = "1.0.0")]
48 pub fn copy<R: ?Sized, W: ?Sized>(reader: &mut R, writer: &mut W) -> io::Result<u64>
49 where R: Read, W: Write
51 let mut buf = unsafe {
52 let mut buf: [u8; super::DEFAULT_BUF_SIZE] = mem::uninitialized();
53 reader.initializer().initialize(&mut buf);
59 let len = match reader.read(&mut buf) {
60 Ok(0) => return Ok(written),
62 Err(ref e) if e.kind() == ErrorKind::Interrupted => continue,
63 Err(e) => return Err(e),
65 writer.write_all(&buf[..len])?;
66 written += len as u64;
70 /// A reader which is always at EOF.
72 /// This struct is generally created by calling [`empty`]. Please see
73 /// the documentation of [`empty()`][`empty`] for more details.
75 /// [`empty`]: fn.empty.html
76 #[stable(feature = "rust1", since = "1.0.0")]
77 pub struct Empty { _priv: () }
79 /// Constructs a new handle to an empty reader.
81 /// All reads from the returned reader will return [`Ok`]`(0)`.
83 /// [`Ok`]: ../result/enum.Result.html#variant.Ok
87 /// A slightly sad example of not reading anything into a buffer:
90 /// use std::io::{self, Read};
92 /// let mut buffer = String::new();
93 /// io::empty().read_to_string(&mut buffer).unwrap();
94 /// assert!(buffer.is_empty());
96 #[stable(feature = "rust1", since = "1.0.0")]
97 pub fn empty() -> Empty { Empty { _priv: () } }
99 #[stable(feature = "rust1", since = "1.0.0")]
100 impl Read for Empty {
102 fn read(&mut self, _buf: &mut [u8]) -> io::Result<usize> { Ok(0) }
105 unsafe fn initializer(&self) -> Initializer {
109 #[stable(feature = "rust1", since = "1.0.0")]
110 impl BufRead for Empty {
112 fn fill_buf(&mut self) -> io::Result<&[u8]> { Ok(&[]) }
114 fn consume(&mut self, _n: usize) {}
117 #[stable(feature = "std_debug", since = "1.16.0")]
118 impl fmt::Debug for Empty {
119 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
120 f.pad("Empty { .. }")
124 /// A reader which yields one byte over and over and over and over and over and...
126 /// This struct is generally created by calling [`repeat`][repeat]. Please
127 /// see the documentation of `repeat()` for more details.
129 /// [repeat]: fn.repeat.html
130 #[stable(feature = "rust1", since = "1.0.0")]
131 pub struct Repeat { byte: u8 }
133 /// Creates an instance of a reader that infinitely repeats one byte.
135 /// All reads from this reader will succeed by filling the specified buffer with
141 /// use std::io::{self, Read};
143 /// let mut buffer = [0; 3];
144 /// io::repeat(0b101).read_exact(&mut buffer).unwrap();
145 /// assert_eq!(buffer, [0b101, 0b101, 0b101]);
147 #[stable(feature = "rust1", since = "1.0.0")]
148 pub fn repeat(byte: u8) -> Repeat { Repeat { byte: byte } }
150 #[stable(feature = "rust1", since = "1.0.0")]
151 impl Read for Repeat {
153 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
154 for slot in &mut *buf {
161 unsafe fn initializer(&self) -> Initializer {
166 #[stable(feature = "std_debug", since = "1.16.0")]
167 impl fmt::Debug for Repeat {
168 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
169 f.pad("Repeat { .. }")
173 /// A writer which will move data into the void.
175 /// This struct is generally created by calling [`sink`][sink]. Please
176 /// see the documentation of `sink()` for more details.
178 /// [sink]: fn.sink.html
179 #[stable(feature = "rust1", since = "1.0.0")]
180 pub struct Sink { _priv: () }
182 /// Creates an instance of a writer which will successfully consume all data.
184 /// All calls to `write` on the returned instance will return `Ok(buf.len())`
185 /// and the contents of the buffer will not be inspected.
190 /// use std::io::{self, Write};
192 /// let buffer = vec![1, 2, 3, 5, 8];
193 /// let num_bytes = io::sink().write(&buffer).unwrap();
194 /// assert_eq!(num_bytes, 5);
196 #[stable(feature = "rust1", since = "1.0.0")]
197 pub fn sink() -> Sink { Sink { _priv: () } }
199 #[stable(feature = "rust1", since = "1.0.0")]
200 impl Write for Sink {
202 fn write(&mut self, buf: &[u8]) -> io::Result<usize> { Ok(buf.len()) }
204 fn flush(&mut self) -> io::Result<()> { Ok(()) }
207 #[stable(feature = "std_debug", since = "1.16.0")]
208 impl fmt::Debug for Sink {
209 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
217 use io::{copy, sink, empty, repeat};
221 let mut r = repeat(0).take(4);
223 assert_eq!(copy(&mut r, &mut w).unwrap(), 4);
225 let mut r = repeat(0).take(1 << 17);
226 assert_eq!(copy(&mut r as &mut Read, &mut w as &mut Write).unwrap(), 1 << 17);
232 assert_eq!(s.write(&[]).unwrap(), 0);
233 assert_eq!(s.write(&[0]).unwrap(), 1);
234 assert_eq!(s.write(&[0; 1024]).unwrap(), 1024);
235 assert_eq!(s.by_ref().write(&[0; 1024]).unwrap(), 1024);
241 assert_eq!(e.read(&mut []).unwrap(), 0);
242 assert_eq!(e.read(&mut [0]).unwrap(), 0);
243 assert_eq!(e.read(&mut [0; 1024]).unwrap(), 0);
244 assert_eq!(e.by_ref().read(&mut [0; 1024]).unwrap(), 0);
248 fn repeat_repeats() {
249 let mut r = repeat(4);
250 let mut b = [0; 1024];
251 assert_eq!(r.read(&mut b).unwrap(), 1024);
252 assert!(b.iter().all(|b| *b == 4));
256 fn take_some_bytes() {
257 assert_eq!(repeat(4).take(100).bytes().count(), 100);
258 assert_eq!(repeat(4).take(100).bytes().next().unwrap().unwrap(), 4);
259 assert_eq!(repeat(1).take(10).chain(repeat(2).take(10)).bytes().count(), 20);