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 = "CURRENT_RUSTC_VERSION")]
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: usize = bufs.iter().map(|b: &IoSlice<'_>| 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: usize = bufs.iter().map(|b: &IoSlice<'_>| 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 = "CURRENT_RUSTC_VERSION")]
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_buf(&mut self, mut buf: BorrowedCursor<'_>) -> io::Result<()> {
192 // SAFETY: No uninit bytes are being written
193 for slot in unsafe { buf.as_mut() } {
194 slot.write(self.byte);
195 }
196
197 let remaining = buf.capacity();
198
199 // SAFETY: the entire unfilled portion of buf has been initialized
200 unsafe {
201 buf.advance_unchecked(remaining);
202 }
203
204 Ok(())
205 }
206
207 /// This function is not supported by `io::Repeat`, because there's no end of its data
208 fn read_to_end(&mut self, _: &mut Vec<u8>) -> io::Result<usize> {
209 Err(io::Error::from(io::ErrorKind::OutOfMemory))
210 }
211
212 /// This function is not supported by `io::Repeat`, because there's no end of its data
213 fn read_to_string(&mut self, _: &mut String) -> io::Result<usize> {
214 Err(io::Error::from(io::ErrorKind::OutOfMemory))
215 }
216
217 #[inline]
218 fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
219 let mut nwritten = 0;
220 for buf in bufs {
221 nwritten += self.read(buf)?;
222 }
223 Ok(nwritten)
224 }
225
226 #[inline]
227 fn is_read_vectored(&self) -> bool {
228 true
229 }
230}
231
232impl SizeHint for Repeat {
233 #[inline]
234 fn lower_bound(&self) -> usize {
235 usize::MAX
236 }
237
238 #[inline]
239 fn upper_bound(&self) -> Option<usize> {
240 None
241 }
242}
243
244#[stable(feature = "std_debug", since = "1.16.0")]
245impl fmt::Debug for Repeat {
246 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
247 f.debug_struct(name:"Repeat").finish_non_exhaustive()
248 }
249}
250
251/// A writer which will move data into the void.
252///
253/// This struct is generally created by calling [`sink()`]. Please
254/// see the documentation of [`sink()`] for more details.
255#[stable(feature = "rust1", since = "1.0.0")]
256#[non_exhaustive]
257#[derive(Copy, Clone, Debug, Default)]
258pub struct Sink;
259
260/// Creates an instance of a writer which will successfully consume all data.
261///
262/// All calls to [`write`] on the returned instance will return [`Ok(buf.len())`]
263/// and the contents of the buffer will not be inspected.
264///
265/// [`write`]: Write::write
266/// [`Ok(buf.len())`]: Ok
267///
268/// # Examples
269///
270/// ```rust
271/// use std::io::{self, Write};
272///
273/// let buffer = vec![1, 2, 3, 5, 8];
274/// let num_bytes = io::sink().write(&buffer).unwrap();
275/// assert_eq!(num_bytes, 5);
276/// ```
277#[must_use]
278#[stable(feature = "rust1", since = "1.0.0")]
279#[rustc_const_stable(feature = "const_io_structs", since = "CURRENT_RUSTC_VERSION")]
280pub const fn sink() -> Sink {
281 Sink
282}
283
284#[stable(feature = "rust1", since = "1.0.0")]
285impl Write for Sink {
286 #[inline]
287 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
288 Ok(buf.len())
289 }
290
291 #[inline]
292 fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
293 let total_len: usize = bufs.iter().map(|b: &IoSlice<'_>| b.len()).sum();
294 Ok(total_len)
295 }
296
297 #[inline]
298 fn is_write_vectored(&self) -> bool {
299 true
300 }
301
302 #[inline]
303 fn flush(&mut self) -> io::Result<()> {
304 Ok(())
305 }
306}
307
308#[stable(feature = "write_mt", since = "1.48.0")]
309impl Write for &Sink {
310 #[inline]
311 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
312 Ok(buf.len())
313 }
314
315 #[inline]
316 fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
317 let total_len: usize = bufs.iter().map(|b: &IoSlice<'_>| b.len()).sum();
318 Ok(total_len)
319 }
320
321 #[inline]
322 fn is_write_vectored(&self) -> bool {
323 true
324 }
325
326 #[inline]
327 fn flush(&mut self) -> io::Result<()> {
328 Ok(())
329 }
330}
331