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