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