synopsys_dw_uart/
embedded_io.rs

1// Copyright 2025 Google LLC
2// This project is dual-licensed under Apache 2.0 and MIT terms.
3// See LICENSE-APACHE and LICENSE-MIT for details.
4
5use super::{SynopsysUart, UartError};
6use embedded_io::{ErrorKind, ErrorType, Read, ReadReady, Write, WriteReady};
7
8impl ErrorType for SynopsysUart<'_> {
9    type Error = UartError;
10}
11
12impl embedded_io::Error for UartError {
13    fn kind(&self) -> ErrorKind {
14        match self {
15            Self::Framing | Self::Parity => ErrorKind::InvalidData,
16            Self::Overrun | Self::Break => ErrorKind::Other,
17        }
18    }
19}
20
21impl Write for SynopsysUart<'_> {
22    fn write(&mut self, buf: &[u8]) -> Result<usize, Self::Error> {
23        if buf.is_empty() {
24            Ok(0)
25        } else {
26            self.write_word(buf[0]);
27            Ok(1)
28        }
29    }
30
31    fn flush(&mut self) -> Result<(), Self::Error> {
32        SynopsysUart::flush(self);
33        Ok(())
34    }
35}
36
37impl WriteReady for SynopsysUart<'_> {
38    fn write_ready(&mut self) -> Result<bool, Self::Error> {
39        Ok(!self.is_tx_fifo_full())
40    }
41}
42
43impl ReadReady for SynopsysUart<'_> {
44    fn read_ready(&mut self) -> Result<bool, Self::Error> {
45        Ok(!self.is_rx_fifo_empty())
46    }
47}
48
49impl Read for SynopsysUart<'_> {
50    fn read(&mut self, buf: &mut [u8]) -> Result<usize, Self::Error> {
51        if buf.is_empty() {
52            Ok(0)
53        } else {
54            // Wait until a byte is available to read.
55            loop {
56                // Read a single byte. No need to wait for more, the caller will retry until it has
57                // as many as it wants.
58                if let Some(byte) = self.read_word()? {
59                    buf[0] = byte;
60                    return Ok(1);
61                }
62            }
63        }
64    }
65}