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