Compare commits
60 Commits
v0.7.0-bet
...
v0.7.0-bet
Author | SHA1 | Date | |
---|---|---|---|
34b58fe9cc | |||
393c73cedf
|
|||
3e97bf0c15
|
|||
7839fb3776 | |||
55ad24db34
|
|||
3b4a909ce1 | |||
76ad1c7ead | |||
79d26e1a67 | |||
be37c15478
|
|||
a6bced7983
|
|||
5d8b5ce370
|
|||
b94d07f6c9
|
|||
90e48483bb
|
|||
963b9dbb5f
|
|||
2a0db6b21c
|
|||
a4b14250c2
|
|||
6116cdb27c
|
|||
6ebdf7e330
|
|||
e935b3825a | |||
a49737fc34
|
|||
3081539bb2 | |||
1b01c8bb0b
|
|||
2ee3eee32e
|
|||
406d731bbe
|
|||
49b50ec682
|
|||
00fdfde015 | |||
491b03c701
|
|||
e090beedde
|
|||
6f2ed3003f | |||
0b5a384743
|
|||
925b2aa8d8
|
|||
d98d4b55c8
|
|||
94c378fa3b | |||
1fc15230fa | |||
e78f196a42
|
|||
2a11359a81 | |||
c226c5ea0f
|
|||
ab65845573 | |||
3206af690c
|
|||
805065a7b9
|
|||
62533bb91c | |||
c085f9ab32 | |||
f208a9b0f0
|
|||
c96a86a994
|
|||
9dfc593d2a
|
|||
990b8de519
|
|||
965541e422
|
|||
9a52066314
|
|||
6ab05e2d83
|
|||
2d81a79321
|
|||
fc7bee342c | |||
1789cff2b8
|
|||
5ae5abe09a
|
|||
407d1e1154
|
|||
3ba575aac1
|
|||
81db36d159
|
|||
081f6e840f
|
|||
3cb19298c8
|
|||
4e2c0f1aa7
|
|||
83db710950
|
36
CHANGELOG.md
36
CHANGELOG.md
@ -8,6 +8,42 @@ and this project adheres to [Semantic Versioning](http://semver.org/).
|
||||
|
||||
# [unreleased]
|
||||
|
||||
## Added
|
||||
|
||||
- `PacketId` trait impls: `Ord`, `PartialOrd` and `Hash`
|
||||
- `SerializablePusPacket` trait: Add `to_vec` method with default implementation.
|
||||
|
||||
# [v0.7.0-beta.1] 2023-08-28
|
||||
|
||||
- Bump `zerocopy` dependency to v0.7.0
|
||||
|
||||
## Changed
|
||||
|
||||
- The `Tlv` and `Lv` API return `&[u8]` instead of `Option<&[u8]>`.
|
||||
- `ByteConversionError` error variants `ToSliceTooSmall` and `FromSliceTooSmall` are struct
|
||||
variants now. `SizeMissmatch` was removed appropriately.
|
||||
- `UnsignedByteFieldError` error variants `ValueTooLargeForWidth` and `InvalidWidth` are struct
|
||||
variants now.
|
||||
- `TimestampError` error variant `InvalidTimeCode` is struct variant now.
|
||||
|
||||
## Added
|
||||
|
||||
- Added `raw_data` API for `Tlv` and `Lv` to retrieve the whole `Lv`/`Tlv` slice if the object
|
||||
was created from a raw bytestream.
|
||||
- Added `MsgToUserTlv` helper class which wraps a regular `Tlv` and adds some useful functionality.
|
||||
- `UnsignedByteField` and `GenericUnsignedByteField` `new` methods are `const` now.
|
||||
- `PduError` variants which contained a tuple variant with multiple fields were converted to a
|
||||
struct variant.
|
||||
|
||||
# Added
|
||||
|
||||
- Added `pdu_datafield_len` getter function for `PduHeader`
|
||||
|
||||
## Removed
|
||||
|
||||
- `SizeMissmatch` because it is not required for the `ByteConversionError` error enumeration
|
||||
anymore.
|
||||
|
||||
# [v0.7.0-beta.0] 2023-08-16
|
||||
|
||||
- Moved MSRV from v1.60 to v1.61.
|
||||
|
@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "spacepackets"
|
||||
version = "0.7.0-beta.0"
|
||||
version = "0.7.0-beta.2"
|
||||
edition = "2021"
|
||||
rust-version = "1.61"
|
||||
authors = ["Robin Mueller <muellerr@irs.uni-stuttgart.de>"]
|
||||
@ -13,16 +13,19 @@ categories = ["aerospace", "aerospace::space-protocols", "no-std", "hardware-sup
|
||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||
|
||||
[dependencies]
|
||||
zerocopy = "0.6"
|
||||
crc = "3"
|
||||
delegate = ">=0.8, <0.11"
|
||||
|
||||
[dependencies.zerocopy]
|
||||
version = "0.7"
|
||||
features = ["derive"]
|
||||
|
||||
[dependencies.thiserror]
|
||||
version = "1"
|
||||
optional = true
|
||||
|
||||
[dependencies.num_enum]
|
||||
version = "0.6"
|
||||
version = ">0.5, <=0.7"
|
||||
default-features = false
|
||||
|
||||
[dependencies.serde]
|
||||
|
5
automation/Jenkinsfile
vendored
5
automation/Jenkinsfile
vendored
@ -8,6 +8,11 @@ pipeline {
|
||||
}
|
||||
|
||||
stages {
|
||||
stage('Rust Toolchain Info') {
|
||||
steps {
|
||||
sh 'rustc --version'
|
||||
}
|
||||
}
|
||||
stage('Clippy') {
|
||||
steps {
|
||||
sh 'cargo clippy'
|
||||
|
@ -4,7 +4,7 @@ Checklist for new releases
|
||||
# Pre-Release
|
||||
|
||||
1. Make sure any new modules are documented sufficiently enough and check docs with
|
||||
`cargo doc --all-features --open`.
|
||||
`cargo +nightly doc --all-features --open`.
|
||||
2. Bump version specifier in `Cargo.toml`.
|
||||
3. Update `CHANGELOG.md`: Convert `unreleased` section into version section with date and add new
|
||||
`unreleased` section.
|
||||
@ -13,6 +13,10 @@ Checklist for new releases
|
||||
6. Wait for CI/CD results for EGit and Github. These also check cross-compilation for bare-metal
|
||||
targets.
|
||||
|
||||
# Release
|
||||
|
||||
1. `cargo publish`
|
||||
|
||||
# Post-Release
|
||||
|
||||
1. Create a new release on `EGit` based on the release branch.
|
||||
|
114
src/cfdp/lv.rs
114
src/cfdp/lv.rs
@ -1,6 +1,6 @@
|
||||
//! Generic CFDP length-value (LV) abstraction as specified in CFDP 5.1.8.
|
||||
use crate::cfdp::TlvLvError;
|
||||
use crate::{ByteConversionError, SizeMissmatch};
|
||||
use crate::ByteConversionError;
|
||||
use core::str::Utf8Error;
|
||||
#[cfg(feature = "serde")]
|
||||
use serde::{Deserialize, Serialize};
|
||||
@ -11,14 +11,26 @@ pub const MIN_LV_LEN: usize = 1;
|
||||
|
||||
/// Generic CFDP length-value (LV) abstraction as specified in CFDP 5.1.8.
|
||||
///
|
||||
/// Please note that this class is zero-copy and does not generate a copy of the value data for
|
||||
/// both the regular [Self::new] constructor and the [Self::from_bytes] constructor.
|
||||
///
|
||||
/// # Lifetimes
|
||||
/// * `data`: If the LV is generated from a raw bytestream, this will be the lifetime of
|
||||
/// the raw bytestream. If the LV is generated from a raw slice or a similar data reference,
|
||||
/// this will be the lifetime of that data reference.
|
||||
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
|
||||
#[derive(Debug, Copy, Clone, Eq)]
|
||||
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
||||
pub struct Lv<'data> {
|
||||
data: Option<&'data [u8]>,
|
||||
data: &'data [u8],
|
||||
// If the LV was generated from a raw bytestream, this will contain the start of the
|
||||
// full LV.
|
||||
pub(crate) raw_data: Option<&'data [u8]>,
|
||||
}
|
||||
|
||||
impl PartialEq for Lv<'_> {
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
self.data == other.data
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn generic_len_check_data_serialization(
|
||||
@ -27,10 +39,10 @@ pub(crate) fn generic_len_check_data_serialization(
|
||||
min_overhead: usize,
|
||||
) -> Result<(), ByteConversionError> {
|
||||
if buf.len() < data_len + min_overhead {
|
||||
return Err(ByteConversionError::ToSliceTooSmall(SizeMissmatch {
|
||||
return Err(ByteConversionError::ToSliceTooSmall {
|
||||
found: buf.len(),
|
||||
expected: data_len + min_overhead,
|
||||
}));
|
||||
});
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@ -40,10 +52,10 @@ pub(crate) fn generic_len_check_deserialization(
|
||||
min_overhead: usize,
|
||||
) -> Result<(), ByteConversionError> {
|
||||
if buf.len() < min_overhead {
|
||||
return Err(ByteConversionError::FromSliceTooSmall(SizeMissmatch {
|
||||
return Err(ByteConversionError::FromSliceTooSmall {
|
||||
found: buf.len(),
|
||||
expected: min_overhead,
|
||||
}));
|
||||
});
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@ -53,12 +65,18 @@ impl<'data> Lv<'data> {
|
||||
if data.len() > u8::MAX as usize {
|
||||
return Err(TlvLvError::DataTooLarge(data.len()));
|
||||
}
|
||||
Ok(Lv { data: Some(data) })
|
||||
Ok(Lv {
|
||||
data,
|
||||
raw_data: None,
|
||||
})
|
||||
}
|
||||
|
||||
/// Creates a LV with an empty value field.
|
||||
pub fn new_empty() -> Lv<'data> {
|
||||
Lv { data: None }
|
||||
Lv {
|
||||
data: &[],
|
||||
raw_data: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Helper function to build a string LV. This is especially useful for the file or directory
|
||||
@ -77,10 +95,7 @@ impl<'data> Lv<'data> {
|
||||
|
||||
/// Returns the length of the value part, not including the length byte.
|
||||
pub fn len_value(&self) -> usize {
|
||||
if self.data.is_none() {
|
||||
return 0;
|
||||
}
|
||||
self.data.unwrap().len()
|
||||
self.data.len()
|
||||
}
|
||||
|
||||
/// Returns the full raw length, including the length byte.
|
||||
@ -90,18 +105,26 @@ impl<'data> Lv<'data> {
|
||||
|
||||
/// Checks whether the value field is empty.
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.data.is_none()
|
||||
self.data.len() == 0
|
||||
}
|
||||
|
||||
pub fn value(&self) -> Option<&[u8]> {
|
||||
pub fn value(&self) -> &[u8] {
|
||||
self.data
|
||||
}
|
||||
|
||||
/// If the LV was generated from a raw bytestream using [Self::from_bytes], the raw start
|
||||
/// of the LV can be retrieved with this method.
|
||||
pub fn raw_data(&self) -> Option<&[u8]> {
|
||||
self.raw_data
|
||||
}
|
||||
|
||||
/// Convenience function to extract the value as a [str]. This is useful if the LV is
|
||||
/// known to contain a [str], for example being a file name.
|
||||
pub fn value_as_str(&self) -> Option<Result<&'data str, Utf8Error>> {
|
||||
self.data?;
|
||||
Some(core::str::from_utf8(self.data.unwrap()))
|
||||
if self.is_empty() {
|
||||
return None;
|
||||
}
|
||||
Some(core::str::from_utf8(self.data))
|
||||
}
|
||||
|
||||
/// Writes the LV to a raw buffer. Please note that the first byte will contain the length
|
||||
@ -118,15 +141,14 @@ impl<'data> Lv<'data> {
|
||||
}
|
||||
|
||||
pub(crate) fn write_to_be_bytes_no_len_check(&self, buf: &mut [u8]) -> usize {
|
||||
if self.data.is_none() {
|
||||
if self.is_empty() {
|
||||
buf[0] = 0;
|
||||
return MIN_LV_LEN;
|
||||
}
|
||||
let data = self.data.unwrap();
|
||||
// Length check in constructor ensures the length always has a valid value.
|
||||
buf[0] = data.len() as u8;
|
||||
buf[MIN_LV_LEN..data.len() + MIN_LV_LEN].copy_from_slice(data);
|
||||
MIN_LV_LEN + data.len()
|
||||
buf[0] = self.data.len() as u8;
|
||||
buf[MIN_LV_LEN..self.data.len() + MIN_LV_LEN].copy_from_slice(self.data);
|
||||
MIN_LV_LEN + self.data.len()
|
||||
}
|
||||
|
||||
pub(crate) fn from_be_bytes_no_len_check(
|
||||
@ -134,11 +156,10 @@ impl<'data> Lv<'data> {
|
||||
) -> Result<Lv<'data>, ByteConversionError> {
|
||||
let value_len = buf[0] as usize;
|
||||
generic_len_check_deserialization(buf, value_len + MIN_LV_LEN)?;
|
||||
let mut data = None;
|
||||
if value_len > 0 {
|
||||
data = Some(&buf[MIN_LV_LEN..MIN_LV_LEN + value_len])
|
||||
}
|
||||
Ok(Self { data })
|
||||
Ok(Self {
|
||||
data: &buf[MIN_LV_LEN..MIN_LV_LEN + value_len],
|
||||
raw_data: Some(buf),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@ -155,8 +176,8 @@ pub mod tests {
|
||||
let lv_res = Lv::new(&lv_data);
|
||||
assert!(lv_res.is_ok());
|
||||
let lv = lv_res.unwrap();
|
||||
assert!(lv.value().is_some());
|
||||
let val = lv.value().unwrap();
|
||||
assert!(lv.value().len() > 0);
|
||||
let val = lv.value();
|
||||
assert_eq!(val[0], 1);
|
||||
assert_eq!(val[1], 2);
|
||||
assert_eq!(val[2], 3);
|
||||
@ -172,7 +193,6 @@ pub mod tests {
|
||||
assert_eq!(lv_empty.len_value(), 0);
|
||||
assert_eq!(lv_empty.len_full(), 1);
|
||||
assert!(lv_empty.is_empty());
|
||||
assert_eq!(lv_empty.value(), None);
|
||||
let mut buf: [u8; 4] = [0xff; 4];
|
||||
let res = lv_empty.write_to_be_bytes(&mut buf);
|
||||
assert!(res.is_ok());
|
||||
@ -211,10 +231,11 @@ pub mod tests {
|
||||
assert!(lv.is_ok());
|
||||
let lv = lv.unwrap();
|
||||
assert!(!lv.is_empty());
|
||||
assert!(lv.value().is_some());
|
||||
assert_eq!(lv.len_value(), 4);
|
||||
assert_eq!(lv.len_full(), 5);
|
||||
let val = lv.value().unwrap();
|
||||
assert!(lv.raw_data().is_some());
|
||||
assert_eq!(lv.raw_data().unwrap(), buf);
|
||||
let val = lv.value();
|
||||
assert_eq!(val[0], 1);
|
||||
assert_eq!(val[1], 2);
|
||||
assert_eq!(val[2], 3);
|
||||
@ -228,7 +249,6 @@ pub mod tests {
|
||||
assert!(lv_empty.is_ok());
|
||||
let lv_empty = lv_empty.unwrap();
|
||||
assert!(lv_empty.is_empty());
|
||||
assert!(lv_empty.value().is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
@ -252,9 +272,9 @@ pub mod tests {
|
||||
let res = lv.write_to_be_bytes(&mut buf);
|
||||
assert!(res.is_err());
|
||||
let error = res.unwrap_err();
|
||||
if let ByteConversionError::ToSliceTooSmall(missmatch) = error {
|
||||
assert_eq!(missmatch.expected, 5);
|
||||
assert_eq!(missmatch.found, 3);
|
||||
if let ByteConversionError::ToSliceTooSmall { found, expected } = error {
|
||||
assert_eq!(expected, 5);
|
||||
assert_eq!(found, 3);
|
||||
} else {
|
||||
panic!("invalid error {}", error);
|
||||
}
|
||||
@ -267,9 +287,9 @@ pub mod tests {
|
||||
let res = Lv::from_bytes(&buf);
|
||||
assert!(res.is_err());
|
||||
let error = res.unwrap_err();
|
||||
if let ByteConversionError::FromSliceTooSmall(missmatch) = error {
|
||||
assert_eq!(missmatch.found, 3);
|
||||
assert_eq!(missmatch.expected, 5);
|
||||
if let ByteConversionError::FromSliceTooSmall { found, expected } = error {
|
||||
assert_eq!(found, 3);
|
||||
assert_eq!(expected, 5);
|
||||
} else {
|
||||
panic!("invalid error {}", error);
|
||||
}
|
||||
@ -282,14 +302,14 @@ pub mod tests {
|
||||
let res = res.unwrap();
|
||||
assert_eq!(res, 8 + 1);
|
||||
assert_eq!(buf[0], 8);
|
||||
assert_eq!(buf[1], 't' as u8);
|
||||
assert_eq!(buf[2], 'e' as u8);
|
||||
assert_eq!(buf[3], 's' as u8);
|
||||
assert_eq!(buf[4], 't' as u8);
|
||||
assert_eq!(buf[5], '.' as u8);
|
||||
assert_eq!(buf[6], 'b' as u8);
|
||||
assert_eq!(buf[7], 'i' as u8);
|
||||
assert_eq!(buf[8], 'n' as u8);
|
||||
assert_eq!(buf[1], b't');
|
||||
assert_eq!(buf[2], b'e');
|
||||
assert_eq!(buf[3], b's');
|
||||
assert_eq!(buf[4], b't');
|
||||
assert_eq!(buf[5], b'.');
|
||||
assert_eq!(buf[6], b'b');
|
||||
assert_eq!(buf[7], b'i');
|
||||
assert_eq!(buf[8], b'n');
|
||||
}
|
||||
#[test]
|
||||
fn test_str_helper() {
|
||||
|
@ -4,7 +4,7 @@ use crate::cfdp::pdu::{
|
||||
};
|
||||
use crate::cfdp::tlv::EntityIdTlv;
|
||||
use crate::cfdp::{ConditionCode, CrcFlag, LargeFileFlag};
|
||||
use crate::{ByteConversionError, SizeMissmatch};
|
||||
use crate::ByteConversionError;
|
||||
#[cfg(feature = "serde")]
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
@ -69,10 +69,10 @@ impl EofPdu {
|
||||
pub fn write_to_bytes(&self, buf: &mut [u8]) -> Result<usize, PduError> {
|
||||
let expected_len = self.written_len();
|
||||
if buf.len() < expected_len {
|
||||
return Err(ByteConversionError::ToSliceTooSmall(SizeMissmatch {
|
||||
return Err(ByteConversionError::ToSliceTooSmall {
|
||||
found: buf.len(),
|
||||
expected: expected_len,
|
||||
})
|
||||
}
|
||||
.into());
|
||||
}
|
||||
let mut current_idx = self.pdu_header.write_to_bytes(buf)?;
|
||||
@ -106,13 +106,16 @@ impl EofPdu {
|
||||
}
|
||||
generic_length_checks_pdu_deserialization(buf, min_expected_len, full_len_without_crc)?;
|
||||
let directive_type = FileDirectiveType::try_from(buf[current_idx]).map_err(|_| {
|
||||
PduError::InvalidDirectiveType((buf[current_idx], FileDirectiveType::EofPdu))
|
||||
PduError::InvalidDirectiveType {
|
||||
found: buf[current_idx],
|
||||
expected: Some(FileDirectiveType::EofPdu),
|
||||
}
|
||||
})?;
|
||||
if directive_type != FileDirectiveType::EofPdu {
|
||||
return Err(PduError::WrongDirectiveType((
|
||||
directive_type,
|
||||
FileDirectiveType::EofPdu,
|
||||
)));
|
||||
return Err(PduError::WrongDirectiveType {
|
||||
found: directive_type,
|
||||
expected: FileDirectiveType::EofPdu,
|
||||
});
|
||||
}
|
||||
current_idx += 1;
|
||||
let condition_code = ConditionCode::try_from((buf[current_idx] >> 4) & 0b1111)
|
||||
|
@ -3,7 +3,7 @@ use crate::cfdp::pdu::{
|
||||
PduError, PduHeader,
|
||||
};
|
||||
use crate::cfdp::{CrcFlag, LargeFileFlag, PduType, SegmentMetadataFlag};
|
||||
use crate::{ByteConversionError, SizeMissmatch};
|
||||
use crate::ByteConversionError;
|
||||
use num_enum::{IntoPrimitive, TryFromPrimitive};
|
||||
#[cfg(feature = "serde")]
|
||||
use serde::{Deserialize, Serialize};
|
||||
@ -48,10 +48,10 @@ impl<'seg_meta> SegmentMetadata<'seg_meta> {
|
||||
|
||||
pub(crate) fn write_to_bytes(&self, buf: &mut [u8]) -> Result<usize, ByteConversionError> {
|
||||
if buf.len() < self.written_len() {
|
||||
return Err(ByteConversionError::ToSliceTooSmall(SizeMissmatch {
|
||||
return Err(ByteConversionError::ToSliceTooSmall {
|
||||
found: buf.len(),
|
||||
expected: self.written_len(),
|
||||
}));
|
||||
});
|
||||
}
|
||||
buf[0] = ((self.record_continuation_state as u8) << 6)
|
||||
| self.metadata.map_or(0, |meta| meta.len() as u8);
|
||||
@ -63,10 +63,10 @@ impl<'seg_meta> SegmentMetadata<'seg_meta> {
|
||||
|
||||
pub(crate) fn from_bytes(buf: &'seg_meta [u8]) -> Result<Self, ByteConversionError> {
|
||||
if buf.is_empty() {
|
||||
return Err(ByteConversionError::FromSliceTooSmall(SizeMissmatch {
|
||||
return Err(ByteConversionError::FromSliceTooSmall {
|
||||
found: buf.len(),
|
||||
expected: 2,
|
||||
}));
|
||||
});
|
||||
}
|
||||
let mut metadata = None;
|
||||
let seg_metadata_len = (buf[0] & 0b111111) as usize;
|
||||
@ -165,10 +165,10 @@ impl<'seg_meta, 'file_data> FileDataPdu<'seg_meta, 'file_data> {
|
||||
|
||||
pub fn write_to_bytes(&self, buf: &mut [u8]) -> Result<usize, PduError> {
|
||||
if buf.len() < self.written_len() {
|
||||
return Err(ByteConversionError::ToSliceTooSmall(SizeMissmatch {
|
||||
return Err(ByteConversionError::ToSliceTooSmall {
|
||||
found: buf.len(),
|
||||
expected: self.written_len(),
|
||||
})
|
||||
}
|
||||
.into());
|
||||
}
|
||||
let mut current_idx = self.pdu_header.write_to_bytes(buf)?;
|
||||
@ -207,10 +207,10 @@ impl<'seg_meta, 'file_data> FileDataPdu<'seg_meta, 'file_data> {
|
||||
let (fss, offset) = read_fss_field(pdu_header.pdu_conf.file_flag, &buf[current_idx..]);
|
||||
current_idx += fss;
|
||||
if current_idx > full_len_without_crc {
|
||||
return Err(ByteConversionError::FromSliceTooSmall(SizeMissmatch {
|
||||
return Err(ByteConversionError::FromSliceTooSmall {
|
||||
found: current_idx,
|
||||
expected: full_len_without_crc,
|
||||
})
|
||||
}
|
||||
.into());
|
||||
}
|
||||
Ok(Self {
|
||||
|
@ -3,7 +3,7 @@ use crate::cfdp::pdu::{
|
||||
};
|
||||
use crate::cfdp::tlv::{EntityIdTlv, Tlv, TlvType, TlvTypeField};
|
||||
use crate::cfdp::{ConditionCode, CrcFlag, PduType, TlvLvError};
|
||||
use crate::{ByteConversionError, SizeMissmatch};
|
||||
use crate::ByteConversionError;
|
||||
use num_enum::{IntoPrimitive, TryFromPrimitive};
|
||||
#[cfg(feature = "serde")]
|
||||
use serde::{Deserialize, Serialize};
|
||||
@ -136,10 +136,10 @@ impl<'fs_responses> FinishedPdu<'fs_responses> {
|
||||
pub fn write_to_bytes(&self, buf: &mut [u8]) -> Result<usize, PduError> {
|
||||
let expected_len = self.written_len();
|
||||
if buf.len() < expected_len {
|
||||
return Err(ByteConversionError::ToSliceTooSmall(SizeMissmatch {
|
||||
return Err(ByteConversionError::ToSliceTooSmall {
|
||||
found: buf.len(),
|
||||
expected: expected_len,
|
||||
})
|
||||
}
|
||||
.into());
|
||||
}
|
||||
|
||||
@ -170,13 +170,16 @@ impl<'fs_responses> FinishedPdu<'fs_responses> {
|
||||
let min_expected_len = current_idx + 2;
|
||||
generic_length_checks_pdu_deserialization(buf, min_expected_len, full_len_without_crc)?;
|
||||
let directive_type = FileDirectiveType::try_from(buf[current_idx]).map_err(|_| {
|
||||
PduError::InvalidDirectiveType((buf[current_idx], FileDirectiveType::FinishedPdu))
|
||||
PduError::InvalidDirectiveType {
|
||||
found: buf[current_idx],
|
||||
expected: Some(FileDirectiveType::FinishedPdu),
|
||||
}
|
||||
})?;
|
||||
if directive_type != FileDirectiveType::FinishedPdu {
|
||||
return Err(PduError::WrongDirectiveType((
|
||||
directive_type,
|
||||
FileDirectiveType::FinishedPdu,
|
||||
)));
|
||||
return Err(PduError::WrongDirectiveType {
|
||||
found: directive_type,
|
||||
expected: FileDirectiveType::FinishedPdu,
|
||||
});
|
||||
}
|
||||
current_idx += 1;
|
||||
let condition_code = ConditionCode::try_from((buf[current_idx] >> 4) & 0b1111)
|
||||
|
@ -5,7 +5,7 @@ use crate::cfdp::pdu::{
|
||||
};
|
||||
use crate::cfdp::tlv::Tlv;
|
||||
use crate::cfdp::{ChecksumType, CrcFlag, LargeFileFlag, PduType};
|
||||
use crate::{ByteConversionError, SizeMissmatch};
|
||||
use crate::ByteConversionError;
|
||||
#[cfg(feature = "alloc")]
|
||||
use alloc::vec::Vec;
|
||||
#[cfg(feature = "serde")]
|
||||
@ -201,10 +201,10 @@ impl<'src_name, 'dest_name, 'opts> MetadataPdu<'src_name, 'dest_name, 'opts> {
|
||||
pub fn write_to_bytes(&self, buf: &mut [u8]) -> Result<usize, PduError> {
|
||||
let expected_len = self.written_len();
|
||||
if buf.len() < expected_len {
|
||||
return Err(ByteConversionError::ToSliceTooSmall(SizeMissmatch {
|
||||
return Err(ByteConversionError::ToSliceTooSmall {
|
||||
found: buf.len(),
|
||||
expected: expected_len,
|
||||
})
|
||||
}
|
||||
.into());
|
||||
}
|
||||
|
||||
@ -248,13 +248,16 @@ impl<'src_name, 'dest_name, 'opts> MetadataPdu<'src_name, 'dest_name, 'opts> {
|
||||
}
|
||||
generic_length_checks_pdu_deserialization(buf, min_expected_len, full_len_without_crc)?;
|
||||
let directive_type = FileDirectiveType::try_from(buf[current_idx]).map_err(|_| {
|
||||
PduError::InvalidDirectiveType((buf[current_idx], FileDirectiveType::MetadataPdu))
|
||||
PduError::InvalidDirectiveType {
|
||||
found: buf[current_idx],
|
||||
expected: Some(FileDirectiveType::MetadataPdu),
|
||||
}
|
||||
})?;
|
||||
if directive_type != FileDirectiveType::MetadataPdu {
|
||||
return Err(PduError::WrongDirectiveType((
|
||||
directive_type,
|
||||
FileDirectiveType::MetadataPdu,
|
||||
)));
|
||||
return Err(PduError::WrongDirectiveType {
|
||||
found: directive_type,
|
||||
expected: FileDirectiveType::MetadataPdu,
|
||||
});
|
||||
}
|
||||
current_idx += 1;
|
||||
let (fss_len, file_size) =
|
||||
|
@ -1,8 +1,8 @@
|
||||
//! CFDP Packet Data Unit (PDU) support.
|
||||
use crate::cfdp::*;
|
||||
use crate::util::{UnsignedByteField, UnsignedByteFieldU8, UnsignedEnum};
|
||||
use crate::ByteConversionError;
|
||||
use crate::CRC_CCITT_FALSE;
|
||||
use crate::{ByteConversionError, SizeMissmatch};
|
||||
use core::fmt::{Display, Formatter};
|
||||
#[cfg(feature = "std")]
|
||||
use std::error::Error;
|
||||
@ -35,16 +35,19 @@ pub enum PduError {
|
||||
InvalidEntityLen(u8),
|
||||
/// Invalid length for the entity ID detected. Only the values 1, 2, 4 and 8 are supported.
|
||||
InvalidTransactionSeqNumLen(u8),
|
||||
/// The first entry will be the source entity ID length, the second one the destination entity
|
||||
/// ID length.
|
||||
SourceDestIdLenMissmatch((usize, usize)),
|
||||
/// The first tuple entry will be the found directive type, the second entry the expected entry
|
||||
/// type.
|
||||
WrongDirectiveType((FileDirectiveType, FileDirectiveType)),
|
||||
SourceDestIdLenMissmatch {
|
||||
src_id_len: usize,
|
||||
dest_id_len: usize,
|
||||
},
|
||||
WrongDirectiveType {
|
||||
found: FileDirectiveType,
|
||||
expected: FileDirectiveType,
|
||||
},
|
||||
/// The directive type field contained a value not in the range of permitted values.
|
||||
/// The first tuple entry will be the found raw number, the second entry the expected entry
|
||||
/// type.
|
||||
InvalidDirectiveType((u8, FileDirectiveType)),
|
||||
InvalidDirectiveType {
|
||||
found: u8,
|
||||
expected: Option<FileDirectiveType>,
|
||||
},
|
||||
/// Invalid condition code. Contains the raw detected value.
|
||||
InvalidConditionCode(u8),
|
||||
/// Invalid checksum type which is not part of the checksums listed in the
|
||||
@ -80,10 +83,13 @@ impl Display for PduError {
|
||||
"cfdp version missmatch, found {raw}, expected {CFDP_VERSION_2}"
|
||||
)
|
||||
}
|
||||
PduError::SourceDestIdLenMissmatch((src_len, dest_len)) => {
|
||||
PduError::SourceDestIdLenMissmatch {
|
||||
src_id_len,
|
||||
dest_id_len,
|
||||
} => {
|
||||
write!(
|
||||
f,
|
||||
"missmatch of PDU source length {src_len} and destination length {dest_len}"
|
||||
"missmatch of PDU source length {src_id_len} and destination length {dest_id_len}"
|
||||
)
|
||||
}
|
||||
PduError::ByteConversionError(e) => {
|
||||
@ -92,17 +98,16 @@ impl Display for PduError {
|
||||
PduError::FileSizeTooLarge(value) => {
|
||||
write!(f, "file size value {value} exceeds allowed 32 bit width")
|
||||
}
|
||||
PduError::WrongDirectiveType((found, expected)) => {
|
||||
PduError::WrongDirectiveType { found, expected } => {
|
||||
write!(f, "found directive type {found:?}, expected {expected:?}")
|
||||
}
|
||||
PduError::InvalidConditionCode(raw_code) => {
|
||||
write!(f, "found invalid condition code with raw value {raw_code}")
|
||||
}
|
||||
PduError::InvalidDirectiveType((found, expected)) => {
|
||||
PduError::InvalidDirectiveType { found, expected } => {
|
||||
write!(
|
||||
f,
|
||||
"invalid directive type value {found}, expected {expected:?} ({})",
|
||||
*expected as u8
|
||||
"invalid directive type value {found}, expected {expected:?}"
|
||||
)
|
||||
}
|
||||
PduError::InvalidChecksumType(checksum_type) => {
|
||||
@ -217,10 +222,10 @@ impl CommonPduConfig {
|
||||
let source_id = source_id.into();
|
||||
let dest_id = dest_id.into();
|
||||
if source_id.size() != dest_id.size() {
|
||||
return Err(PduError::SourceDestIdLenMissmatch((
|
||||
source_id.size(),
|
||||
dest_id.size(),
|
||||
)));
|
||||
return Err(PduError::SourceDestIdLenMissmatch {
|
||||
src_id_len: source_id.size(),
|
||||
dest_id_len: dest_id.size(),
|
||||
});
|
||||
}
|
||||
if source_id.size() != 1
|
||||
&& source_id.size() != 2
|
||||
@ -340,6 +345,10 @@ impl PduHeader {
|
||||
+ self.pdu_conf.dest_entity_id.size()
|
||||
}
|
||||
|
||||
pub fn pdu_datafield_len(&self) -> usize {
|
||||
self.pdu_datafield_len.into()
|
||||
}
|
||||
|
||||
/// Returns the full length of the PDU when written to a raw buffer, which is the header length
|
||||
/// plus the PDU datafield length.
|
||||
pub fn pdu_len(&self) -> usize {
|
||||
@ -350,20 +359,20 @@ impl PduHeader {
|
||||
// Internal note: There is currently no way to pass a PDU configuration like this, but
|
||||
// this check is still kept for defensive programming.
|
||||
if self.pdu_conf.source_entity_id.size() != self.pdu_conf.dest_entity_id.size() {
|
||||
return Err(PduError::SourceDestIdLenMissmatch((
|
||||
self.pdu_conf.source_entity_id.size(),
|
||||
self.pdu_conf.dest_entity_id.size(),
|
||||
)));
|
||||
return Err(PduError::SourceDestIdLenMissmatch {
|
||||
src_id_len: self.pdu_conf.source_entity_id.size(),
|
||||
dest_id_len: self.pdu_conf.dest_entity_id.size(),
|
||||
});
|
||||
}
|
||||
if buf.len()
|
||||
< FIXED_HEADER_LEN
|
||||
+ self.pdu_conf.source_entity_id.size()
|
||||
+ self.pdu_conf.transaction_seq_num.size()
|
||||
{
|
||||
return Err(ByteConversionError::ToSliceTooSmall(SizeMissmatch {
|
||||
return Err(ByteConversionError::ToSliceTooSmall {
|
||||
found: buf.len(),
|
||||
expected: FIXED_HEADER_LEN,
|
||||
})
|
||||
}
|
||||
.into());
|
||||
}
|
||||
let mut current_idx = 0;
|
||||
@ -404,10 +413,10 @@ impl PduHeader {
|
||||
/// flag is not set, it will simply return the PDU length.
|
||||
pub fn verify_length_and_checksum(&self, buf: &[u8]) -> Result<usize, PduError> {
|
||||
if buf.len() < self.pdu_len() {
|
||||
return Err(ByteConversionError::FromSliceTooSmall(SizeMissmatch {
|
||||
return Err(ByteConversionError::FromSliceTooSmall {
|
||||
found: buf.len(),
|
||||
expected: self.pdu_len(),
|
||||
})
|
||||
}
|
||||
.into());
|
||||
}
|
||||
if self.pdu_conf.crc_flag == CrcFlag::WithCrc {
|
||||
@ -434,10 +443,10 @@ impl PduHeader {
|
||||
pub fn from_bytes(buf: &[u8]) -> Result<(Self, usize), PduError> {
|
||||
if buf.len() < FIXED_HEADER_LEN {
|
||||
return Err(PduError::ByteConversionError(
|
||||
ByteConversionError::FromSliceTooSmall(SizeMissmatch {
|
||||
ByteConversionError::FromSliceTooSmall {
|
||||
found: buf.len(),
|
||||
expected: FIXED_HEADER_LEN,
|
||||
}),
|
||||
},
|
||||
));
|
||||
}
|
||||
let cfdp_version_raw = (buf[0] >> 5) & 0b111;
|
||||
@ -472,10 +481,10 @@ impl PduHeader {
|
||||
));
|
||||
}
|
||||
if buf.len() < (4 + 2 * expected_len_entity_ids + expected_len_seq_num) {
|
||||
return Err(ByteConversionError::FromSliceTooSmall(SizeMissmatch {
|
||||
return Err(ByteConversionError::FromSliceTooSmall {
|
||||
found: buf.len(),
|
||||
expected: 4 + 2 * expected_len_entity_ids + expected_len_seq_num,
|
||||
})
|
||||
}
|
||||
.into());
|
||||
}
|
||||
let mut current_idx = 4;
|
||||
@ -571,17 +580,17 @@ pub(crate) fn generic_length_checks_pdu_deserialization(
|
||||
) -> Result<(), ByteConversionError> {
|
||||
// Buffer too short to hold additional expected minimum datasize.
|
||||
if buf.len() < min_expected_len {
|
||||
return Err(ByteConversionError::FromSliceTooSmall(SizeMissmatch {
|
||||
return Err(ByteConversionError::FromSliceTooSmall {
|
||||
found: buf.len(),
|
||||
expected: min_expected_len,
|
||||
}));
|
||||
});
|
||||
}
|
||||
// This can happen if the PDU datafield length value is invalid.
|
||||
if full_len_without_crc < min_expected_len {
|
||||
return Err(ByteConversionError::FromSliceTooSmall(SizeMissmatch {
|
||||
return Err(ByteConversionError::FromSliceTooSmall {
|
||||
found: full_len_without_crc,
|
||||
expected: min_expected_len,
|
||||
}));
|
||||
});
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@ -718,6 +727,8 @@ mod tests {
|
||||
assert_eq!(default_conf.crc_flag, CrcFlag::NoCrc);
|
||||
assert_eq!(default_conf.file_flag, LargeFileFlag::Normal);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_pdu_header_setter() {
|
||||
let src_id = UnsignedByteFieldU8::new(1);
|
||||
let dest_id = UnsignedByteFieldU8::new(2);
|
||||
@ -851,11 +862,13 @@ mod tests {
|
||||
let res = PduHeader::from_bytes(&buf);
|
||||
assert!(res.is_err());
|
||||
let error = res.unwrap_err();
|
||||
if let PduError::ByteConversionError(ByteConversionError::FromSliceTooSmall(missmatch)) =
|
||||
error
|
||||
if let PduError::ByteConversionError(ByteConversionError::FromSliceTooSmall {
|
||||
found,
|
||||
expected,
|
||||
}) = error
|
||||
{
|
||||
assert_eq!(missmatch.found, 3);
|
||||
assert_eq!(missmatch.expected, FIXED_HEADER_LEN);
|
||||
assert_eq!(found, 3);
|
||||
assert_eq!(expected, FIXED_HEADER_LEN);
|
||||
} else {
|
||||
panic!("invalid exception: {}", error);
|
||||
}
|
||||
@ -875,11 +888,13 @@ mod tests {
|
||||
let header = PduHeader::from_bytes(&buf[0..6]);
|
||||
assert!(header.is_err());
|
||||
let error = header.unwrap_err();
|
||||
if let PduError::ByteConversionError(ByteConversionError::FromSliceTooSmall(missmatch)) =
|
||||
error
|
||||
if let PduError::ByteConversionError(ByteConversionError::FromSliceTooSmall {
|
||||
found,
|
||||
expected,
|
||||
}) = error
|
||||
{
|
||||
assert_eq!(missmatch.found, 6);
|
||||
assert_eq!(missmatch.expected, 7);
|
||||
assert_eq!(found, 6);
|
||||
assert_eq!(expected, 7);
|
||||
}
|
||||
}
|
||||
|
||||
@ -920,9 +935,13 @@ mod tests {
|
||||
CommonPduConfig::new_with_byte_fields(src_id, dest_id, transaction_seq_id);
|
||||
assert!(pdu_conf_res.is_err());
|
||||
let error = pdu_conf_res.unwrap_err();
|
||||
if let PduError::SourceDestIdLenMissmatch((src_len, dest_len)) = error {
|
||||
assert_eq!(src_len, 1);
|
||||
assert_eq!(dest_len, 2);
|
||||
if let PduError::SourceDestIdLenMissmatch {
|
||||
src_id_len,
|
||||
dest_id_len,
|
||||
} = error
|
||||
{
|
||||
assert_eq!(src_id_len, 1);
|
||||
assert_eq!(dest_id_len, 2);
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -4,11 +4,13 @@ use crate::cfdp::lv::{
|
||||
};
|
||||
use crate::cfdp::TlvLvError;
|
||||
use crate::util::{UnsignedByteField, UnsignedByteFieldError, UnsignedEnum};
|
||||
use crate::{ByteConversionError, SizeMissmatch};
|
||||
use crate::ByteConversionError;
|
||||
use num_enum::{IntoPrimitive, TryFromPrimitive};
|
||||
#[cfg(feature = "serde")]
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
pub mod msg_to_user;
|
||||
|
||||
pub const MIN_TLV_LEN: usize = 2;
|
||||
|
||||
#[derive(Debug, Copy, Clone, PartialEq, Eq, TryFromPrimitive, IntoPrimitive)]
|
||||
@ -70,6 +72,9 @@ impl From<TlvTypeField> for u8 {
|
||||
|
||||
/// Generic CFDP type-length-value (TLV) abstraction as specified in CFDP 5.1.9.
|
||||
///
|
||||
/// Please note that this class is zero-copy and does not generate a copy of the value data for
|
||||
/// both the regular [Self::new] constructor and the [Self::from_bytes] constructor.
|
||||
///
|
||||
/// # Lifetimes
|
||||
/// * `data`: If the TLV is generated from a raw bytestream, this will be the lifetime of
|
||||
/// the raw bytestream. If the TLV is generated from a raw slice or a similar data reference,
|
||||
@ -98,22 +103,41 @@ impl<'data> Tlv<'data> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Checks whether the type field contains one of the standard types specified in the CFDP
|
||||
/// standard and is part of the [TlvType] enum.
|
||||
pub fn is_standard_tlv(&self) -> bool {
|
||||
if let TlvTypeField::Standard(_) = self.tlv_type_field {
|
||||
return true;
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
/// Returns the standard TLV type if the TLV field is not a custom field
|
||||
pub fn tlv_type(&self) -> Option<TlvType> {
|
||||
if let TlvTypeField::Standard(tlv_type) = self.tlv_type_field {
|
||||
Some(tlv_type)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
pub fn tlv_type_field(&self) -> TlvTypeField {
|
||||
self.tlv_type_field
|
||||
}
|
||||
|
||||
pub fn write_to_bytes(&self, buf: &mut [u8]) -> Result<usize, ByteConversionError> {
|
||||
generic_len_check_data_serialization(buf, self.len_value(), MIN_TLV_LEN)?;
|
||||
generic_len_check_data_serialization(buf, self.value().len(), MIN_TLV_LEN)?;
|
||||
buf[0] = self.tlv_type_field.into();
|
||||
self.lv.write_to_be_bytes_no_len_check(&mut buf[1..]);
|
||||
Ok(self.len_full())
|
||||
}
|
||||
|
||||
pub fn value(&self) -> Option<&[u8]> {
|
||||
pub fn value(&self) -> &[u8] {
|
||||
self.lv.value()
|
||||
}
|
||||
|
||||
/// Returns the length of the value part, not including the length byte.
|
||||
/// Helper method to retrieve the length of the value. Simply calls the [slice::len] method of
|
||||
/// [Self::value]
|
||||
pub fn len_value(&self) -> usize {
|
||||
self.lv.len_value()
|
||||
}
|
||||
@ -134,10 +158,20 @@ impl<'data> Tlv<'data> {
|
||||
/// [Self::len_full].
|
||||
pub fn from_bytes(buf: &'data [u8]) -> Result<Tlv<'data>, TlvLvError> {
|
||||
generic_len_check_deserialization(buf, MIN_TLV_LEN)?;
|
||||
Ok(Self {
|
||||
let mut tlv = Self {
|
||||
tlv_type_field: TlvTypeField::from(buf[0]),
|
||||
lv: Lv::from_bytes(&buf[MIN_LV_LEN..])?,
|
||||
})
|
||||
};
|
||||
// We re-use this field so we do not need an additional struct field to store the raw start
|
||||
// of the TLV.
|
||||
tlv.lv.raw_data = Some(buf);
|
||||
Ok(tlv)
|
||||
}
|
||||
|
||||
/// If the TLV was generated from a raw bytestream using [Self::from_bytes], the raw start
|
||||
/// of the TLV can be retrieved with this method.
|
||||
pub fn raw_data(&self) -> Option<&[u8]> {
|
||||
self.lv.raw_data()
|
||||
}
|
||||
}
|
||||
|
||||
@ -166,10 +200,10 @@ impl EntityIdTlv {
|
||||
|
||||
fn len_check(buf: &[u8]) -> Result<(), ByteConversionError> {
|
||||
if buf.len() < 2 {
|
||||
return Err(ByteConversionError::ToSliceTooSmall(SizeMissmatch {
|
||||
return Err(ByteConversionError::ToSliceTooSmall {
|
||||
found: buf.len(),
|
||||
expected: 2,
|
||||
}));
|
||||
});
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@ -234,21 +268,19 @@ impl<'data> TryFrom<Tlv<'data>> for EntityIdTlv {
|
||||
)));
|
||||
}
|
||||
}
|
||||
if value.len_value() != 1
|
||||
&& value.len_value() != 2
|
||||
&& value.len_value() != 4
|
||||
&& value.len_value() != 8
|
||||
{
|
||||
return Err(TlvLvError::InvalidValueLength(value.len_value()));
|
||||
let len_value = value.value().len();
|
||||
if len_value != 1 && len_value != 2 && len_value != 4 && len_value != 8 {
|
||||
return Err(TlvLvError::InvalidValueLength(len_value));
|
||||
}
|
||||
Ok(Self::new(
|
||||
UnsignedByteField::new_from_be_bytes(value.len_value(), value.value().unwrap())
|
||||
.map_err(|e| match e {
|
||||
UnsignedByteField::new_from_be_bytes(len_value, value.value()).map_err(
|
||||
|e| match e {
|
||||
UnsignedByteFieldError::ByteConversionError(e) => e,
|
||||
// This can not happen, we checked for the length validity, and the data is always smaller than
|
||||
// 255 bytes.
|
||||
_ => panic!("unexpected error"),
|
||||
})?,
|
||||
},
|
||||
)?,
|
||||
))
|
||||
}
|
||||
}
|
||||
@ -390,10 +422,10 @@ impl<'first_name, 'second_name> FilestoreRequestTlv<'first_name, 'second_name> {
|
||||
|
||||
pub fn write_to_bytes(&self, buf: &mut [u8]) -> Result<usize, ByteConversionError> {
|
||||
if buf.len() < self.len_full() {
|
||||
return Err(ByteConversionError::ToSliceTooSmall(SizeMissmatch {
|
||||
return Err(ByteConversionError::ToSliceTooSmall {
|
||||
found: buf.len(),
|
||||
expected: self.len_full(),
|
||||
}));
|
||||
});
|
||||
}
|
||||
buf[0] = TlvType::FilestoreRequest as u8;
|
||||
buf[1] = self.len_value() as u8;
|
||||
@ -417,10 +449,10 @@ impl<'first_name, 'second_name> FilestoreRequestTlv<'first_name, 'second_name> {
|
||||
buf: &'longest [u8],
|
||||
) -> Result<Self, TlvLvError> {
|
||||
if buf.len() < 2 {
|
||||
return Err(ByteConversionError::FromSliceTooSmall(SizeMissmatch {
|
||||
return Err(ByteConversionError::FromSliceTooSmall {
|
||||
found: buf.len(),
|
||||
expected: 2,
|
||||
})
|
||||
}
|
||||
.into());
|
||||
}
|
||||
verify_tlv_type(buf[0], TlvType::FilestoreRequest)?;
|
||||
@ -454,8 +486,8 @@ mod tests {
|
||||
use crate::cfdp::TlvLvError;
|
||||
use crate::util::{UbfU8, UnsignedEnum};
|
||||
|
||||
const TLV_TEST_STR_0: &'static str = "hello.txt";
|
||||
const TLV_TEST_STR_1: &'static str = "hello2.txt";
|
||||
const TLV_TEST_STR_0: &str = "hello.txt";
|
||||
const TLV_TEST_STR_1: &str = "hello2.txt";
|
||||
|
||||
#[test]
|
||||
fn test_basic() {
|
||||
@ -470,10 +502,10 @@ mod tests {
|
||||
TlvTypeField::Standard(TlvType::EntityId)
|
||||
);
|
||||
assert_eq!(tlv_res.len_full(), 3);
|
||||
assert_eq!(tlv_res.value().len(), 1);
|
||||
assert_eq!(tlv_res.len_value(), 1);
|
||||
assert!(!tlv_res.is_empty());
|
||||
assert!(tlv_res.value().is_some());
|
||||
assert_eq!(tlv_res.value().unwrap()[0], 5);
|
||||
assert_eq!(tlv_res.value()[0], 5);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@ -498,26 +530,27 @@ mod tests {
|
||||
assert!(entity_id.write_to_be_bytes(&mut buf[2..]).is_ok());
|
||||
buf[0] = TlvType::EntityId as u8;
|
||||
buf[1] = 1;
|
||||
let tlv_from_raw = Tlv::from_bytes(&mut buf);
|
||||
let tlv_from_raw = Tlv::from_bytes(&buf);
|
||||
assert!(tlv_from_raw.is_ok());
|
||||
let tlv_from_raw = tlv_from_raw.unwrap();
|
||||
assert!(tlv_from_raw.raw_data().is_some());
|
||||
assert_eq!(tlv_from_raw.raw_data().unwrap(), buf);
|
||||
assert_eq!(
|
||||
tlv_from_raw.tlv_type_field(),
|
||||
TlvTypeField::Standard(TlvType::EntityId)
|
||||
);
|
||||
assert_eq!(tlv_from_raw.len_value(), 1);
|
||||
assert_eq!(tlv_from_raw.value().len(), 1);
|
||||
assert_eq!(tlv_from_raw.len_full(), 3);
|
||||
assert!(tlv_from_raw.value().is_some());
|
||||
assert_eq!(tlv_from_raw.value().unwrap()[0], 5);
|
||||
assert_eq!(tlv_from_raw.value()[0], 5);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_empty() {
|
||||
let tlv_empty = Tlv::new_empty(TlvType::MsgToUser);
|
||||
assert!(tlv_empty.value().is_none());
|
||||
assert_eq!(tlv_empty.value().len(), 0);
|
||||
assert!(tlv_empty.is_empty());
|
||||
assert_eq!(tlv_empty.len_full(), 2);
|
||||
assert_eq!(tlv_empty.len_value(), 0);
|
||||
assert!(tlv_empty.value().is_empty());
|
||||
assert_eq!(
|
||||
tlv_empty.tlv_type_field(),
|
||||
TlvTypeField::Standard(TlvType::MsgToUser)
|
||||
@ -538,17 +571,17 @@ mod tests {
|
||||
let mut buf: [u8; 4] = [0; 4];
|
||||
buf[0] = TlvType::MsgToUser as u8;
|
||||
buf[1] = 0;
|
||||
let tlv_empty = Tlv::from_bytes(&mut buf);
|
||||
let tlv_empty = Tlv::from_bytes(&buf);
|
||||
assert!(tlv_empty.is_ok());
|
||||
let tlv_empty = tlv_empty.unwrap();
|
||||
assert!(tlv_empty.is_empty());
|
||||
assert!(tlv_empty.value().is_none());
|
||||
assert_eq!(tlv_empty.value().len(), 0);
|
||||
assert_eq!(
|
||||
tlv_empty.tlv_type_field(),
|
||||
TlvTypeField::Standard(TlvType::MsgToUser)
|
||||
);
|
||||
assert_eq!(tlv_empty.len_full(), 2);
|
||||
assert_eq!(tlv_empty.len_value(), 0);
|
||||
assert!(tlv_empty.value().is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
@ -570,11 +603,11 @@ mod tests {
|
||||
buf[0] = 3;
|
||||
buf[1] = 1;
|
||||
buf[2] = 5;
|
||||
let tlv = Tlv::from_bytes(&mut buf);
|
||||
let tlv = Tlv::from_bytes(&buf);
|
||||
assert!(tlv.is_ok());
|
||||
let tlv = tlv.unwrap();
|
||||
assert_eq!(tlv.tlv_type_field(), TlvTypeField::Custom(3));
|
||||
assert_eq!(tlv.len_value(), 1);
|
||||
assert_eq!(tlv.value().len(), 1);
|
||||
assert_eq!(tlv.len_full(), 3);
|
||||
}
|
||||
|
110
src/cfdp/tlv/msg_to_user.rs
Normal file
110
src/cfdp/tlv/msg_to_user.rs
Normal file
@ -0,0 +1,110 @@
|
||||
//! Abstractions for the Message to User CFDP TLV subtype.
|
||||
use super::{Tlv, TlvLvError, TlvType, TlvTypeField};
|
||||
use crate::ByteConversionError;
|
||||
use delegate::delegate;
|
||||
|
||||
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
|
||||
pub struct MsgToUserTlv<'data> {
|
||||
pub tlv: Tlv<'data>,
|
||||
}
|
||||
|
||||
impl<'data> MsgToUserTlv<'data> {
|
||||
/// Create a new message to user TLV where the type field is set correctly.
|
||||
pub fn new(value: &'data [u8]) -> Result<MsgToUserTlv<'data>, TlvLvError> {
|
||||
Ok(Self {
|
||||
tlv: Tlv::new(TlvType::MsgToUser, value)?,
|
||||
})
|
||||
}
|
||||
|
||||
delegate! {
|
||||
to self.tlv {
|
||||
pub fn tlv_type_field(&self) -> TlvTypeField;
|
||||
pub fn write_to_bytes(&self, buf: &mut [u8]) -> Result<usize, ByteConversionError>;
|
||||
pub fn value(&self) -> &[u8];
|
||||
/// Helper method to retrieve the length of the value. Simply calls the [slice::len] method of
|
||||
/// [Self::value]
|
||||
pub fn len_value(&self) -> usize;
|
||||
/// Returns the full raw length, including the length byte.
|
||||
pub fn len_full(&self) -> usize;
|
||||
/// Checks whether the value field is empty.
|
||||
pub fn is_empty(&self) -> bool;
|
||||
/// If the TLV was generated from a raw bytestream using [Self::from_bytes], the raw start
|
||||
/// of the TLV can be retrieved with this method.
|
||||
pub fn raw_data(&self) -> Option<&[u8]>;
|
||||
}
|
||||
}
|
||||
|
||||
pub fn is_standard_tlv(&self) -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
pub fn tlv_type(&self) -> Option<TlvType> {
|
||||
Some(TlvType::MsgToUser)
|
||||
}
|
||||
|
||||
/// Check whether this message is a reserved CFDP message like a Proxy Operation Message.
|
||||
pub fn is_reserved_cfdp_msg(&self) -> bool {
|
||||
if self.value().len() < 4 {
|
||||
return false;
|
||||
}
|
||||
let value = self.value();
|
||||
if value[0] == b'c' && value[1] == b'f' && value[2] == b'd' && value[3] == b'p' {
|
||||
return true;
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
/// This is a thin wrapper around [Tlv::from_bytes] with the additional type check.
|
||||
pub fn from_bytes(buf: &'data [u8]) -> Result<MsgToUserTlv<'data>, TlvLvError> {
|
||||
let msg_to_user = Self {
|
||||
tlv: Tlv::from_bytes(buf)?,
|
||||
};
|
||||
match msg_to_user.tlv_type_field() {
|
||||
TlvTypeField::Standard(tlv_type) => {
|
||||
if tlv_type != TlvType::MsgToUser {
|
||||
return Err(TlvLvError::InvalidTlvTypeField((
|
||||
tlv_type as u8,
|
||||
Some(TlvType::MsgToUser as u8),
|
||||
)));
|
||||
}
|
||||
}
|
||||
TlvTypeField::Custom(raw) => {
|
||||
return Err(TlvLvError::InvalidTlvTypeField((
|
||||
raw,
|
||||
Some(TlvType::MsgToUser as u8),
|
||||
)));
|
||||
}
|
||||
}
|
||||
Ok(msg_to_user)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
#[test]
|
||||
fn test_basic() {
|
||||
let custom_value: [u8; 4] = [1, 2, 3, 4];
|
||||
let msg_to_user = MsgToUserTlv::new(&custom_value);
|
||||
assert!(msg_to_user.is_ok());
|
||||
let msg_to_user = msg_to_user.unwrap();
|
||||
assert!(msg_to_user.is_standard_tlv());
|
||||
assert_eq!(msg_to_user.tlv_type().unwrap(), TlvType::MsgToUser);
|
||||
assert_eq!(msg_to_user.value(), custom_value);
|
||||
assert_eq!(msg_to_user.value().len(), 4);
|
||||
assert_eq!(msg_to_user.len_value(), 4);
|
||||
assert_eq!(msg_to_user.len_full(), 6);
|
||||
assert!(!msg_to_user.is_empty());
|
||||
assert!(msg_to_user.raw_data().is_none());
|
||||
assert!(!msg_to_user.is_reserved_cfdp_msg());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_reserved_msg() {
|
||||
let reserved_str = "cfdp";
|
||||
let msg_to_user = MsgToUserTlv::new(reserved_str.as_bytes());
|
||||
assert!(msg_to_user.is_ok());
|
||||
let msg_to_user = msg_to_user.unwrap();
|
||||
assert!(msg_to_user.is_reserved_cfdp_msg());
|
||||
}
|
||||
}
|
@ -4,6 +4,8 @@
|
||||
//! You can find the PUS telecommand definitions in the [tc] module and ithe PUS telemetry definitions
|
||||
//! inside the [tm] module.
|
||||
use crate::{ByteConversionError, CcsdsPacket, CRC_CCITT_FALSE};
|
||||
#[cfg(feature = "alloc")]
|
||||
use alloc::vec::Vec;
|
||||
use core::fmt::{Debug, Display, Formatter};
|
||||
use core::mem::size_of;
|
||||
use num_enum::{IntoPrimitive, TryFromPrimitive};
|
||||
@ -361,6 +363,15 @@ pub type EcssEnumU64 = GenericEcssEnumWrapper<u64>;
|
||||
pub trait SerializablePusPacket {
|
||||
fn len_packed(&self) -> usize;
|
||||
fn write_to_bytes(&self, slice: &mut [u8]) -> Result<usize, PusError>;
|
||||
#[cfg(feature = "alloc")]
|
||||
fn to_vec(&self) -> Result<Vec<u8>, PusError> {
|
||||
// This is the correct way to do this. See
|
||||
// [this issue](https://github.com/rust-lang/rust-clippy/issues/4483) for caveats of more
|
||||
// "efficient" implementations.
|
||||
let mut vec = alloc::vec![0; self.len_packed()];
|
||||
self.write_to_bytes(&mut vec)?;
|
||||
Ok(vec)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@ -397,9 +408,9 @@ mod tests {
|
||||
assert!(res.is_err());
|
||||
let error = res.unwrap_err();
|
||||
match error {
|
||||
ByteConversionError::ToSliceTooSmall(missmatch) => {
|
||||
assert_eq!(missmatch.expected, 2);
|
||||
assert_eq!(missmatch.found, 1);
|
||||
ByteConversionError::ToSliceTooSmall { found, expected } => {
|
||||
assert_eq!(expected, 2);
|
||||
assert_eq!(found, 1);
|
||||
}
|
||||
_ => {
|
||||
panic!("Unexpected error {:?}", error);
|
||||
@ -428,9 +439,9 @@ mod tests {
|
||||
assert!(res.is_err());
|
||||
let error = res.unwrap_err();
|
||||
match error {
|
||||
ByteConversionError::ToSliceTooSmall(missmatch) => {
|
||||
assert_eq!(missmatch.expected, 4);
|
||||
assert_eq!(missmatch.found, 3);
|
||||
ByteConversionError::ToSliceTooSmall { found, expected } => {
|
||||
assert_eq!(expected, 4);
|
||||
assert_eq!(found, 3);
|
||||
}
|
||||
_ => {
|
||||
panic!("Unexpected error {:?}", error);
|
||||
|
@ -36,9 +36,7 @@ use crate::ecss::{
|
||||
verify_crc16_ccitt_false_from_raw_to_pus_error, CrcType, PusError, PusPacket, PusVersion,
|
||||
SerializablePusPacket,
|
||||
};
|
||||
use crate::{
|
||||
ByteConversionError, CcsdsPacket, PacketType, SequenceFlags, SizeMissmatch, CCSDS_HEADER_LEN,
|
||||
};
|
||||
use crate::{ByteConversionError, CcsdsPacket, PacketType, SequenceFlags, CCSDS_HEADER_LEN};
|
||||
use crate::{SpHeader, CRC_CCITT_FALSE};
|
||||
use core::mem::size_of;
|
||||
use delegate::delegate;
|
||||
@ -84,9 +82,9 @@ pub trait GenericPusTcSecondaryHeader {
|
||||
pub mod zc {
|
||||
use crate::ecss::tc::GenericPusTcSecondaryHeader;
|
||||
use crate::ecss::{PusError, PusVersion};
|
||||
use zerocopy::{AsBytes, FromBytes, NetworkEndian, Unaligned, U16};
|
||||
use zerocopy::{AsBytes, FromBytes, FromZeroes, NetworkEndian, Unaligned, U16};
|
||||
|
||||
#[derive(FromBytes, AsBytes, Unaligned)]
|
||||
#[derive(FromZeroes, FromBytes, AsBytes, Unaligned)]
|
||||
#[repr(C)]
|
||||
pub struct PusTcSecondaryHeader {
|
||||
version_ack: u8,
|
||||
@ -223,9 +221,7 @@ pub mod legacy_tc {
|
||||
};
|
||||
use crate::ecss::{user_data_from_raw, PusVersion};
|
||||
use crate::SequenceFlags;
|
||||
use crate::{
|
||||
ByteConversionError, CcsdsPacket, PacketType, SizeMissmatch, SpHeader, CRC_CCITT_FALSE,
|
||||
};
|
||||
use crate::{ByteConversionError, CcsdsPacket, PacketType, SpHeader, CRC_CCITT_FALSE};
|
||||
use core::mem::size_of;
|
||||
use delegate::delegate;
|
||||
use zerocopy::AsBytes;
|
||||
@ -462,10 +458,10 @@ pub mod legacy_tc {
|
||||
let tc_header_len = size_of::<zc::PusTcSecondaryHeader>();
|
||||
let total_size = self.len_packed();
|
||||
if total_size > slice.len() {
|
||||
return Err(ByteConversionError::ToSliceTooSmall(SizeMissmatch {
|
||||
return Err(ByteConversionError::ToSliceTooSmall {
|
||||
found: slice.len(),
|
||||
expected: total_size,
|
||||
})
|
||||
}
|
||||
.into());
|
||||
}
|
||||
self.sp_header.write_to_be_bytes(slice)?;
|
||||
@ -668,10 +664,10 @@ impl SerializablePusPacket for PusTcCreator<'_> {
|
||||
let tc_header_len = size_of::<zc::PusTcSecondaryHeader>();
|
||||
let total_size = self.len_packed();
|
||||
if total_size > slice.len() {
|
||||
return Err(ByteConversionError::ToSliceTooSmall(SizeMissmatch {
|
||||
return Err(ByteConversionError::ToSliceTooSmall {
|
||||
found: slice.len(),
|
||||
expected: total_size,
|
||||
})
|
||||
}
|
||||
.into());
|
||||
}
|
||||
self.sp_header.write_to_be_bytes(slice)?;
|
||||
@ -996,9 +992,9 @@ mod tests {
|
||||
let err = res.unwrap_err();
|
||||
match err {
|
||||
PusError::ByteConversion(err) => match err {
|
||||
ByteConversionError::ToSliceTooSmall(missmatch) => {
|
||||
assert_eq!(missmatch.expected, pus_tc.len_packed());
|
||||
assert_eq!(missmatch.found, 12);
|
||||
ByteConversionError::ToSliceTooSmall { found, expected } => {
|
||||
assert_eq!(expected, pus_tc.len_packed());
|
||||
assert_eq!(found, 12);
|
||||
}
|
||||
_ => panic!("Unexpected error"),
|
||||
},
|
||||
|
@ -6,8 +6,8 @@ use crate::ecss::{
|
||||
SerializablePusPacket,
|
||||
};
|
||||
use crate::{
|
||||
ByteConversionError, CcsdsPacket, PacketType, SequenceFlags, SizeMissmatch, SpHeader,
|
||||
CCSDS_HEADER_LEN, CRC_CCITT_FALSE, MAX_APID, MAX_SEQ_COUNT,
|
||||
ByteConversionError, CcsdsPacket, PacketType, SequenceFlags, SpHeader, CCSDS_HEADER_LEN,
|
||||
CRC_CCITT_FALSE, MAX_APID, MAX_SEQ_COUNT,
|
||||
};
|
||||
use core::mem::size_of;
|
||||
#[cfg(feature = "serde")]
|
||||
@ -40,9 +40,9 @@ pub trait GenericPusTmSecondaryHeader {
|
||||
pub mod zc {
|
||||
use super::GenericPusTmSecondaryHeader;
|
||||
use crate::ecss::{PusError, PusVersion};
|
||||
use zerocopy::{AsBytes, FromBytes, NetworkEndian, Unaligned, U16};
|
||||
use zerocopy::{AsBytes, FromBytes, FromZeroes, NetworkEndian, Unaligned, U16};
|
||||
|
||||
#[derive(FromBytes, AsBytes, Unaligned)]
|
||||
#[derive(FromBytes, FromZeroes, AsBytes, Unaligned)]
|
||||
#[repr(C)]
|
||||
pub struct PusTmSecHeaderWithoutTimestamp {
|
||||
pus_version_and_sc_time_ref_status: u8,
|
||||
@ -207,9 +207,7 @@ pub mod legacy_tm {
|
||||
CCSDS_HEADER_LEN,
|
||||
};
|
||||
use crate::SequenceFlags;
|
||||
use crate::{
|
||||
ByteConversionError, CcsdsPacket, PacketType, SizeMissmatch, SpHeader, CRC_CCITT_FALSE,
|
||||
};
|
||||
use crate::{ByteConversionError, CcsdsPacket, PacketType, SpHeader, CRC_CCITT_FALSE};
|
||||
use core::mem::size_of;
|
||||
use zerocopy::AsBytes;
|
||||
|
||||
@ -436,10 +434,10 @@ pub mod legacy_tm {
|
||||
let mut curr_idx = 0;
|
||||
let total_size = self.len_packed();
|
||||
if total_size > slice.len() {
|
||||
return Err(ByteConversionError::ToSliceTooSmall(SizeMissmatch {
|
||||
return Err(ByteConversionError::ToSliceTooSmall {
|
||||
found: slice.len(),
|
||||
expected: total_size,
|
||||
})
|
||||
}
|
||||
.into());
|
||||
}
|
||||
self.sp_header
|
||||
@ -663,10 +661,10 @@ impl SerializablePusPacket for PusTmCreator<'_> {
|
||||
let mut curr_idx = 0;
|
||||
let total_size = self.len_packed();
|
||||
if total_size > slice.len() {
|
||||
return Err(ByteConversionError::ToSliceTooSmall(SizeMissmatch {
|
||||
return Err(ByteConversionError::ToSliceTooSmall {
|
||||
found: slice.len(),
|
||||
expected: total_size,
|
||||
})
|
||||
}
|
||||
.into());
|
||||
}
|
||||
self.sp_header
|
||||
@ -1055,9 +1053,9 @@ mod tests {
|
||||
assert!(matches!(error, PusError::ByteConversion { .. }));
|
||||
match error {
|
||||
PusError::ByteConversion(err) => match err {
|
||||
ByteConversionError::ToSliceTooSmall(size_missmatch) => {
|
||||
assert_eq!(size_missmatch.expected, 22);
|
||||
assert_eq!(size_missmatch.found, 16);
|
||||
ByteConversionError::ToSliceTooSmall { found, expected } => {
|
||||
assert_eq!(expected, 22);
|
||||
assert_eq!(found, 16);
|
||||
}
|
||||
_ => panic!("Invalid PUS error {:?}", err),
|
||||
},
|
||||
|
91
src/lib.rs
91
src/lib.rs
@ -62,7 +62,10 @@ extern crate alloc;
|
||||
extern crate std;
|
||||
|
||||
use crate::ecss::CCSDS_HEADER_LEN;
|
||||
use core::fmt::{Debug, Display, Formatter};
|
||||
use core::{
|
||||
fmt::{Debug, Display, Formatter},
|
||||
hash::Hash,
|
||||
};
|
||||
use crc::{Crc, CRC_16_IBM_3740};
|
||||
use delegate::delegate;
|
||||
|
||||
@ -87,20 +90,20 @@ pub const CRC_CCITT_FALSE: Crc<u16> = Crc::<u16>::new(&CRC_16_IBM_3740);
|
||||
pub const MAX_APID: u16 = 2u16.pow(11) - 1;
|
||||
pub const MAX_SEQ_COUNT: u16 = 2u16.pow(14) - 1;
|
||||
|
||||
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
|
||||
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
||||
pub struct SizeMissmatch {
|
||||
pub found: usize,
|
||||
pub expected: usize,
|
||||
}
|
||||
|
||||
/// Generic error type when converting to and from raw byte slices.
|
||||
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
|
||||
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
||||
pub enum ByteConversionError {
|
||||
/// The passed slice is too small. Returns the passed slice length and expected minimum size
|
||||
ToSliceTooSmall(SizeMissmatch),
|
||||
ToSliceTooSmall {
|
||||
found: usize,
|
||||
expected: usize,
|
||||
},
|
||||
/// The provider buffer is too small. Returns the passed slice length and expected minimum size
|
||||
FromSliceTooSmall(SizeMissmatch),
|
||||
FromSliceTooSmall {
|
||||
found: usize,
|
||||
expected: usize,
|
||||
},
|
||||
/// The [zerocopy] library failed to write to bytes
|
||||
ZeroCopyToError,
|
||||
ZeroCopyFromError,
|
||||
@ -109,18 +112,18 @@ pub enum ByteConversionError {
|
||||
impl Display for ByteConversionError {
|
||||
fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
|
||||
match self {
|
||||
ByteConversionError::ToSliceTooSmall(missmatch) => {
|
||||
ByteConversionError::ToSliceTooSmall { found, expected } => {
|
||||
write!(
|
||||
f,
|
||||
"target slice with size {} is too small, expected size of at least {}",
|
||||
missmatch.found, missmatch.expected
|
||||
found, expected
|
||||
)
|
||||
}
|
||||
ByteConversionError::FromSliceTooSmall(missmatch) => {
|
||||
ByteConversionError::FromSliceTooSmall { found, expected } => {
|
||||
write!(
|
||||
f,
|
||||
"source slice with size {} too small, expected at least {} bytes",
|
||||
missmatch.found, missmatch.expected
|
||||
found, expected
|
||||
)
|
||||
}
|
||||
ByteConversionError::ZeroCopyToError => {
|
||||
@ -187,7 +190,7 @@ impl TryFrom<u8> for SequenceFlags {
|
||||
|
||||
/// Abstraction for the CCSDS Packet ID, which forms the last thirteen bits
|
||||
/// of the first two bytes in the CCSDS primary header.
|
||||
#[derive(Debug, PartialEq, Eq, Copy, Clone)]
|
||||
#[derive(Debug, Eq, Copy, Clone)]
|
||||
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
||||
pub struct PacketId {
|
||||
pub ptype: PacketType,
|
||||
@ -195,6 +198,31 @@ pub struct PacketId {
|
||||
apid: u16,
|
||||
}
|
||||
|
||||
impl PartialEq for PacketId {
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
self.raw().eq(&other.raw())
|
||||
}
|
||||
}
|
||||
|
||||
impl PartialOrd for PacketId {
|
||||
fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> {
|
||||
self.raw().partial_cmp(&other.raw())
|
||||
}
|
||||
}
|
||||
|
||||
impl Ord for PacketId {
|
||||
fn cmp(&self, other: &Self) -> core::cmp::Ordering {
|
||||
self.raw().cmp(&other.raw())
|
||||
}
|
||||
}
|
||||
|
||||
impl Hash for PacketId {
|
||||
fn hash<H: core::hash::Hasher>(&self, state: &mut H) {
|
||||
let raw = self.raw();
|
||||
raw.hash(state);
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for PacketId {
|
||||
fn default() -> Self {
|
||||
PacketId {
|
||||
@ -255,6 +283,7 @@ impl PacketId {
|
||||
self.apid
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn raw(&self) -> u16 {
|
||||
((self.ptype as u16) << 12) | ((self.sec_header_flag as u16) << 11) | self.apid
|
||||
}
|
||||
@ -564,10 +593,10 @@ impl SpHeader {
|
||||
/// CCSDS header.
|
||||
pub fn from_be_bytes(buf: &[u8]) -> Result<(Self, &[u8]), ByteConversionError> {
|
||||
if buf.len() < CCSDS_HEADER_LEN {
|
||||
return Err(ByteConversionError::FromSliceTooSmall(SizeMissmatch {
|
||||
return Err(ByteConversionError::FromSliceTooSmall {
|
||||
found: buf.len(),
|
||||
expected: CCSDS_HEADER_LEN,
|
||||
}));
|
||||
});
|
||||
}
|
||||
let zc_header = zc::SpHeader::from_bytes(&buf[0..CCSDS_HEADER_LEN])
|
||||
.ok_or(ByteConversionError::ZeroCopyFromError)?;
|
||||
@ -581,10 +610,10 @@ impl SpHeader {
|
||||
buf: &'a mut [u8],
|
||||
) -> Result<&'a mut [u8], ByteConversionError> {
|
||||
if buf.len() < CCSDS_HEADER_LEN {
|
||||
return Err(ByteConversionError::FromSliceTooSmall(SizeMissmatch {
|
||||
return Err(ByteConversionError::FromSliceTooSmall {
|
||||
found: buf.len(),
|
||||
expected: CCSDS_HEADER_LEN,
|
||||
}));
|
||||
});
|
||||
}
|
||||
let zc_header: zc::SpHeader = zc::SpHeader::from(*self);
|
||||
zc_header
|
||||
@ -641,9 +670,9 @@ sph_from_other!(SpHeader, crate::zc::SpHeader);
|
||||
pub mod zc {
|
||||
use crate::{CcsdsPacket, CcsdsPrimaryHeader, PacketId, PacketSequenceCtrl, VERSION_MASK};
|
||||
use zerocopy::byteorder::NetworkEndian;
|
||||
use zerocopy::{AsBytes, FromBytes, Unaligned, U16};
|
||||
use zerocopy::{AsBytes, FromBytes, FromZeroes, Unaligned, U16};
|
||||
|
||||
#[derive(FromBytes, AsBytes, Unaligned, Debug)]
|
||||
#[derive(FromBytes, FromZeroes, AsBytes, Unaligned, Debug)]
|
||||
#[repr(C)]
|
||||
pub struct SpHeader {
|
||||
version_packet_id: U16<NetworkEndian>,
|
||||
@ -721,6 +750,8 @@ pub mod zc {
|
||||
|
||||
#[cfg(all(test, feature = "std"))]
|
||||
mod tests {
|
||||
use std::collections::HashSet;
|
||||
|
||||
#[cfg(feature = "serde")]
|
||||
use crate::CcsdsPrimaryHeader;
|
||||
use crate::{
|
||||
@ -1034,4 +1065,22 @@ mod tests {
|
||||
assert_eq!(sp_header.ptype(), PacketType::Tc);
|
||||
assert_eq!(sp_header.data_len(), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn packet_id_ord_partial_ord() {
|
||||
let packet_id_small = PacketId::from(1_u16);
|
||||
let packet_id_larger = PacketId::from(2_u16);
|
||||
assert!(packet_id_small < packet_id_larger);
|
||||
assert!(packet_id_larger > packet_id_small);
|
||||
assert_eq!(
|
||||
packet_id_small.cmp(&packet_id_larger),
|
||||
core::cmp::Ordering::Less
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn packet_id_hashable() {
|
||||
let mut id_set = HashSet::new();
|
||||
id_set.insert(PacketId::from(1_u16));
|
||||
}
|
||||
}
|
||||
|
@ -428,14 +428,17 @@ pub fn get_dyn_time_provider_from_bytes(
|
||||
) -> Result<Box<dyn DynCdsTimeProvider>, TimestampError> {
|
||||
let time_code = ccsds_time_code_from_p_field(buf[0]);
|
||||
if let Err(e) = time_code {
|
||||
return Err(TimestampError::InvalidTimeCode(CcsdsTimeCodes::Cds, e));
|
||||
return Err(TimestampError::InvalidTimeCode {
|
||||
expected: CcsdsTimeCodes::Cds,
|
||||
found: e,
|
||||
});
|
||||
}
|
||||
let time_code = time_code.unwrap();
|
||||
if time_code != CcsdsTimeCodes::Cds {
|
||||
return Err(TimestampError::InvalidTimeCode(
|
||||
CcsdsTimeCodes::Cds,
|
||||
time_code as u8,
|
||||
));
|
||||
return Err(TimestampError::InvalidTimeCode {
|
||||
expected: CcsdsTimeCodes::Cds,
|
||||
found: time_code as u8,
|
||||
});
|
||||
}
|
||||
if length_of_day_segment_from_pfield(buf[0]) == LengthOfDaySegment::Short16Bits {
|
||||
Ok(Box::new(TimeProvider::from_bytes_with_u16_days(buf)?))
|
||||
@ -512,10 +515,10 @@ impl<ProvidesDaysLen: ProvidesDaysLength> TimeProvider<ProvidesDaysLen> {
|
||||
) -> Result<SubmillisPrecision, TimestampError> {
|
||||
if buf.len() < MIN_CDS_FIELD_LEN {
|
||||
return Err(TimestampError::ByteConversion(
|
||||
ByteConversionError::FromSliceTooSmall(SizeMissmatch {
|
||||
ByteConversionError::FromSliceTooSmall {
|
||||
expected: MIN_CDS_FIELD_LEN,
|
||||
found: buf.len(),
|
||||
}),
|
||||
},
|
||||
));
|
||||
}
|
||||
let pfield = buf[0];
|
||||
@ -523,17 +526,17 @@ impl<ProvidesDaysLen: ProvidesDaysLength> TimeProvider<ProvidesDaysLen> {
|
||||
Ok(cds_type) => match cds_type {
|
||||
CcsdsTimeCodes::Cds => (),
|
||||
_ => {
|
||||
return Err(TimestampError::InvalidTimeCode(
|
||||
CcsdsTimeCodes::Cds,
|
||||
cds_type as u8,
|
||||
))
|
||||
return Err(TimestampError::InvalidTimeCode {
|
||||
expected: CcsdsTimeCodes::Cds,
|
||||
found: cds_type as u8,
|
||||
})
|
||||
}
|
||||
},
|
||||
_ => {
|
||||
return Err(TimestampError::InvalidTimeCode(
|
||||
CcsdsTimeCodes::Cds,
|
||||
pfield >> 4 & 0b111,
|
||||
))
|
||||
return Err(TimestampError::InvalidTimeCode {
|
||||
expected: CcsdsTimeCodes::Cds,
|
||||
found: pfield >> 4 & 0b111,
|
||||
});
|
||||
}
|
||||
};
|
||||
if ((pfield >> 3) & 0b1) == 1 {
|
||||
@ -546,10 +549,10 @@ impl<ProvidesDaysLen: ProvidesDaysLength> TimeProvider<ProvidesDaysLen> {
|
||||
let stamp_len = Self::calc_stamp_len(pfield);
|
||||
if buf.len() < stamp_len {
|
||||
return Err(TimestampError::ByteConversion(
|
||||
ByteConversionError::FromSliceTooSmall(SizeMissmatch {
|
||||
ByteConversionError::FromSliceTooSmall {
|
||||
expected: stamp_len,
|
||||
found: buf.len(),
|
||||
}),
|
||||
},
|
||||
));
|
||||
}
|
||||
Ok(precision_from_pfield(pfield))
|
||||
@ -603,10 +606,10 @@ impl<ProvidesDaysLen: ProvidesDaysLength> TimeProvider<ProvidesDaysLen> {
|
||||
fn length_check(&self, buf: &[u8], len_as_bytes: usize) -> Result<(), TimestampError> {
|
||||
if buf.len() < len_as_bytes {
|
||||
return Err(TimestampError::ByteConversion(
|
||||
ByteConversionError::ToSliceTooSmall(SizeMissmatch {
|
||||
ByteConversionError::ToSliceTooSmall {
|
||||
expected: len_as_bytes,
|
||||
found: buf.len(),
|
||||
}),
|
||||
},
|
||||
));
|
||||
}
|
||||
Ok(())
|
||||
@ -1445,9 +1448,9 @@ mod tests {
|
||||
let res = time_stamper.write_to_bytes(&mut buf[0..i]);
|
||||
assert!(res.is_err());
|
||||
match res.unwrap_err() {
|
||||
ByteConversion(ToSliceTooSmall(missmatch)) => {
|
||||
assert_eq!(missmatch.found, i);
|
||||
assert_eq!(missmatch.expected, 7);
|
||||
ByteConversion(ToSliceTooSmall { found, expected }) => {
|
||||
assert_eq!(found, i);
|
||||
assert_eq!(expected, 7);
|
||||
}
|
||||
_ => panic!(
|
||||
"{}",
|
||||
@ -1466,9 +1469,9 @@ mod tests {
|
||||
let err = res.unwrap_err();
|
||||
match err {
|
||||
ByteConversion(e) => match e {
|
||||
FromSliceTooSmall(missmatch) => {
|
||||
assert_eq!(missmatch.found, i);
|
||||
assert_eq!(missmatch.expected, 7);
|
||||
FromSliceTooSmall { found, expected } => {
|
||||
assert_eq!(found, i);
|
||||
assert_eq!(expected, 7);
|
||||
}
|
||||
_ => panic!("{}", format!("Invalid error {:?} detected", e)),
|
||||
},
|
||||
@ -1490,9 +1493,9 @@ mod tests {
|
||||
assert!(res.is_err());
|
||||
let err = res.unwrap_err();
|
||||
match err {
|
||||
InvalidTimeCode(code, raw) => {
|
||||
assert_eq!(code, CcsdsTimeCodes::Cds);
|
||||
assert_eq!(raw, 0);
|
||||
InvalidTimeCode { expected, found } => {
|
||||
assert_eq!(expected, CcsdsTimeCodes::Cds);
|
||||
assert_eq!(found, 0);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
@ -1713,11 +1716,12 @@ mod tests {
|
||||
}
|
||||
|
||||
fn generic_dt_case_0_no_prec(subsec_millis: u32) -> DateTime<Utc> {
|
||||
let naivedatetime_utc = NaiveDate::from_ymd_opt(2023, 01, 14)
|
||||
NaiveDate::from_ymd_opt(2023, 1, 14)
|
||||
.unwrap()
|
||||
.and_hms_milli_opt(16, 49, 30, subsec_millis)
|
||||
.unwrap();
|
||||
DateTime::<Utc>::from_utc(naivedatetime_utc, Utc)
|
||||
.unwrap()
|
||||
.and_local_timezone(Utc)
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
fn generic_check_dt_case_0<DaysLen: ProvidesDaysLength>(
|
||||
@ -1761,11 +1765,12 @@ mod tests {
|
||||
fn generic_dt_case_1_us_prec(subsec_millis: u32) -> DateTime<Utc> {
|
||||
// 250 ms + 500 us
|
||||
let subsec_micros = subsec_millis * 1000 + 500;
|
||||
let naivedatetime_utc = NaiveDate::from_ymd_opt(2023, 01, 14)
|
||||
NaiveDate::from_ymd_opt(2023, 1, 14)
|
||||
.unwrap()
|
||||
.and_hms_micro_opt(16, 49, 30, subsec_micros)
|
||||
.unwrap();
|
||||
DateTime::<Utc>::from_utc(naivedatetime_utc, Utc)
|
||||
.unwrap()
|
||||
.and_local_timezone(Utc)
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
fn generic_check_dt_case_1_us_prec<DaysLen: ProvidesDaysLength>(
|
||||
@ -1812,12 +1817,13 @@ mod tests {
|
||||
// 250 ms + 500 us
|
||||
let subsec_nanos = subsec_millis * 1000 * 1000 + 500 * 1000;
|
||||
let submilli_nanos = subsec_nanos % 10_u32.pow(6);
|
||||
let naivedatetime_utc = NaiveDate::from_ymd_opt(2023, 01, 14)
|
||||
.unwrap()
|
||||
.and_hms_nano_opt(16, 49, 30, subsec_nanos)
|
||||
.unwrap();
|
||||
(
|
||||
DateTime::<Utc>::from_utc(naivedatetime_utc, Utc),
|
||||
NaiveDate::from_ymd_opt(2023, 1, 14)
|
||||
.unwrap()
|
||||
.and_hms_nano_opt(16, 49, 30, subsec_nanos)
|
||||
.unwrap()
|
||||
.and_local_timezone(Utc)
|
||||
.unwrap(),
|
||||
submilli_nanos,
|
||||
)
|
||||
}
|
||||
@ -1900,11 +1906,12 @@ mod tests {
|
||||
#[test]
|
||||
fn test_creation_from_unix_stamp_1() {
|
||||
let subsec_millis = 250;
|
||||
let naivedatetime_utc = NaiveDate::from_ymd_opt(2023, 01, 14)
|
||||
let datetime_utc = NaiveDate::from_ymd_opt(2023, 1, 14)
|
||||
.unwrap()
|
||||
.and_hms_milli_opt(16, 49, 30, subsec_millis)
|
||||
.unwrap()
|
||||
.and_local_timezone(Utc)
|
||||
.unwrap();
|
||||
let datetime_utc = DateTime::<Utc>::from_utc(naivedatetime_utc, Utc);
|
||||
let time_provider = TimeProvider::from_unix_secs_with_u16_days(&datetime_utc.into())
|
||||
.expect("creating provider from unix stamp failed");
|
||||
// https://www.timeanddate.com/date/durationresult.html?d1=01&m1=01&y1=1958&d2=14&m2=01&y2=2023
|
||||
@ -2182,11 +2189,12 @@ mod tests {
|
||||
#[test]
|
||||
fn test_from_dt_invalid_time() {
|
||||
// Date before CCSDS epoch
|
||||
let naivedatetime_utc = NaiveDate::from_ymd_opt(1957, 12, 31)
|
||||
let datetime_utc = NaiveDate::from_ymd_opt(1957, 12, 31)
|
||||
.unwrap()
|
||||
.and_hms_milli_opt(23, 59, 59, 999)
|
||||
.unwrap()
|
||||
.and_local_timezone(Utc)
|
||||
.unwrap();
|
||||
let datetime_utc = DateTime::<Utc>::from_utc(naivedatetime_utc, Utc);
|
||||
let time_provider = TimeProvider::from_dt_with_u24_days(&datetime_utc);
|
||||
assert!(time_provider.is_err());
|
||||
if let TimestampError::DateBeforeCcsdsEpoch(dt) = time_provider.unwrap_err() {
|
||||
@ -2201,8 +2209,8 @@ mod tests {
|
||||
stamp0.write_to_bytes(&mut buf).unwrap();
|
||||
let stamp1 = TimeProvider::from_bytes_with_u16_days(&buf).unwrap();
|
||||
assert_eq!(stamp0, stamp1);
|
||||
assert!(!(stamp0 < stamp1));
|
||||
assert!(!(stamp1 > stamp0));
|
||||
assert!(stamp0 >= stamp1);
|
||||
assert!(stamp1 <= stamp0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
@ -454,36 +454,36 @@ impl TimeReader for TimeProviderCcsdsEpoch {
|
||||
{
|
||||
if buf.len() < MIN_CUC_LEN {
|
||||
return Err(TimestampError::ByteConversion(
|
||||
ByteConversionError::FromSliceTooSmall(SizeMissmatch {
|
||||
ByteConversionError::FromSliceTooSmall {
|
||||
expected: MIN_CUC_LEN,
|
||||
found: buf.len(),
|
||||
}),
|
||||
},
|
||||
));
|
||||
}
|
||||
match ccsds_time_code_from_p_field(buf[0]) {
|
||||
Ok(code) => {
|
||||
if code != CcsdsTimeCodes::CucCcsdsEpoch {
|
||||
return Err(TimestampError::InvalidTimeCode(
|
||||
CcsdsTimeCodes::CucCcsdsEpoch,
|
||||
code as u8,
|
||||
));
|
||||
return Err(TimestampError::InvalidTimeCode {
|
||||
expected: CcsdsTimeCodes::CucCcsdsEpoch,
|
||||
found: code as u8,
|
||||
});
|
||||
}
|
||||
}
|
||||
Err(raw) => {
|
||||
return Err(TimestampError::InvalidTimeCode(
|
||||
CcsdsTimeCodes::CucCcsdsEpoch,
|
||||
raw,
|
||||
))
|
||||
return Err(TimestampError::InvalidTimeCode {
|
||||
expected: CcsdsTimeCodes::CucCcsdsEpoch,
|
||||
found: raw,
|
||||
});
|
||||
}
|
||||
}
|
||||
let (cntr_len, fractions_len, total_len) =
|
||||
Self::len_components_and_total_from_pfield(buf[0]);
|
||||
if buf.len() < total_len {
|
||||
return Err(TimestampError::ByteConversion(
|
||||
ByteConversionError::FromSliceTooSmall(SizeMissmatch {
|
||||
ByteConversionError::FromSliceTooSmall {
|
||||
expected: total_len,
|
||||
found: buf.len(),
|
||||
}),
|
||||
},
|
||||
));
|
||||
}
|
||||
let mut current_idx = 1;
|
||||
@ -536,10 +536,10 @@ impl TimeWriter for TimeProviderCcsdsEpoch {
|
||||
// Cross check the sizes of the counters against byte widths in the ctor
|
||||
if bytes.len() < self.len_as_bytes() {
|
||||
return Err(TimestampError::ByteConversion(
|
||||
ByteConversionError::ToSliceTooSmall(SizeMissmatch {
|
||||
ByteConversionError::ToSliceTooSmall {
|
||||
found: bytes.len(),
|
||||
expected: self.len_as_bytes(),
|
||||
}),
|
||||
},
|
||||
));
|
||||
}
|
||||
bytes[0] = self.pfield;
|
||||
@ -797,9 +797,13 @@ mod tests {
|
||||
let res = TimeProviderCcsdsEpoch::from_bytes(&buf[0..i]);
|
||||
assert!(res.is_err());
|
||||
let err = res.unwrap_err();
|
||||
if let TimestampError::ByteConversion(ByteConversionError::FromSliceTooSmall(e)) = err {
|
||||
assert_eq!(e.found, i);
|
||||
assert_eq!(e.expected, 2);
|
||||
if let TimestampError::ByteConversion(ByteConversionError::FromSliceTooSmall {
|
||||
found,
|
||||
expected,
|
||||
}) = err
|
||||
{
|
||||
assert_eq!(found, i);
|
||||
assert_eq!(expected, 2);
|
||||
}
|
||||
}
|
||||
let large_stamp = TimeProviderCcsdsEpoch::new_with_fine_fractions(22, 300).unwrap();
|
||||
@ -808,9 +812,13 @@ mod tests {
|
||||
let res = TimeProviderCcsdsEpoch::from_bytes(&buf[0..i]);
|
||||
assert!(res.is_err());
|
||||
let err = res.unwrap_err();
|
||||
if let TimestampError::ByteConversion(ByteConversionError::FromSliceTooSmall(e)) = err {
|
||||
assert_eq!(e.found, i);
|
||||
assert_eq!(e.expected, large_stamp.len_as_bytes());
|
||||
if let TimestampError::ByteConversion(ByteConversionError::FromSliceTooSmall {
|
||||
found,
|
||||
expected,
|
||||
}) = err
|
||||
{
|
||||
assert_eq!(found, i);
|
||||
assert_eq!(expected, large_stamp.len_as_bytes());
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -882,9 +890,13 @@ mod tests {
|
||||
let err = cuc.write_to_bytes(&mut buf[0..i]);
|
||||
assert!(err.is_err());
|
||||
let err = err.unwrap_err();
|
||||
if let TimestampError::ByteConversion(ByteConversionError::ToSliceTooSmall(e)) = err {
|
||||
assert_eq!(e.expected, cuc.len_as_bytes());
|
||||
assert_eq!(e.found, i);
|
||||
if let TimestampError::ByteConversion(ByteConversionError::ToSliceTooSmall {
|
||||
found,
|
||||
expected,
|
||||
}) = err
|
||||
{
|
||||
assert_eq!(expected, cuc.len_as_bytes());
|
||||
assert_eq!(found, i);
|
||||
} else {
|
||||
panic!("unexpected error: {}", err);
|
||||
}
|
||||
@ -897,9 +909,9 @@ mod tests {
|
||||
let res = TimeProviderCcsdsEpoch::from_bytes(&buf);
|
||||
assert!(res.is_err());
|
||||
let err = res.unwrap_err();
|
||||
if let TimestampError::InvalidTimeCode(code, raw) = err {
|
||||
assert_eq!(code, CcsdsTimeCodes::CucCcsdsEpoch);
|
||||
assert_eq!(raw, CcsdsTimeCodes::CucAgencyEpoch as u8);
|
||||
if let TimestampError::InvalidTimeCode { expected, found } = err {
|
||||
assert_eq!(expected, CcsdsTimeCodes::CucCcsdsEpoch);
|
||||
assert_eq!(found, CcsdsTimeCodes::CucAgencyEpoch as u8);
|
||||
} else {
|
||||
panic!("unexpected error: {}", err);
|
||||
}
|
||||
|
@ -1,10 +1,11 @@
|
||||
//! CCSDS Time Code Formats according to [CCSDS 301.0-B-4](https://public.ccsds.org/Pubs/301x0b4e1.pdf)
|
||||
use crate::{ByteConversionError, SizeMissmatch};
|
||||
use crate::ByteConversionError;
|
||||
use chrono::{DateTime, LocalResult, TimeZone, Utc};
|
||||
use core::cmp::Ordering;
|
||||
use core::fmt::{Display, Formatter};
|
||||
use core::ops::{Add, AddAssign};
|
||||
use core::time::Duration;
|
||||
use core::u8;
|
||||
|
||||
#[allow(unused_imports)]
|
||||
#[cfg(not(feature = "std"))]
|
||||
@ -63,9 +64,7 @@ pub fn ccsds_time_code_from_p_field(pfield: u8) -> Result<CcsdsTimeCodes, u8> {
|
||||
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
||||
#[non_exhaustive]
|
||||
pub enum TimestampError {
|
||||
/// Contains tuple where first value is the expected time code and the second
|
||||
/// value is the found raw value
|
||||
InvalidTimeCode(CcsdsTimeCodes, u8),
|
||||
InvalidTimeCode { expected: CcsdsTimeCodes, found: u8 },
|
||||
ByteConversion(ByteConversionError),
|
||||
Cds(cds::CdsError),
|
||||
Cuc(cuc::CucError),
|
||||
@ -76,10 +75,10 @@ pub enum TimestampError {
|
||||
impl Display for TimestampError {
|
||||
fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
|
||||
match self {
|
||||
TimestampError::InvalidTimeCode(time_code, raw_val) => {
|
||||
TimestampError::InvalidTimeCode { expected, found } => {
|
||||
write!(
|
||||
f,
|
||||
"invalid raw time code value {raw_val} for time code {time_code:?}"
|
||||
"invalid raw time code value {found} for time code {expected:?}"
|
||||
)
|
||||
}
|
||||
TimestampError::Cds(e) => {
|
||||
|
114
src/util.rs
114
src/util.rs
@ -1,4 +1,4 @@
|
||||
use crate::{ByteConversionError, SizeMissmatch};
|
||||
use crate::ByteConversionError;
|
||||
use core::fmt::{Debug, Display, Formatter};
|
||||
#[cfg(feature = "serde")]
|
||||
use serde::{Deserialize, Serialize};
|
||||
@ -80,12 +80,17 @@ pub trait UnsignedEnumExt: UnsignedEnum + Debug + Copy + Clone + PartialEq + Eq
|
||||
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
|
||||
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
||||
pub enum UnsignedByteFieldError {
|
||||
/// Value is too large for specified width of byte field. The first value contains the width,
|
||||
/// the second value contains the detected value.
|
||||
ValueTooLargeForWidth((usize, u64)),
|
||||
/// Value is too large for specified width of byte field.
|
||||
ValueTooLargeForWidth {
|
||||
width: usize,
|
||||
value: u64,
|
||||
},
|
||||
/// Only 1, 2, 4 and 8 are allow width values. Optionally contains the expected width if
|
||||
/// applicable, for example for conversions.
|
||||
InvalidWidth(usize, Option<usize>),
|
||||
InvalidWidth {
|
||||
found: usize,
|
||||
expected: Option<usize>,
|
||||
},
|
||||
ByteConversionError(ByteConversionError),
|
||||
}
|
||||
|
||||
@ -101,10 +106,10 @@ impl Display for UnsignedByteFieldError {
|
||||
Self::ByteConversionError(e) => {
|
||||
write!(f, "low level byte conversion error: {e}")
|
||||
}
|
||||
Self::InvalidWidth(val, _) => {
|
||||
write!(f, "invalid width {val}, only 1, 2, 4 and 8 are allowed.")
|
||||
Self::InvalidWidth { found, .. } => {
|
||||
write!(f, "invalid width {found}, only 1, 2, 4 and 8 are allowed.")
|
||||
}
|
||||
Self::ValueTooLargeForWidth((width, value)) => {
|
||||
Self::ValueTooLargeForWidth { width, value } => {
|
||||
write!(f, "value {value} too large for width {width}")
|
||||
}
|
||||
}
|
||||
@ -123,7 +128,7 @@ pub struct UnsignedByteField {
|
||||
}
|
||||
|
||||
impl UnsignedByteField {
|
||||
pub fn new(width: usize, value: u64) -> Self {
|
||||
pub const fn new(width: usize, value: u64) -> Self {
|
||||
Self { width, value }
|
||||
}
|
||||
|
||||
@ -133,10 +138,10 @@ impl UnsignedByteField {
|
||||
|
||||
pub fn new_from_be_bytes(width: usize, buf: &[u8]) -> Result<Self, UnsignedByteFieldError> {
|
||||
if width > buf.len() {
|
||||
return Err(ByteConversionError::FromSliceTooSmall(SizeMissmatch {
|
||||
return Err(ByteConversionError::FromSliceTooSmall {
|
||||
expected: width,
|
||||
found: buf.len(),
|
||||
})
|
||||
}
|
||||
.into());
|
||||
}
|
||||
match width {
|
||||
@ -154,7 +159,10 @@ impl UnsignedByteField {
|
||||
width,
|
||||
u64::from_be_bytes(buf[0..8].try_into().unwrap()),
|
||||
)),
|
||||
_ => Err(UnsignedByteFieldError::InvalidWidth(width, None)),
|
||||
_ => Err(UnsignedByteFieldError::InvalidWidth {
|
||||
found: width,
|
||||
expected: None,
|
||||
}),
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -166,10 +174,10 @@ impl UnsignedEnum for UnsignedByteField {
|
||||
|
||||
fn write_to_be_bytes(&self, buf: &mut [u8]) -> Result<usize, ByteConversionError> {
|
||||
if buf.len() < self.size() {
|
||||
return Err(ByteConversionError::ToSliceTooSmall(SizeMissmatch {
|
||||
return Err(ByteConversionError::ToSliceTooSmall {
|
||||
expected: self.size(),
|
||||
found: buf.len(),
|
||||
}));
|
||||
});
|
||||
}
|
||||
match self.size() {
|
||||
0 => Ok(0),
|
||||
@ -204,7 +212,7 @@ pub struct GenericUnsignedByteField<TYPE> {
|
||||
}
|
||||
|
||||
impl<TYPE> GenericUnsignedByteField<TYPE> {
|
||||
pub fn new(val: TYPE) -> Self {
|
||||
pub const fn new(val: TYPE) -> Self {
|
||||
Self { value: val }
|
||||
}
|
||||
}
|
||||
@ -216,10 +224,10 @@ impl<TYPE: ToBeBytes> UnsignedEnum for GenericUnsignedByteField<TYPE> {
|
||||
|
||||
fn write_to_be_bytes(&self, buf: &mut [u8]) -> Result<usize, ByteConversionError> {
|
||||
if buf.len() < self.size() {
|
||||
return Err(ByteConversionError::ToSliceTooSmall(SizeMissmatch {
|
||||
return Err(ByteConversionError::ToSliceTooSmall {
|
||||
found: buf.len(),
|
||||
expected: self.size(),
|
||||
}));
|
||||
});
|
||||
}
|
||||
buf[0..self.size()].copy_from_slice(self.value.to_be_bytes().as_ref());
|
||||
Ok(self.value.written_len())
|
||||
@ -248,7 +256,10 @@ impl TryFrom<UnsignedByteField> for UnsignedByteFieldU8 {
|
||||
|
||||
fn try_from(value: UnsignedByteField) -> Result<Self, Self::Error> {
|
||||
if value.width != 1 {
|
||||
return Err(UnsignedByteFieldError::InvalidWidth(value.width, Some(1)));
|
||||
return Err(UnsignedByteFieldError::InvalidWidth {
|
||||
found: value.width,
|
||||
expected: Some(1),
|
||||
});
|
||||
}
|
||||
Ok(Self::new(value.value as u8))
|
||||
}
|
||||
@ -265,7 +276,10 @@ impl TryFrom<UnsignedByteField> for UnsignedByteFieldU16 {
|
||||
|
||||
fn try_from(value: UnsignedByteField) -> Result<Self, Self::Error> {
|
||||
if value.width != 2 {
|
||||
return Err(UnsignedByteFieldError::InvalidWidth(value.width, Some(2)));
|
||||
return Err(UnsignedByteFieldError::InvalidWidth {
|
||||
found: value.width,
|
||||
expected: Some(2),
|
||||
});
|
||||
}
|
||||
Ok(Self::new(value.value as u16))
|
||||
}
|
||||
@ -282,7 +296,10 @@ impl TryFrom<UnsignedByteField> for UnsignedByteFieldU32 {
|
||||
|
||||
fn try_from(value: UnsignedByteField) -> Result<Self, Self::Error> {
|
||||
if value.width != 4 {
|
||||
return Err(UnsignedByteFieldError::InvalidWidth(value.width, Some(4)));
|
||||
return Err(UnsignedByteFieldError::InvalidWidth {
|
||||
found: value.width,
|
||||
expected: Some(4),
|
||||
});
|
||||
}
|
||||
Ok(Self::new(value.value as u32))
|
||||
}
|
||||
@ -299,7 +316,10 @@ impl TryFrom<UnsignedByteField> for UnsignedByteFieldU64 {
|
||||
|
||||
fn try_from(value: UnsignedByteField) -> Result<Self, Self::Error> {
|
||||
if value.width != 8 {
|
||||
return Err(UnsignedByteFieldError::InvalidWidth(value.width, Some(8)));
|
||||
return Err(UnsignedByteFieldError::InvalidWidth {
|
||||
found: value.width,
|
||||
expected: Some(8),
|
||||
});
|
||||
}
|
||||
Ok(Self::new(value.value))
|
||||
}
|
||||
@ -393,8 +413,11 @@ pub mod tests {
|
||||
assert!(conv_fails.is_err());
|
||||
let err = conv_fails.unwrap_err();
|
||||
match err {
|
||||
UnsignedByteFieldError::InvalidWidth(width, Some(expected)) => {
|
||||
assert_eq!(width, 2);
|
||||
UnsignedByteFieldError::InvalidWidth {
|
||||
found,
|
||||
expected: Some(expected),
|
||||
} => {
|
||||
assert_eq!(found, 2);
|
||||
assert_eq!(expected, 1);
|
||||
}
|
||||
_ => {
|
||||
@ -422,8 +445,11 @@ pub mod tests {
|
||||
assert!(conv_fails.is_err());
|
||||
let err = conv_fails.unwrap_err();
|
||||
match err {
|
||||
UnsignedByteFieldError::InvalidWidth(width, Some(expected)) => {
|
||||
assert_eq!(width, 4);
|
||||
UnsignedByteFieldError::InvalidWidth {
|
||||
found,
|
||||
expected: Some(expected),
|
||||
} => {
|
||||
assert_eq!(found, 4);
|
||||
assert_eq!(expected, 2);
|
||||
}
|
||||
_ => {
|
||||
@ -451,8 +477,11 @@ pub mod tests {
|
||||
assert!(conv_fails.is_err());
|
||||
let err = conv_fails.unwrap_err();
|
||||
match err {
|
||||
UnsignedByteFieldError::InvalidWidth(width, Some(expected)) => {
|
||||
assert_eq!(width, 8);
|
||||
UnsignedByteFieldError::InvalidWidth {
|
||||
found,
|
||||
expected: Some(expected),
|
||||
} => {
|
||||
assert_eq!(found, 8);
|
||||
assert_eq!(expected, 4);
|
||||
}
|
||||
_ => {
|
||||
@ -480,8 +509,11 @@ pub mod tests {
|
||||
assert!(conv_fails.is_err());
|
||||
let err = conv_fails.unwrap_err();
|
||||
match err {
|
||||
UnsignedByteFieldError::InvalidWidth(width, Some(expected)) => {
|
||||
assert_eq!(width, 4);
|
||||
UnsignedByteFieldError::InvalidWidth {
|
||||
found,
|
||||
expected: Some(expected),
|
||||
} => {
|
||||
assert_eq!(found, 4);
|
||||
assert_eq!(expected, 8);
|
||||
}
|
||||
_ => {
|
||||
@ -582,9 +614,9 @@ pub mod tests {
|
||||
assert!(res.is_err());
|
||||
let err = res.unwrap_err();
|
||||
match err {
|
||||
ByteConversionError::ToSliceTooSmall(missmatch) => {
|
||||
assert_eq!(missmatch.found, 1);
|
||||
assert_eq!(missmatch.expected, 2);
|
||||
ByteConversionError::ToSliceTooSmall { found, expected } => {
|
||||
assert_eq!(found, 1);
|
||||
assert_eq!(expected, 2);
|
||||
}
|
||||
_ => {
|
||||
panic!("invalid exception")
|
||||
@ -600,9 +632,9 @@ pub mod tests {
|
||||
assert!(res.is_err());
|
||||
let err = res.unwrap_err();
|
||||
match err {
|
||||
ByteConversionError::ToSliceTooSmall(missmatch) => {
|
||||
assert_eq!(missmatch.found, 1);
|
||||
assert_eq!(missmatch.expected, 2);
|
||||
ByteConversionError::ToSliceTooSmall { found, expected } => {
|
||||
assert_eq!(found, 1);
|
||||
assert_eq!(expected, 2);
|
||||
}
|
||||
_ => {
|
||||
panic!("invalid exception {}", err)
|
||||
@ -612,11 +644,11 @@ pub mod tests {
|
||||
assert!(u16.is_err());
|
||||
let err = u16.unwrap_err();
|
||||
if let UnsignedByteFieldError::ByteConversionError(
|
||||
ByteConversionError::FromSliceTooSmall(missmatch),
|
||||
ByteConversionError::FromSliceTooSmall { found, expected },
|
||||
) = err
|
||||
{
|
||||
assert_eq!(missmatch.expected, 2);
|
||||
assert_eq!(missmatch.found, 1);
|
||||
assert_eq!(expected, 2);
|
||||
assert_eq!(found, 1);
|
||||
} else {
|
||||
panic!("unexpected exception {}", err);
|
||||
}
|
||||
@ -630,9 +662,9 @@ pub mod tests {
|
||||
assert!(res.is_err());
|
||||
let err = res.unwrap_err();
|
||||
match err {
|
||||
ByteConversionError::ToSliceTooSmall(missmatch) => {
|
||||
assert_eq!(missmatch.found, 3);
|
||||
assert_eq!(missmatch.expected, 4);
|
||||
ByteConversionError::ToSliceTooSmall { found, expected } => {
|
||||
assert_eq!(found, 3);
|
||||
assert_eq!(expected, 4);
|
||||
}
|
||||
_ => {
|
||||
panic!("invalid exception")
|
||||
|
Reference in New Issue
Block a user