std/io/
util.rs

1#![allow(missing_copy_implementations)]
2
3#[cfg(test)]
4mod tests;
5
6use crate::fmt;
7use crate::io::{
8    self, BorrowedCursor, BufRead, IoSlice, IoSliceMut, Read, Seek, SeekFrom, SizeHint, Write,
9};
10use crate::mem::MaybeUninit;
11
12/// `Empty` ignores any data written via [`Write`], and will always be empty
13/// (returning zero bytes) when read via [`Read`].
14///
15/// This struct is generally created by calling [`empty()`]. Please
16/// see the documentation of [`empty()`] for more details.
17#[stable(feature = "rust1", since = "1.0.0")]
18#[non_exhaustive]
19#[derive(Copy, Clone, Debug, Default)]
20pub struct Empty;
21
22/// Creates a value that is always at EOF for reads, and ignores all data written.
23///
24/// All calls to [`write`] on the returned instance will return [`Ok(buf.len())`]
25/// and the contents of the buffer will not be inspected.
26///
27/// All calls to [`read`] from the returned reader will return [`Ok(0)`].
28///
29/// [`Ok(buf.len())`]: Ok
30/// [`Ok(0)`]: Ok
31///
32/// [`write`]: Write::write
33/// [`read`]: Read::read
34///
35/// # Examples
36///
37/// ```rust
38/// use std::io::{self, Write};
39///
40/// let buffer = vec![1, 2, 3, 5, 8];
41/// let num_bytes = io::empty().write(&buffer).unwrap();
42/// assert_eq!(num_bytes, 5);
43/// ```
44///
45///
46/// ```rust
47/// use std::io::{self, Read};
48///
49/// let mut buffer = String::new();
50/// io::empty().read_to_string(&mut buffer).unwrap();
51/// assert!(buffer.is_empty());
52/// ```
53#[must_use]
54#[stable(feature = "rust1", since = "1.0.0")]
55#[rustc_const_stable(feature = "const_io_structs", since = "1.79.0")]
56pub const fn empty() -> Empty {
57    Empty
58}
59
60#[stable(feature = "rust1", since = "1.0.0")]
61impl Read for Empty {
62    #[inline]
63    fn read(&mut self, _buf: &mut [u8]) -> io::Result<usize> {
64        Ok(0)
65    }
66
67    #[inline]
68    fn read_buf(&mut self, _cursor: BorrowedCursor<'_>) -> io::Result<()> {
69        Ok(())
70    }
71}
72#[stable(feature = "rust1", since = "1.0.0")]
73impl BufRead for Empty {
74    #[inline]
75    fn fill_buf(&mut self) -> io::Result<&[u8]> {
76        Ok(&[])
77    }
78    #[inline]
79    fn consume(&mut self, _n: usize) {}
80}
81
82#[stable(feature = "empty_seek", since = "1.51.0")]
83impl Seek for Empty {
84    fn seek(&mut self, _pos: SeekFrom) -> io::Result<u64> {
85        Ok(0)
86    }
87
88    fn stream_len(&mut self) -> io::Result<u64> {
89        Ok(0)
90    }
91
92    fn stream_position(&mut self) -> io::Result<u64> {
93        Ok(0)
94    }
95}
96
97impl SizeHint for Empty {
98    #[inline]
99    fn upper_bound(&self) -> Option<usize> {
100        Some(0)
101    }
102}
103
104#[stable(feature = "empty_write", since = "1.73.0")]
105impl Write for Empty {
106    #[inline]
107    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
108        Ok(buf.len())
109    }
110
111    #[inline]
112    fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
113        let total_len = bufs.iter().map(|b| b.len()).sum();
114        Ok(total_len)
115    }
116
117    #[inline]
118    fn is_write_vectored(&self) -> bool {
119        true
120    }
121
122    #[inline]
123    fn flush(&mut self) -> io::Result<()> {
124        Ok(())
125    }
126}
127
128#[stable(feature = "empty_write", since = "1.73.0")]
129impl Write for &Empty {
130    #[inline]
131    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
132        Ok(buf.len())
133    }
134
135    #[inline]
136    fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
137        let total_len = bufs.iter().map(|b| b.len()).sum();
138        Ok(total_len)
139    }
140
141    #[inline]
142    fn is_write_vectored(&self) -> bool {
143        true
144    }
145
146    #[inline]
147    fn flush(&mut self) -> io::Result<()> {
148        Ok(())
149    }
150}
151
152/// A reader which yields one byte over and over and over and over and over and...
153///
154/// This struct is generally created by calling [`repeat()`]. Please
155/// see the documentation of [`repeat()`] for more details.
156#[stable(feature = "rust1", since = "1.0.0")]
157pub struct Repeat {
158    byte: u8,
159}
160
161/// Creates an instance of a reader that infinitely repeats one byte.
162///
163/// All reads from this reader will succeed by filling the specified buffer with
164/// the given byte.
165///
166/// # Examples
167///
168/// ```
169/// use std::io::{self, Read};
170///
171/// let mut buffer = [0; 3];
172/// io::repeat(0b101).read_exact(&mut buffer).unwrap();
173/// assert_eq!(buffer, [0b101, 0b101, 0b101]);
174/// ```
175#[must_use]
176#[stable(feature = "rust1", since = "1.0.0")]
177#[rustc_const_stable(feature = "const_io_structs", since = "1.79.0")]
178pub const fn repeat(byte: u8) -> Repeat {
179    Repeat { byte }
180}
181
182#[stable(feature = "rust1", since = "1.0.0")]
183impl Read for Repeat {
184    #[inline]
185    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
186        buf.fill(self.byte);
187        Ok(buf.len())
188    }
189
190    #[inline]
191    fn read_exact(&mut self, buf: &mut [u8]) -> io::Result<()> {
192        buf.fill(self.byte);
193        Ok(())
194    }
195
196    #[inline]
197    fn read_buf(&mut self, mut buf: BorrowedCursor<'_>) -> io::Result<()> {
198        // SAFETY: No uninit bytes are being written.
199        MaybeUninit::fill(unsafe { buf.as_mut() }, self.byte);
200        // SAFETY: the entire unfilled portion of buf has been initialized.
201        unsafe { buf.advance_unchecked(buf.capacity()) };
202        Ok(())
203    }
204
205    #[inline]
206    fn read_buf_exact(&mut self, buf: BorrowedCursor<'_>) -> io::Result<()> {
207        self.read_buf(buf)
208    }
209
210    /// This function is not supported by `io::Repeat`, because there's no end of its data
211    fn read_to_end(&mut self, _: &mut Vec<u8>) -> io::Result<usize> {
212        Err(io::Error::from(io::ErrorKind::OutOfMemory))
213    }
214
215    /// This function is not supported by `io::Repeat`, because there's no end of its data
216    fn read_to_string(&mut self, _: &mut String) -> io::Result<usize> {
217        Err(io::Error::from(io::ErrorKind::OutOfMemory))
218    }
219
220    #[inline]
221    fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
222        let mut nwritten = 0;
223        for buf in bufs {
224            nwritten += self.read(buf)?;
225        }
226        Ok(nwritten)
227    }
228
229    #[inline]
230    fn is_read_vectored(&self) -> bool {
231        true
232    }
233}
234
235impl SizeHint for Repeat {
236    #[inline]
237    fn lower_bound(&self) -> usize {
238        usize::MAX
239    }
240
241    #[inline]
242    fn upper_bound(&self) -> Option<usize> {
243        None
244    }
245}
246
247#[stable(feature = "std_debug", since = "1.16.0")]
248impl fmt::Debug for Repeat {
249    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
250        f.debug_struct("Repeat").finish_non_exhaustive()
251    }
252}
253
254/// A writer which will move data into the void.
255///
256/// This struct is generally created by calling [`sink()`]. Please
257/// see the documentation of [`sink()`] for more details.
258#[stable(feature = "rust1", since = "1.0.0")]
259#[non_exhaustive]
260#[derive(Copy, Clone, Debug, Default)]
261pub struct Sink;
262
263/// Creates an instance of a writer which will successfully consume all data.
264///
265/// All calls to [`write`] on the returned instance will return [`Ok(buf.len())`]
266/// and the contents of the buffer will not be inspected.
267///
268/// [`write`]: Write::write
269/// [`Ok(buf.len())`]: Ok
270///
271/// # Examples
272///
273/// ```rust
274/// use std::io::{self, Write};
275///
276/// let buffer = vec![1, 2, 3, 5, 8];
277/// let num_bytes = io::sink().write(&buffer).unwrap();
278/// assert_eq!(num_bytes, 5);
279/// ```
280#[must_use]
281#[stable(feature = "rust1", since = "1.0.0")]
282#[rustc_const_stable(feature = "const_io_structs", since = "1.79.0")]
283pub const fn sink() -> Sink {
284    Sink
285}
286
287#[stable(feature = "rust1", since = "1.0.0")]
288impl Write for Sink {
289    #[inline]
290    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
291        Ok(buf.len())
292    }
293
294    #[inline]
295    fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
296        let total_len = bufs.iter().map(|b| b.len()).sum();
297        Ok(total_len)
298    }
299
300    #[inline]
301    fn is_write_vectored(&self) -> bool {
302        true
303    }
304
305    #[inline]
306    fn flush(&mut self) -> io::Result<()> {
307        Ok(())
308    }
309}
310
311#[stable(feature = "write_mt", since = "1.48.0")]
312impl Write for &Sink {
313    #[inline]
314    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
315        Ok(buf.len())
316    }
317
318    #[inline]
319    fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
320        let total_len = bufs.iter().map(|b| b.len()).sum();
321        Ok(total_len)
322    }
323
324    #[inline]
325    fn is_write_vectored(&self) -> bool {
326        true
327    }
328
329    #[inline]
330    fn flush(&mut self) -> io::Result<()> {
331        Ok(())
332    }
333}