1use crate::{Error, ErrorKind, ErrorType, SliceWriteError, Write};
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
22#[cfg(feature = "std")]
23#[cfg_attr(docsrs, doc(cfg(feature = "std")))]
24impl std::error::Error for SliceWriteError {}
25
26/// Write is implemented for `&mut [u8]` by copying into the slice, overwriting
27/// its data.
28///
29/// Note that writing updates the slice to point to the yet unwritten part.
30/// The slice will be empty when it has been completely overwritten.
31///
32/// If the number of bytes to be written exceeds the size of the slice, write operations will
33/// return short writes: ultimately, a `SliceWriteError::Full`.
34impl Write for &mut [u8] {
35 #[inline]
36 fn write(&mut self, buf: &[u8]) -> Result<usize, Self::Error> {
37 let amt: usize = core::cmp::min(v1:buf.len(), self.len());
38 if !buf.is_empty() && amt == 0 {
39 return Err(SliceWriteError::Full);
40 }
41 let (a: &mut [u8], b: &mut [u8]) = mem::take(self).split_at_mut(mid:amt);
42 a.copy_from_slice(&buf[..amt]);
43 *self = b;
44 Ok(amt)
45 }
46
47 #[inline]
48 fn flush(&mut self) -> Result<(), Self::Error> {
49 Ok(())
50 }
51}
52