]> git.lizzy.rs Git - rust.git/blob - library/std/src/io/impls.rs
Rollup merge of #98776 - notriddle:notriddle/mobile-sidebar-auto-close, r=GuillaumeGomez
[rust.git] / library / std / src / io / impls.rs
1 #[cfg(test)]
2 mod tests;
3
4 use crate::alloc::Allocator;
5 use crate::cmp;
6 use crate::collections::VecDeque;
7 use crate::fmt;
8 use crate::io::{
9     self, BufRead, ErrorKind, IoSlice, IoSliceMut, Read, ReadBuf, Seek, SeekFrom, Write,
10 };
11 use crate::mem;
12
13 // =============================================================================
14 // Forwarding implementations
15
16 #[stable(feature = "rust1", since = "1.0.0")]
17 impl<R: Read + ?Sized> Read for &mut R {
18     #[inline]
19     fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
20         (**self).read(buf)
21     }
22
23     #[inline]
24     fn read_buf(&mut self, buf: &mut ReadBuf<'_>) -> io::Result<()> {
25         (**self).read_buf(buf)
26     }
27
28     #[inline]
29     fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
30         (**self).read_vectored(bufs)
31     }
32
33     #[inline]
34     fn is_read_vectored(&self) -> bool {
35         (**self).is_read_vectored()
36     }
37
38     #[inline]
39     fn read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<usize> {
40         (**self).read_to_end(buf)
41     }
42
43     #[inline]
44     fn read_to_string(&mut self, buf: &mut String) -> io::Result<usize> {
45         (**self).read_to_string(buf)
46     }
47
48     #[inline]
49     fn read_exact(&mut self, buf: &mut [u8]) -> io::Result<()> {
50         (**self).read_exact(buf)
51     }
52 }
53 #[stable(feature = "rust1", since = "1.0.0")]
54 impl<W: Write + ?Sized> Write for &mut W {
55     #[inline]
56     fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
57         (**self).write(buf)
58     }
59
60     #[inline]
61     fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
62         (**self).write_vectored(bufs)
63     }
64
65     #[inline]
66     fn is_write_vectored(&self) -> bool {
67         (**self).is_write_vectored()
68     }
69
70     #[inline]
71     fn flush(&mut self) -> io::Result<()> {
72         (**self).flush()
73     }
74
75     #[inline]
76     fn write_all(&mut self, buf: &[u8]) -> io::Result<()> {
77         (**self).write_all(buf)
78     }
79
80     #[inline]
81     fn write_fmt(&mut self, fmt: fmt::Arguments<'_>) -> io::Result<()> {
82         (**self).write_fmt(fmt)
83     }
84 }
85 #[stable(feature = "rust1", since = "1.0.0")]
86 impl<S: Seek + ?Sized> Seek for &mut S {
87     #[inline]
88     fn seek(&mut self, pos: SeekFrom) -> io::Result<u64> {
89         (**self).seek(pos)
90     }
91
92     #[inline]
93     fn stream_position(&mut self) -> io::Result<u64> {
94         (**self).stream_position()
95     }
96 }
97 #[stable(feature = "rust1", since = "1.0.0")]
98 impl<B: BufRead + ?Sized> BufRead for &mut B {
99     #[inline]
100     fn fill_buf(&mut self) -> io::Result<&[u8]> {
101         (**self).fill_buf()
102     }
103
104     #[inline]
105     fn consume(&mut self, amt: usize) {
106         (**self).consume(amt)
107     }
108
109     #[inline]
110     fn read_until(&mut self, byte: u8, buf: &mut Vec<u8>) -> io::Result<usize> {
111         (**self).read_until(byte, buf)
112     }
113
114     #[inline]
115     fn read_line(&mut self, buf: &mut String) -> io::Result<usize> {
116         (**self).read_line(buf)
117     }
118 }
119
120 #[stable(feature = "rust1", since = "1.0.0")]
121 impl<R: Read + ?Sized> Read for Box<R> {
122     #[inline]
123     fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
124         (**self).read(buf)
125     }
126
127     #[inline]
128     fn read_buf(&mut self, buf: &mut ReadBuf<'_>) -> io::Result<()> {
129         (**self).read_buf(buf)
130     }
131
132     #[inline]
133     fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
134         (**self).read_vectored(bufs)
135     }
136
137     #[inline]
138     fn is_read_vectored(&self) -> bool {
139         (**self).is_read_vectored()
140     }
141
142     #[inline]
143     fn read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<usize> {
144         (**self).read_to_end(buf)
145     }
146
147     #[inline]
148     fn read_to_string(&mut self, buf: &mut String) -> io::Result<usize> {
149         (**self).read_to_string(buf)
150     }
151
152     #[inline]
153     fn read_exact(&mut self, buf: &mut [u8]) -> io::Result<()> {
154         (**self).read_exact(buf)
155     }
156 }
157 #[stable(feature = "rust1", since = "1.0.0")]
158 impl<W: Write + ?Sized> Write for Box<W> {
159     #[inline]
160     fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
161         (**self).write(buf)
162     }
163
164     #[inline]
165     fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
166         (**self).write_vectored(bufs)
167     }
168
169     #[inline]
170     fn is_write_vectored(&self) -> bool {
171         (**self).is_write_vectored()
172     }
173
174     #[inline]
175     fn flush(&mut self) -> io::Result<()> {
176         (**self).flush()
177     }
178
179     #[inline]
180     fn write_all(&mut self, buf: &[u8]) -> io::Result<()> {
181         (**self).write_all(buf)
182     }
183
184     #[inline]
185     fn write_fmt(&mut self, fmt: fmt::Arguments<'_>) -> io::Result<()> {
186         (**self).write_fmt(fmt)
187     }
188 }
189 #[stable(feature = "rust1", since = "1.0.0")]
190 impl<S: Seek + ?Sized> Seek for Box<S> {
191     #[inline]
192     fn seek(&mut self, pos: SeekFrom) -> io::Result<u64> {
193         (**self).seek(pos)
194     }
195
196     #[inline]
197     fn stream_position(&mut self) -> io::Result<u64> {
198         (**self).stream_position()
199     }
200 }
201 #[stable(feature = "rust1", since = "1.0.0")]
202 impl<B: BufRead + ?Sized> BufRead for Box<B> {
203     #[inline]
204     fn fill_buf(&mut self) -> io::Result<&[u8]> {
205         (**self).fill_buf()
206     }
207
208     #[inline]
209     fn consume(&mut self, amt: usize) {
210         (**self).consume(amt)
211     }
212
213     #[inline]
214     fn read_until(&mut self, byte: u8, buf: &mut Vec<u8>) -> io::Result<usize> {
215         (**self).read_until(byte, buf)
216     }
217
218     #[inline]
219     fn read_line(&mut self, buf: &mut String) -> io::Result<usize> {
220         (**self).read_line(buf)
221     }
222 }
223
224 // =============================================================================
225 // In-memory buffer implementations
226
227 /// Read is implemented for `&[u8]` by copying from the slice.
228 ///
229 /// Note that reading updates the slice to point to the yet unread part.
230 /// The slice will be empty when EOF is reached.
231 #[stable(feature = "rust1", since = "1.0.0")]
232 impl Read for &[u8] {
233     #[inline]
234     fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
235         let amt = cmp::min(buf.len(), self.len());
236         let (a, b) = self.split_at(amt);
237
238         // First check if the amount of bytes we want to read is small:
239         // `copy_from_slice` will generally expand to a call to `memcpy`, and
240         // for a single byte the overhead is significant.
241         if amt == 1 {
242             buf[0] = a[0];
243         } else {
244             buf[..amt].copy_from_slice(a);
245         }
246
247         *self = b;
248         Ok(amt)
249     }
250
251     #[inline]
252     fn read_buf(&mut self, buf: &mut ReadBuf<'_>) -> io::Result<()> {
253         let amt = cmp::min(buf.remaining(), self.len());
254         let (a, b) = self.split_at(amt);
255
256         buf.append(a);
257
258         *self = b;
259         Ok(())
260     }
261
262     #[inline]
263     fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
264         let mut nread = 0;
265         for buf in bufs {
266             nread += self.read(buf)?;
267             if self.is_empty() {
268                 break;
269             }
270         }
271
272         Ok(nread)
273     }
274
275     #[inline]
276     fn is_read_vectored(&self) -> bool {
277         true
278     }
279
280     #[inline]
281     fn read_exact(&mut self, buf: &mut [u8]) -> io::Result<()> {
282         if buf.len() > self.len() {
283             return Err(io::const_io_error!(
284                 ErrorKind::UnexpectedEof,
285                 "failed to fill whole buffer"
286             ));
287         }
288         let (a, b) = self.split_at(buf.len());
289
290         // First check if the amount of bytes we want to read is small:
291         // `copy_from_slice` will generally expand to a call to `memcpy`, and
292         // for a single byte the overhead is significant.
293         if buf.len() == 1 {
294             buf[0] = a[0];
295         } else {
296             buf.copy_from_slice(a);
297         }
298
299         *self = b;
300         Ok(())
301     }
302
303     #[inline]
304     fn read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<usize> {
305         buf.extend_from_slice(*self);
306         let len = self.len();
307         *self = &self[len..];
308         Ok(len)
309     }
310 }
311
312 #[stable(feature = "rust1", since = "1.0.0")]
313 impl BufRead for &[u8] {
314     #[inline]
315     fn fill_buf(&mut self) -> io::Result<&[u8]> {
316         Ok(*self)
317     }
318
319     #[inline]
320     fn consume(&mut self, amt: usize) {
321         *self = &self[amt..];
322     }
323 }
324
325 /// Write is implemented for `&mut [u8]` by copying into the slice, overwriting
326 /// its data.
327 ///
328 /// Note that writing updates the slice to point to the yet unwritten part.
329 /// The slice will be empty when it has been completely overwritten.
330 ///
331 /// If the number of bytes to be written exceeds the size of the slice, write operations will
332 /// return short writes: ultimately, `Ok(0)`; in this situation, `write_all` returns an error of
333 /// kind `ErrorKind::WriteZero`.
334 #[stable(feature = "rust1", since = "1.0.0")]
335 impl Write for &mut [u8] {
336     #[inline]
337     fn write(&mut self, data: &[u8]) -> io::Result<usize> {
338         let amt = cmp::min(data.len(), self.len());
339         let (a, b) = mem::replace(self, &mut []).split_at_mut(amt);
340         a.copy_from_slice(&data[..amt]);
341         *self = b;
342         Ok(amt)
343     }
344
345     #[inline]
346     fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
347         let mut nwritten = 0;
348         for buf in bufs {
349             nwritten += self.write(buf)?;
350             if self.is_empty() {
351                 break;
352             }
353         }
354
355         Ok(nwritten)
356     }
357
358     #[inline]
359     fn is_write_vectored(&self) -> bool {
360         true
361     }
362
363     #[inline]
364     fn write_all(&mut self, data: &[u8]) -> io::Result<()> {
365         if self.write(data)? == data.len() {
366             Ok(())
367         } else {
368             Err(io::const_io_error!(ErrorKind::WriteZero, "failed to write whole buffer"))
369         }
370     }
371
372     #[inline]
373     fn flush(&mut self) -> io::Result<()> {
374         Ok(())
375     }
376 }
377
378 /// Write is implemented for `Vec<u8>` by appending to the vector.
379 /// The vector will grow as needed.
380 #[stable(feature = "rust1", since = "1.0.0")]
381 impl<A: Allocator> Write for Vec<u8, A> {
382     #[inline]
383     fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
384         self.extend_from_slice(buf);
385         Ok(buf.len())
386     }
387
388     #[inline]
389     fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
390         let len = bufs.iter().map(|b| b.len()).sum();
391         self.reserve(len);
392         for buf in bufs {
393             self.extend_from_slice(buf);
394         }
395         Ok(len)
396     }
397
398     #[inline]
399     fn is_write_vectored(&self) -> bool {
400         true
401     }
402
403     #[inline]
404     fn write_all(&mut self, buf: &[u8]) -> io::Result<()> {
405         self.extend_from_slice(buf);
406         Ok(())
407     }
408
409     #[inline]
410     fn flush(&mut self) -> io::Result<()> {
411         Ok(())
412     }
413 }
414
415 /// Read is implemented for `VecDeque<u8>` by consuming bytes from the front of the `VecDeque`.
416 #[stable(feature = "vecdeque_read_write", since = "1.63.0")]
417 impl<A: Allocator> Read for VecDeque<u8, A> {
418     /// Fill `buf` with the contents of the "front" slice as returned by
419     /// [`as_slices`][`VecDeque::as_slices`]. If the contained byte slices of the `VecDeque` are
420     /// discontiguous, multiple calls to `read` will be needed to read the entire content.
421     #[inline]
422     fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
423         let (ref mut front, _) = self.as_slices();
424         let n = Read::read(front, buf)?;
425         self.drain(..n);
426         Ok(n)
427     }
428
429     #[inline]
430     fn read_buf(&mut self, buf: &mut ReadBuf<'_>) -> io::Result<()> {
431         let (ref mut front, _) = self.as_slices();
432         let n = cmp::min(buf.remaining(), front.len());
433         Read::read_buf(front, buf)?;
434         self.drain(..n);
435         Ok(())
436     }
437 }
438
439 /// Write is implemented for `VecDeque<u8>` by appending to the `VecDeque`, growing it as needed.
440 #[stable(feature = "vecdeque_read_write", since = "1.63.0")]
441 impl<A: Allocator> Write for VecDeque<u8, A> {
442     #[inline]
443     fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
444         self.extend(buf);
445         Ok(buf.len())
446     }
447
448     #[inline]
449     fn write_all(&mut self, buf: &[u8]) -> io::Result<()> {
450         self.extend(buf);
451         Ok(())
452     }
453
454     #[inline]
455     fn flush(&mut self) -> io::Result<()> {
456         Ok(())
457     }
458 }