]> git.proxmox.com Git - rustc.git/blob - src/libstd/io/util.rs
New upstream version 1.41.1+dfsg1
[rustc.git] / src / libstd / io / util.rs
1 #![allow(missing_copy_implementations)]
2
3 use crate::fmt;
4 use crate::io::{self, BufRead, ErrorKind, Initializer, IoSlice, IoSliceMut, Read, Write};
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
45 R: Read,
46 W: Write,
47 {
48 let mut buf = MaybeUninit::<[u8; super::DEFAULT_BUF_SIZE]>::uninit();
49 // FIXME(#53491): This is calling `get_mut` and `get_ref` on an uninitialized
50 // `MaybeUninit`. Revisit this once we decided whether that is valid or not.
51 // This is still technically undefined behavior due to creating a reference
52 // to uninitialized data, but within libstd we can rely on more guarantees
53 // than if this code were in an external lib.
54 unsafe {
55 reader.initializer().initialize(buf.get_mut());
56 }
57
58 let mut written = 0;
59 loop {
60 let len = match reader.read(unsafe { buf.get_mut() }) {
61 Ok(0) => return Ok(written),
62 Ok(len) => len,
63 Err(ref e) if e.kind() == ErrorKind::Interrupted => continue,
64 Err(e) => return Err(e),
65 };
66 writer.write_all(unsafe { &buf.get_ref()[..len] })?;
67 written += len as u64;
68 }
69 }
70
71 /// A reader which is always at EOF.
72 ///
73 /// This struct is generally created by calling [`empty`]. Please see
74 /// the documentation of [`empty()`][`empty`] for more details.
75 ///
76 /// [`empty`]: fn.empty.html
77 #[stable(feature = "rust1", since = "1.0.0")]
78 pub struct Empty {
79 _priv: (),
80 }
81
82 /// Constructs a new handle to an empty reader.
83 ///
84 /// All reads from the returned reader will return [`Ok`]`(0)`.
85 ///
86 /// [`Ok`]: ../result/enum.Result.html#variant.Ok
87 ///
88 /// # Examples
89 ///
90 /// A slightly sad example of not reading anything into a buffer:
91 ///
92 /// ```
93 /// use std::io::{self, Read};
94 ///
95 /// let mut buffer = String::new();
96 /// io::empty().read_to_string(&mut buffer).unwrap();
97 /// assert!(buffer.is_empty());
98 /// ```
99 #[stable(feature = "rust1", since = "1.0.0")]
100 pub fn empty() -> Empty {
101 Empty { _priv: () }
102 }
103
104 #[stable(feature = "rust1", since = "1.0.0")]
105 impl Read for Empty {
106 #[inline]
107 fn read(&mut self, _buf: &mut [u8]) -> io::Result<usize> {
108 Ok(0)
109 }
110
111 #[inline]
112 unsafe fn initializer(&self) -> Initializer {
113 Initializer::nop()
114 }
115 }
116 #[stable(feature = "rust1", since = "1.0.0")]
117 impl BufRead for Empty {
118 #[inline]
119 fn fill_buf(&mut self) -> io::Result<&[u8]> {
120 Ok(&[])
121 }
122 #[inline]
123 fn consume(&mut self, _n: usize) {}
124 }
125
126 #[stable(feature = "std_debug", since = "1.16.0")]
127 impl fmt::Debug for Empty {
128 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
129 f.pad("Empty { .. }")
130 }
131 }
132
133 /// A reader which yields one byte over and over and over and over and over and...
134 ///
135 /// This struct is generally created by calling [`repeat`][repeat]. Please
136 /// see the documentation of `repeat()` for more details.
137 ///
138 /// [repeat]: fn.repeat.html
139 #[stable(feature = "rust1", since = "1.0.0")]
140 pub struct Repeat {
141 byte: u8,
142 }
143
144 /// Creates an instance of a reader that infinitely repeats one byte.
145 ///
146 /// All reads from this reader will succeed by filling the specified buffer with
147 /// the given byte.
148 ///
149 /// # Examples
150 ///
151 /// ```
152 /// use std::io::{self, Read};
153 ///
154 /// let mut buffer = [0; 3];
155 /// io::repeat(0b101).read_exact(&mut buffer).unwrap();
156 /// assert_eq!(buffer, [0b101, 0b101, 0b101]);
157 /// ```
158 #[stable(feature = "rust1", since = "1.0.0")]
159 pub fn repeat(byte: u8) -> Repeat {
160 Repeat { byte }
161 }
162
163 #[stable(feature = "rust1", since = "1.0.0")]
164 impl Read for Repeat {
165 #[inline]
166 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
167 for slot in &mut *buf {
168 *slot = self.byte;
169 }
170 Ok(buf.len())
171 }
172
173 #[inline]
174 fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
175 let mut nwritten = 0;
176 for buf in bufs {
177 nwritten += self.read(buf)?;
178 }
179 Ok(nwritten)
180 }
181
182 #[inline]
183 unsafe fn initializer(&self) -> Initializer {
184 Initializer::nop()
185 }
186 }
187
188 #[stable(feature = "std_debug", since = "1.16.0")]
189 impl fmt::Debug for Repeat {
190 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
191 f.pad("Repeat { .. }")
192 }
193 }
194
195 /// A writer which will move data into the void.
196 ///
197 /// This struct is generally created by calling [`sink`][sink]. Please
198 /// see the documentation of `sink()` for more details.
199 ///
200 /// [sink]: fn.sink.html
201 #[stable(feature = "rust1", since = "1.0.0")]
202 pub struct Sink {
203 _priv: (),
204 }
205
206 /// Creates an instance of a writer which will successfully consume all data.
207 ///
208 /// All calls to `write` on the returned instance will return `Ok(buf.len())`
209 /// and the contents of the buffer will not be inspected.
210 ///
211 /// # Examples
212 ///
213 /// ```rust
214 /// use std::io::{self, Write};
215 ///
216 /// let buffer = vec![1, 2, 3, 5, 8];
217 /// let num_bytes = io::sink().write(&buffer).unwrap();
218 /// assert_eq!(num_bytes, 5);
219 /// ```
220 #[stable(feature = "rust1", since = "1.0.0")]
221 pub fn sink() -> Sink {
222 Sink { _priv: () }
223 }
224
225 #[stable(feature = "rust1", since = "1.0.0")]
226 impl Write for Sink {
227 #[inline]
228 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
229 Ok(buf.len())
230 }
231
232 #[inline]
233 fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
234 let total_len = bufs.iter().map(|b| b.len()).sum();
235 Ok(total_len)
236 }
237
238 #[inline]
239 fn flush(&mut self) -> io::Result<()> {
240 Ok(())
241 }
242 }
243
244 #[stable(feature = "std_debug", since = "1.16.0")]
245 impl fmt::Debug for Sink {
246 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
247 f.pad("Sink { .. }")
248 }
249 }
250
251 #[cfg(test)]
252 mod tests {
253 use crate::io::prelude::*;
254 use crate::io::{copy, empty, repeat, sink};
255
256 #[test]
257 fn copy_copies() {
258 let mut r = repeat(0).take(4);
259 let mut w = sink();
260 assert_eq!(copy(&mut r, &mut w).unwrap(), 4);
261
262 let mut r = repeat(0).take(1 << 17);
263 assert_eq!(copy(&mut r as &mut dyn Read, &mut w as &mut dyn Write).unwrap(), 1 << 17);
264 }
265
266 #[test]
267 fn sink_sinks() {
268 let mut s = sink();
269 assert_eq!(s.write(&[]).unwrap(), 0);
270 assert_eq!(s.write(&[0]).unwrap(), 1);
271 assert_eq!(s.write(&[0; 1024]).unwrap(), 1024);
272 assert_eq!(s.by_ref().write(&[0; 1024]).unwrap(), 1024);
273 }
274
275 #[test]
276 fn empty_reads() {
277 let mut e = empty();
278 assert_eq!(e.read(&mut []).unwrap(), 0);
279 assert_eq!(e.read(&mut [0]).unwrap(), 0);
280 assert_eq!(e.read(&mut [0; 1024]).unwrap(), 0);
281 assert_eq!(e.by_ref().read(&mut [0; 1024]).unwrap(), 0);
282 }
283
284 #[test]
285 fn repeat_repeats() {
286 let mut r = repeat(4);
287 let mut b = [0; 1024];
288 assert_eq!(r.read(&mut b).unwrap(), 1024);
289 assert!(b.iter().all(|b| *b == 4));
290 }
291
292 #[test]
293 fn take_some_bytes() {
294 assert_eq!(repeat(4).take(100).bytes().count(), 100);
295 assert_eq!(repeat(4).take(100).bytes().next().unwrap().unwrap(), 4);
296 assert_eq!(repeat(1).take(10).chain(repeat(2).take(10)).bytes().count(), 20);
297 }
298 }