]> git.lizzy.rs Git - rust.git/blob - src/libstd/io/util.rs
rollup merge of #23923: steveklabnik/gh23688
[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 use prelude::v1::*;
14
15 use io::{self, Read, Write, ErrorKind, BufRead};
16
17 /// Copies the entire contents of a reader into a writer.
18 ///
19 /// This function will continuously read data from `r` and then write it into
20 /// `w` in a streaming fashion until `r` returns EOF.
21 ///
22 /// On success the total number of bytes that were copied from `r` to `w` is
23 /// returned.
24 ///
25 /// # Errors
26 ///
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.
30 #[stable(feature = "rust1", since = "1.0.0")]
31 pub fn copy<R: Read, W: Write>(r: &mut R, w: &mut W) -> io::Result<u64> {
32     let mut buf = [0; super::DEFAULT_BUF_SIZE];
33     let mut written = 0;
34     loop {
35         let len = match r.read(&mut buf) {
36             Ok(0) => return Ok(written),
37             Ok(len) => len,
38             Err(ref e) if e.kind() == ErrorKind::Interrupted => continue,
39             Err(e) => return Err(e),
40         };
41         try!(w.write_all(&buf[..len]));
42         written += len as u64;
43     }
44 }
45
46 /// A reader which is always at EOF.
47 #[stable(feature = "rust1", since = "1.0.0")]
48 pub struct Empty { _priv: () }
49
50 /// Creates an instance of an empty reader.
51 ///
52 /// All reads from the returned reader will return `Ok(0)`.
53 #[stable(feature = "rust1", since = "1.0.0")]
54 pub fn empty() -> Empty { Empty { _priv: () } }
55
56 #[stable(feature = "rust1", since = "1.0.0")]
57 impl Read for Empty {
58     fn read(&mut self, _buf: &mut [u8]) -> io::Result<usize> { Ok(0) }
59 }
60 #[stable(feature = "rust1", since = "1.0.0")]
61 impl BufRead for Empty {
62     fn fill_buf(&mut self) -> io::Result<&[u8]> { Ok(&[]) }
63     fn consume(&mut self, _n: usize) {}
64 }
65
66 /// A reader which infinitely yields one byte.
67 #[stable(feature = "rust1", since = "1.0.0")]
68 pub struct Repeat { byte: u8 }
69
70 /// Creates an instance of a reader that infinitely repeats one byte.
71 ///
72 /// All reads from this reader will succeed by filling the specified buffer with
73 /// the given byte.
74 #[stable(feature = "rust1", since = "1.0.0")]
75 pub fn repeat(byte: u8) -> Repeat { Repeat { byte: byte } }
76
77 #[stable(feature = "rust1", since = "1.0.0")]
78 impl Read for Repeat {
79     fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
80         for slot in buf.iter_mut() {
81             *slot = self.byte;
82         }
83         Ok(buf.len())
84     }
85 }
86
87 /// A writer which will move data into the void.
88 #[stable(feature = "rust1", since = "1.0.0")]
89 pub struct Sink { _priv: () }
90
91 /// Creates an instance of a writer which will successfully consume all data.
92 ///
93 /// All calls to `write` on the returned instance will return `Ok(buf.len())`
94 /// and the contents of the buffer will not be inspected.
95 #[stable(feature = "rust1", since = "1.0.0")]
96 pub fn sink() -> Sink { Sink { _priv: () } }
97
98 #[stable(feature = "rust1", since = "1.0.0")]
99 impl Write for Sink {
100     fn write(&mut self, buf: &[u8]) -> io::Result<usize> { Ok(buf.len()) }
101     fn flush(&mut self) -> io::Result<()> { Ok(()) }
102 }
103
104 #[cfg(test)]
105 mod test {
106     use prelude::v1::*;
107
108     use io::prelude::*;
109     use io::{sink, empty, repeat};
110
111     #[test]
112     fn sink_sinks() {
113         let mut s = sink();
114         assert_eq!(s.write(&[]).unwrap(), 0);
115         assert_eq!(s.write(&[0]).unwrap(), 1);
116         assert_eq!(s.write(&[0; 1024]).unwrap(), 1024);
117         assert_eq!(s.by_ref().write(&[0; 1024]).unwrap(), 1024);
118     }
119
120     #[test]
121     fn empty_reads() {
122         let mut e = empty();
123         assert_eq!(e.read(&mut []).unwrap(), 0);
124         assert_eq!(e.read(&mut [0]).unwrap(), 0);
125         assert_eq!(e.read(&mut [0; 1024]).unwrap(), 0);
126         assert_eq!(e.by_ref().read(&mut [0; 1024]).unwrap(), 0);
127     }
128
129     #[test]
130     fn repeat_repeats() {
131         let mut r = repeat(4);
132         let mut b = [0; 1024];
133         assert_eq!(r.read(&mut b).unwrap(), 1024);
134         assert!(b.iter().all(|b| *b == 4));
135     }
136
137     #[test]
138     fn take_some_bytes() {
139         assert_eq!(repeat(4).take(100).bytes().count(), 100);
140         assert_eq!(repeat(4).take(100).bytes().next().unwrap().unwrap(), 4);
141         assert_eq!(repeat(1).take(10).chain(repeat(2).take(10)).bytes().count(), 20);
142     }
143
144     #[test]
145     fn tee() {
146         let mut buf = [0; 10];
147         {
148             let mut ptr: &mut [u8] = &mut buf;
149             assert_eq!(repeat(4).tee(&mut ptr).take(5).read(&mut [0; 10]).unwrap(), 5);
150         }
151         assert_eq!(buf, [4, 4, 4, 4, 4, 0, 0, 0, 0, 0]);
152     }
153
154     #[test]
155     fn broadcast() {
156         let mut buf1 = [0; 10];
157         let mut buf2 = [0; 10];
158         {
159             let mut ptr1: &mut [u8] = &mut buf1;
160             let mut ptr2: &mut [u8] = &mut buf2;
161
162             assert_eq!((&mut ptr1).broadcast(&mut ptr2)
163                                   .write(&[1, 2, 3]).unwrap(), 3);
164         }
165         assert_eq!(buf1, buf2);
166         assert_eq!(buf1, [1, 2, 3, 0, 0, 0, 0, 0, 0, 0]);
167     }
168 }