spi_memory_async/
error.rs

1use core::fmt::{self, Debug, Display};
2use embedded_hal_async::spi::SpiDevice;
3use embedded_storage::nor_flash::NorFlashError;
4
5/// The error type used by this library.
6///
7/// This can encapsulate an SPI error, and adds its own protocol errors
8/// on top of that.
9#[non_exhaustive]
10pub enum Error<SPI: SpiDevice<u8>> {
11    /// The arguments are not properly aligned.
12    NotAligned,
13    /// The arguments are out of bounds.
14    OutOfBounds,
15    /// An SPI transfer failed.
16    Spi(SPI::Error),
17    /// Status register contained unexpected flags.
18    ///
19    /// This can happen when the chip is faulty, incorrectly connected, or the
20    /// driver wasn't constructed or destructed properly (eg. while there is
21    /// still a write in progress).
22    UnexpectedStatus,
23}
24
25impl<SPI: SpiDevice<u8>> NorFlashError for Error<SPI> {
26    fn kind(&self) -> embedded_storage::nor_flash::NorFlashErrorKind {
27        use embedded_storage::nor_flash::NorFlashErrorKind;
28        match self {
29            Error::NotAligned => NorFlashErrorKind::NotAligned,
30            Error::OutOfBounds => NorFlashErrorKind::OutOfBounds,
31            Error::Spi(_) => NorFlashErrorKind::Other,
32            Error::UnexpectedStatus => NorFlashErrorKind::Other,
33        }
34    }
35}
36
37impl<SPI: SpiDevice<u8>> Debug for Error<SPI> {
38    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
39        match self {
40            Error::NotAligned => f.write_str("Error::NotAligned"),
41            Error::OutOfBounds => f.write_str("Error::OutOfBounds"),
42            Error::Spi(spi) => write!(f, "Error::Spi({:?})", spi),
43            Error::UnexpectedStatus => f.write_str("Error::UnexpectedStatus"),
44        }
45    }
46}
47
48impl<SPI: SpiDevice<u8>> Display for Error<SPI>
49where
50    SPI::Error: Display,
51{
52    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
53        match self {
54            Error::NotAligned => f.write_str("arguments are not properly aligned"),
55            Error::OutOfBounds => f.write_str("arguments are out of bounds"),
56            Error::Spi(spi) => write!(f, "SPI error: {}", spi),
57            Error::UnexpectedStatus => f.write_str("unexpected value in status register"),
58        }
59    }
60}
61
62impl<SPI: SpiDevice<u8>> defmt::Format for Error<SPI>
63where
64    SPI::Error: defmt::Format,
65{
66    fn format(&self, f: defmt::Formatter<'_>) {
67        match self {
68            Error::NotAligned => defmt::write!(f, "arguments are not properly aligned"),
69            Error::OutOfBounds => defmt::write!(f, "arguments are out of bounds"),
70            Error::Spi(spi) => defmt::write!(f, "SPI error: {}", spi),
71            Error::UnexpectedStatus => defmt::write!(f, "unexpected value in status register"),
72        }
73    }
74}