Skip to content

Commit

Permalink
switch to thiserror completely
Browse files Browse the repository at this point in the history
  • Loading branch information
robamu committed Nov 8, 2024
1 parent c0b4653 commit 9d23ac5
Show file tree
Hide file tree
Showing 14 changed files with 153 additions and 427 deletions.
10 changes: 5 additions & 5 deletions src/cfdp/lv.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ use serde::{Deserialize, Serialize};
#[cfg(feature = "std")]
use std::string::String;

use super::TlvLvDataTooLarge;
use super::TlvLvDataTooLargeError;

pub const MIN_LV_LEN: usize = 1;

Expand Down Expand Up @@ -64,9 +64,9 @@ pub(crate) fn generic_len_check_deserialization(

impl<'data> Lv<'data> {
#[inline]
pub fn new(data: &[u8]) -> Result<Lv, TlvLvDataTooLarge> {
pub fn new(data: &[u8]) -> Result<Lv, TlvLvDataTooLargeError> {
if data.len() > u8::MAX as usize {
return Err(TlvLvDataTooLarge(data.len()));
return Err(TlvLvDataTooLargeError(data.len()));
}
Ok(Lv {
data,
Expand All @@ -86,15 +86,15 @@ impl<'data> Lv<'data> {
/// Helper function to build a string LV. This is especially useful for the file or directory
/// path LVs
#[inline]
pub fn new_from_str(str_slice: &str) -> Result<Lv, TlvLvDataTooLarge> {
pub fn new_from_str(str_slice: &str) -> Result<Lv, TlvLvDataTooLargeError> {
Self::new(str_slice.as_bytes())
}

/// Helper function to build a string LV. This is especially useful for the file or directory
/// path LVs
#[cfg(feature = "std")]
#[inline]
pub fn new_from_string(string: &'data String) -> Result<Lv<'data>, TlvLvDataTooLarge> {
pub fn new_from_string(string: &'data String) -> Result<Lv<'data>, TlvLvDataTooLargeError> {
Self::new(string.as_bytes())
}

Expand Down
99 changes: 21 additions & 78 deletions src/cfdp/mod.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,8 @@
//! Low-level CCSDS File Delivery Protocol (CFDP) support according to [CCSDS 727.0-B-5](https://public.ccsds.org/Pubs/727x0b5.pdf).
use crate::ByteConversionError;
use core::fmt::{Display, Formatter};
use num_enum::{IntoPrimitive, TryFromPrimitive};
#[cfg(feature = "serde")]
use serde::{Deserialize, Serialize};
#[cfg(feature = "std")]
use std::error::Error;

pub mod lv;
pub mod pdu;
Expand Down Expand Up @@ -176,97 +173,43 @@ impl Default for ChecksumType {

pub const NULL_CHECKSUM_U32: [u8; 4] = [0; 4];

#[derive(Debug, Copy, Clone, PartialEq, Eq)]
#[derive(Debug, Copy, Clone, PartialEq, Eq, thiserror::Error)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub struct TlvLvDataTooLarge(pub usize);
#[error("data with size {0} larger than allowed {max} bytes", max = u8::MAX)]
pub struct TlvLvDataTooLargeError(pub usize);

impl Display for TlvLvDataTooLarge {
fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
write!(
f,
"data with size {} larger than allowed {} bytes",
self.0,
u8::MAX
)
}
/// First value: Found value. Second value: Expected value if there is one.
#[derive(Debug, Copy, Clone, PartialEq, Eq, thiserror::Error)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
#[error("invalid TLV type field, found {found}, expected {expected:?}")]
pub struct InvalidTlvTypeFieldError {
found: u8,
expected: Option<u8>,
}

#[cfg(feature = "std")]
impl Error for TlvLvDataTooLarge {}

#[derive(Debug, Copy, Clone, PartialEq, Eq)]
#[derive(Debug, Copy, Clone, PartialEq, Eq, thiserror::Error)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub enum TlvLvError {
DataTooLarge(TlvLvDataTooLarge),
ByteConversion(ByteConversionError),
/// First value: Found value. Second value: Expected value if there is one.
InvalidTlvTypeField {
found: u8,
expected: Option<u8>,
},
/// Logically invalid value length detected. The value length may not exceed 255 bytes.
/// Depending on the concrete TLV type, the value length may also be logically invalid.
#[error("{0}")]
DataTooLarge(#[from] TlvLvDataTooLargeError),
#[error("byte conversion error: {0}")]
ByteConversion(#[from] ByteConversionError),
#[error("{0}")]
InvalidTlvTypeField(#[from] InvalidTlvTypeFieldError),
#[error("invalid value length {0}")]
InvalidValueLength(usize),
/// Only applies to filestore requests and responses. Second name was missing where one is
/// expected.
#[error("second name missing for filestore request or response")]
SecondNameMissing,
/// Invalid action code for filestore requests or responses.
#[error("invalid action code {0}")]
InvalidFilestoreActionCode(u8),
}

impl From<TlvLvDataTooLarge> for TlvLvError {
fn from(value: TlvLvDataTooLarge) -> Self {
Self::DataTooLarge(value)
}
}

impl From<ByteConversionError> for TlvLvError {
fn from(value: ByteConversionError) -> Self {
Self::ByteConversion(value)
}
}

impl Display for TlvLvError {
fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
match self {
TlvLvError::DataTooLarge(e) => {
write!(f, "{}", e)
}
TlvLvError::ByteConversion(e) => {
write!(f, "tlv or lv byte conversion: {}", e)
}
TlvLvError::InvalidTlvTypeField { found, expected } => {
write!(
f,
"invalid TLV type field, found {found}, expected {expected:?}"
)
}
TlvLvError::InvalidValueLength(len) => {
write!(f, "invalid value length {len}")
}
TlvLvError::SecondNameMissing => {
write!(f, "second name missing for filestore request or response")
}
TlvLvError::InvalidFilestoreActionCode(raw) => {
write!(f, "invalid filestore action code with raw value {raw}")
}
}
}
}

#[cfg(feature = "std")]
impl Error for TlvLvError {
fn source(&self) -> Option<&(dyn Error + 'static)> {
match self {
TlvLvError::DataTooLarge(e) => Some(e),
TlvLvError::ByteConversion(e) => Some(e),
_ => None,
}
}
}

#[cfg(test)]
mod tests {
use super::*;
Expand Down
2 changes: 1 addition & 1 deletion src/cfdp/pdu/eof.rs
Original file line number Diff line number Diff line change
Expand Up @@ -297,7 +297,7 @@ mod tests {
buf[written - 1] -= 1;
let crc: u16 = ((buf[written - 2] as u16) << 8) as u16 | buf[written - 1] as u16;
let error = EofPdu::from_bytes(&buf).unwrap_err();
if let PduError::ChecksumError(e) = error {
if let PduError::Checksum(e) = error {
assert_eq!(e, crc);
} else {
panic!("expected crc error");
Expand Down
4 changes: 2 additions & 2 deletions src/cfdp/pdu/file_data.rs
Original file line number Diff line number Diff line change
Expand Up @@ -544,7 +544,7 @@ mod tests {
buf[written - 1] -= 1;
let crc: u16 = ((buf[written - 2] as u16) << 8) | buf[written - 1] as u16;
let error = FileDataPdu::from_bytes(&buf).unwrap_err();
if let PduError::ChecksumError(e) = error {
if let PduError::Checksum(e) = error {
assert_eq!(e, crc);
} else {
panic!("expected crc error");
Expand Down Expand Up @@ -753,7 +753,7 @@ mod tests {
assert!(pdu_reader_error.is_err());
let error = pdu_reader_error.unwrap_err();
match error {
PduError::ChecksumError(_) => (),
PduError::Checksum(_) => (),
_ => {
panic!("unexpected PDU error {}", error)
}
Expand Down
32 changes: 18 additions & 14 deletions src/cfdp/pdu/finished.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,14 @@ use crate::cfdp::pdu::{
use crate::cfdp::tlv::{
EntityIdTlv, FilestoreResponseTlv, GenericTlv, Tlv, TlvType, TlvTypeField, WritableTlv,
};
use crate::cfdp::{ConditionCode, CrcFlag, Direction, PduType, TlvLvError};
use crate::cfdp::{ConditionCode, CrcFlag, Direction, PduType};
use crate::ByteConversionError;
use num_enum::{IntoPrimitive, TryFromPrimitive};
#[cfg(feature = "serde")]
use serde::{Deserialize, Serialize};

use super::tlv::ReadableTlv;
use super::{CfdpPdu, WritablePduPacket};
use super::{CfdpPdu, InvalidTlvTypeFieldError, WritablePduPacket};

#[derive(Debug, Copy, Clone, PartialEq, Eq, TryFromPrimitive, IntoPrimitive)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
Expand Down Expand Up @@ -332,22 +332,26 @@ impl<'buf> FinishedPduReader<'buf> {
// last TLV, everything else would break the whole handling of the packet
// TLVs.
if current_idx != full_len_without_crc {
return Err(PduError::FormatError);
return Err(PduError::Format);
}
} else {
return Err(TlvLvError::InvalidTlvTypeField {
found: tlv_type.into(),
expected: Some(TlvType::FilestoreResponse.into()),
}
.into());
return Err(PduError::TlvLv(
InvalidTlvTypeFieldError {
found: tlv_type.into(),
expected: Some(TlvType::FilestoreResponse.into()),
}
.into(),
));
}
}
TlvTypeField::Custom(raw) => {
return Err(TlvLvError::InvalidTlvTypeField {
found: raw,
expected: None,
}
.into());
return Err(PduError::TlvLv(
InvalidTlvTypeFieldError {
found: raw,
expected: None,
}
.into(),
));
}
}
}
Expand Down Expand Up @@ -564,7 +568,7 @@ mod tests {
buf[written - 1] -= 1;
let crc: u16 = ((buf[written - 2] as u16) << 8) as u16 | buf[written - 1] as u16;
let error = FinishedPduReader::new(&buf).unwrap_err();
if let PduError::ChecksumError(e) = error {
if let PduError::Checksum(e) = error {
assert_eq!(e, crc);
} else {
panic!("expected crc error");
Expand Down
6 changes: 3 additions & 3 deletions src/cfdp/pdu/metadata.rs
Original file line number Diff line number Diff line change
Expand Up @@ -720,7 +720,7 @@ pub mod tests {
fn test_with_owned_opts() {
let tlv1 = TlvOwned::new_empty(TlvType::FlowLabel);
let msg_to_user: [u8; 4] = [1, 2, 3, 4];
let tlv2 = TlvOwned::new(TlvType::MsgToUser, &msg_to_user).unwrap();
let tlv2 = TlvOwned::new(TlvType::MsgToUser, &msg_to_user);
let mut all_tlvs = tlv1.to_vec();
all_tlvs.extend(tlv2.to_vec());
let (src_filename, dest_filename, metadata_pdu) = generic_metadata_pdu(
Expand Down Expand Up @@ -780,7 +780,7 @@ pub mod tests {
assert_eq!(expected, Some(FileDirectiveType::MetadataPdu));
assert_eq!(
error.to_string(),
"invalid directive type value 255, expected Some(MetadataPdu)"
"invalid directive type, found 255, expected Some(MetadataPdu)"
);
} else {
panic!("Expected InvalidDirectiveType error, got {:?}", error);
Expand All @@ -806,7 +806,7 @@ pub mod tests {
assert_eq!(expected, FileDirectiveType::MetadataPdu);
assert_eq!(
error.to_string(),
"found directive type EofPdu, expected MetadataPdu"
"wrong directive type, found EofPdu, expected MetadataPdu"
);
} else {
panic!("Expected InvalidDirectiveType error, got {:?}", error);
Expand Down
Loading

0 comments on commit 9d23ac5

Please sign in to comment.