]> git.lizzy.rs Git - rust.git/blob - src/libstd/io/util.rs
rollup merge of #27605: AlisdairO/diagnostics387
[rust.git] / src / libstd / io / util.rs
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.
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 #![allow(missing_copy_implementations)]
12
13 #[cfg(stage0)]
14 use prelude::v1::*;
15
16 use io::{self, Read, Write, ErrorKind, BufRead};
17
18 /// Copies the entire contents of a reader into a writer.
19 ///
20 /// This function will continuously read data from `reader` and then
21 /// write it into `writer` in a streaming fashion until `reader`
22 /// returns EOF.
23 ///
24 /// On success, the total number of bytes that were copied from
25 /// `reader` to `writer` is returned.
26 ///
27 /// # Errors
28 ///
29 /// This function will return an error immediately if any call to `read` or
30 /// `write` returns an error. All instances of `ErrorKind::Interrupted` are
31 /// handled by this function and the underlying operation is retried.
32 ///
33 /// # Examples
34 ///
35 /// ```
36 /// use std::io;
37 ///
38 /// # fn foo() -> io::Result<()> {
39 /// let mut reader: &[u8] = b"hello";
40 /// let mut writer: Vec<u8> = vec![];
41 ///
42 /// try!(io::copy(&mut reader, &mut writer));
43 ///
44 /// assert_eq!(reader, &writer[..]);
45 /// # Ok(())
46 /// # }
47 /// ```
48 #[stable(feature = "rust1", since = "1.0.0")]
49 pub fn copy<R: ?Sized, W: ?Sized>(reader: &mut R, writer: &mut W) -> io::Result<u64>
50     where R: Read, W: Write
51 {
52     let mut buf = [0; super::DEFAULT_BUF_SIZE];
53     let mut written = 0;
54     loop {
55         let len = match reader.read(&mut buf) {
56             Ok(0) => return Ok(written),
57             Ok(len) => len,
58             Err(ref e) if e.kind() == ErrorKind::Interrupted => continue,
59             Err(e) => return Err(e),
60         };
61         try!(writer.write_all(&buf[..len]));
62         written += len as u64;
63     }
64 }
65
66 /// A reader which is always at EOF.
67 ///
68 /// This struct is generally created by calling [`empty()`][empty]. Please see
69 /// the documentation of `empty()` for more details.
70 ///
71 /// [empty]: fn.empty.html
72 #[stable(feature = "rust1", since = "1.0.0")]
73 pub struct Empty { _priv: () }
74
75 /// Constructs a new handle to an empty reader.
76 ///
77 /// All reads from the returned reader will return `Ok(0)`.
78 ///
79 /// # Examples
80 ///
81 /// A slightly sad example of not reading anything into a buffer:
82 ///
83 /// ```
84 /// use std::io;
85 /// use std::io::Read;
86 ///
87 /// # fn foo() -> io::Result<String> {
88 /// let mut buffer = String::new();
89 /// try!(io::empty().read_to_string(&mut buffer));
90 /// # Ok(buffer)
91 /// # }
92 /// ```
93 #[stable(feature = "rust1", since = "1.0.0")]
94 pub fn empty() -> Empty { Empty { _priv: () } }
95
96 #[stable(feature = "rust1", since = "1.0.0")]
97 impl Read for Empty {
98     fn read(&mut self, _buf: &mut [u8]) -> io::Result<usize> { Ok(0) }
99 }
100 #[stable(feature = "rust1", since = "1.0.0")]
101 impl BufRead for Empty {
102     fn fill_buf(&mut self) -> io::Result<&[u8]> { Ok(&[]) }
103     fn consume(&mut self, _n: usize) {}
104 }
105
106 /// A reader which yields one byte over and over and over and over and over and...
107 ///
108 /// This struct is generally created by calling [`repeat()`][repeat]. Please
109 /// see the documentation of `repeat()` for more details.
110 ///
111 /// [repeat]: fn.repeat.html
112 #[stable(feature = "rust1", since = "1.0.0")]
113 pub struct Repeat { byte: u8 }
114
115 /// Creates an instance of a reader that infinitely repeats one byte.
116 ///
117 /// All reads from this reader will succeed by filling the specified buffer with
118 /// the given byte.
119 #[stable(feature = "rust1", since = "1.0.0")]
120 pub fn repeat(byte: u8) -> Repeat { Repeat { byte: byte } }
121
122 #[stable(feature = "rust1", since = "1.0.0")]
123 impl Read for Repeat {
124     fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
125         for slot in &mut *buf {
126             *slot = self.byte;
127         }
128         Ok(buf.len())
129     }
130 }
131
132 /// A writer which will move data into the void.
133 ///
134 /// This struct is generally created by calling [`sink()`][sink]. Please
135 /// see the documentation of `sink()` for more details.
136 ///
137 /// [sink]: fn.sink.html
138 #[stable(feature = "rust1", since = "1.0.0")]
139 pub struct Sink { _priv: () }
140
141 /// Creates an instance of a writer which will successfully consume all data.
142 ///
143 /// All calls to `write` on the returned instance will return `Ok(buf.len())`
144 /// and the contents of the buffer will not be inspected.
145 #[stable(feature = "rust1", since = "1.0.0")]
146 pub fn sink() -> Sink { Sink { _priv: () } }
147
148 #[stable(feature = "rust1", since = "1.0.0")]
149 impl Write for Sink {
150     fn write(&mut self, buf: &[u8]) -> io::Result<usize> { Ok(buf.len()) }
151     fn flush(&mut self) -> io::Result<()> { Ok(()) }
152 }
153
154 #[cfg(test)]
155 mod tests {
156     use prelude::v1::*;
157
158     use io::prelude::*;
159     use io::{copy, sink, empty, repeat};
160
161     #[test]
162     fn copy_copies() {
163         let mut r = repeat(0).take(4);
164         let mut w = sink();
165         assert_eq!(copy(&mut r, &mut w).unwrap(), 4);
166
167         let mut r = repeat(0).take(1 << 17);
168         assert_eq!(copy(&mut r as &mut Read, &mut w as &mut Write).unwrap(), 1 << 17);
169     }
170
171     #[test]
172     fn sink_sinks() {
173         let mut s = sink();
174         assert_eq!(s.write(&[]).unwrap(), 0);
175         assert_eq!(s.write(&[0]).unwrap(), 1);
176         assert_eq!(s.write(&[0; 1024]).unwrap(), 1024);
177         assert_eq!(s.by_ref().write(&[0; 1024]).unwrap(), 1024);
178     }
179
180     #[test]
181     fn empty_reads() {
182         let mut e = empty();
183         assert_eq!(e.read(&mut []).unwrap(), 0);
184         assert_eq!(e.read(&mut [0]).unwrap(), 0);
185         assert_eq!(e.read(&mut [0; 1024]).unwrap(), 0);
186         assert_eq!(e.by_ref().read(&mut [0; 1024]).unwrap(), 0);
187     }
188
189     #[test]
190     fn repeat_repeats() {
191         let mut r = repeat(4);
192         let mut b = [0; 1024];
193         assert_eq!(r.read(&mut b).unwrap(), 1024);
194         assert!(b.iter().all(|b| *b == 4));
195     }
196
197     #[test]
198     fn take_some_bytes() {
199         assert_eq!(repeat(4).take(100).bytes().count(), 100);
200         assert_eq!(repeat(4).take(100).bytes().next().unwrap().unwrap(), 4);
201         assert_eq!(repeat(1).take(10).chain(repeat(2).take(10)).bytes().count(), 20);
202     }
203
204     #[test]
205     fn tee() {
206         let mut buf = [0; 10];
207         {
208             let mut ptr: &mut [u8] = &mut buf;
209             assert_eq!(repeat(4).tee(&mut ptr).take(5).read(&mut [0; 10]).unwrap(), 5);
210         }
211         assert_eq!(buf, [4, 4, 4, 4, 4, 0, 0, 0, 0, 0]);
212     }
213
214     #[test]
215     fn broadcast() {
216         let mut buf1 = [0; 10];
217         let mut buf2 = [0; 10];
218         {
219             let mut ptr1: &mut [u8] = &mut buf1;
220             let mut ptr2: &mut [u8] = &mut buf2;
221
222             assert_eq!((&mut ptr1).broadcast(&mut ptr2)
223                                   .write(&[1, 2, 3]).unwrap(), 3);
224         }
225         assert_eq!(buf1, buf2);
226         assert_eq!(buf1, [1, 2, 3, 0, 0, 0, 0, 0, 0, 0]);
227     }
228 }