1 use crate::io::{self, ErrorKind, Read, Write};
2 use crate::mem::MaybeUninit;
4 /// Copies the entire contents of a reader into a writer.
6 /// This function will continuously read data from `reader` and then
7 /// write it into `writer` in a streaming fashion until `reader`
10 /// On success, the total number of bytes that were copied from
11 /// `reader` to `writer` is returned.
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.
16 /// [`fs::copy`]: crate::fs::copy
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.
24 /// [`read`]: Read::read
25 /// [`write`]: Write::write
32 /// fn main() -> io::Result<()> {
33 /// let mut reader: &[u8] = b"hello";
34 /// let mut writer: Vec<u8> = vec![];
36 /// io::copy(&mut reader, &mut writer)?;
38 /// assert_eq!(&b"hello"[..], &writer[..]);
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>
49 if #[cfg(any(target_os = "linux", target_os = "android"))] {
50 crate::sys::kernel_copy::copy_spec(reader, writer)
52 generic_copy(reader, writer)
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>
64 let mut buf = MaybeUninit::<[u8; super::DEFAULT_BUF_SIZE]>::uninit();
67 // - This creates a (mut) reference to a slice of
68 // _uninitialized_ integers, which is **undefined behavior**
70 // - Only the standard library gets to soundly "ignore" this,
71 // based on its privileged knowledge of unstable rustc
74 reader.initializer().initialize(buf.assume_init_mut());
79 let len = match reader.read(unsafe { buf.assume_init_mut() }) {
80 Ok(0) => return Ok(written),
82 Err(ref e) if e.kind() == ErrorKind::Interrupted => continue,
83 Err(e) => return Err(e),
85 writer.write_all(unsafe { &buf.assume_init_ref()[..len] })?;
86 written += len as u64;