]> git.lizzy.rs Git - rust.git/blob - library/std/src/io/copy.rs
Document Linux kernel handoff in std::io::copy and std::fs::copy
[rust.git] / library / std / src / io / copy.rs
1 use super::{BufWriter, ErrorKind, Read, ReadBuf, Result, Write, DEFAULT_BUF_SIZE};
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 ///
43 /// # Platform-specific behavior
44 ///
45 /// On Linux (including Android), this function uses `copy_file_range(2)`,
46 /// `sendfile(2)` or `splice(2)` syscalls to move data directly between file
47 /// descriptors if possible.
48 #[stable(feature = "rust1", since = "1.0.0")]
49 pub fn copy<R: ?Sized, W: ?Sized>(reader: &mut R, writer: &mut W) -> Result<u64>
50 where
51     R: Read,
52     W: Write,
53 {
54     cfg_if::cfg_if! {
55         if #[cfg(any(target_os = "linux", target_os = "android"))] {
56             crate::sys::kernel_copy::copy_spec(reader, writer)
57         } else {
58             generic_copy(reader, writer)
59         }
60     }
61 }
62
63 /// The userspace read-write-loop implementation of `io::copy` that is used when
64 /// OS-specific specializations for copy offloading are not available or not applicable.
65 pub(crate) fn generic_copy<R: ?Sized, W: ?Sized>(reader: &mut R, writer: &mut W) -> Result<u64>
66 where
67     R: Read,
68     W: Write,
69 {
70     BufferedCopySpec::copy_to(reader, writer)
71 }
72
73 /// Specialization of the read-write loop that either uses a stack buffer
74 /// or reuses the internal buffer of a BufWriter
75 trait BufferedCopySpec: Write {
76     fn copy_to<R: Read + ?Sized>(reader: &mut R, writer: &mut Self) -> Result<u64>;
77 }
78
79 impl<W: Write + ?Sized> BufferedCopySpec for W {
80     default fn copy_to<R: Read + ?Sized>(reader: &mut R, writer: &mut Self) -> Result<u64> {
81         stack_buffer_copy(reader, writer)
82     }
83 }
84
85 impl<I: Write> BufferedCopySpec for BufWriter<I> {
86     fn copy_to<R: Read + ?Sized>(reader: &mut R, writer: &mut Self) -> Result<u64> {
87         if writer.capacity() < DEFAULT_BUF_SIZE {
88             return stack_buffer_copy(reader, writer);
89         }
90
91         let mut len = 0;
92         let mut init = 0;
93
94         loop {
95             let buf = writer.buffer_mut();
96             let mut read_buf = ReadBuf::uninit(buf.spare_capacity_mut());
97
98             // SAFETY: init is either 0 or the initialized_len of the previous iteration
99             unsafe {
100                 read_buf.assume_init(init);
101             }
102
103             if read_buf.capacity() >= DEFAULT_BUF_SIZE {
104                 match reader.read_buf(&mut read_buf) {
105                     Ok(()) => {
106                         let bytes_read = read_buf.filled_len();
107
108                         if bytes_read == 0 {
109                             return Ok(len);
110                         }
111
112                         init = read_buf.initialized_len() - bytes_read;
113
114                         // SAFETY: ReadBuf guarantees all of its filled bytes are init
115                         unsafe { buf.set_len(buf.len() + bytes_read) };
116                         len += bytes_read as u64;
117                         // Read again if the buffer still has enough capacity, as BufWriter itself would do
118                         // This will occur if the reader returns short reads
119                         continue;
120                     }
121                     Err(ref e) if e.kind() == ErrorKind::Interrupted => continue,
122                     Err(e) => return Err(e),
123                 }
124             }
125
126             writer.flush_buf()?;
127         }
128     }
129 }
130
131 fn stack_buffer_copy<R: Read + ?Sized, W: Write + ?Sized>(
132     reader: &mut R,
133     writer: &mut W,
134 ) -> Result<u64> {
135     let mut buf = [MaybeUninit::uninit(); DEFAULT_BUF_SIZE];
136     let mut buf = ReadBuf::uninit(&mut buf);
137
138     let mut len = 0;
139
140     loop {
141         match reader.read_buf(&mut buf) {
142             Ok(()) => {}
143             Err(e) if e.kind() == ErrorKind::Interrupted => continue,
144             Err(e) => return Err(e),
145         };
146
147         if buf.filled().is_empty() {
148             break;
149         }
150
151         len += buf.filled().len() as u64;
152         writer.write_all(buf.filled())?;
153         buf.clear();
154     }
155
156     Ok(len)
157 }