1 | use crate::{BufRead, ErrorType, Read}; |
2 | |
3 | impl ErrorType for &[u8] { |
4 | type Error = core::convert::Infallible; |
5 | } |
6 | |
7 | /// Read is implemented for `&[u8]` by copying from the slice. |
8 | /// |
9 | /// Note that reading updates the slice to point to the yet unread part. |
10 | /// The slice will be empty when EOF is reached. |
11 | impl Read for &[u8] { |
12 | #[inline ] |
13 | fn read(&mut self, buf: &mut [u8]) -> Result<usize, Self::Error> { |
14 | let amt: usize = core::cmp::min(v1:buf.len(), self.len()); |
15 | let (a: &[u8], b: &[u8]) = self.split_at(mid:amt); |
16 | |
17 | // First check if the amount of bytes we want to read is small: |
18 | // `copy_from_slice` will generally expand to a call to `memcpy`, and |
19 | // for a single byte the overhead is significant. |
20 | if amt == 1 { |
21 | buf[0] = a[0]; |
22 | } else { |
23 | buf[..amt].copy_from_slice(src:a); |
24 | } |
25 | |
26 | *self = b; |
27 | Ok(amt) |
28 | } |
29 | } |
30 | |
31 | impl BufRead for &[u8] { |
32 | #[inline ] |
33 | fn fill_buf(&mut self) -> Result<&[u8], Self::Error> { |
34 | Ok(*self) |
35 | } |
36 | |
37 | #[inline ] |
38 | fn consume(&mut self, amt: usize) { |
39 | *self = &self[amt..]; |
40 | } |
41 | } |
42 | |