1 #![allow(missing_copy_implementations)]
4 use crate::io::{self, BufRead, ErrorKind, Initializer, IoSlice, IoSliceMut, Read, Write};
5 use crate::mem::MaybeUninit;
7 /// Copies the entire contents of a reader into a writer.
9 /// This function will continuously read data from `reader` and then
10 /// write it into `writer` in a streaming fashion until `reader`
13 /// On success, the total number of bytes that were copied from
14 /// `reader` to `writer` is returned.
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.
19 /// [`fs::copy`]: ../fs/fn.copy.html
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.
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>
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.
55 reader.initializer().initialize(buf.get_mut());
60 let len = match reader.read(unsafe { buf.get_mut() }) {
61 Ok(0) => return Ok(written),
63 Err(ref e) if e.kind() == ErrorKind::Interrupted => continue,
64 Err(e) => return Err(e),
66 writer.write_all(unsafe { &buf.get_ref()[..len] })?;
67 written += len as u64;
71 /// A reader which is always at EOF.
73 /// This struct is generally created by calling [`empty`]. Please see
74 /// the documentation of [`empty()`][`empty`] for more details.
76 /// [`empty`]: fn.empty.html
77 #[stable(feature = "rust1", since = "1.0.0")]
82 /// Constructs a new handle to an empty reader.
84 /// All reads from the returned reader will return [`Ok`]`(0)`.
86 /// [`Ok`]: ../result/enum.Result.html#variant.Ok
90 /// A slightly sad example of not reading anything into a buffer:
93 /// use std::io::{self, Read};
95 /// let mut buffer = String::new();
96 /// io::empty().read_to_string(&mut buffer).unwrap();
97 /// assert!(buffer.is_empty());
99 #[stable(feature = "rust1", since = "1.0.0")]
100 pub fn empty() -> Empty {
104 #[stable(feature = "rust1", since = "1.0.0")]
105 impl Read for Empty {
107 fn read(&mut self, _buf: &mut [u8]) -> io::Result<usize> {
112 unsafe fn initializer(&self) -> Initializer {
116 #[stable(feature = "rust1", since = "1.0.0")]
117 impl BufRead for Empty {
119 fn fill_buf(&mut self) -> io::Result<&[u8]> {
123 fn consume(&mut self, _n: usize) {}
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 { .. }")
133 /// A reader which yields one byte over and over and over and over and over and...
135 /// This struct is generally created by calling [`repeat`][repeat]. Please
136 /// see the documentation of `repeat()` for more details.
138 /// [repeat]: fn.repeat.html
139 #[stable(feature = "rust1", since = "1.0.0")]
144 /// Creates an instance of a reader that infinitely repeats one byte.
146 /// All reads from this reader will succeed by filling the specified buffer with
152 /// use std::io::{self, Read};
154 /// let mut buffer = [0; 3];
155 /// io::repeat(0b101).read_exact(&mut buffer).unwrap();
156 /// assert_eq!(buffer, [0b101, 0b101, 0b101]);
158 #[stable(feature = "rust1", since = "1.0.0")]
159 pub fn repeat(byte: u8) -> Repeat {
163 #[stable(feature = "rust1", since = "1.0.0")]
164 impl Read for Repeat {
166 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
167 for slot in &mut *buf {
174 fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
175 let mut nwritten = 0;
177 nwritten += self.read(buf)?;
183 unsafe fn initializer(&self) -> Initializer {
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 { .. }")
195 /// A writer which will move data into the void.
197 /// This struct is generally created by calling [`sink`][sink]. Please
198 /// see the documentation of `sink()` for more details.
200 /// [sink]: fn.sink.html
201 #[stable(feature = "rust1", since = "1.0.0")]
206 /// Creates an instance of a writer which will successfully consume all data.
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.
214 /// use std::io::{self, Write};
216 /// let buffer = vec![1, 2, 3, 5, 8];
217 /// let num_bytes = io::sink().write(&buffer).unwrap();
218 /// assert_eq!(num_bytes, 5);
220 #[stable(feature = "rust1", since = "1.0.0")]
221 pub fn sink() -> Sink {
225 #[stable(feature = "rust1", since = "1.0.0")]
226 impl Write for Sink {
228 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
233 fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
234 let total_len = bufs.iter().map(|b| b.len()).sum();
239 fn flush(&mut self) -> io::Result<()> {
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 {
253 use crate::io::prelude::*;
254 use crate::io::{copy, empty, repeat, sink};
258 let mut r = repeat(0).take(4);
260 assert_eq!(copy(&mut r, &mut w).unwrap(), 4);
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);
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);
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);
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));
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);