improve std timestamp error further
Some checks failed
Rust/spacepackets/pipeline/head There was a failure building this commit

This commit is contained in:
Robin Müller 2023-07-09 16:46:25 +02:00
parent b5bea3e1c6
commit 581b51c61c
Signed by: muellerr
GPG Key ID: A649FB78196E3849
4 changed files with 42 additions and 44 deletions

View File

@ -8,6 +8,11 @@ and this project adheres to [Semantic Versioning](http://semver.org/).
# [unreleased] # [unreleased]
## Changed
- Implement `Display` and `Error` for `StdTimestampError` properly.
- Implement some redundant `Error` suffixes for enum error variants.
# [v0.6.0] 2023-07-06 # [v0.6.0] 2023-07-06
## Added ## Added

View File

@ -514,7 +514,7 @@ impl<ProvidesDaysLen: ProvidesDaysLength> TimeProvider<ProvidesDaysLen> {
days_len: LengthOfDaySegment, days_len: LengthOfDaySegment,
) -> Result<SubmillisPrecision, TimestampError> { ) -> Result<SubmillisPrecision, TimestampError> {
if buf.len() < MIN_CDS_FIELD_LEN { if buf.len() < MIN_CDS_FIELD_LEN {
return Err(TimestampError::ByteConversionError( return Err(TimestampError::ByteConversion(
ByteConversionError::FromSliceTooSmall(SizeMissmatch { ByteConversionError::FromSliceTooSmall(SizeMissmatch {
expected: MIN_CDS_FIELD_LEN, expected: MIN_CDS_FIELD_LEN,
found: buf.len(), found: buf.len(),
@ -548,7 +548,7 @@ impl<ProvidesDaysLen: ProvidesDaysLength> TimeProvider<ProvidesDaysLen> {
} }
let stamp_len = Self::calc_stamp_len(pfield); let stamp_len = Self::calc_stamp_len(pfield);
if buf.len() < stamp_len { if buf.len() < stamp_len {
return Err(TimestampError::ByteConversionError( return Err(TimestampError::ByteConversion(
ByteConversionError::FromSliceTooSmall(SizeMissmatch { ByteConversionError::FromSliceTooSmall(SizeMissmatch {
expected: stamp_len, expected: stamp_len,
found: buf.len(), found: buf.len(),
@ -605,7 +605,7 @@ impl<ProvidesDaysLen: ProvidesDaysLength> TimeProvider<ProvidesDaysLen> {
fn length_check(&self, buf: &[u8], len_as_bytes: usize) -> Result<(), TimestampError> { fn length_check(&self, buf: &[u8], len_as_bytes: usize) -> Result<(), TimestampError> {
if buf.len() < len_as_bytes { if buf.len() < len_as_bytes {
return Err(TimestampError::ByteConversionError( return Err(TimestampError::ByteConversion(
ByteConversionError::ToSliceTooSmall(SizeMissmatch { ByteConversionError::ToSliceTooSmall(SizeMissmatch {
expected: len_as_bytes, expected: len_as_bytes,
found: buf.len(), found: buf.len(),
@ -674,21 +674,21 @@ impl<ProvidesDaysLen: ProvidesDaysLength> TimeProvider<ProvidesDaysLen> {
fn from_now_generic(days_len: LengthOfDaySegment) -> Result<Self, StdTimestampError> { fn from_now_generic(days_len: LengthOfDaySegment) -> Result<Self, StdTimestampError> {
let conversion_from_now = ConversionFromNow::new()?; let conversion_from_now = ConversionFromNow::new()?;
Self::generic_from_conversion(days_len, conversion_from_now) Self::generic_from_conversion(days_len, conversion_from_now)
.map_err(StdTimestampError::TimestampError) .map_err(StdTimestampError::Timestamp)
} }
#[cfg(feature = "std")] #[cfg(feature = "std")]
fn from_now_generic_us_prec(days_len: LengthOfDaySegment) -> Result<Self, StdTimestampError> { fn from_now_generic_us_prec(days_len: LengthOfDaySegment) -> Result<Self, StdTimestampError> {
let conversion_from_now = ConversionFromNow::new_with_submillis_us_prec()?; let conversion_from_now = ConversionFromNow::new_with_submillis_us_prec()?;
Self::generic_from_conversion(days_len, conversion_from_now) Self::generic_from_conversion(days_len, conversion_from_now)
.map_err(StdTimestampError::TimestampError) .map_err(StdTimestampError::Timestamp)
} }
#[cfg(feature = "std")] #[cfg(feature = "std")]
fn from_now_generic_ps_prec(days_len: LengthOfDaySegment) -> Result<Self, StdTimestampError> { fn from_now_generic_ps_prec(days_len: LengthOfDaySegment) -> Result<Self, StdTimestampError> {
let conversion_from_now = ConversionFromNow::new_with_submillis_ps_prec()?; let conversion_from_now = ConversionFromNow::new_with_submillis_ps_prec()?;
Self::generic_from_conversion(days_len, conversion_from_now) Self::generic_from_conversion(days_len, conversion_from_now)
.map_err(StdTimestampError::TimestampError) .map_err(StdTimestampError::Timestamp)
} }
fn generic_from_conversion<C: CdsConverter>( fn generic_from_conversion<C: CdsConverter>(
@ -697,7 +697,7 @@ impl<ProvidesDaysLen: ProvidesDaysLength> TimeProvider<ProvidesDaysLen> {
) -> Result<Self, TimestampError> { ) -> Result<Self, TimestampError> {
let ccsds_days: ProvidesDaysLen::FieldType = let ccsds_days: ProvidesDaysLen::FieldType =
converter.ccsds_days_as_u32().try_into().map_err(|_| { converter.ccsds_days_as_u32().try_into().map_err(|_| {
TimestampError::CdsError(CdsError::InvalidCcsdsDays( TimestampError::Cds(CdsError::InvalidCcsdsDays(
converter.ccsds_days_as_u32().into(), converter.ccsds_days_as_u32().into(),
)) ))
})?; })?;
@ -753,7 +753,7 @@ impl<ProvidesDaysLen: ProvidesDaysLength> TimeProvider<ProvidesDaysLen> {
.ccsds_days .ccsds_days
.try_into() .try_into()
.map_err(|_| { .map_err(|_| {
StdTimestampError::TimestampError( StdTimestampError::Timestamp(
CdsError::InvalidCcsdsDays( CdsError::InvalidCcsdsDays(
conversion_from_now.unix_conversion.ccsds_days as i64, conversion_from_now.unix_conversion.ccsds_days as i64,
) )
@ -791,7 +791,7 @@ impl TimeProvider<DaysLen24Bits> {
/// ## Errors /// ## Errors
/// ///
/// This function will return [TimestampError::DateBeforeCcsdsEpoch] or /// This function will return [TimestampError::DateBeforeCcsdsEpoch] or
/// [TimestampError::CdsError] if the time is before the CCSDS epoch (1958-01-01T00:00:00+00:00) /// [TimestampError::Cds] if the time is before the CCSDS epoch (1958-01-01T00:00:00+00:00)
/// or the CCSDS days value exceeds the allowed bit width (24 bits). /// or the CCSDS days value exceeds the allowed bit width (24 bits).
pub fn from_dt_with_u24_days(dt: &DateTime<Utc>) -> Result<Self, TimestampError> { pub fn from_dt_with_u24_days(dt: &DateTime<Utc>) -> Result<Self, TimestampError> {
Self::from_dt_generic(dt, LengthOfDaySegment::Long24Bits) Self::from_dt_generic(dt, LengthOfDaySegment::Long24Bits)
@ -802,7 +802,7 @@ impl TimeProvider<DaysLen24Bits> {
/// ## Errors /// ## Errors
/// ///
/// This function will return [TimestampError::DateBeforeCcsdsEpoch] or /// This function will return [TimestampError::DateBeforeCcsdsEpoch] or
/// [TimestampError::CdsError] if the time is before the CCSDS epoch (1958-01-01T00:00:00+00:00) /// [TimestampError::Cds] if the time is before the CCSDS epoch (1958-01-01T00:00:00+00:00)
/// or the CCSDS days value exceeds the allowed bit width (24 bits). /// or the CCSDS days value exceeds the allowed bit width (24 bits).
pub fn from_unix_secs_with_u24_days( pub fn from_unix_secs_with_u24_days(
unix_stamp: &UnixTimestamp, unix_stamp: &UnixTimestamp,
@ -867,7 +867,7 @@ impl TimeProvider<DaysLen16Bits> {
/// Create a provider from a [`DateTime<Utc>`] struct. /// Create a provider from a [`DateTime<Utc>`] struct.
/// ///
/// This function will return a [TimestampError::DateBeforeCcsdsEpoch] or a /// This function will return a [TimestampError::DateBeforeCcsdsEpoch] or a
/// [TimestampError::CdsError] if the time is before the CCSDS epoch (01-01-1958 00:00:00) or /// [TimestampError::Cds] if the time is before the CCSDS epoch (01-01-1958 00:00:00) or
/// the CCSDS days value exceeds the allowed bit width (16 bits). /// the CCSDS days value exceeds the allowed bit width (16 bits).
pub fn from_dt_with_u16_days(dt: &DateTime<Utc>) -> Result<Self, TimestampError> { pub fn from_dt_with_u16_days(dt: &DateTime<Utc>) -> Result<Self, TimestampError> {
Self::from_dt_generic(dt, LengthOfDaySegment::Short16Bits) Self::from_dt_generic(dt, LengthOfDaySegment::Short16Bits)
@ -885,7 +885,7 @@ impl TimeProvider<DaysLen16Bits> {
/// ## Errors /// ## Errors
/// ///
/// This function will return [TimestampError::DateBeforeCcsdsEpoch] or /// This function will return [TimestampError::DateBeforeCcsdsEpoch] or
/// [TimestampError::CdsError] if the time is before the CCSDS epoch (1958-01-01T00:00:00+00:00) /// [TimestampError::Cds] if the time is before the CCSDS epoch (1958-01-01T00:00:00+00:00)
/// or the CCSDS days value exceeds the allowed bit width (24 bits). /// or the CCSDS days value exceeds the allowed bit width (24 bits).
pub fn from_unix_secs_with_u16_days( pub fn from_unix_secs_with_u16_days(
unix_stamp: &UnixTimestamp, unix_stamp: &UnixTimestamp,
@ -1305,7 +1305,7 @@ impl TryFrom<TimeProvider<DaysLen24Bits>> for TimeProvider<DaysLen16Bits> {
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::*; use super::*;
use crate::time::TimestampError::{ByteConversionError, InvalidTimeCode}; use crate::time::TimestampError::{ByteConversion, InvalidTimeCode};
use crate::ByteConversionError::{FromSliceTooSmall, ToSliceTooSmall}; use crate::ByteConversionError::{FromSliceTooSmall, ToSliceTooSmall};
use chrono::{Datelike, NaiveDate, Timelike}; use chrono::{Datelike, NaiveDate, Timelike};
#[cfg(feature = "serde")] #[cfg(feature = "serde")]
@ -1403,8 +1403,7 @@ mod tests {
let faulty_ctor = TimeProvider::<DaysLen16Bits>::from_bytes(&buf); let faulty_ctor = TimeProvider::<DaysLen16Bits>::from_bytes(&buf);
assert!(faulty_ctor.is_err()); assert!(faulty_ctor.is_err());
let error = faulty_ctor.unwrap_err(); let error = faulty_ctor.unwrap_err();
if let TimestampError::CdsError(CdsError::InvalidCtorForDaysOfLenInPreamble(len_of_day)) = if let TimestampError::Cds(CdsError::InvalidCtorForDaysOfLenInPreamble(len_of_day)) = error
error
{ {
assert_eq!(len_of_day, LengthOfDaySegment::Long24Bits); assert_eq!(len_of_day, LengthOfDaySegment::Long24Bits);
} else { } else {
@ -1449,7 +1448,7 @@ mod tests {
let res = time_stamper.write_to_bytes(&mut buf[0..i]); let res = time_stamper.write_to_bytes(&mut buf[0..i]);
assert!(res.is_err()); assert!(res.is_err());
match res.unwrap_err() { match res.unwrap_err() {
ByteConversionError(ToSliceTooSmall(missmatch)) => { ByteConversion(ToSliceTooSmall(missmatch)) => {
assert_eq!(missmatch.found, i); assert_eq!(missmatch.found, i);
assert_eq!(missmatch.expected, 7); assert_eq!(missmatch.expected, 7);
} }
@ -1469,7 +1468,7 @@ mod tests {
assert!(res.is_err()); assert!(res.is_err());
let err = res.unwrap_err(); let err = res.unwrap_err();
match err { match err {
ByteConversionError(e) => match e { ByteConversion(e) => match e {
FromSliceTooSmall(missmatch) => { FromSliceTooSmall(missmatch) => {
assert_eq!(missmatch.found, i); assert_eq!(missmatch.found, i);
assert_eq!(missmatch.expected, 7); assert_eq!(missmatch.expected, 7);
@ -1946,7 +1945,7 @@ mod tests {
panic!("creation should not succeed") panic!("creation should not succeed")
} }
Err(e) => { Err(e) => {
if let TimestampError::CdsError(CdsError::InvalidCcsdsDays(days)) = e { if let TimestampError::Cds(CdsError::InvalidCcsdsDays(days)) = e {
assert_eq!( assert_eq!(
days, days,
unix_to_ccsds_days(invalid_unix_secs / SECONDS_PER_DAY as i64) unix_to_ccsds_days(invalid_unix_secs / SECONDS_PER_DAY as i64)

View File

@ -245,7 +245,7 @@ impl TimeProviderCcsdsEpoch {
let fractions = let fractions =
fractional_part_from_subsec_ns(fraction_resolution, now.subsec_nanos() as u64); fractional_part_from_subsec_ns(fraction_resolution, now.subsec_nanos() as u64);
Self::new_with_fractions(ccsds_epoch as u32, fractions.unwrap()) Self::new_with_fractions(ccsds_epoch as u32, fractions.unwrap())
.map_err(|e| StdTimestampError::TimestampError(e.into())) .map_err(|e| StdTimestampError::Timestamp(e.into()))
} }
/// Updates the current time stamp from the current time. The fractional field width remains /// Updates the current time stamp from the current time. The fractional field width remains
@ -454,7 +454,7 @@ impl TimeReader for TimeProviderCcsdsEpoch {
Self: Sized, Self: Sized,
{ {
if buf.len() < MIN_CUC_LEN { if buf.len() < MIN_CUC_LEN {
return Err(TimestampError::ByteConversionError( return Err(TimestampError::ByteConversion(
ByteConversionError::FromSliceTooSmall(SizeMissmatch { ByteConversionError::FromSliceTooSmall(SizeMissmatch {
expected: MIN_CUC_LEN, expected: MIN_CUC_LEN,
found: buf.len(), found: buf.len(),
@ -480,7 +480,7 @@ impl TimeReader for TimeProviderCcsdsEpoch {
let (cntr_len, fractions_len, total_len) = let (cntr_len, fractions_len, total_len) =
Self::len_components_and_total_from_pfield(buf[0]); Self::len_components_and_total_from_pfield(buf[0]);
if buf.len() < total_len { if buf.len() < total_len {
return Err(TimestampError::ByteConversionError( return Err(TimestampError::ByteConversion(
ByteConversionError::FromSliceTooSmall(SizeMissmatch { ByteConversionError::FromSliceTooSmall(SizeMissmatch {
expected: total_len, expected: total_len,
found: buf.len(), found: buf.len(),
@ -536,7 +536,7 @@ impl TimeWriter for TimeProviderCcsdsEpoch {
fn write_to_bytes(&self, bytes: &mut [u8]) -> Result<usize, TimestampError> { fn write_to_bytes(&self, bytes: &mut [u8]) -> Result<usize, TimestampError> {
// Cross check the sizes of the counters against byte widths in the ctor // Cross check the sizes of the counters against byte widths in the ctor
if bytes.len() < self.len_as_bytes() { if bytes.len() < self.len_as_bytes() {
return Err(TimestampError::ByteConversionError( return Err(TimestampError::ByteConversion(
ByteConversionError::ToSliceTooSmall(SizeMissmatch { ByteConversionError::ToSliceTooSmall(SizeMissmatch {
found: bytes.len(), found: bytes.len(),
expected: self.len_as_bytes(), expected: self.len_as_bytes(),
@ -798,9 +798,7 @@ mod tests {
let res = TimeProviderCcsdsEpoch::from_bytes(&buf[0..i]); let res = TimeProviderCcsdsEpoch::from_bytes(&buf[0..i]);
assert!(res.is_err()); assert!(res.is_err());
let err = res.unwrap_err(); let err = res.unwrap_err();
if let TimestampError::ByteConversionError(ByteConversionError::FromSliceTooSmall(e)) = if let TimestampError::ByteConversion(ByteConversionError::FromSliceTooSmall(e)) = err {
err
{
assert_eq!(e.found, i); assert_eq!(e.found, i);
assert_eq!(e.expected, 2); assert_eq!(e.expected, 2);
} }
@ -811,9 +809,7 @@ mod tests {
let res = TimeProviderCcsdsEpoch::from_bytes(&buf[0..i]); let res = TimeProviderCcsdsEpoch::from_bytes(&buf[0..i]);
assert!(res.is_err()); assert!(res.is_err());
let err = res.unwrap_err(); let err = res.unwrap_err();
if let TimestampError::ByteConversionError(ByteConversionError::FromSliceTooSmall(e)) = if let TimestampError::ByteConversion(ByteConversionError::FromSliceTooSmall(e)) = err {
err
{
assert_eq!(e.found, i); assert_eq!(e.found, i);
assert_eq!(e.expected, large_stamp.len_as_bytes()); assert_eq!(e.expected, large_stamp.len_as_bytes());
} }
@ -887,9 +883,7 @@ mod tests {
let err = cuc.write_to_bytes(&mut buf[0..i]); let err = cuc.write_to_bytes(&mut buf[0..i]);
assert!(err.is_err()); assert!(err.is_err());
let err = err.unwrap_err(); let err = err.unwrap_err();
if let TimestampError::ByteConversionError(ByteConversionError::ToSliceTooSmall(e)) = if let TimestampError::ByteConversion(ByteConversionError::ToSliceTooSmall(e)) = err {
err
{
assert_eq!(e.expected, cuc.len_as_bytes()); assert_eq!(e.expected, cuc.len_as_bytes());
assert_eq!(e.found, i); assert_eq!(e.found, i);
} else { } else {

View File

@ -64,9 +64,9 @@ pub enum TimestampError {
/// Contains tuple where first value is the expected time code and the second /// Contains tuple where first value is the expected time code and the second
/// value is the found raw value /// value is the found raw value
InvalidTimeCode(CcsdsTimeCodes, u8), InvalidTimeCode(CcsdsTimeCodes, u8),
ByteConversionError(ByteConversionError), ByteConversion(ByteConversionError),
CdsError(cds::CdsError), Cds(cds::CdsError),
CucError(cuc::CucError), Cuc(cuc::CucError),
DateBeforeCcsdsEpoch(DateTime<Utc>), DateBeforeCcsdsEpoch(DateTime<Utc>),
CustomEpochNotSupported, CustomEpochNotSupported,
} }
@ -80,13 +80,13 @@ impl Display for TimestampError {
"invalid raw time code value {raw_val} for time code {time_code:?}" "invalid raw time code value {raw_val} for time code {time_code:?}"
) )
} }
TimestampError::CdsError(e) => { TimestampError::Cds(e) => {
write!(f, "cds error {e}") write!(f, "cds error {e}")
} }
TimestampError::CucError(e) => { TimestampError::Cuc(e) => {
write!(f, "cuc error {e}") write!(f, "cuc error {e}")
} }
TimestampError::ByteConversionError(e) => { TimestampError::ByteConversion(e) => {
write!(f, "byte conversion error {e}") write!(f, "byte conversion error {e}")
} }
TimestampError::DateBeforeCcsdsEpoch(e) => { TimestampError::DateBeforeCcsdsEpoch(e) => {
@ -103,22 +103,22 @@ impl Display for TimestampError {
impl Error for TimestampError { impl Error for TimestampError {
fn source(&self) -> Option<&(dyn Error + 'static)> { fn source(&self) -> Option<&(dyn Error + 'static)> {
match self { match self {
TimestampError::ByteConversionError(e) => Some(e), TimestampError::ByteConversion(e) => Some(e),
TimestampError::CdsError(e) => Some(e), TimestampError::Cds(e) => Some(e),
TimestampError::CucError(e) => Some(e), TimestampError::Cuc(e) => Some(e),
_ => None, _ => None,
} }
} }
} }
impl From<cds::CdsError> for TimestampError { impl From<cds::CdsError> for TimestampError {
fn from(e: cds::CdsError) -> Self { fn from(e: cds::CdsError) -> Self {
TimestampError::CdsError(e) TimestampError::Cds(e)
} }
} }
impl From<cuc::CucError> for TimestampError { impl From<cuc::CucError> for TimestampError {
fn from(e: cuc::CucError) -> Self { fn from(e: cuc::CucError) -> Self {
TimestampError::CucError(e) TimestampError::Cuc(e)
} }
} }
@ -132,9 +132,9 @@ pub mod std_mod {
#[derive(Debug, Clone, Error)] #[derive(Debug, Clone, Error)]
pub enum StdTimestampError { pub enum StdTimestampError {
#[error("system time error: {0}")] #[error("system time error: {0}")]
SystemTimeError(#[from] SystemTimeError), SystemTime(#[from] SystemTimeError),
#[error("timestamp error: {0}")] #[error("timestamp error: {0}")]
TimestampError(#[from] TimestampError), Timestamp(#[from] TimestampError),
} }
} }