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    #[inline]
72    fn read_vectored(&mut self, _bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
73        Ok(0)
74    }
75
76    #[inline]
77    fn is_read_vectored(&self) -> bool {
78        // Do not force `Chain<Empty, T>` or `Chain<T, Empty>` to use vectored
79        // reads, unless the other reader is vectored.
80        false
81    }
82
83    #[inline]
84    fn read_exact(&mut self, buf: &mut [u8]) -> io::Result<()> {
85        if !buf.is_empty() { Err(io::Error::READ_EXACT_EOF) } else { Ok(()) }
86    }
87
88    #[inline]
89    fn read_buf_exact(&mut self, cursor: BorrowedCursor<'_>) -> io::Result<()> {
90        if cursor.capacity() != 0 { Err(io::Error::READ_EXACT_EOF) } else { Ok(()) }
91    }
92
93    #[inline]
94    fn read_to_end(&mut self, _buf: &mut Vec<u8>) -> io::Result<usize> {
95        Ok(0)
96    }
97
98    #[inline]
99    fn read_to_string(&mut self, _buf: &mut String) -> io::Result<usize> {
100        Ok(0)
101    }
102}
103#[stable(feature = "rust1", since = "1.0.0")]
104impl BufRead for Empty {
105    #[inline]
106    fn fill_buf(&mut self) -> io::Result<&[u8]> {
107        Ok(&[])
108    }
109
110    #[inline]
111    fn consume(&mut self, _n: usize) {}
112
113    #[inline]
114    fn has_data_left(&mut self) -> io::Result<bool> {
115        Ok(false)
116    }
117
118    #[inline]
119    fn read_until(&mut self, _byte: u8, _buf: &mut Vec<u8>) -> io::Result<usize> {
120        Ok(0)
121    }
122
123    #[inline]
124    fn skip_until(&mut self, _byte: u8) -> io::Result<usize> {
125        Ok(0)
126    }
127
128    #[inline]
129    fn read_line(&mut self, _buf: &mut String) -> io::Result<usize> {
130        Ok(0)
131    }
132}
133
134#[stable(feature = "empty_seek", since = "1.51.0")]
135impl Seek for Empty {
136    #[inline]
137    fn seek(&mut self, _pos: SeekFrom) -> io::Result<u64> {
138        Ok(0)
139    }
140
141    #[inline]
142    fn stream_len(&mut self) -> io::Result<u64> {
143        Ok(0)
144    }
145
146    #[inline]
147    fn stream_position(&mut self) -> io::Result<u64> {
148        Ok(0)
149    }
150}
151
152impl SizeHint for Empty {
153    #[inline]
154    fn upper_bound(&self) -> Option<usize> {
155        Some(0)
156    }
157}
158
159#[stable(feature = "empty_write", since = "1.73.0")]
160impl Write for Empty {
161    #[inline]
162    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
163        Ok(buf.len())
164    }
165
166    #[inline]
167    fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
168        let total_len = bufs.iter().map(|b| b.len()).sum();
169        Ok(total_len)
170    }
171
172    #[inline]
173    fn is_write_vectored(&self) -> bool {
174        true
175    }
176
177    #[inline]
178    fn write_all(&mut self, _buf: &[u8]) -> io::Result<()> {
179        Ok(())
180    }
181
182    #[inline]
183    fn write_all_vectored(&mut self, _bufs: &mut [IoSlice<'_>]) -> io::Result<()> {
184        Ok(())
185    }
186
187    #[inline]
188    fn write_fmt(&mut self, _args: fmt::Arguments<'_>) -> io::Result<()> {
189        Ok(())
190    }
191
192    #[inline]
193    fn flush(&mut self) -> io::Result<()> {
194        Ok(())
195    }
196}
197
198#[stable(feature = "empty_write", since = "1.73.0")]
199impl Write for &Empty {
200    #[inline]
201    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
202        Ok(buf.len())
203    }
204
205    #[inline]
206    fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
207        let total_len = bufs.iter().map(|b| b.len()).sum();
208        Ok(total_len)
209    }
210
211    #[inline]
212    fn is_write_vectored(&self) -> bool {
213        true
214    }
215
216    #[inline]
217    fn write_all(&mut self, _buf: &[u8]) -> io::Result<()> {
218        Ok(())
219    }
220
221    #[inline]
222    fn write_all_vectored(&mut self, _bufs: &mut [IoSlice<'_>]) -> io::Result<()> {
223        Ok(())
224    }
225
226    #[inline]
227    fn write_fmt(&mut self, _args: fmt::Arguments<'_>) -> io::Result<()> {
228        Ok(())
229    }
230
231    #[inline]
232    fn flush(&mut self) -> io::Result<()> {
233        Ok(())
234    }
235}
236
237/// A reader which yields one byte over and over and over and over and over and...
238///
239/// This struct is generally created by calling [`repeat()`]. Please
240/// see the documentation of [`repeat()`] for more details.
241#[stable(feature = "rust1", since = "1.0.0")]
242pub struct Repeat {
243    byte: u8,
244}
245
246/// Creates an instance of a reader that infinitely repeats one byte.
247///
248/// All reads from this reader will succeed by filling the specified buffer with
249/// the given byte.
250///
251/// # Examples
252///
253/// ```
254/// use std::io::{self, Read};
255///
256/// let mut buffer = [0; 3];
257/// io::repeat(0b101).read_exact(&mut buffer).unwrap();
258/// assert_eq!(buffer, [0b101, 0b101, 0b101]);
259/// ```
260#[must_use]
261#[stable(feature = "rust1", since = "1.0.0")]
262#[rustc_const_stable(feature = "const_io_structs", since = "1.79.0")]
263pub const fn repeat(byte: u8) -> Repeat {
264    Repeat { byte }
265}
266
267#[stable(feature = "rust1", since = "1.0.0")]
268impl Read for Repeat {
269    #[inline]
270    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
271        buf.fill(self.byte);
272        Ok(buf.len())
273    }
274
275    #[inline]
276    fn read_exact(&mut self, buf: &mut [u8]) -> io::Result<()> {
277        buf.fill(self.byte);
278        Ok(())
279    }
280
281    #[inline]
282    fn read_buf(&mut self, mut buf: BorrowedCursor<'_>) -> io::Result<()> {
283        // SAFETY: No uninit bytes are being written.
284        unsafe { buf.as_mut() }.write_filled(self.byte);
285        // SAFETY: the entire unfilled portion of buf has been initialized.
286        unsafe { buf.advance_unchecked(buf.capacity()) };
287        Ok(())
288    }
289
290    #[inline]
291    fn read_buf_exact(&mut self, buf: BorrowedCursor<'_>) -> io::Result<()> {
292        self.read_buf(buf)
293    }
294
295    /// This function is not supported by `io::Repeat`, because there's no end of its data
296    fn read_to_end(&mut self, _: &mut Vec<u8>) -> io::Result<usize> {
297        Err(io::Error::from(io::ErrorKind::OutOfMemory))
298    }
299
300    /// This function is not supported by `io::Repeat`, because there's no end of its data
301    fn read_to_string(&mut self, _: &mut String) -> io::Result<usize> {
302        Err(io::Error::from(io::ErrorKind::OutOfMemory))
303    }
304
305    #[inline]
306    fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
307        let mut nwritten = 0;
308        for buf in bufs {
309            nwritten += self.read(buf)?;
310        }
311        Ok(nwritten)
312    }
313
314    #[inline]
315    fn is_read_vectored(&self) -> bool {
316        true
317    }
318}
319
320impl SizeHint for Repeat {
321    #[inline]
322    fn lower_bound(&self) -> usize {
323        usize::MAX
324    }
325
326    #[inline]
327    fn upper_bound(&self) -> Option<usize> {
328        None
329    }
330}
331
332#[stable(feature = "std_debug", since = "1.16.0")]
333impl fmt::Debug for Repeat {
334    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
335        f.debug_struct("Repeat").finish_non_exhaustive()
336    }
337}
338
339/// A writer which will move data into the void.
340///
341/// This struct is generally created by calling [`sink()`]. Please
342/// see the documentation of [`sink()`] for more details.
343#[stable(feature = "rust1", since = "1.0.0")]
344#[non_exhaustive]
345#[derive(Copy, Clone, Debug, Default)]
346pub struct Sink;
347
348/// Creates an instance of a writer which will successfully consume all data.
349///
350/// All calls to [`write`] on the returned instance will return [`Ok(buf.len())`]
351/// and the contents of the buffer will not be inspected.
352///
353/// [`write`]: Write::write
354/// [`Ok(buf.len())`]: Ok
355///
356/// # Examples
357///
358/// ```rust
359/// use std::io::{self, Write};
360///
361/// let buffer = vec![1, 2, 3, 5, 8];
362/// let num_bytes = io::sink().write(&buffer).unwrap();
363/// assert_eq!(num_bytes, 5);
364/// ```
365#[must_use]
366#[stable(feature = "rust1", since = "1.0.0")]
367#[rustc_const_stable(feature = "const_io_structs", since = "1.79.0")]
368pub const fn sink() -> Sink {
369    Sink
370}
371
372#[stable(feature = "rust1", since = "1.0.0")]
373impl Write for Sink {
374    #[inline]
375    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
376        Ok(buf.len())
377    }
378
379    #[inline]
380    fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
381        let total_len = bufs.iter().map(|b| b.len()).sum();
382        Ok(total_len)
383    }
384
385    #[inline]
386    fn is_write_vectored(&self) -> bool {
387        true
388    }
389
390    #[inline]
391    fn write_all(&mut self, _buf: &[u8]) -> io::Result<()> {
392        Ok(())
393    }
394
395    #[inline]
396    fn write_all_vectored(&mut self, _bufs: &mut [IoSlice<'_>]) -> io::Result<()> {
397        Ok(())
398    }
399
400    #[inline]
401    fn write_fmt(&mut self, _args: fmt::Arguments<'_>) -> io::Result<()> {
402        Ok(())
403    }
404
405    #[inline]
406    fn flush(&mut self) -> io::Result<()> {
407        Ok(())
408    }
409}
410
411#[stable(feature = "write_mt", since = "1.48.0")]
412impl Write for &Sink {
413    #[inline]
414    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
415        Ok(buf.len())
416    }
417
418    #[inline]
419    fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
420        let total_len = bufs.iter().map(|b| b.len()).sum();
421        Ok(total_len)
422    }
423
424    #[inline]
425    fn is_write_vectored(&self) -> bool {
426        true
427    }
428
429    #[inline]
430    fn write_all(&mut self, _buf: &[u8]) -> io::Result<()> {
431        Ok(())
432    }
433
434    #[inline]
435    fn write_all_vectored(&mut self, _bufs: &mut [IoSlice<'_>]) -> io::Result<()> {
436        Ok(())
437    }
438
439    #[inline]
440    fn write_fmt(&mut self, _args: fmt::Arguments<'_>) -> io::Result<()> {
441        Ok(())
442    }
443
444    #[inline]
445    fn flush(&mut self) -> io::Result<()> {
446        Ok(())
447    }
448}