midi-codec 0.4.0

Tools for encoding and decoding a stream of MIDI messages.
Documentation
use core::fmt::Debug;
use std::io::ErrorKind;

/// A simple read trait suitable for embedded devices.
pub trait ReadSimple {
    /// The error type used by this reader.
    type Error: Debug;

    /// Read up to `buf.len()` bytes into the given buffer,
    /// returning the exact number of bytes read.
    ///
    /// The caller makes no guarantees about the contents of `buf`.
    ///
    /// In the case of an error, the contents of `buf` are undefined.
    fn read_simple(&mut self, buf: &mut [u8]) -> Result<usize, Self::Error>;
}

#[cfg(feature = "std")]
impl<T> ReadSimple for T
where
    T: std::io::Read,
{
    type Error = std::io::Error;

    #[inline]
    fn read_simple(&mut self, buf: &mut [u8]) -> Result<usize, Self::Error> {
        let result = self.read(buf);

        if let Err(e) = &result {
            if e.kind() == ErrorKind::WouldBlock {
                // tracing::trace!("would block - returning size 0");
                return Ok(0);
            }
        }

        if let Ok(size) = &result {
            tracing::trace!("read {:#?}", &buf[0..*size]);
        }

        result
    }
}

/// A simple write trait suitable for embedded devices.
pub trait WriteSimple {
    /// The error type used by this reader.
    type Error: Debug;

    /// Write all the bytes in `buf`.
    ///
    /// Upon returning an error, the number of bytes written is undefined.
    fn write_all_simple(&mut self, buf: &[u8]) -> Result<(), Self::Error>;
}

#[cfg(feature = "std")]
impl<T> WriteSimple for T
where
    T: std::io::Write,
{
    type Error = std::io::Error;

    #[inline]
    fn write_all_simple(&mut self, buf: &[u8]) -> Result<(), Self::Error> {
        tracing::trace!("writing {:#?}", buf);

        self.write_all(buf)
    }
}