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