embedded_io/impls/
slice_mut.rs

1use crate::{Error, ErrorKind, ErrorType, SliceWriteError, Write, WriteReady};
2use core::mem;
3
4impl Error for SliceWriteError {
5    fn kind(&self) -> ErrorKind {
6        match self {
7            SliceWriteError::Full => ErrorKind::WriteZero,
8        }
9    }
10}
11
12impl ErrorType for &mut [u8] {
13    type Error = SliceWriteError;
14}
15
16impl core::fmt::Display for SliceWriteError {
17    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
18        write!(f, "{self:?}")
19    }
20}
21
22impl core::error::Error for SliceWriteError {}
23
24/// Write is implemented for `&mut [u8]` by copying into the slice, overwriting
25/// its data.
26///
27/// Note that writing updates the slice to point to the yet unwritten part.
28/// The slice will be empty when it has been completely overwritten.
29///
30/// If the number of bytes to be written exceeds the size of the slice, write operations will
31/// return short writes: ultimately, a `SliceWriteError::Full`.
32impl Write for &mut [u8] {
33    #[inline]
34    fn write(&mut self, buf: &[u8]) -> Result<usize, Self::Error> {
35        let amt = core::cmp::min(buf.len(), self.len());
36        if !buf.is_empty() && amt == 0 {
37            return Err(SliceWriteError::Full);
38        }
39        let (a, b) = mem::take(self).split_at_mut(amt);
40        a.copy_from_slice(&buf[..amt]);
41        *self = b;
42        Ok(amt)
43    }
44
45    #[inline]
46    fn write_all(&mut self, buf: &[u8]) -> Result<(), Self::Error> {
47        if self.len() < buf.len() {
48            return Err(SliceWriteError::Full);
49        }
50        self.write(buf)?;
51        Ok(())
52    }
53
54    #[inline]
55    fn flush(&mut self) -> Result<(), Self::Error> {
56        Ok(())
57    }
58}
59
60impl WriteReady for &mut [u8] {
61    #[inline]
62    fn write_ready(&mut self) -> Result<bool, Self::Error> {
63        Ok(true)
64    }
65}