Skip to content

Commit

Permalink
adding additional try_from instead of new
Browse files Browse the repository at this point in the history
  • Loading branch information
maebli committed Mar 10, 2024
1 parent 9c86ae2 commit 2aa42be
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 11 deletions.
24 changes: 14 additions & 10 deletions src/user_data/data_information.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,10 @@ pub enum DataInformationError {
DataTooShort,
}

impl DataInformation {
pub fn new(data: &[u8]) -> Result<Self, DataInformationError> {
impl TryFrom<&[u8]> for DataInformation {
type Error = DataInformationError;

fn try_from(data: &[u8]) -> Result<Self, DataInformationError> {
let first_byte = *data.get(0).ok_or(DataInformationError::DataTooLong)?;

let mut storage_number = ((first_byte & 0b0100_0000) >> 6) as u64;
Expand Down Expand Up @@ -197,11 +199,13 @@ pub enum Unit {

#[cfg(test)]
mod tests {


use super::*;
#[test]
fn test_data_information() {
let data = &[0x13];
let result = DataInformation::new(data);
let data = [0x13 as u8];
let result = DataInformation::try_from(data.as_slice());
assert_eq!(
result,
Ok(DataInformation {
Expand All @@ -216,25 +220,25 @@ mod tests {

#[test]
fn test_invalid_data_information() {
let data = &[
let data = [
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
];
let result = DataInformation::new(data);
let result = DataInformation::try_from(data.as_slice());
assert_eq!(result, Err(DataInformationError::DataTooLong));
}
#[test]
fn test_longest_data_information_not_too_long() {
let data = &[
let data = [
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
];
let result = DataInformation::new(data);
let result = DataInformation::try_from(data.as_slice());
assert_ne!(result, Err(DataInformationError::DataTooLong));
}

#[test]
fn test_short_data_information() {
let data = &[0xFF];
let result = DataInformation::new(data);
let data = [0xFF];
let result = DataInformation::try_from(data.as_slice());
assert_eq!(result, Err(DataInformationError::DataTooShort));
}
}
2 changes: 1 addition & 1 deletion src/user_data/variable_user_data.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ impl From<data_information::DataInformationError> for DataRecordError {

impl DataRecord {
pub fn new(data: &[u8]) -> Result<DataRecord, DataRecordError> {
let data_information = DataInformation::new(data)?;
let data_information = DataInformation::try_from(data)?;
let _value_information = ValueInformation::new(data);

let storage_number = data_information.storage_number;
Expand Down

0 comments on commit 2aa42be

Please sign in to comment.