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