1 #![allow(missing_copy_implementations)]
4 use crate::io::{self, Read, Initializer, Write, ErrorKind, BufRead, IoSlice, IoSliceMut};
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>
44 where R: Read, W: Write
46 let mut buf = MaybeUninit::<[u8; super::DEFAULT_BUF_SIZE]>::uninit();
47 // FIXME(#53491): This is calling `get_mut` and `get_ref` on an uninitialized
48 // `MaybeUninit`. Revisit this once we decided whether that is valid or not.
49 // This is still technically undefined behavior due to creating a reference
50 // to uninitialized data, but within libstd we can rely on more guarantees
51 // than if this code were in an external lib.
52 unsafe { reader.initializer().initialize(buf.get_mut()); }
56 let len = match reader.read(unsafe { buf.get_mut() }) {
57 Ok(0) => return Ok(written),
59 Err(ref e) if e.kind() == ErrorKind::Interrupted => continue,
60 Err(e) => return Err(e),
62 writer.write_all(unsafe { &buf.get_ref()[..len] })?;
63 written += len as u64;
67 /// A reader which is always at EOF.
69 /// This struct is generally created by calling [`empty`]. Please see
70 /// the documentation of [`empty()`][`empty`] for more details.
72 /// [`empty`]: fn.empty.html
73 #[stable(feature = "rust1", since = "1.0.0")]
74 pub struct Empty { _priv: () }
76 /// Constructs a new handle to an empty reader.
78 /// All reads from the returned reader will return [`Ok`]`(0)`.
80 /// [`Ok`]: ../result/enum.Result.html#variant.Ok
84 /// A slightly sad example of not reading anything into a buffer:
87 /// use std::io::{self, Read};
89 /// let mut buffer = String::new();
90 /// io::empty().read_to_string(&mut buffer).unwrap();
91 /// assert!(buffer.is_empty());
93 #[stable(feature = "rust1", since = "1.0.0")]
94 pub fn empty() -> Empty { Empty { _priv: () } }
96 #[stable(feature = "rust1", since = "1.0.0")]
99 fn read(&mut self, _buf: &mut [u8]) -> io::Result<usize> { Ok(0) }
102 unsafe fn initializer(&self) -> Initializer {
106 #[stable(feature = "rust1", since = "1.0.0")]
107 impl BufRead for Empty {
109 fn fill_buf(&mut self) -> io::Result<&[u8]> { Ok(&[]) }
111 fn consume(&mut self, _n: usize) {}
114 #[stable(feature = "std_debug", since = "1.16.0")]
115 impl fmt::Debug for Empty {
116 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
117 f.pad("Empty { .. }")
121 /// A reader which yields one byte over and over and over and over and over and...
123 /// This struct is generally created by calling [`repeat`][repeat]. Please
124 /// see the documentation of `repeat()` for more details.
126 /// [repeat]: fn.repeat.html
127 #[stable(feature = "rust1", since = "1.0.0")]
128 pub struct Repeat { byte: u8 }
130 /// Creates an instance of a reader that infinitely repeats one byte.
132 /// All reads from this reader will succeed by filling the specified buffer with
138 /// use std::io::{self, Read};
140 /// let mut buffer = [0; 3];
141 /// io::repeat(0b101).read_exact(&mut buffer).unwrap();
142 /// assert_eq!(buffer, [0b101, 0b101, 0b101]);
144 #[stable(feature = "rust1", since = "1.0.0")]
145 pub fn repeat(byte: u8) -> Repeat { Repeat { byte } }
147 #[stable(feature = "rust1", since = "1.0.0")]
148 impl Read for Repeat {
150 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
151 for slot in &mut *buf {
158 fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
159 let mut nwritten = 0;
161 nwritten += self.read(buf)?;
167 unsafe fn initializer(&self) -> Initializer {
172 #[stable(feature = "std_debug", since = "1.16.0")]
173 impl fmt::Debug for Repeat {
174 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
175 f.pad("Repeat { .. }")
179 /// A writer which will move data into the void.
181 /// This struct is generally created by calling [`sink`][sink]. Please
182 /// see the documentation of `sink()` for more details.
184 /// [sink]: fn.sink.html
185 #[stable(feature = "rust1", since = "1.0.0")]
186 pub struct Sink { _priv: () }
188 /// Creates an instance of a writer which will successfully consume all data.
190 /// All calls to `write` on the returned instance will return `Ok(buf.len())`
191 /// and the contents of the buffer will not be inspected.
196 /// use std::io::{self, Write};
198 /// let buffer = vec![1, 2, 3, 5, 8];
199 /// let num_bytes = io::sink().write(&buffer).unwrap();
200 /// assert_eq!(num_bytes, 5);
202 #[stable(feature = "rust1", since = "1.0.0")]
203 pub fn sink() -> Sink { Sink { _priv: () } }
205 #[stable(feature = "rust1", since = "1.0.0")]
206 impl Write for Sink {
208 fn write(&mut self, buf: &[u8]) -> io::Result<usize> { Ok(buf.len()) }
211 fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
212 let total_len = bufs.iter().map(|b| b.len()).sum();
217 fn flush(&mut self) -> io::Result<()> { Ok(()) }
220 #[stable(feature = "std_debug", since = "1.16.0")]
221 impl fmt::Debug for Sink {
222 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
229 use crate::io::prelude::*;
230 use crate::io::{copy, sink, empty, repeat};
234 let mut r = repeat(0).take(4);
236 assert_eq!(copy(&mut r, &mut w).unwrap(), 4);
238 let mut r = repeat(0).take(1 << 17);
239 assert_eq!(copy(&mut r as &mut dyn Read, &mut w as &mut dyn Write).unwrap(), 1 << 17);
245 assert_eq!(s.write(&[]).unwrap(), 0);
246 assert_eq!(s.write(&[0]).unwrap(), 1);
247 assert_eq!(s.write(&[0; 1024]).unwrap(), 1024);
248 assert_eq!(s.by_ref().write(&[0; 1024]).unwrap(), 1024);
254 assert_eq!(e.read(&mut []).unwrap(), 0);
255 assert_eq!(e.read(&mut [0]).unwrap(), 0);
256 assert_eq!(e.read(&mut [0; 1024]).unwrap(), 0);
257 assert_eq!(e.by_ref().read(&mut [0; 1024]).unwrap(), 0);
261 fn repeat_repeats() {
262 let mut r = repeat(4);
263 let mut b = [0; 1024];
264 assert_eq!(r.read(&mut b).unwrap(), 1024);
265 assert!(b.iter().all(|b| *b == 4));
269 fn take_some_bytes() {
270 assert_eq!(repeat(4).take(100).bytes().count(), 100);
271 assert_eq!(repeat(4).take(100).bytes().next().unwrap().unwrap(), 4);
272 assert_eq!(repeat(1).take(10).chain(repeat(2).take(10)).bytes().count(), 20);