1use super::SerialPort;
2use core::borrow::BorrowMut;
3use usb_device::bus::UsbBus;
4
5#[derive(Debug)]
6pub struct Error(usb_device::UsbError);
7
8impl From<usb_device::UsbError> for Error {
9 fn from(e: usb_device::UsbError) -> Self {
10 Self(e)
11 }
12}
13
14impl embedded_io::Error for Error {
15 fn kind(&self) -> embedded_io::ErrorKind {
16 match self.0 {
17 usb_device::UsbError::Unsupported => embedded_io::ErrorKind::Unsupported,
18 usb_device::UsbError::BufferOverflow
19 | usb_device::UsbError::EndpointOverflow
20 | usb_device::UsbError::EndpointMemoryOverflow => embedded_io::ErrorKind::OutOfMemory,
21 _ => embedded_io::ErrorKind::Other,
22 }
23 }
24}
25
26impl<Bus: UsbBus, RS: BorrowMut<[u8]>, WS: BorrowMut<[u8]>> embedded_io::ErrorType
27 for SerialPort<'_, Bus, RS, WS>
28{
29 type Error = Error;
30}
31
32impl<Bus: UsbBus, RS: BorrowMut<[u8]>, WS: BorrowMut<[u8]>> embedded_io::Read
33 for SerialPort<'_, Bus, RS, WS>
34{
35 fn read(&mut self, buf: &mut [u8]) -> Result<usize, Self::Error> {
36 loop {
37 match self.read(buf).map_err(From::from) {
38 Ok(0) => {}
41 Err(usb_device::UsbError::WouldBlock) => {}
42 other => return Ok(other?),
43 }
44 }
45 }
46}
47
48impl<Bus: UsbBus, RS: BorrowMut<[u8]>, WS: BorrowMut<[u8]>> embedded_io::ReadReady
49 for SerialPort<'_, Bus, RS, WS>
50{
51 fn read_ready(&mut self) -> Result<bool, Self::Error> {
52 self.poll()?;
53 Ok(self.read_buf.available_read() != 0)
54 }
55}
56
57impl<Bus: UsbBus, RS: BorrowMut<[u8]>, WS: BorrowMut<[u8]>> embedded_io::Write
58 for SerialPort<'_, Bus, RS, WS>
59{
60 fn write(&mut self, buf: &[u8]) -> Result<usize, Self::Error> {
61 if buf.is_empty() {
62 return Ok(0);
63 }
64
65 loop {
66 match self.write(buf) {
67 Ok(0) => {}
70 Err(usb_device::UsbError::WouldBlock) => {}
71 other => return Ok(other?),
72 }
73 }
74 }
75
76 fn flush(&mut self) -> Result<(), Self::Error> {
77 self.flush().map_err(From::from)
78 }
79}
80
81impl<Bus: UsbBus, RS: BorrowMut<[u8]>, WS: BorrowMut<[u8]>> embedded_io::WriteReady
82 for SerialPort<'_, Bus, RS, WS>
83{
84 fn write_ready(&mut self) -> Result<bool, Self::Error> {
85 Ok(self.write_buf.available_write() != 0)
86 }
87}