Skip to content

Commit

Permalink
Added U14 primitive value type
Browse files Browse the repository at this point in the history
  • Loading branch information
sourcebox committed Jan 14, 2025
1 parent 5155ddf commit ae3e65b
Show file tree
Hide file tree
Showing 3 changed files with 80 additions and 0 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.
### Added

- `Message` enum variants for *System Common* and *System Realtime* messages.
- `U14` primitive value type.
- Derive `Debug`, `Clone`, `Eq`, and `PartialEq` for `U4`.
- Derive `Debug`, `Clone`, `Eq`, and `PartialEq` for `InvalidU4`.
- Derive `Debug`, `Clone`, `Eq`, and `PartialEq` for `InvalidU7`.
Expand Down
1 change: 1 addition & 0 deletions src/message/data/mod.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
//! Primitives and structures used in USB MIDI data.
pub mod u14;
pub mod u4;
pub mod u7;

Expand Down
78 changes: 78 additions & 0 deletions src/message/data/u14.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
//! A primitive value with 14-bit length.
use crate::message::data::{FromClamped, FromOverFlow};

/// A primitive value that can be from 0-0x4000
#[derive(Debug, Clone, Eq, PartialEq)]
pub struct U14(u16);

/// Error representing that this value is not a valid u14
#[derive(Debug, Clone, Eq, PartialEq)]
pub struct InvalidU14(pub u16);

impl TryFrom<u16> for U14 {
type Error = InvalidU14;

fn try_from(value: u16) -> Result<Self, Self::Error> {
if value > 0x3FFF {
Err(InvalidU14(value))
} else {
Ok(U14(value))
}
}
}

impl From<U14> for u16 {
fn from(value: U14) -> u16 {
value.0
}
}

impl FromOverFlow<u16> for U14 {
fn from_overflow(value: u16) -> U14 {
const MASK: u16 = 0b0011_1111_1111_1111;
let value = MASK & value;
U14(value)
}
}

impl FromClamped<u16> for U14 {
fn from_clamped(value: u16) -> U14 {
match U14::try_from(value) {
Ok(x) => x,
_ => U14::MAX,
}
}
}

impl U14 {
/// Maximum value for the type.
pub const MAX: U14 = U14(0x3FFF);
/// Minimum value for the type.
pub const MIN: U14 = U14(0);
}

#[cfg(test)]
mod tests {
use super::*;

#[test]
fn try_from_valid() {
assert_eq!(U14::try_from(0x1234), Ok(U14(0x1234)));
}

#[test]
fn try_from_invalid() {
assert_eq!(U14::try_from(0x4000), Err(InvalidU14(0x4000)));
}

#[test]
fn from_overflow() {
assert_eq!(U14::from_overflow(0x400F), U14(0x0F));
}

#[test]
fn from_clamped() {
assert_eq!(U14::from_clamped(0x400F), U14(0x3FFF));
}
}

0 comments on commit ae3e65b

Please sign in to comment.