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