embedded_io_async/impls/
slice_ref.rs

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 = core::cmp::min(buf.len(), self.len());
11        let (a, b) = self.split_at(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(a);
20        }
21
22        *self = b;
23        Ok(amt)
24    }
25
26    async fn read_exact(
27        &mut self,
28        buf: &mut [u8],
29    ) -> Result<(), embedded_io::ReadExactError<Self::Error>> {
30        if self.len() < buf.len() {
31            return Err(crate::ReadExactError::UnexpectedEof);
32        }
33        self.read(buf).await?;
34        Ok(())
35    }
36}
37
38impl BufRead for &[u8] {
39    #[inline]
40    async fn fill_buf(&mut self) -> Result<&[u8], Self::Error> {
41        Ok(*self)
42    }
43
44    #[inline]
45    fn consume(&mut self, amt: usize) {
46        *self = &self[amt..];
47    }
48}