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