Skip to content

Commit

Permalink
misc: add LogicalUnit::from_ls_bits and use it
Browse files Browse the repository at this point in the history
  • Loading branch information
datdenkikniet committed May 13, 2024
1 parent 3a0e9eb commit f409ef4
Show file tree
Hide file tree
Showing 4 changed files with 25 additions and 14 deletions.
29 changes: 21 additions & 8 deletions src/connection/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -101,18 +101,31 @@ pub enum LogicalUnit {
Three,
}

impl LogicalUnit {
/// Construct a `LogicalUnit` from the two lowest bits of `value`,
/// ignoring all other bits.
pub fn from_low_bits(value: u8) -> Self {
let value = value & 0b11;

match value {
0b00 => Self::Zero,
0b01 => Self::One,
0b10 => Self::Two,
0b11 => Self::Three,
_ => unreachable!("Value bitmasked with 0b11 has value greater than 3"),
}
}
}

impl TryFrom<u8> for LogicalUnit {
type Error = ();

fn try_from(value: u8) -> Result<Self, Self::Error> {
let val = match value {
0 => Self::Zero,
1 => Self::One,
2 => Self::Two,
3 => Self::Three,
_ => return Err(()),
};
Ok(val)
if value <= 0b11 {
Ok(Self::from_low_bits(value))
} else {
Err(())
}
}
}

Expand Down
3 changes: 1 addition & 2 deletions src/storage/sdr/record/fru_device_locator.rs
Original file line number Diff line number Diff line change
Expand Up @@ -68,8 +68,7 @@ impl FruDeviceLocator {
})
};

// NOTE(unwrap): `LogicalUnit::try_from` always succeeds for data masked with 0b11.
let lun = LogicalUnit::try_from((record_data[2] >> 3) & 0b11).unwrap();
let lun = LogicalUnit::from_low_bits(record_data[2] >> 3);
let private_bus_id = record_data[2] & 0b111;
let channel_number = record_data[3];

Expand Down
5 changes: 2 additions & 3 deletions src/storage/sdr/record/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -66,9 +66,8 @@ impl SensorKey {
// NOTE(unwrap): value is guaranteed to be in the correct range due to mask + shift.
let owner_channel = Channel::new((owner_channel_fru_lun & 0xF0) >> 4).unwrap();

let fru_inv_device_owner_lun =
LogicalUnit::try_from((owner_channel_fru_lun >> 2) & 0x3).unwrap();
let owner_lun = LogicalUnit::try_from(owner_channel_fru_lun & 0x3).unwrap();
let fru_inv_device_owner_lun = LogicalUnit::from_low_bits(owner_channel_fru_lun >> 2);
let owner_lun = LogicalUnit::from_low_bits(owner_channel_fru_lun & 0b11);

let sensor_number =
SensorNumber(NonMaxU8::new(record_data[2]).ok_or(ParseError::InvalidSensorNumber)?);
Expand Down
2 changes: 1 addition & 1 deletion src/storage/sel/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,7 @@ impl From<(u8, u8)> for EventGenerator {
channel_number,
}
} else {
let lun = (value.1 & 0x3).try_into().unwrap();
let lun = LogicalUnit::from_low_bits(value.1);

Self::RqSAAndLun {
i2c_addr: i2c_or_sid,
Expand Down

0 comments on commit f409ef4

Please sign in to comment.