opentitanlib/io/
console.rs

1// Copyright lowRISC contributors (OpenTitan project).
2// Licensed under the Apache License, Version 2.0, see LICENSE for details.
3// SPDX-License-Identifier: Apache-2.0
4
5use std::task::{Context, Poll};
6
7use anyhow::Result;
8use serde::{Deserialize, Serialize};
9use thiserror::Error;
10
11use crate::impl_serializable_error;
12
13pub mod broadcast;
14mod buf;
15pub mod ext;
16mod logged;
17pub use broadcast::Broadcaster;
18pub use buf::Buffered;
19pub use ext::ConsoleExt;
20pub use logged::Logged;
21
22/// Errors related to the console interface.
23#[derive(Error, Debug, Serialize, Deserialize)]
24pub enum ConsoleError {
25    #[error("Timed Out")]
26    TimedOut,
27    #[error("{0}")]
28    GenericError(String),
29}
30impl_serializable_error!(ConsoleError);
31
32pub trait ConsoleDevice {
33    /// Reads received data into `buf`, returning the number of bytes read.
34    ///
35    /// If data is not yet ready, `Poll::Pending` will be returned and `cx` would be notified when it's available.
36    /// When this function is called with multiple wakers, all wakers should be notified instead of just the last one.
37    fn poll_read(&self, cx: &mut Context<'_>, buf: &mut [u8]) -> Poll<Result<usize>>;
38
39    /// Writes data from `buf` to the UART.
40    fn write(&self, buf: &[u8]) -> Result<()>;
41}
42
43impl<T: ConsoleDevice + ?Sized> ConsoleDevice for &T {
44    fn poll_read(&self, cx: &mut Context<'_>, buf: &mut [u8]) -> Poll<Result<usize>> {
45        T::poll_read(self, cx, buf)
46    }
47
48    /// Writes data from `buf` to the UART.
49    fn write(&self, buf: &[u8]) -> Result<()> {
50        T::write(self, buf)
51    }
52}
53
54impl<T: ConsoleDevice + ?Sized> ConsoleDevice for std::rc::Rc<T> {
55    fn poll_read(&self, cx: &mut Context<'_>, buf: &mut [u8]) -> Poll<Result<usize>> {
56        T::poll_read(self, cx, buf)
57    }
58
59    /// Writes data from `buf` to the UART.
60    fn write(&self, buf: &[u8]) -> Result<()> {
61        T::write(self, buf)
62    }
63}