Skip to content

Commit

Permalink
Added CodeIndexNumber::event_size function
Browse files Browse the repository at this point in the history
  • Loading branch information
sourcebox committed Dec 19, 2024
1 parent 98d0626 commit 4947626
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 8 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.
- `TryFrom<&UsbMidiEventPacket>` implementation for `Message` type.
- `Message::into_packet` function.
- `Message::code_index_number` function.
- `CodeIndexNumber::event_size()` function.
- Re-exports of common items in crate root.

### Changed
Expand Down
25 changes: 25 additions & 0 deletions src/packet/code_index_number.rs
Original file line number Diff line number Diff line change
Expand Up @@ -90,3 +90,28 @@ impl From<CodeIndexNumber> for U4 {
U4::from_overflowing_u8(value as u8)
}
}

impl CodeIndexNumber {
/// Returns the size of the MIDI_x event in bytes.
pub fn event_size(&self) -> usize {
match self {
Self::SystemCommon1Byte | Self::SingleByte => 1,
Self::SystemCommon2Bytes
| Self::SysexEnds2Bytes
| Self::ProgramChange
| Self::ChannelPressure => 2,
Self::SystemCommon3Bytes
| Self::SysexEnds3Bytes
| Self::SysexStartsOrContinues
| Self::NoteOff
| Self::NoteOn
| Self::PolyKeyPress
| Self::ControlChange
| Self::PitchBendChange => 3,

// These variants are reserved for future use.
// We assume the maximum length of 3 bytes so that no data can get lost.
Self::MiscFunction | Self::CableEvents => 3,
}
}
}
13 changes: 5 additions & 8 deletions src/packet/event_packet.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ use crate::data::u4::U4;
use crate::message::raw::{Payload, Raw};
use crate::message::Message;
use crate::packet::cable_number::CableNumber;
use crate::packet::code_index_number::CodeIndexNumber;

/// A packet that communicates with the host.
///
Expand Down Expand Up @@ -65,21 +66,17 @@ impl TryFrom<&[u8]> for UsbMidiEventPacket {
impl UsbMidiEventPacket {
/// Returns the cable number.
pub fn cable_number(&self) -> CableNumber {
let raw_cable_number = self.raw.first().unwrap() >> 4;
let raw_cable_number = self.raw[0] >> 4;

CableNumber::try_from(raw_cable_number).unwrap()
}

/// Returns a slice to the message bytes. The length is dependent on the message type.
pub fn as_message_bytes(&self) -> &[u8] {
let r = Raw::from(Message::try_from(self).unwrap());
let length = match r.payload {
Payload::Empty => 1,
Payload::SingleByte(_) => 2,
Payload::DoubleByte(_, _) => 3,
};
let cin = CodeIndexNumber::try_from(self.raw[0] & 0x0F).unwrap();
let size = cin.event_size();

&self.raw[1..1 + length]
&self.raw[1..1 + size]
}

/// Returns a reference to the raw bytes.
Expand Down

0 comments on commit 4947626

Please sign in to comment.