]> git.lizzy.rs Git - rust.git/blob - src/libstd/io/util.rs
Rollup merge of #62737 - timvermeulen:cycle_try_fold, r=scottmcm
[rust.git] / src / libstd / io / util.rs
1 #![allow(missing_copy_implementations)]
2
3 use crate::fmt;
4 use crate::io::{self, Read, Initializer, Write, ErrorKind, BufRead, IoSlice, IoSliceMut};
5 use crate::mem::MaybeUninit;
6
7 /// Copies the entire contents of a reader into a writer.
8 ///
9 /// This function will continuously read data from `reader` and then
10 /// write it into `writer` in a streaming fashion until `reader`
11 /// returns EOF.
12 ///
13 /// On success, the total number of bytes that were copied from
14 /// `reader` to `writer` is returned.
15 ///
16 /// If you’re wanting to copy the contents of one file to another and you’re
17 /// working with filesystem paths, see the [`fs::copy`] function.
18 ///
19 /// [`fs::copy`]: ../fs/fn.copy.html
20 ///
21 /// # Errors
22 ///
23 /// This function will return an error immediately if any call to `read` or
24 /// `write` returns an error. All instances of `ErrorKind::Interrupted` are
25 /// handled by this function and the underlying operation is retried.
26 ///
27 /// # Examples
28 ///
29 /// ```
30 /// use std::io;
31 ///
32 /// fn main() -> io::Result<()> {
33 ///     let mut reader: &[u8] = b"hello";
34 ///     let mut writer: Vec<u8> = vec![];
35 ///
36 ///     io::copy(&mut reader, &mut writer)?;
37 ///
38 ///     assert_eq!(&b"hello"[..], &writer[..]);
39 ///     Ok(())
40 /// }
41 /// ```
42 #[stable(feature = "rust1", since = "1.0.0")]
43 pub fn copy<R: ?Sized, W: ?Sized>(reader: &mut R, writer: &mut W) -> io::Result<u64>
44     where R: Read, W: Write
45 {
46     let mut buf = MaybeUninit::<[u8; super::DEFAULT_BUF_SIZE]>::uninit();
47     // FIXME(#53491): This is calling `get_mut` and `get_ref` on an uninitialized
48     // `MaybeUninit`. Revisit this once we decided whether that is valid or not.
49     // This is still technically undefined behavior due to creating a reference
50     // to uninitialized data, but within libstd we can rely on more guarantees
51     // than if this code were in an external lib.
52     unsafe { reader.initializer().initialize(buf.get_mut()); }
53
54     let mut written = 0;
55     loop {
56         let len = match reader.read(unsafe { buf.get_mut() }) {
57             Ok(0) => return Ok(written),
58             Ok(len) => len,
59             Err(ref e) if e.kind() == ErrorKind::Interrupted => continue,
60             Err(e) => return Err(e),
61         };
62         writer.write_all(unsafe { &buf.get_ref()[..len] })?;
63         written += len as u64;
64     }
65 }
66
67 /// A reader which is always at EOF.
68 ///
69 /// This struct is generally created by calling [`empty`]. Please see
70 /// the documentation of [`empty()`][`empty`] for more details.
71 ///
72 /// [`empty`]: fn.empty.html
73 #[stable(feature = "rust1", since = "1.0.0")]
74 pub struct Empty { _priv: () }
75
76 /// Constructs a new handle to an empty reader.
77 ///
78 /// All reads from the returned reader will return [`Ok`]`(0)`.
79 ///
80 /// [`Ok`]: ../result/enum.Result.html#variant.Ok
81 ///
82 /// # Examples
83 ///
84 /// A slightly sad example of not reading anything into a buffer:
85 ///
86 /// ```
87 /// use std::io::{self, Read};
88 ///
89 /// let mut buffer = String::new();
90 /// io::empty().read_to_string(&mut buffer).unwrap();
91 /// assert!(buffer.is_empty());
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     #[inline]
99     fn read(&mut self, _buf: &mut [u8]) -> io::Result<usize> { Ok(0) }
100
101     #[inline]
102     unsafe fn initializer(&self) -> Initializer {
103         Initializer::nop()
104     }
105 }
106 #[stable(feature = "rust1", since = "1.0.0")]
107 impl BufRead for Empty {
108     #[inline]
109     fn fill_buf(&mut self) -> io::Result<&[u8]> { Ok(&[]) }
110     #[inline]
111     fn consume(&mut self, _n: usize) {}
112 }
113
114 #[stable(feature = "std_debug", since = "1.16.0")]
115 impl fmt::Debug for Empty {
116     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
117         f.pad("Empty { .. }")
118     }
119 }
120
121 /// A reader which yields one byte over and over and over and over and over and...
122 ///
123 /// This struct is generally created by calling [`repeat`][repeat]. Please
124 /// see the documentation of `repeat()` for more details.
125 ///
126 /// [repeat]: fn.repeat.html
127 #[stable(feature = "rust1", since = "1.0.0")]
128 pub struct Repeat { byte: u8 }
129
130 /// Creates an instance of a reader that infinitely repeats one byte.
131 ///
132 /// All reads from this reader will succeed by filling the specified buffer with
133 /// the given byte.
134 ///
135 /// # Examples
136 ///
137 /// ```
138 /// use std::io::{self, Read};
139 ///
140 /// let mut buffer = [0; 3];
141 /// io::repeat(0b101).read_exact(&mut buffer).unwrap();
142 /// assert_eq!(buffer, [0b101, 0b101, 0b101]);
143 /// ```
144 #[stable(feature = "rust1", since = "1.0.0")]
145 pub fn repeat(byte: u8) -> Repeat { Repeat { byte } }
146
147 #[stable(feature = "rust1", since = "1.0.0")]
148 impl Read for Repeat {
149     #[inline]
150     fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
151         for slot in &mut *buf {
152             *slot = self.byte;
153         }
154         Ok(buf.len())
155     }
156
157     #[inline]
158     fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
159         let mut nwritten = 0;
160         for buf in bufs {
161             nwritten += self.read(buf)?;
162         }
163         Ok(nwritten)
164     }
165
166     #[inline]
167     unsafe fn initializer(&self) -> Initializer {
168         Initializer::nop()
169     }
170 }
171
172 #[stable(feature = "std_debug", since = "1.16.0")]
173 impl fmt::Debug for Repeat {
174     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
175         f.pad("Repeat { .. }")
176     }
177 }
178
179 /// A writer which will move data into the void.
180 ///
181 /// This struct is generally created by calling [`sink`][sink]. Please
182 /// see the documentation of `sink()` for more details.
183 ///
184 /// [sink]: fn.sink.html
185 #[stable(feature = "rust1", since = "1.0.0")]
186 pub struct Sink { _priv: () }
187
188 /// Creates an instance of a writer which will successfully consume all data.
189 ///
190 /// All calls to `write` on the returned instance will return `Ok(buf.len())`
191 /// and the contents of the buffer will not be inspected.
192 ///
193 /// # Examples
194 ///
195 /// ```rust
196 /// use std::io::{self, Write};
197 ///
198 /// let buffer = vec![1, 2, 3, 5, 8];
199 /// let num_bytes = io::sink().write(&buffer).unwrap();
200 /// assert_eq!(num_bytes, 5);
201 /// ```
202 #[stable(feature = "rust1", since = "1.0.0")]
203 pub fn sink() -> Sink { Sink { _priv: () } }
204
205 #[stable(feature = "rust1", since = "1.0.0")]
206 impl Write for Sink {
207     #[inline]
208     fn write(&mut self, buf: &[u8]) -> io::Result<usize> { Ok(buf.len()) }
209
210     #[inline]
211     fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
212         let total_len = bufs.iter().map(|b| b.len()).sum();
213         Ok(total_len)
214     }
215
216     #[inline]
217     fn flush(&mut self) -> io::Result<()> { Ok(()) }
218 }
219
220 #[stable(feature = "std_debug", since = "1.16.0")]
221 impl fmt::Debug for Sink {
222     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
223         f.pad("Sink { .. }")
224     }
225 }
226
227 #[cfg(test)]
228 mod tests {
229     use crate::io::prelude::*;
230     use crate::io::{copy, sink, empty, repeat};
231
232     #[test]
233     fn copy_copies() {
234         let mut r = repeat(0).take(4);
235         let mut w = sink();
236         assert_eq!(copy(&mut r, &mut w).unwrap(), 4);
237
238         let mut r = repeat(0).take(1 << 17);
239         assert_eq!(copy(&mut r as &mut dyn Read, &mut w as &mut dyn Write).unwrap(), 1 << 17);
240     }
241
242     #[test]
243     fn sink_sinks() {
244         let mut s = sink();
245         assert_eq!(s.write(&[]).unwrap(), 0);
246         assert_eq!(s.write(&[0]).unwrap(), 1);
247         assert_eq!(s.write(&[0; 1024]).unwrap(), 1024);
248         assert_eq!(s.by_ref().write(&[0; 1024]).unwrap(), 1024);
249     }
250
251     #[test]
252     fn empty_reads() {
253         let mut e = empty();
254         assert_eq!(e.read(&mut []).unwrap(), 0);
255         assert_eq!(e.read(&mut [0]).unwrap(), 0);
256         assert_eq!(e.read(&mut [0; 1024]).unwrap(), 0);
257         assert_eq!(e.by_ref().read(&mut [0; 1024]).unwrap(), 0);
258     }
259
260     #[test]
261     fn repeat_repeats() {
262         let mut r = repeat(4);
263         let mut b = [0; 1024];
264         assert_eq!(r.read(&mut b).unwrap(), 1024);
265         assert!(b.iter().all(|b| *b == 4));
266     }
267
268     #[test]
269     fn take_some_bytes() {
270         assert_eq!(repeat(4).take(100).bytes().count(), 100);
271         assert_eq!(repeat(4).take(100).bytes().next().unwrap().unwrap(), 4);
272         assert_eq!(repeat(1).take(10).chain(repeat(2).take(10)).bytes().count(), 20);
273     }
274 }