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