|
| 1 | +//! A primitive value with 14-bit length. |
| 2 | +
|
| 3 | +use crate::message::data::{u7::U7, FromClamped, FromOverFlow}; |
| 4 | + |
| 5 | +/// A primitive value that can be from 0-0x4000 |
| 6 | +#[derive(Debug, Clone, Eq, PartialEq)] |
| 7 | +pub struct U14(pub(crate) u16); |
| 8 | + |
| 9 | +/// Error representing that this value is not a valid u14 |
| 10 | +#[derive(Debug, Clone, Eq, PartialEq)] |
| 11 | +pub struct InvalidU14(pub u16); |
| 12 | + |
| 13 | +impl TryFrom<u16> for U14 { |
| 14 | + type Error = InvalidU14; |
| 15 | + |
| 16 | + fn try_from(value: u16) -> Result<Self, Self::Error> { |
| 17 | + if value > 0x3FFF { |
| 18 | + Err(InvalidU14(value)) |
| 19 | + } else { |
| 20 | + Ok(U14(value)) |
| 21 | + } |
| 22 | + } |
| 23 | +} |
| 24 | + |
| 25 | +impl From<U14> for u16 { |
| 26 | + fn from(value: U14) -> u16 { |
| 27 | + value.0 |
| 28 | + } |
| 29 | +} |
| 30 | + |
| 31 | +impl FromOverFlow<u16> for U14 { |
| 32 | + fn from_overflow(value: u16) -> U14 { |
| 33 | + const MASK: u16 = 0b0011_1111_1111_1111; |
| 34 | + let value = MASK & value; |
| 35 | + U14(value) |
| 36 | + } |
| 37 | +} |
| 38 | + |
| 39 | +impl FromClamped<u16> for U14 { |
| 40 | + fn from_clamped(value: u16) -> U14 { |
| 41 | + match U14::try_from(value) { |
| 42 | + Ok(x) => x, |
| 43 | + _ => U14::MAX, |
| 44 | + } |
| 45 | + } |
| 46 | +} |
| 47 | + |
| 48 | +impl U14 { |
| 49 | + /// Maximum value for the type. |
| 50 | + pub const MAX: U14 = U14(0x3FFF); |
| 51 | + /// Minimum value for the type. |
| 52 | + pub const MIN: U14 = U14(0); |
| 53 | + |
| 54 | + /// Creates a new U14 value from an (U7, U7) tuple containing the LSB and MSB. |
| 55 | + pub fn from_split_u7(value: (U7, U7)) -> Self { |
| 56 | + Self((value.0 .0 as u16) | ((value.1 .0 as u16) << 7)) |
| 57 | + } |
| 58 | + |
| 59 | + /// Returns the LSB and MSB of the value as (U7, U7) tuple. |
| 60 | + pub fn split_u7(&self) -> (U7, U7) { |
| 61 | + (U7((self.0 & 0x7F) as u8), U7((self.0 >> 7) as u8)) |
| 62 | + } |
| 63 | +} |
| 64 | + |
| 65 | +#[cfg(test)] |
| 66 | +mod tests { |
| 67 | + use super::*; |
| 68 | + |
| 69 | + #[test] |
| 70 | + fn try_from_valid() { |
| 71 | + assert_eq!(U14::try_from(0x1234), Ok(U14(0x1234))); |
| 72 | + } |
| 73 | + |
| 74 | + #[test] |
| 75 | + fn try_from_invalid() { |
| 76 | + assert_eq!(U14::try_from(0x4000), Err(InvalidU14(0x4000))); |
| 77 | + } |
| 78 | + |
| 79 | + #[test] |
| 80 | + fn from_overflow() { |
| 81 | + assert_eq!(U14::from_overflow(0x400F), U14(0x0F)); |
| 82 | + } |
| 83 | + |
| 84 | + #[test] |
| 85 | + fn from_clamped() { |
| 86 | + assert_eq!(U14::from_clamped(0x400F), U14(0x3FFF)); |
| 87 | + } |
| 88 | + |
| 89 | + #[test] |
| 90 | + fn from_split_u7() { |
| 91 | + assert_eq!(U14::from_split_u7((U7(0x7F), U7(0x6F))), U14(0x37FF)); |
| 92 | + } |
| 93 | + |
| 94 | + #[test] |
| 95 | + fn split_u7() { |
| 96 | + assert_eq!(U14(0x37FF).split_u7(), (U7(0x7F), U7(0x6F))); |
| 97 | + } |
| 98 | +} |
0 commit comments