midi_codec/
io.rs

1use core::fmt::Debug;
2use std::io::ErrorKind;
3
4/// A simple read trait suitable for embedded devices.
5pub trait ReadSimple {
6    /// The error type used by this reader.
7    type Error: Debug;
8
9    /// Read up to `buf.len()` bytes into the given buffer,
10    /// returning the exact number of bytes read.
11    ///
12    /// The caller makes no guarantees about the contents of `buf`.
13    ///
14    /// In the case of an error, the contents of `buf` are undefined.
15    fn read_simple(&mut self, buf: &mut [u8]) -> Result<usize, Self::Error>;
16}
17
18#[cfg(feature = "std")]
19impl<T> ReadSimple for T
20where
21    T: std::io::Read,
22{
23    type Error = std::io::Error;
24
25    #[inline]
26    fn read_simple(&mut self, buf: &mut [u8]) -> Result<usize, Self::Error> {
27        let result = self.read(buf);
28
29        if let Err(e) = &result {
30            if e.kind() == ErrorKind::WouldBlock {
31                // tracing::trace!("would block - returning size 0");
32                return Ok(0);
33            }
34        }
35
36        if let Ok(size) = &result {
37            tracing::trace!("read {:#?}", &buf[0..*size]);
38        }
39
40        result
41    }
42}
43
44/// A simple write trait suitable for embedded devices.
45pub trait WriteSimple {
46    /// The error type used by this reader.
47    type Error: Debug;
48
49    /// Write all the bytes in `buf`.
50    ///
51    /// Upon returning an error, the number of bytes written is undefined.
52    fn write_all_simple(&mut self, buf: &[u8]) -> Result<(), Self::Error>;
53}
54
55#[cfg(feature = "std")]
56impl<T> WriteSimple for T
57where
58    T: std::io::Write,
59{
60    type Error = std::io::Error;
61
62    #[inline]
63    fn write_all_simple(&mut self, buf: &[u8]) -> Result<(), Self::Error> {
64        tracing::trace!("writing {:#?}", buf);
65
66        self.write_all(buf)
67    }
68}