Add safety checks for parsing

This commit is contained in:
Patric Kanngießer 2020-12-29 18:05:20 +01:00
parent 487a379633
commit 96f5135427
2 changed files with 15 additions and 3 deletions

View file

@ -78,7 +78,11 @@ impl From<Message> for Raw {
impl<'a> TryFrom<&'a [u8]> for Message { impl<'a> TryFrom<&'a [u8]> for Message {
type Error = MidiPacketParsingError; type Error = MidiPacketParsingError;
fn try_from(data: &[u8]) -> Result<Self, Self::Error> { fn try_from(data: &[u8]) -> Result<Self, Self::Error> {
let status_byte = data[0]; let status_byte = match data.get(0) {
Some(byte) => byte,
None => return Err(MidiPacketParsingError::MissingDataPacket)
};
let event_type = status_byte & 0b1111_0000; let event_type = status_byte & 0b1111_0000;
let channel_bytes = (status_byte) & 0b0000_1111; let channel_bytes = (status_byte) & 0b0000_1111;

View file

@ -56,14 +56,22 @@ impl TryFrom<&[u8]> for UsbMidiEventPacket {
type Error = MidiPacketParsingError; type Error = MidiPacketParsingError;
fn try_from(value: &[u8]) -> Result<Self, Self::Error> { fn try_from(value: &[u8]) -> Result<Self, Self::Error> {
let raw_cable_number= value[0] >> 4; let raw_cable_number= match value.get(0) {
Some(byte) => *byte >> 4,
None => return Err(MidiPacketParsingError::MissingDataPacket)
};
let cable_number = match CableNumber::try_from(u8::from(raw_cable_number)) { let cable_number = match CableNumber::try_from(u8::from(raw_cable_number)) {
Ok(val) => val, Ok(val) => val,
_ => return Err(MidiPacketParsingError::InvalidCableNumber(raw_cable_number)) _ => return Err(MidiPacketParsingError::InvalidCableNumber(raw_cable_number))
}; };
let message = Message::try_from(&value[1..])?; let message_body = match value.get(1..) {
Some(bytes) => bytes,
None => return Err(MidiPacketParsingError::MissingDataPacket)
};
let message = Message::try_from(message_body)?;
Ok(UsbMidiEventPacket { Ok(UsbMidiEventPacket {
cable_number, cable_number,