embedded_io/impls/
slice_ref.rs

1use crate::{BufRead, ErrorType, Read, ReadReady};
2
3impl 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.
11impl Read for &[u8] {
12    #[inline]
13    fn read(&mut self, buf: &mut [u8]) -> Result<usize, Self::Error> {
14        let amt = core::cmp::min(buf.len(), self.len());
15        let (a, b) = self.split_at(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(a);
24        }
25
26        *self = b;
27        Ok(amt)
28    }
29
30    #[inline]
31    fn read_exact(&mut self, buf: &mut [u8]) -> Result<(), crate::ReadExactError<Self::Error>> {
32        if self.len() < buf.len() {
33            return Err(crate::ReadExactError::UnexpectedEof);
34        }
35        self.read(buf)?;
36        Ok(())
37    }
38}
39
40impl BufRead for &[u8] {
41    #[inline]
42    fn fill_buf(&mut self) -> Result<&[u8], Self::Error> {
43        Ok(*self)
44    }
45
46    #[inline]
47    fn consume(&mut self, amt: usize) {
48        *self = &self[amt..];
49    }
50}
51
52impl ReadReady for &[u8] {
53    #[inline]
54    fn read_ready(&mut self) -> Result<bool, Self::Error> {
55        Ok(true)
56    }
57}