opentitanlib/io/console/
ext.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::time::Duration;
6
7use anyhow::Result;
8
9use super::ConsoleDevice;
10
11/// Extension trait to [`Uart`] where useful methods are provided.
12pub trait ConsoleExt {
13    /// Reads UART receive data into `buf`, returning the number of bytes read.
14    /// This function is blocking.
15    fn read(&self, buf: &mut [u8]) -> Result<usize>;
16
17    /// Reads UART receive data into `buf`, returning the number of bytes read.
18    /// The `timeout` may be used to specify a duration to wait for data.
19    /// If timeout expires without any data arriving `Ok(0)` will be returned, never `Err(_)`.
20    fn read_timeout(&self, buf: &mut [u8], timeout: Duration) -> Result<usize>;
21}
22
23impl<T: ConsoleDevice + ?Sized> ConsoleExt for T {
24    fn read(&self, buf: &mut [u8]) -> Result<usize> {
25        crate::util::runtime::block_on(std::future::poll_fn(|cx| self.poll_read(cx, buf)))
26    }
27
28    fn read_timeout(&self, buf: &mut [u8], timeout: Duration) -> Result<usize> {
29        crate::util::runtime::block_on(async {
30            tokio::time::timeout(timeout, std::future::poll_fn(|cx| self.poll_read(cx, buf))).await
31        })
32        .unwrap_or(Ok(0))
33    }
34}