]> git.lizzy.rs Git - rust.git/blob - library/std/src/io/util.rs
protect `std::io::Take::limit` from overflow in `read`
[rust.git] / library / std / src / io / util.rs
1 #![allow(missing_copy_implementations)]
2
3 #[cfg(test)]
4 mod tests;
5
6 use crate::fmt;
7 use crate::io::{
8     self, BufRead, IoSlice, IoSliceMut, Read, ReadBuf, Seek, SeekFrom, SizeHint, Write,
9 };
10
11 /// A reader which is always at EOF.
12 ///
13 /// This struct is generally created by calling [`empty()`]. Please see
14 /// the documentation of [`empty()`] for more details.
15 #[stable(feature = "rust1", since = "1.0.0")]
16 #[non_exhaustive]
17 #[derive(Copy, Clone, Default)]
18 pub struct Empty;
19
20 /// Constructs a new handle to an empty reader.
21 ///
22 /// All reads from the returned reader will return <code>[Ok]\(0)</code>.
23 ///
24 /// # Examples
25 ///
26 /// A slightly sad example of not reading anything into a buffer:
27 ///
28 /// ```
29 /// use std::io::{self, Read};
30 ///
31 /// let mut buffer = String::new();
32 /// io::empty().read_to_string(&mut buffer).unwrap();
33 /// assert!(buffer.is_empty());
34 /// ```
35 #[must_use]
36 #[stable(feature = "rust1", since = "1.0.0")]
37 #[rustc_const_unstable(feature = "const_io_structs", issue = "78812")]
38 pub const fn empty() -> Empty {
39     Empty
40 }
41
42 #[stable(feature = "rust1", since = "1.0.0")]
43 impl Read for Empty {
44     #[inline]
45     fn read(&mut self, _buf: &mut [u8]) -> io::Result<usize> {
46         Ok(0)
47     }
48
49     #[inline]
50     fn read_buf(&mut self, _buf: &mut ReadBuf<'_>) -> io::Result<()> {
51         Ok(())
52     }
53 }
54 #[stable(feature = "rust1", since = "1.0.0")]
55 impl BufRead for Empty {
56     #[inline]
57     fn fill_buf(&mut self) -> io::Result<&[u8]> {
58         Ok(&[])
59     }
60     #[inline]
61     fn consume(&mut self, _n: usize) {}
62 }
63
64 #[stable(feature = "empty_seek", since = "1.51.0")]
65 impl Seek for Empty {
66     fn seek(&mut self, _pos: SeekFrom) -> io::Result<u64> {
67         Ok(0)
68     }
69
70     fn stream_len(&mut self) -> io::Result<u64> {
71         Ok(0)
72     }
73
74     fn stream_position(&mut self) -> io::Result<u64> {
75         Ok(0)
76     }
77 }
78
79 #[stable(feature = "std_debug", since = "1.16.0")]
80 impl fmt::Debug for Empty {
81     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
82         f.debug_struct("Empty").finish_non_exhaustive()
83     }
84 }
85
86 impl SizeHint for Empty {
87     #[inline]
88     fn upper_bound(&self) -> Option<usize> {
89         Some(0)
90     }
91 }
92
93 /// A reader which yields one byte over and over and over and over and over and...
94 ///
95 /// This struct is generally created by calling [`repeat()`]. Please
96 /// see the documentation of [`repeat()`] for more details.
97 #[stable(feature = "rust1", since = "1.0.0")]
98 pub struct Repeat {
99     byte: u8,
100 }
101
102 /// Creates an instance of a reader that infinitely repeats one byte.
103 ///
104 /// All reads from this reader will succeed by filling the specified buffer with
105 /// the given byte.
106 ///
107 /// # Examples
108 ///
109 /// ```
110 /// use std::io::{self, Read};
111 ///
112 /// let mut buffer = [0; 3];
113 /// io::repeat(0b101).read_exact(&mut buffer).unwrap();
114 /// assert_eq!(buffer, [0b101, 0b101, 0b101]);
115 /// ```
116 #[must_use]
117 #[stable(feature = "rust1", since = "1.0.0")]
118 #[rustc_const_unstable(feature = "const_io_structs", issue = "78812")]
119 pub const fn repeat(byte: u8) -> Repeat {
120     Repeat { byte }
121 }
122
123 #[stable(feature = "rust1", since = "1.0.0")]
124 impl Read for Repeat {
125     #[inline]
126     fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
127         for slot in &mut *buf {
128             *slot = self.byte;
129         }
130         Ok(buf.len())
131     }
132
133     fn read_buf(&mut self, buf: &mut ReadBuf<'_>) -> io::Result<()> {
134         // SAFETY: No uninit bytes are being written
135         for slot in unsafe { buf.unfilled_mut() } {
136             slot.write(self.byte);
137         }
138
139         let remaining = buf.remaining();
140
141         // SAFETY: the entire unfilled portion of buf has been initialized
142         unsafe {
143             buf.assume_init(remaining);
144         }
145
146         buf.add_filled(remaining);
147
148         Ok(())
149     }
150
151     #[inline]
152     fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
153         let mut nwritten = 0;
154         for buf in bufs {
155             nwritten += self.read(buf)?;
156         }
157         Ok(nwritten)
158     }
159
160     #[inline]
161     fn is_read_vectored(&self) -> bool {
162         true
163     }
164 }
165
166 impl SizeHint for Repeat {
167     #[inline]
168     fn lower_bound(&self) -> usize {
169         usize::MAX
170     }
171
172     #[inline]
173     fn upper_bound(&self) -> Option<usize> {
174         None
175     }
176 }
177
178 #[stable(feature = "std_debug", since = "1.16.0")]
179 impl fmt::Debug for Repeat {
180     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
181         f.debug_struct("Repeat").finish_non_exhaustive()
182     }
183 }
184
185 /// A writer which will move data into the void.
186 ///
187 /// This struct is generally created by calling [`sink`]. Please
188 /// see the documentation of [`sink()`] for more details.
189 #[stable(feature = "rust1", since = "1.0.0")]
190 #[non_exhaustive]
191 #[derive(Copy, Clone, Default)]
192 pub struct Sink;
193
194 /// Creates an instance of a writer which will successfully consume all data.
195 ///
196 /// All calls to [`write`] on the returned instance will return `Ok(buf.len())`
197 /// and the contents of the buffer will not be inspected.
198 ///
199 /// [`write`]: Write::write
200 ///
201 /// # Examples
202 ///
203 /// ```rust
204 /// use std::io::{self, Write};
205 ///
206 /// let buffer = vec![1, 2, 3, 5, 8];
207 /// let num_bytes = io::sink().write(&buffer).unwrap();
208 /// assert_eq!(num_bytes, 5);
209 /// ```
210 #[must_use]
211 #[stable(feature = "rust1", since = "1.0.0")]
212 #[rustc_const_unstable(feature = "const_io_structs", issue = "78812")]
213 pub const fn sink() -> Sink {
214     Sink
215 }
216
217 #[stable(feature = "rust1", since = "1.0.0")]
218 impl Write for Sink {
219     #[inline]
220     fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
221         Ok(buf.len())
222     }
223
224     #[inline]
225     fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
226         let total_len = bufs.iter().map(|b| b.len()).sum();
227         Ok(total_len)
228     }
229
230     #[inline]
231     fn is_write_vectored(&self) -> bool {
232         true
233     }
234
235     #[inline]
236     fn flush(&mut self) -> io::Result<()> {
237         Ok(())
238     }
239 }
240
241 #[stable(feature = "write_mt", since = "1.48.0")]
242 impl Write for &Sink {
243     #[inline]
244     fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
245         Ok(buf.len())
246     }
247
248     #[inline]
249     fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
250         let total_len = bufs.iter().map(|b| b.len()).sum();
251         Ok(total_len)
252     }
253
254     #[inline]
255     fn is_write_vectored(&self) -> bool {
256         true
257     }
258
259     #[inline]
260     fn flush(&mut self) -> io::Result<()> {
261         Ok(())
262     }
263 }
264
265 #[stable(feature = "std_debug", since = "1.16.0")]
266 impl fmt::Debug for Sink {
267     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
268         f.debug_struct("Sink").finish_non_exhaustive()
269     }
270 }