portable_io/
impls.rs

1use core::cmp;
2use core::fmt;
3use core::mem;
4
5extern crate alloc;
6use alloc::boxed::Box;
7use alloc::string::String;
8use alloc::vec::Vec;
9
10use crate::{
11    self as io, BufRead, Error, ErrorKind, IoSlice, IoSliceMut, Read, ReadBuf, Seek, SeekFrom,
12    Write,
13};
14
15// =============================================================================
16// Forwarding implementations
17
18impl<R: Read + ?Sized> Read for &mut R {
19    #[inline]
20    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
21        (**self).read(buf)
22    }
23
24    #[inline]
25    fn read_buf(&mut self, buf: &mut ReadBuf<'_>) -> io::Result<()> {
26        (**self).read_buf(buf)
27    }
28
29    #[inline]
30    fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
31        (**self).read_vectored(bufs)
32    }
33
34    #[inline]
35    fn is_read_vectored(&self) -> bool {
36        (**self).is_read_vectored()
37    }
38
39    #[inline]
40    fn read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<usize> {
41        (**self).read_to_end(buf)
42    }
43
44    #[inline]
45    fn read_to_string(&mut self, buf: &mut String) -> io::Result<usize> {
46        (**self).read_to_string(buf)
47    }
48
49    #[inline]
50    fn read_exact(&mut self, buf: &mut [u8]) -> io::Result<()> {
51        (**self).read_exact(buf)
52    }
53}
54impl<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}
85impl<S: Seek + ?Sized> Seek for &mut S {
86    #[inline]
87    fn seek(&mut self, pos: SeekFrom) -> io::Result<u64> {
88        (**self).seek(pos)
89    }
90
91    #[inline]
92    fn stream_position(&mut self) -> io::Result<u64> {
93        (**self).stream_position()
94    }
95}
96impl<B: BufRead + ?Sized> BufRead for &mut B {
97    #[inline]
98    fn fill_buf(&mut self) -> io::Result<&[u8]> {
99        (**self).fill_buf()
100    }
101
102    #[inline]
103    fn consume(&mut self, amt: usize) {
104        (**self).consume(amt)
105    }
106
107    #[inline]
108    fn read_until(&mut self, byte: u8, buf: &mut Vec<u8>) -> io::Result<usize> {
109        (**self).read_until(byte, buf)
110    }
111
112    #[inline]
113    fn read_line(&mut self, buf: &mut String) -> io::Result<usize> {
114        (**self).read_line(buf)
115    }
116}
117
118impl<R: Read + ?Sized> Read for Box<R> {
119    #[inline]
120    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
121        (**self).read(buf)
122    }
123
124    #[inline]
125    fn read_buf(&mut self, buf: &mut ReadBuf<'_>) -> io::Result<()> {
126        (**self).read_buf(buf)
127    }
128
129    #[inline]
130    fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
131        (**self).read_vectored(bufs)
132    }
133
134    #[inline]
135    fn is_read_vectored(&self) -> bool {
136        (**self).is_read_vectored()
137    }
138
139    #[inline]
140    fn read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<usize> {
141        (**self).read_to_end(buf)
142    }
143
144    #[inline]
145    fn read_to_string(&mut self, buf: &mut String) -> io::Result<usize> {
146        (**self).read_to_string(buf)
147    }
148
149    #[inline]
150    fn read_exact(&mut self, buf: &mut [u8]) -> io::Result<()> {
151        (**self).read_exact(buf)
152    }
153}
154impl<W: Write + ?Sized> Write for Box<W> {
155    #[inline]
156    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
157        (**self).write(buf)
158    }
159
160    #[inline]
161    fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
162        (**self).write_vectored(bufs)
163    }
164
165    #[inline]
166    fn is_write_vectored(&self) -> bool {
167        (**self).is_write_vectored()
168    }
169
170    #[inline]
171    fn flush(&mut self) -> io::Result<()> {
172        (**self).flush()
173    }
174
175    #[inline]
176    fn write_all(&mut self, buf: &[u8]) -> io::Result<()> {
177        (**self).write_all(buf)
178    }
179
180    #[inline]
181    fn write_fmt(&mut self, fmt: fmt::Arguments<'_>) -> io::Result<()> {
182        (**self).write_fmt(fmt)
183    }
184}
185impl<S: Seek + ?Sized> Seek for Box<S> {
186    #[inline]
187    fn seek(&mut self, pos: SeekFrom) -> io::Result<u64> {
188        (**self).seek(pos)
189    }
190
191    #[inline]
192    fn stream_position(&mut self) -> io::Result<u64> {
193        (**self).stream_position()
194    }
195}
196impl<B: BufRead + ?Sized> BufRead for Box<B> {
197    #[inline]
198    fn fill_buf(&mut self) -> io::Result<&[u8]> {
199        (**self).fill_buf()
200    }
201
202    #[inline]
203    fn consume(&mut self, amt: usize) {
204        (**self).consume(amt)
205    }
206
207    #[inline]
208    fn read_until(&mut self, byte: u8, buf: &mut Vec<u8>) -> io::Result<usize> {
209        (**self).read_until(byte, buf)
210    }
211
212    #[inline]
213    fn read_line(&mut self, buf: &mut String) -> io::Result<usize> {
214        (**self).read_line(buf)
215    }
216}
217
218// =============================================================================
219// In-memory buffer implementations
220
221/// Read is implemented for `&[u8]` by copying from the slice.
222///
223/// Note that reading updates the slice to point to the yet unread part.
224/// The slice will be empty when EOF is reached.
225impl Read for &[u8] {
226    #[inline]
227    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
228        let amt = cmp::min(buf.len(), self.len());
229        let (a, b) = self.split_at(amt);
230
231        // First check if the amount of bytes we want to read is small:
232        // `copy_from_slice` will generally expand to a call to `memcpy`, and
233        // for a single byte the overhead is significant.
234        if amt == 1 {
235            buf[0] = a[0];
236        } else {
237            buf[..amt].copy_from_slice(a);
238        }
239
240        *self = b;
241        Ok(amt)
242    }
243
244    #[inline]
245    fn read_buf(&mut self, buf: &mut ReadBuf<'_>) -> io::Result<()> {
246        let amt = cmp::min(buf.remaining(), self.len());
247        let (a, b) = self.split_at(amt);
248
249        buf.append(a);
250
251        *self = b;
252        Ok(())
253    }
254
255    #[inline]
256    fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
257        let mut nread = 0;
258        for buf in bufs {
259            nread += self.read(buf)?;
260            if self.is_empty() {
261                break;
262            }
263        }
264
265        Ok(nread)
266    }
267
268    #[inline]
269    fn is_read_vectored(&self) -> bool {
270        true
271    }
272
273    #[inline]
274    fn read_exact(&mut self, buf: &mut [u8]) -> io::Result<()> {
275        if buf.len() > self.len() {
276            return Err(Error::new_const(ErrorKind::UnexpectedEof, &"failed to fill whole buffer"));
277        }
278        let (a, b) = self.split_at(buf.len());
279
280        // First check if the amount of bytes we want to read is small:
281        // `copy_from_slice` will generally expand to a call to `memcpy`, and
282        // for a single byte the overhead is significant.
283        if buf.len() == 1 {
284            buf[0] = a[0];
285        } else {
286            buf.copy_from_slice(a);
287        }
288
289        *self = b;
290        Ok(())
291    }
292
293    #[inline]
294    fn read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<usize> {
295        buf.extend_from_slice(*self);
296        let len = self.len();
297        *self = &self[len..];
298        Ok(len)
299    }
300}
301
302impl BufRead for &[u8] {
303    #[inline]
304    fn fill_buf(&mut self) -> io::Result<&[u8]> {
305        Ok(*self)
306    }
307
308    #[inline]
309    fn consume(&mut self, amt: usize) {
310        *self = &self[amt..];
311    }
312}
313
314/// Write is implemented for `&mut [u8]` by copying into the slice, overwriting
315/// its data.
316///
317/// Note that writing updates the slice to point to the yet unwritten part.
318/// The slice will be empty when it has been completely overwritten.
319///
320/// If the number of bytes to be written exceeds the size of the slice, write operations will
321/// return short writes: ultimately, `Ok(0)`; in this situation, `write_all` returns an error of
322/// kind `ErrorKind::WriteZero`.
323impl Write for &mut [u8] {
324    #[inline]
325    fn write(&mut self, data: &[u8]) -> io::Result<usize> {
326        let amt = cmp::min(data.len(), self.len());
327        let (a, b) = mem::replace(self, &mut []).split_at_mut(amt);
328        a.copy_from_slice(&data[..amt]);
329        *self = b;
330        Ok(amt)
331    }
332
333    #[inline]
334    fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
335        let mut nwritten = 0;
336        for buf in bufs {
337            nwritten += self.write(buf)?;
338            if self.is_empty() {
339                break;
340            }
341        }
342
343        Ok(nwritten)
344    }
345
346    #[inline]
347    fn is_write_vectored(&self) -> bool {
348        true
349    }
350
351    #[inline]
352    fn write_all(&mut self, data: &[u8]) -> io::Result<()> {
353        if self.write(data)? == data.len() {
354            Ok(())
355        } else {
356            Err(Error::new_const(ErrorKind::WriteZero, &"failed to write whole buffer"))
357        }
358    }
359
360    #[inline]
361    fn flush(&mut self) -> io::Result<()> {
362        Ok(())
363    }
364}
365
366/// Write is implemented for `Vec<u8>` by appending to the vector.
367/// The vector will grow as needed.
368///
369/// NOTE: Unlike `std::io`, this does not support `Write` for `Vec` with a custom allocator.
370impl Write for Vec<u8> {
371    #[inline]
372    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
373        self.extend_from_slice(buf);
374        Ok(buf.len())
375    }
376
377    #[inline]
378    fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
379        let len = bufs.iter().map(|b| b.len()).sum();
380        self.reserve(len);
381        for buf in bufs {
382            self.extend_from_slice(buf);
383        }
384        Ok(len)
385    }
386
387    #[inline]
388    fn is_write_vectored(&self) -> bool {
389        true
390    }
391
392    #[inline]
393    fn write_all(&mut self, buf: &[u8]) -> io::Result<()> {
394        self.extend_from_slice(buf);
395        Ok(())
396    }
397
398    #[inline]
399    fn flush(&mut self) -> io::Result<()> {
400        Ok(())
401    }
402}