]> git.lizzy.rs Git - rust.git/blob - library/std/src/io/copy.rs
Add a `std::io::read_to_string` function
[rust.git] / library / std / src / io / copy.rs
1 use crate::io::{self, ErrorKind, Read, Write};
2 use crate::mem::MaybeUninit;
3
4 /// Copies the entire contents of a reader into a writer.
5 ///
6 /// This function will continuously read data from `reader` and then
7 /// write it into `writer` in a streaming fashion until `reader`
8 /// returns EOF.
9 ///
10 /// On success, the total number of bytes that were copied from
11 /// `reader` to `writer` is returned.
12 ///
13 /// If you’re wanting to copy the contents of one file to another and you’re
14 /// working with filesystem paths, see the [`fs::copy`] function.
15 ///
16 /// [`fs::copy`]: crate::fs::copy
17 ///
18 /// # Errors
19 ///
20 /// This function will return an error immediately if any call to [`read`] or
21 /// [`write`] returns an error. All instances of [`ErrorKind::Interrupted`] are
22 /// handled by this function and the underlying operation is retried.
23 ///
24 /// [`read`]: Read::read
25 /// [`write`]: Write::write
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     cfg_if::cfg_if! {
49         if #[cfg(any(target_os = "linux", target_os = "android"))] {
50             crate::sys::kernel_copy::copy_spec(reader, writer)
51         } else {
52             generic_copy(reader, writer)
53         }
54     }
55 }
56
57 /// The general read-write-loop implementation of
58 /// `io::copy` that is used when specializations are not available or not applicable.
59 pub(crate) fn generic_copy<R: ?Sized, W: ?Sized>(reader: &mut R, writer: &mut W) -> io::Result<u64>
60 where
61     R: Read,
62     W: Write,
63 {
64     let mut buf = MaybeUninit::<[u8; super::DEFAULT_BUF_SIZE]>::uninit();
65     // FIXME: #42788
66     //
67     //   - This creates a (mut) reference to a slice of
68     //     _uninitialized_ integers, which is **undefined behavior**
69     //
70     //   - Only the standard library gets to soundly "ignore" this,
71     //     based on its privileged knowledge of unstable rustc
72     //     internals;
73     unsafe {
74         reader.initializer().initialize(buf.assume_init_mut());
75     }
76
77     let mut written = 0;
78     loop {
79         let len = match reader.read(unsafe { buf.assume_init_mut() }) {
80             Ok(0) => return Ok(written),
81             Ok(len) => len,
82             Err(ref e) if e.kind() == ErrorKind::Interrupted => continue,
83             Err(e) => return Err(e),
84         };
85         writer.write_all(unsafe { &buf.assume_init_ref()[..len] })?;
86         written += len as u64;
87     }
88 }