• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2022, The Android Open Source Project
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 //     http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14 
15 //! Minimal driver for an 8250 UART. This only implements enough to work with the emulated 8250
16 //! provided by crosvm, and won't work with real hardware.
17 
18 use core::fmt::{self, Write};
19 
20 /// The backend for [`Uart`] that abstracts the access to 8250 register map
21 pub trait UartBackend {
22     /// Writes a byte value on the offset to the hardware registers.
write_register_u8(&mut self, offset: usize, byte: u8)23     fn write_register_u8(&mut self, offset: usize, byte: u8);
24 }
25 
26 /// Minimal driver for an 8250 UART. This only implements enough to work with the emulated 8250
27 /// provided by crosvm, and won't work with real hardware.
28 pub struct Uart<Backend: UartBackend> {
29     backend: Backend,
30 }
31 
32 impl<Backend: UartBackend> Uart<Backend> {
33     /// Constructs a new instance of the UART driver with given backend.
create(backend: Backend) -> Self34     pub(crate) fn create(backend: Backend) -> Self {
35         Self { backend }
36     }
37 
38     /// Writes a single byte to the UART.
write_byte(&mut self, byte: u8)39     pub fn write_byte(&mut self, byte: u8) {
40         self.backend.write_register_u8(0, byte)
41     }
42 }
43 
44 impl<Backend: UartBackend> Write for Uart<Backend> {
write_str(&mut self, s: &str) -> fmt::Result45     fn write_str(&mut self, s: &str) -> fmt::Result {
46         for c in s.as_bytes() {
47             self.write_byte(*c);
48         }
49         Ok(())
50     }
51 }
52