7 Commits

6 changed files with 1211 additions and 80 deletions

View File

@ -8,6 +8,12 @@ and this project adheres to [Semantic Versioning](http://semver.org/).
# [unreleased]
## Added
- `PusTcCreatorWithReservedAppData` and `PusTmCreatorWithReservedSourceData` constructor variants
which allow writing source/app data into the serialization buffer directly without
requiring an extra buffer.
# [v0.14.0] 2025-05-10
## Changed

View File

@ -377,7 +377,7 @@ pub trait WritablePusPacket {
fn write_to_bytes_no_crc(&self, slice: &mut [u8]) -> Result<usize, PusError>;
/// First uses [Self::write_to_bytes_no_crc] to write the packet to the given slice and then
/// uses the [CRC_CCITT_FALS] to calculate the CRC and write it to the slice.
/// uses the [CRC_CCITT_FALSE] to calculate the CRC and write it to the slice.
fn write_to_bytes(&self, slice: &mut [u8]) -> Result<usize, PusError> {
let mut curr_idx = self.write_to_bytes_no_crc(slice)?;
let mut digest = CRC_CCITT_FALSE.digest();

View File

@ -372,6 +372,49 @@ impl<'app_data> PusTcCreator<'app_data> {
vec.extend_from_slice(&digest.finalize().to_be_bytes());
appended_len
}
/// Write the raw PUS byte representation to a provided buffer.
pub fn write_to_bytes(&self, slice: &mut [u8]) -> Result<usize, ByteConversionError> {
let writer_unfinalized = self.common_write(slice)?;
Ok(writer_unfinalized.finalize())
}
/// Write the raw PUS byte representation to a provided buffer.
pub fn write_to_bytes_crc_no_table(
&self,
slice: &mut [u8],
) -> Result<usize, ByteConversionError> {
let writer_unfinalized = self.common_write(slice)?;
Ok(writer_unfinalized.finalize_crc_no_table())
}
/// Write the raw PUS byte representation to a provided buffer.
pub fn write_to_bytes_no_crc(&self, slice: &mut [u8]) -> Result<usize, ByteConversionError> {
let writer_unfinalized = self.common_write(slice)?;
Ok(writer_unfinalized.finalize_no_crc())
}
fn common_write<'a>(
&self,
slice: &'a mut [u8],
) -> Result<PusTcCreatorWithReservedAppData<'a>, ByteConversionError> {
if self.len_written() > slice.len() {
return Err(ByteConversionError::ToSliceTooSmall {
found: slice.len(),
expected: self.len_written(),
});
}
let mut writer_unfinalized = PusTcCreatorWithReservedAppData::write_to_bytes_partially(
slice,
self.sp_header,
self.sec_header,
self.app_data.len(),
)?;
writer_unfinalized
.app_data_mut()
.copy_from_slice(self.app_data);
Ok(writer_unfinalized)
}
}
impl WritablePusPacket for PusTcCreator<'_> {
@ -380,31 +423,17 @@ impl WritablePusPacket for PusTcCreator<'_> {
PUS_TC_MIN_LEN_WITHOUT_APP_DATA + self.app_data.len()
}
/// Writes the packet to the given slice without writing the CRC.
///
/// The returned size is the written size WITHOUT the CRC.
/// Write the raw PUS byte representation to a provided buffer.
fn write_to_bytes_no_crc(&self, slice: &mut [u8]) -> Result<usize, PusError> {
let mut curr_idx = 0;
let tc_header_len = size_of::<zc::PusTcSecondaryHeader>();
let total_size = self.len_written();
if total_size > slice.len() {
return Err(ByteConversionError::ToSliceTooSmall {
found: slice.len(),
expected: total_size,
}
.into());
}
self.sp_header.write_to_be_bytes(slice)?;
curr_idx += CCSDS_HEADER_LEN;
let sec_header = zc::PusTcSecondaryHeader::try_from(self.sec_header).unwrap();
sec_header
.write_to(&mut slice[curr_idx..curr_idx + tc_header_len])
.map_err(|_| ByteConversionError::ZeroCopyToError)?;
Ok(Self::write_to_bytes_no_crc(self, slice)?)
}
curr_idx += tc_header_len;
slice[curr_idx..curr_idx + self.app_data.len()].copy_from_slice(self.app_data);
curr_idx += self.app_data.len();
Ok(curr_idx)
fn write_to_bytes(&self, slice: &mut [u8]) -> Result<usize, PusError> {
Ok(Self::write_to_bytes(self, slice)?)
}
fn write_to_bytes_crc_no_table(&self, slice: &mut [u8]) -> Result<usize, PusError> {
Ok(Self::write_to_bytes_crc_no_table(self, slice)?)
}
}
@ -450,6 +479,133 @@ impl GenericPusTcSecondaryHeader for PusTcCreator<'_> {
impl IsPusTelecommand for PusTcCreator<'_> {}
/// A specialized variant of [PusTcCreator] designed for efficiency when handling large source
/// data.
///
/// Unlike [PusTcCreator], this type does not require the user to provide the application data
/// as a separate slice. Instead, it allows writing the application data directly into the provided
/// serialization buffer. This eliminates the need for an intermediate buffer and the associated
/// memory copy, improving performance, particularly when working with large payloads.
///
/// **Important:** The total length of the source data must be known and specified in advance
/// to ensure correct serialization behavior.
///
/// Note that this abstraction intentionally omits certain trait implementations that are available
/// on [PusTcCreator], as they are not applicable in this optimized usage pattern.
pub struct PusTcCreatorWithReservedAppData<'buf> {
buf: &'buf mut [u8],
app_data_offset: usize,
full_len: usize,
}
impl<'buf> PusTcCreatorWithReservedAppData<'buf> {
/// Generates a new instance with reserved space for the user application data.
///
/// # Arguments
///
/// * `sp_header` - Space packet header information. The correct packet type and the secondary
/// header flag are set correctly by the constructor.
/// * `sec_header` - Information contained in the secondary header, including the service
/// and subservice type
/// * `app_data_len` - Custom application data length
#[inline]
pub fn new(
buf: &'buf mut [u8],
mut sp_header: SpHeader,
sec_header: PusTcSecondaryHeader,
app_data_len: usize,
) -> Result<Self, ByteConversionError> {
sp_header.set_packet_type(PacketType::Tc);
sp_header.set_sec_header_flag();
let len_written = PUS_TC_MIN_LEN_WITHOUT_APP_DATA + app_data_len;
if len_written > buf.len() {
return Err(ByteConversionError::ToSliceTooSmall {
found: buf.len(),
expected: len_written,
});
}
sp_header.data_len = len_written as u16 - size_of::<crate::zc::SpHeader>() as u16 - 1;
Self::write_to_bytes_partially(buf, sp_header, sec_header, app_data_len)
}
fn write_to_bytes_partially(
buf: &'buf mut [u8],
sp_header: SpHeader,
sec_header: PusTcSecondaryHeader,
app_data_len: usize,
) -> Result<Self, ByteConversionError> {
let mut curr_idx = 0;
sp_header.write_to_be_bytes(&mut buf[0..CCSDS_HEADER_LEN])?;
curr_idx += CCSDS_HEADER_LEN;
let sec_header_len = size_of::<zc::PusTcSecondaryHeader>();
let sec_header_zc = zc::PusTcSecondaryHeader::try_from(sec_header).unwrap();
sec_header_zc
.write_to(&mut buf[curr_idx..curr_idx + sec_header_len])
.map_err(|_| ByteConversionError::ZeroCopyToError)?;
curr_idx += sec_header_len;
let app_data_offset = curr_idx;
curr_idx += app_data_len;
Ok(Self {
buf,
app_data_offset,
full_len: curr_idx + 2,
})
}
#[inline]
pub const fn len_written(&self) -> usize {
self.full_len
}
/// Mutable access to the application data buffer.
#[inline]
pub fn app_data_mut(&mut self) -> &mut [u8] {
&mut self.buf[self.app_data_offset..self.full_len - 2]
}
/// Access to the source data buffer.
#[inline]
pub fn app_data(&self) -> &[u8] {
&self.buf[self.app_data_offset..self.full_len - 2]
}
#[inline]
pub fn app_data_len(&self) -> usize {
self.full_len - 2 - self.app_data_offset
}
/// Finalize the TC packet by calculating and writing the CRC16.
///
/// Returns the full packet length.
pub fn finalize(self) -> usize {
let mut digest = CRC_CCITT_FALSE.digest();
digest.update(&self.buf[0..self.full_len - 2]);
self.buf[self.full_len - 2..self.full_len]
.copy_from_slice(&digest.finalize().to_be_bytes());
self.full_len
}
/// Finalize the TC packet by calculating and writing the CRC16 using a table-less
/// implementation.
///
/// Returns the full packet length.
pub fn finalize_crc_no_table(self) -> usize {
let mut digest = CRC_CCITT_FALSE_NO_TABLE.digest();
digest.update(&self.buf[0..self.full_len - 2]);
self.buf[self.full_len - 2..self.full_len]
.copy_from_slice(&digest.finalize().to_be_bytes());
self.full_len
}
/// Finalize the TC packet without writing the CRC16.
///
/// Returns the length WITHOUT the CRC16.
#[inline]
pub fn finalize_no_crc(self) -> usize {
self.full_len - 2
}
}
/// This class can be used to read a PUS TC telecommand from raw memory.
///
/// This class also derives the [serde::Serialize] and [serde::Deserialize] trait if the
@ -627,8 +783,6 @@ impl PartialEq<PusTcReader<'_>> for PusTcCreator<'_> {
#[cfg(all(test, feature = "std"))]
mod tests {
use std::error::Error;
use super::*;
use crate::ecss::PusVersion::PusC;
use crate::ecss::{PusError, PusPacket, WritablePusPacket};
@ -675,6 +829,32 @@ mod tests {
);
}
#[test]
fn test_serialization_with_trait_1() {
let pus_tc = base_ping_tc_simple_ctor();
let mut test_buf: [u8; 32] = [0; 32];
let size = WritablePusPacket::write_to_bytes(&pus_tc, test_buf.as_mut_slice())
.expect("Error writing TC to buffer");
assert_eq!(size, 13);
assert_eq!(
pus_tc.opt_crc16().unwrap(),
u16::from_be_bytes(test_buf[size - 2..size].try_into().unwrap())
);
}
#[test]
fn test_serialization_with_trait_2() {
let pus_tc = base_ping_tc_simple_ctor();
let mut test_buf: [u8; 32] = [0; 32];
let size = WritablePusPacket::write_to_bytes_crc_no_table(&pus_tc, test_buf.as_mut_slice())
.expect("Error writing TC to buffer");
assert_eq!(size, 13);
assert_eq!(
pus_tc.opt_crc16().unwrap(),
u16::from_be_bytes(test_buf[size - 2..size].try_into().unwrap())
);
}
#[test]
fn test_serialization_crc_no_table() {
let pus_tc = base_ping_tc_simple_ctor();
@ -701,6 +881,17 @@ mod tests {
assert_eq!(test_buf[12], 0);
}
#[test]
fn test_serialization_no_crc_with_trait() {
let pus_tc = base_ping_tc_simple_ctor();
let mut test_buf: [u8; 32] = [0; 32];
let size = WritablePusPacket::write_to_bytes_no_crc(&pus_tc, test_buf.as_mut_slice())
.expect("error writing tc to buffer");
assert_eq!(size, 11);
assert_eq!(test_buf[11], 0);
assert_eq!(test_buf[12], 0);
}
#[test]
fn test_deserialization() {
let pus_tc = base_ping_tc_simple_ctor();
@ -718,6 +909,28 @@ mod tests {
verify_crc_no_app_data(&test_buf);
}
#[test]
fn test_deserialization_alt_ctor() {
let sph = SpHeader::new_for_unseg_tc_checked(0x02, 0x34, 0).unwrap();
let tc_header = PusTcSecondaryHeader::new_simple(17, 1);
let mut test_buf: [u8; 32] = [0; 32];
let mut pus_tc =
PusTcCreatorWithReservedAppData::new(&mut test_buf, sph, tc_header, 0).unwrap();
assert_eq!(pus_tc.len_written(), 13);
assert_eq!(pus_tc.app_data_len(), 0);
assert_eq!(pus_tc.app_data(), &[]);
assert_eq!(pus_tc.app_data_mut(), &[]);
let size = pus_tc.finalize();
assert_eq!(size, 13);
let tc_from_raw =
PusTcReader::new(&test_buf).expect("Creating PUS TC struct from raw buffer failed");
assert_eq!(tc_from_raw.total_len(), 13);
verify_test_tc_with_reader(&tc_from_raw, false, 13);
assert!(tc_from_raw.user_data().is_empty());
verify_test_tc_raw(&test_buf);
verify_crc_no_app_data(&test_buf);
}
#[test]
fn test_deserialization_no_table() {
let pus_tc = base_ping_tc_simple_ctor();
@ -757,6 +970,7 @@ mod tests {
tc.update_ccsds_data_len();
assert_eq!(tc.data_len(), 6);
}
#[test]
fn test_deserialization_with_app_data() {
let pus_tc = base_ping_tc_simple_ctor_with_app_data(&[1, 2, 3]);
@ -859,22 +1073,17 @@ mod tests {
let res = pus_tc.write_to_bytes(test_buf.as_mut_slice());
assert!(res.is_err());
let err = res.unwrap_err();
if let PusError::ByteConversion(e) = err {
assert_eq!(
e,
ByteConversionError::ToSliceTooSmall {
found: 12,
expected: 13
}
);
assert_eq!(
err.to_string(),
"pus error: target slice with size 12 is too small, expected size of at least 13"
);
assert_eq!(err.source().unwrap().to_string(), e.to_string());
} else {
panic!("unexpected error {err}");
}
assert_eq!(
err,
ByteConversionError::ToSliceTooSmall {
found: 12,
expected: 13
}
);
assert_eq!(
err.to_string(),
"target slice with size 12 is too small, expected size of at least 13"
);
}
#[test]

View File

@ -392,12 +392,8 @@ impl<'time, 'src_data> PusTmCreator<'time, 'src_data> {
/// Write the raw PUS byte representation to a provided buffer.
pub fn write_to_bytes(&self, slice: &mut [u8]) -> Result<usize, ByteConversionError> {
let mut curr_idx = self.write_to_bytes_no_crc(slice)?;
let mut digest = CRC_CCITT_FALSE.digest();
digest.update(&slice[0..curr_idx]);
slice[curr_idx..curr_idx + 2].copy_from_slice(&digest.finalize().to_be_bytes());
curr_idx += 2;
Ok(curr_idx)
let writer_unfinalized = self.common_write(slice)?;
Ok(writer_unfinalized.finalize())
}
/// Write the raw PUS byte representation to a provided buffer.
@ -405,39 +401,36 @@ impl<'time, 'src_data> PusTmCreator<'time, 'src_data> {
&self,
slice: &mut [u8],
) -> Result<usize, ByteConversionError> {
let mut curr_idx = self.write_to_bytes_no_crc(slice)?;
let mut digest = CRC_CCITT_FALSE_NO_TABLE.digest();
digest.update(&slice[0..curr_idx]);
slice[curr_idx..curr_idx + 2].copy_from_slice(&digest.finalize().to_be_bytes());
curr_idx += 2;
Ok(curr_idx)
let writer_unfinalized = self.common_write(slice)?;
Ok(writer_unfinalized.finalize_crc_no_table())
}
/// Write the raw PUS byte representation to a provided buffer.
pub fn write_to_bytes_no_crc(&self, slice: &mut [u8]) -> Result<usize, ByteConversionError> {
let mut curr_idx = 0;
let total_size = self.len_written();
if total_size > slice.len() {
let writer_unfinalized = self.common_write(slice)?;
Ok(writer_unfinalized.finalize_no_crc())
}
fn common_write<'a>(
&self,
slice: &'a mut [u8],
) -> Result<PusTmCreatorWithReservedSourceData<'a>, ByteConversionError> {
if self.len_written() > slice.len() {
return Err(ByteConversionError::ToSliceTooSmall {
found: slice.len(),
expected: total_size,
expected: self.len_written(),
});
}
self.sp_header
.write_to_be_bytes(&mut slice[0..CCSDS_HEADER_LEN])?;
curr_idx += CCSDS_HEADER_LEN;
let sec_header_len = size_of::<zc::PusTmSecHeaderWithoutTimestamp>();
let sec_header = zc::PusTmSecHeaderWithoutTimestamp::try_from(self.sec_header).unwrap();
sec_header
.write_to(&mut slice[curr_idx..curr_idx + sec_header_len])
.map_err(|_| ByteConversionError::ZeroCopyToError)?;
curr_idx += sec_header_len;
slice[curr_idx..curr_idx + self.sec_header.timestamp.len()]
.copy_from_slice(self.sec_header.timestamp);
curr_idx += self.sec_header.timestamp.len();
slice[curr_idx..curr_idx + self.source_data.len()].copy_from_slice(self.source_data);
curr_idx += self.source_data.len();
Ok(curr_idx)
let mut writer_unfinalized = PusTmCreatorWithReservedSourceData::write_to_bytes_partially(
slice,
self.sp_header,
self.sec_header,
self.source_data.len(),
)?;
writer_unfinalized
.source_data_mut()
.copy_from_slice(self.source_data);
Ok(writer_unfinalized)
}
/// Append the raw PUS byte representation to a provided [alloc::vec::Vec]
@ -471,9 +464,18 @@ impl WritablePusPacket for PusTmCreator<'_, '_> {
fn write_to_bytes_no_crc(&self, slice: &mut [u8]) -> Result<usize, PusError> {
Ok(Self::write_to_bytes_no_crc(self, slice)?)
}
fn write_to_bytes(&self, slice: &mut [u8]) -> Result<usize, PusError> {
Ok(Self::write_to_bytes(self, slice)?)
}
fn write_to_bytes_crc_no_table(&self, slice: &mut [u8]) -> Result<usize, PusError> {
Ok(Self::write_to_bytes_crc_no_table(self, slice)?)
}
}
impl PartialEq for PusTmCreator<'_, '_> {
#[inline]
fn eq(&self, other: &Self) -> bool {
self.sp_header == other.sp_header
&& self.sec_header == other.sec_header
@ -525,6 +527,136 @@ impl GenericPusTmSecondaryHeader for PusTmCreator<'_, '_> {
impl IsPusTelemetry for PusTmCreator<'_, '_> {}
/// A specialized variant of [PusTmCreator] designed for efficiency when handling large source
/// data.
///
/// Unlike [PusTmCreator], this type does not require the user to provide the source data
/// as a separate slice. Instead, it allows writing the source data directly into the provided
/// serialization buffer. This eliminates the need for an intermediate buffer and the associated
/// memory copy, improving performance, particularly when working with large payloads.
///
/// **Important:** The total length of the source data must be known and specified in advance
/// to ensure correct serialization behavior.
///
/// Note that this abstraction intentionally omits certain trait implementations that are available
/// on [PusTmCreator], as they are not applicable in this optimized usage pattern.
pub struct PusTmCreatorWithReservedSourceData<'buf> {
buf: &'buf mut [u8],
source_data_offset: usize,
full_len: usize,
}
impl<'buf> PusTmCreatorWithReservedSourceData<'buf> {
/// Generates a new instance with reserved space for the user source data.
///
/// # Arguments
///
/// * `sp_header` - Space packet header information. The correct packet type and the secondary
/// header flag are set correctly by the constructor.
/// * `sec_header` - Information contained in the secondary header, including the service
/// and subservice type
/// * `src_data_len` - Custom source data length
#[inline]
pub fn new(
buf: &'buf mut [u8],
mut sp_header: SpHeader,
sec_header: PusTmSecondaryHeader,
src_data_len: usize,
) -> Result<Self, ByteConversionError> {
sp_header.set_packet_type(PacketType::Tm);
sp_header.set_sec_header_flag();
let len_written =
PUS_TM_MIN_LEN_WITHOUT_SOURCE_DATA + sec_header.timestamp.len() + src_data_len;
if len_written > buf.len() {
return Err(ByteConversionError::ToSliceTooSmall {
found: buf.len(),
expected: len_written,
});
}
sp_header.data_len = len_written as u16 - size_of::<crate::zc::SpHeader>() as u16 - 1;
Self::write_to_bytes_partially(buf, sp_header, sec_header, src_data_len)
}
fn write_to_bytes_partially(
buf: &'buf mut [u8],
sp_header: SpHeader,
sec_header: PusTmSecondaryHeader,
src_data_len: usize,
) -> Result<Self, ByteConversionError> {
let mut curr_idx = 0;
sp_header.write_to_be_bytes(&mut buf[0..CCSDS_HEADER_LEN])?;
curr_idx += CCSDS_HEADER_LEN;
let sec_header_len = size_of::<zc::PusTmSecHeaderWithoutTimestamp>();
let sec_header_zc = zc::PusTmSecHeaderWithoutTimestamp::try_from(sec_header).unwrap();
sec_header_zc
.write_to(&mut buf[curr_idx..curr_idx + sec_header_len])
.map_err(|_| ByteConversionError::ZeroCopyToError)?;
curr_idx += sec_header_len;
buf[curr_idx..curr_idx + sec_header.timestamp.len()].copy_from_slice(sec_header.timestamp);
curr_idx += sec_header.timestamp.len();
let source_data_offset = curr_idx;
curr_idx += src_data_len;
Ok(Self {
buf,
source_data_offset,
full_len: curr_idx + 2,
})
}
#[inline]
pub const fn len_written(&self) -> usize {
self.full_len
}
/// Mutable access to the source data buffer.
#[inline]
pub fn source_data_mut(&mut self) -> &mut [u8] {
&mut self.buf[self.source_data_offset..self.full_len - 2]
}
/// Access to the source data buffer.
#[inline]
pub fn source_data(&self) -> &[u8] {
&self.buf[self.source_data_offset..self.full_len - 2]
}
#[inline]
pub fn source_data_len(&self) -> usize {
self.full_len - 2 - self.source_data_offset
}
/// Finalize the TM packet by calculating and writing the CRC16.
///
/// Returns the full packet length.
pub fn finalize(self) -> usize {
let mut digest = CRC_CCITT_FALSE.digest();
digest.update(&self.buf[0..self.full_len - 2]);
self.buf[self.full_len - 2..self.full_len]
.copy_from_slice(&digest.finalize().to_be_bytes());
self.full_len
}
/// Finalize the TM packet by calculating and writing the CRC16 using a table-less
/// implementation.
///
/// Returns the full packet length.
pub fn finalize_crc_no_table(self) -> usize {
let mut digest = CRC_CCITT_FALSE_NO_TABLE.digest();
digest.update(&self.buf[0..self.full_len - 2]);
self.buf[self.full_len - 2..self.full_len]
.copy_from_slice(&digest.finalize().to_be_bytes());
self.full_len
}
/// Finalize the TM packet without writing the CRC16.
///
/// Returns the length WITHOUT the CRC16.
#[inline]
pub fn finalize_no_crc(self) -> usize {
self.full_len - 2
}
}
/// This class models the PUS C telemetry packet. It is the primary data structure to read
/// a telemetry packet from raw bytes.
///
@ -962,7 +1094,41 @@ mod tests {
.write_to_bytes(&mut buf)
.expect("Serialization failed");
assert_eq!(ser_len, 22);
verify_raw_ping_reply(pus_tm.opt_crc16().unwrap(), &buf);
verify_raw_ping_reply(pus_tm.opt_crc16(), &buf);
}
#[test]
fn test_serialization_no_source_data_alt_ctor() {
let timestamp = dummy_timestamp();
let sph = SpHeader::new_for_unseg_tm_checked(0x123, 0x234, 0).unwrap();
let tm_header = PusTmSecondaryHeader::new_simple(17, 2, timestamp);
let mut buf: [u8; 32] = [0; 32];
let mut pus_tm =
PusTmCreatorWithReservedSourceData::new(&mut buf, sph, tm_header, 0).unwrap();
assert_eq!(pus_tm.source_data_len(), 0);
assert_eq!(pus_tm.source_data(), &[]);
assert_eq!(pus_tm.source_data_mut(), &[]);
let ser_len = pus_tm.finalize();
assert_eq!(ser_len, 22);
verify_raw_ping_reply(None, &buf);
}
#[test]
fn test_serialization_no_source_data_alt_ctor_no_crc() {
let timestamp = dummy_timestamp();
let sph = SpHeader::new_for_unseg_tm_checked(0x123, 0x234, 0).unwrap();
let tm_header = PusTmSecondaryHeader::new_simple(17, 2, timestamp);
let mut buf: [u8; 32] = [0; 32];
let mut pus_tm =
PusTmCreatorWithReservedSourceData::new(&mut buf, sph, tm_header, 0).unwrap();
assert_eq!(pus_tm.source_data_len(), 0);
assert_eq!(pus_tm.source_data(), &[]);
assert_eq!(pus_tm.source_data_mut(), &[]);
let ser_len = pus_tm.finalize_no_crc();
assert_eq!(ser_len, 20);
verify_raw_ping_reply_no_crc(&buf);
assert_eq!(buf[20], 0);
assert_eq!(buf[21], 0);
}
#[test]
@ -974,7 +1140,7 @@ mod tests {
.write_to_bytes_crc_no_table(&mut buf)
.expect("Serialization failed");
assert_eq!(ser_len, 22);
verify_raw_ping_reply(pus_tm.opt_crc16().unwrap(), &buf);
verify_raw_ping_reply(pus_tm.opt_crc16(), &buf);
}
#[test]
@ -1004,6 +1170,46 @@ mod tests {
assert_eq!(buf[22], 3);
}
#[test]
fn test_serialization_with_source_data_alt_ctor() {
let src_data = &[1, 2, 3];
let mut buf: [u8; 32] = [0; 32];
let sph = SpHeader::new_for_unseg_tm_checked(0x123, 0x234, 0).unwrap();
let tc_header = PusTmSecondaryHeader::new_simple(3, 5, dummy_timestamp());
let mut hk_reply_unwritten =
PusTmCreatorWithReservedSourceData::new(&mut buf, sph, tc_header, 3).unwrap();
assert_eq!(hk_reply_unwritten.source_data_len(), 3);
assert_eq!(hk_reply_unwritten.source_data(), &[0, 0, 0]);
assert_eq!(hk_reply_unwritten.source_data_mut(), &[0, 0, 0]);
let source_data_mut = hk_reply_unwritten.source_data_mut();
source_data_mut.copy_from_slice(src_data);
let ser_len = hk_reply_unwritten.finalize();
assert_eq!(ser_len, 25);
assert_eq!(buf[20], 1);
assert_eq!(buf[21], 2);
assert_eq!(buf[22], 3);
}
#[test]
fn test_serialization_with_source_data_alt_ctor_no_table() {
let src_data = &[1, 2, 3];
let mut buf: [u8; 32] = [0; 32];
let sph = SpHeader::new_for_unseg_tm_checked(0x123, 0x234, 0).unwrap();
let tc_header = PusTmSecondaryHeader::new_simple(3, 5, dummy_timestamp());
let mut hk_reply_unwritten =
PusTmCreatorWithReservedSourceData::new(&mut buf, sph, tc_header, 3).unwrap();
assert_eq!(hk_reply_unwritten.source_data_len(), 3);
assert_eq!(hk_reply_unwritten.source_data(), &[0, 0, 0]);
assert_eq!(hk_reply_unwritten.source_data_mut(), &[0, 0, 0]);
let source_data_mut = hk_reply_unwritten.source_data_mut();
source_data_mut.copy_from_slice(src_data);
let ser_len = hk_reply_unwritten.finalize_crc_no_table();
assert_eq!(ser_len, 25);
assert_eq!(buf[20], 1);
assert_eq!(buf[21], 2);
assert_eq!(buf[22], 3);
}
#[test]
fn test_setters() {
let timestamp = dummy_timestamp();
@ -1029,6 +1235,7 @@ mod tests {
assert_eq!(tm_vec.len(), tm_deserialized.total_len());
verify_ping_reply_with_reader(&tm_deserialized, false, 22, dummy_timestamp());
}
#[test]
fn test_deserialization_no_source_data() {
let timestamp = dummy_timestamp();
@ -1046,6 +1253,22 @@ mod tests {
verify_ping_reply_with_reader(&tm_deserialized, false, 22, dummy_timestamp());
}
#[test]
fn test_deserialization_no_source_data_with_trait() {
let timestamp = dummy_timestamp();
let pus_tm = base_ping_reply_full_ctor(timestamp);
let mut buf: [u8; 32] = [0; 32];
let ser_len =
WritablePusPacket::write_to_bytes(&pus_tm, &mut buf).expect("Serialization failed");
assert_eq!(ser_len, 22);
let tm_deserialized = PusTmReader::new(&buf, 7).expect("Deserialization failed");
assert_eq!(ser_len, tm_deserialized.total_len());
assert_eq!(tm_deserialized.user_data(), tm_deserialized.source_data());
assert_eq!(tm_deserialized.raw_data(), &buf[..ser_len]);
assert_eq!(tm_deserialized.crc16(), pus_tm.opt_crc16().unwrap());
verify_ping_reply_with_reader(&tm_deserialized, false, 22, dummy_timestamp());
}
#[test]
fn test_deserialization_no_table() {
let timestamp = dummy_timestamp();
@ -1130,7 +1353,7 @@ mod tests {
let res = pus_tm.append_to_vec(&mut vec);
assert!(res.is_ok());
assert_eq!(res.unwrap(), 22);
verify_raw_ping_reply(pus_tm.opt_crc16().unwrap(), vec.as_slice());
verify_raw_ping_reply(pus_tm.opt_crc16(), vec.as_slice());
}
#[test]
@ -1146,7 +1369,7 @@ mod tests {
assert_eq!(vec.len(), 26);
}
fn verify_raw_ping_reply(crc16: u16, buf: &[u8]) {
fn verify_raw_ping_reply_no_crc(buf: &[u8]) {
// Secondary header is set -> 0b0000_1001 , APID occupies last bit of first byte
assert_eq!(buf[0], 0x09);
// Rest of APID 0x123
@ -1167,12 +1390,19 @@ mod tests {
assert_eq!(buf[12], 0x00);
// Timestamp
assert_eq!(&buf[13..20], dummy_timestamp());
}
fn verify_raw_ping_reply(crc16: Option<u16>, buf: &[u8]) {
verify_raw_ping_reply_no_crc(buf);
let mut digest = CRC_CCITT_FALSE.digest();
digest.update(&buf[0..20]);
let crc16_calced = digest.finalize();
assert_eq!(((crc16 >> 8) & 0xff) as u8, buf[20]);
assert_eq!((crc16 & 0xff) as u8, buf[21]);
assert_eq!(crc16, crc16_calced);
let crc16_read = u16::from_be_bytes([buf[20], buf[21]]);
assert_eq!(crc16_read, crc16_calced);
if let Some(crc16) = crc16 {
assert_eq!(((crc16 >> 8) & 0xff) as u8, buf[20]);
assert_eq!((crc16 & 0xff) as u8, buf[21]);
}
}
fn verify_ping_reply(

View File

@ -73,6 +73,7 @@ pub mod crc;
pub mod ecss;
pub mod seq_count;
pub mod time;
pub mod uslp;
pub mod util;
mod private {

685
src/uslp/mod.rs Normal file
View File

@ -0,0 +1,685 @@
/// # Support of the CCSDS Unified Space Data Link Protocol (USLP)
use crate::{ByteConversionError, crc::CRC_CCITT_FALSE};
/// Only this version is supported by the library
pub const USLP_VERSION_NUMBER: u8 = 0b1100;
/// Identifies the association of the data contained in the transfer frame.
#[derive(
Debug, Copy, Clone, PartialEq, Eq, num_enum::TryFromPrimitive, num_enum::IntoPrimitive,
)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
#[repr(u8)]
pub enum SourceOrDestField {
/// SCID refers to the source of the transfer frame.
Source = 0,
/// SCID refers to the destination of the transfer frame.
Dest = 1,
}
#[derive(
Debug, Copy, Clone, PartialEq, Eq, num_enum::TryFromPrimitive, num_enum::IntoPrimitive,
)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
#[repr(u8)]
pub enum BypassSequenceControlFlag {
/// Acceptance of this frame on the receiving end is subject to normal frame acceptance
/// checks of FARM.
SequenceControlledQoS = 0,
/// Frame Acceptance Checks of FARM by the receiving end shall be bypassed.
ExpeditedQoS = 1,
}
#[derive(
Debug, Copy, Clone, PartialEq, Eq, num_enum::TryFromPrimitive, num_enum::IntoPrimitive,
)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
#[repr(u8)]
pub enum ProtocolControlCommandFlag {
TfdfContainsUserData = 0,
TfdfContainsProtocolInfo = 1,
}
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub enum UslpError {
ByteConversion(ByteConversionError),
HeaderIsTruncated,
InvalidProtocolId(u8),
InvalidConstructionRule(u8),
InvalidVersionNumber(u8),
InvalidVcid(u8),
InvalidMapId(u8),
ChecksumFailure(u16),
}
impl From<ByteConversionError> for UslpError {
fn from(value: ByteConversionError) -> Self {
Self::ByteConversion(value)
}
}
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub struct InvalidValueForLen {
value: u64,
len: u8,
}
#[derive(Debug, Copy, Clone, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub struct PrimaryHeader {
pub spacecraft_id: u16,
pub source_or_dest_field: SourceOrDestField,
pub vc_id: u8,
pub map_id: u8,
frame_len_field: u16,
pub sequence_control_flag: BypassSequenceControlFlag,
pub protocol_control_command_flag: ProtocolControlCommandFlag,
pub ocf_flag: bool,
vc_frame_count_len: u8,
vc_frame_count: u64,
}
impl PrimaryHeader {
pub fn new(
spacecraft_id: u16,
source_or_dest_field: SourceOrDestField,
vc_id: u8,
map_id: u8,
frame_len: u16,
) -> Result<Self, UslpError> {
if vc_id > 0b111111 {
return Err(UslpError::InvalidVcid(vc_id));
}
if map_id > 0b1111 {
return Err(UslpError::InvalidMapId(map_id));
}
Ok(Self {
spacecraft_id,
source_or_dest_field,
vc_id,
map_id,
frame_len_field: frame_len.saturating_sub(1),
sequence_control_flag: BypassSequenceControlFlag::SequenceControlledQoS,
protocol_control_command_flag: ProtocolControlCommandFlag::TfdfContainsUserData,
ocf_flag: false,
vc_frame_count_len: 0,
vc_frame_count: 0,
})
}
pub fn set_vc_frame_count(
&mut self,
count_len: u8,
count: u64,
) -> Result<(), InvalidValueForLen> {
if count > 2_u64.pow(count_len as u32 * 8) - 1 {
return Err(InvalidValueForLen {
value: count,
len: count_len,
});
}
self.vc_frame_count_len = count_len;
self.vc_frame_count = count;
Ok(())
}
#[inline(always)]
pub fn vc_frame_count(&self) -> u64 {
self.vc_frame_count
}
#[inline(always)]
pub fn vc_frame_count_len(&self) -> u8 {
self.vc_frame_count_len
}
pub fn from_bytes(buf: &[u8]) -> Result<Self, UslpError> {
if buf.len() < 4 {
return Err(ByteConversionError::FromSliceTooSmall {
found: buf.len(),
expected: 4,
}
.into());
}
// Can only deal with regular frames for now.
if (buf[3] & 0b1) == 1 {
return Err(UslpError::HeaderIsTruncated);
}
// We could check this above, but this is a better error for the case where the user
// tries to read a truncated frame.
if buf.len() < 7 {
return Err(ByteConversionError::FromSliceTooSmall {
found: buf.len(),
expected: 7,
}
.into());
}
let version_number = (buf[0] >> 4) & 0b1111;
if version_number != USLP_VERSION_NUMBER {
return Err(UslpError::InvalidVersionNumber(version_number));
}
let source_or_dest_field = match (buf[2] >> 3) & 1 {
0 => SourceOrDestField::Source,
1 => SourceOrDestField::Dest,
_ => unreachable!(),
};
let vc_frame_count_len = buf[6] & 0b111;
if buf.len() < 7 + vc_frame_count_len as usize {
return Err(ByteConversionError::FromSliceTooSmall {
found: buf.len(),
expected: 7 + vc_frame_count_len as usize,
}
.into());
}
let vc_frame_count = match vc_frame_count_len {
1 => buf[7] as u64,
2 => u16::from_be_bytes(buf[7..9].try_into().unwrap()) as u64,
4 => u32::from_be_bytes(buf[7..11].try_into().unwrap()) as u64,
len => {
let mut vcf_count = 0u64;
let mut end = len;
for byte in buf[7..7 + len as usize].iter() {
vcf_count |= (*byte as u64) << ((end - 1) * 8);
end -= 1;
}
vcf_count
}
};
Ok(Self {
spacecraft_id: (((buf[0] as u16) & 0b1111) << 12)
| ((buf[1] as u16) << 4)
| ((buf[2] as u16) >> 4) & 0b1111,
source_or_dest_field,
vc_id: ((buf[2] & 0b111) << 3) | (buf[3] >> 5) & 0b111,
map_id: (buf[3] >> 1) & 0b1111,
frame_len_field: ((buf[4] as u16) << 8) | buf[5] as u16,
sequence_control_flag: ((buf[6] >> 7) & 0b1).try_into().unwrap(),
protocol_control_command_flag: ((buf[6] >> 6) & 0b1).try_into().unwrap(),
ocf_flag: ((buf[6] >> 3) & 0b1) != 0,
vc_frame_count_len,
vc_frame_count,
})
}
pub fn write_to_be_bytes(&self, buf: &mut [u8]) -> Result<usize, ByteConversionError> {
if buf.len() < self.len_header() {
return Err(ByteConversionError::ToSliceTooSmall {
found: buf.len(),
expected: self.len_header(),
});
}
buf[0] = (USLP_VERSION_NUMBER << 4) | ((self.spacecraft_id >> 12) as u8) & 0b1111;
buf[1] = (self.spacecraft_id >> 4) as u8;
buf[2] = (((self.spacecraft_id & 0b1111) as u8) << 4)
| ((self.source_or_dest_field as u8) << 3)
| (self.vc_id >> 3) & 0b111;
buf[3] = ((self.vc_id & 0b111) << 5) | (self.map_id << 1);
buf[4..6].copy_from_slice(&self.frame_len_field.to_be_bytes());
buf[6] = ((self.sequence_control_flag as u8) << 7)
| ((self.protocol_control_command_flag as u8) << 6)
| ((self.ocf_flag as u8) << 3)
| self.vc_frame_count_len;
let mut packet_idx = 7;
for idx in (0..self.vc_frame_count_len).rev() {
buf[packet_idx] = ((self.vc_frame_count >> (idx * 8)) & 0xff) as u8;
packet_idx += 1;
}
Ok(self.len_header())
}
#[inline(always)]
pub fn set_frame_len(&mut self, frame_len: usize) {
// 4.1.2.7.2
// The field contains a length count C that equals one fewer than the total octets
// in the transfer frame.
self.frame_len_field = frame_len.saturating_sub(1) as u16;
}
#[inline(always)]
pub fn len_header(&self) -> usize {
7 + self.vc_frame_count_len as usize
}
#[inline(always)]
pub fn len_frame(&self) -> usize {
// 4.1.2.7.2
// The field contains a length count C that equals one fewer than the total octets
// in the transfer frame.
self.frame_len_field as usize + 1
}
}
/// Custom implementation which skips the check whether the VC frame count length field is equal.
/// Only the actual VC count value is compared.
impl PartialEq for PrimaryHeader {
fn eq(&self, other: &Self) -> bool {
self.spacecraft_id == other.spacecraft_id
&& self.source_or_dest_field == other.source_or_dest_field
&& self.vc_id == other.vc_id
&& self.map_id == other.map_id
&& self.frame_len_field == other.frame_len_field
&& self.sequence_control_flag == other.sequence_control_flag
&& self.protocol_control_command_flag == other.protocol_control_command_flag
&& self.ocf_flag == other.ocf_flag
&& self.vc_frame_count == other.vc_frame_count
}
}
#[derive(
Debug, Copy, Clone, PartialEq, Eq, num_enum::TryFromPrimitive, num_enum::IntoPrimitive,
)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
#[repr(u8)]
#[non_exhaustive]
pub enum UslpProtocolId {
SpacePacketsOrEncapsulation = 0b00000,
/// COP-1 control commands within the TFDZ.
Cop1ControlCommands = 0b00001,
/// COP-P control commands within the TFDZ.
CopPControlCommands = 0b00010,
/// SDLS control commands within the TFDZ.
Sdls = 0b00011,
UserDefinedOctetStream = 0b00100,
/// Proximity-1 Supervisory Protocol Data Units (SPDUs) within the TFDZ.
Spdu = 0b00111,
/// Entire fixed-length TFDZ contains idle data.
Idle = 0b11111,
}
#[derive(
Debug, Copy, Clone, PartialEq, Eq, num_enum::TryFromPrimitive, num_enum::IntoPrimitive,
)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
#[repr(u8)]
pub enum ConstructionRule {
/// Indicated fixed-length TFDZ whose contents are CCSDS packets concatenated together, which
/// span transfer frame boundaries. The First Header Pointer (FHP) is required for packet
/// extraction.
PacketSpanningMultipleFrames = 0b000,
StartOfMapaSduOrVcaSdu = 0b001,
ContinuingPortionOfMapaSdu = 0b010,
OctetStream = 0b011,
StartingSegment = 0b100,
ContinuingSegment = 0b101,
LastSegment = 0b110,
NoSegmentation = 0b111,
}
impl ConstructionRule {
pub const fn applicable_to_fixed_len_tfdz(&self) -> bool {
match self {
ConstructionRule::PacketSpanningMultipleFrames => true,
ConstructionRule::StartOfMapaSduOrVcaSdu => true,
ConstructionRule::ContinuingPortionOfMapaSdu => true,
ConstructionRule::OctetStream => false,
ConstructionRule::StartingSegment => false,
ConstructionRule::ContinuingSegment => false,
ConstructionRule::LastSegment => false,
ConstructionRule::NoSegmentation => false,
}
}
}
pub struct TransferFrameDataFieldHeader {
/// Construction rule for the TFDZ.
construction_rule: ConstructionRule,
uslp_protocol_id: UslpProtocolId,
/// First header or last valid octet pointer. Only present if the constuction rule indicated
/// a fixed-length TFDZ.
fhp_or_lvo: Option<u16>,
}
impl TransferFrameDataFieldHeader {
pub fn len_header(&self) -> usize {
if self.construction_rule.applicable_to_fixed_len_tfdz() {
3
} else {
1
}
}
pub fn construction_rule(&self) -> ConstructionRule {
self.construction_rule
}
pub fn uslp_protocol_id(&self) -> UslpProtocolId {
self.uslp_protocol_id
}
pub fn fhp_or_lvo(&self) -> Option<u16> {
self.fhp_or_lvo
}
pub fn from_bytes(buf: &[u8]) -> Result<Self, UslpError> {
if buf.is_empty() {
return Err(ByteConversionError::FromSliceTooSmall {
found: 0,
expected: 1,
}
.into());
}
let construction_rule = ConstructionRule::try_from((buf[0] >> 5) & 0b111)
.map_err(|e| UslpError::InvalidConstructionRule(e.number))?;
let mut fhp_or_lvo = None;
if construction_rule.applicable_to_fixed_len_tfdz() {
if buf.len() < 3 {
return Err(ByteConversionError::FromSliceTooSmall {
found: buf.len(),
expected: 3,
}
.into());
}
fhp_or_lvo = Some(u16::from_be_bytes(buf[1..3].try_into().unwrap()));
}
Ok(Self {
construction_rule,
uslp_protocol_id: UslpProtocolId::try_from(buf[0] & 0b11111)
.map_err(|e| UslpError::InvalidProtocolId(e.number))?,
fhp_or_lvo,
})
}
}
/// Simple USLP transfer frame reader.
///
/// Currently, only insert zone lengths of 0 are supported.
pub struct TransferFrameReader<'buf> {
primary_header: PrimaryHeader,
data_field_header: TransferFrameDataFieldHeader,
data: &'buf [u8],
operational_control_field: Option<u32>,
}
impl<'buf> TransferFrameReader<'buf> {
/// This function assumes an insert zone length of 0.
pub fn from_bytes(
buf: &'buf [u8],
has_fecf: bool,
) -> Result<TransferFrameReader<'buf>, UslpError> {
let primary_header = PrimaryHeader::from_bytes(buf)?;
if primary_header.len_frame() > buf.len() {
return Err(ByteConversionError::FromSliceTooSmall {
expected: primary_header.len_frame(),
found: buf.len(),
}
.into());
}
let data_field_header =
TransferFrameDataFieldHeader::from_bytes(&buf[primary_header.len_header()..])?;
let data_idx = primary_header.len_header() + data_field_header.len_header();
let frame_len = primary_header.len_frame();
let mut operational_control_field = None;
let mut data_len = frame_len - data_idx;
if has_fecf {
data_len -= 2;
}
if primary_header.ocf_flag {
data_len -= 4;
operational_control_field = Some(u32::from_be_bytes(
buf[data_idx + data_len..data_idx + data_len + 4]
.try_into()
.unwrap(),
));
}
let data_end = data_idx + data_len;
let mut digest = CRC_CCITT_FALSE.digest();
digest.update(&buf[0..frame_len]);
if digest.finalize() != 0 {
return Err(UslpError::ChecksumFailure(u16::from_be_bytes(
buf[frame_len - 2..frame_len].try_into().unwrap(),
)));
}
Ok(Self {
primary_header,
data_field_header,
data: buf[data_idx..data_end].try_into().unwrap(),
operational_control_field,
})
}
pub fn len_frame(&self) -> usize {
self.primary_header.len_frame()
}
pub fn primary_header(&self) -> &PrimaryHeader {
&self.primary_header
}
pub fn data_field_header(&self) -> &TransferFrameDataFieldHeader {
&self.data_field_header
}
pub fn data(&self) -> &'buf [u8] {
self.data
}
pub fn operational_control_field(&self) -> &Option<u32> {
&self.operational_control_field
}
}
#[cfg(test)]
mod tests {
use std::println;
use super::*;
fn common_basic_check(buf: &[u8]) {
assert_eq!(buf[0] >> 4, USLP_VERSION_NUMBER);
// First four bits SCID.
assert_eq!(buf[0] & 0b1111, 0b1010);
// Next eight bits SCID.
assert_eq!(buf[1], 0b01011100);
// Last four bits SCID.
assert_eq!(buf[2] >> 4, 0b0011);
assert_eq!((buf[2] >> 3) & 0b1, SourceOrDestField::Dest as u8);
// First three bits VCID.
assert_eq!(buf[2] & 0b111, 0b110);
// Last three bits VCID.
assert_eq!(buf[3] >> 5, 0b101);
// MAP ID
assert_eq!((buf[3] >> 1) & 0b1111, 0b1010);
// End of primary header flag
assert_eq!(buf[3] & 0b1, 0);
assert_eq!(u16::from_be_bytes(buf[4..6].try_into().unwrap()), 0x2345);
}
#[test]
fn test_basic_0() {
let mut buf: [u8; 8] = [0; 8];
// Should be all zeros after writing.
buf[6] = 0xff;
let primary_header = PrimaryHeader::new(
0b10100101_11000011,
SourceOrDestField::Dest,
0b110101,
0b1010,
0x2345,
)
.unwrap();
// Virtual channel count 0.
assert_eq!(primary_header.write_to_be_bytes(&mut buf).unwrap(), 7);
common_basic_check(&buf);
// Bypass / Sequence Control Flag.
assert_eq!(
(buf[6] >> 7) & 0b1,
BypassSequenceControlFlag::SequenceControlledQoS as u8
);
// Protocol Control Command Flag.
assert_eq!(
(buf[6] >> 6) & 0b1,
ProtocolControlCommandFlag::TfdfContainsUserData as u8
);
// OCF flag.
assert_eq!((buf[6] >> 3) & 0b1, false as u8);
// VCF count length.
assert_eq!(buf[6] & 0b111, 0);
}
#[test]
fn test_basic_1() {
let mut buf: [u8; 16] = [0; 16];
// Should be all zeros after writing.
buf[6] = 0xff;
let mut primary_header = PrimaryHeader::new(
0b10100101_11000011,
SourceOrDestField::Dest,
0b110101,
0b1010,
0x2345,
)
.unwrap();
primary_header.sequence_control_flag = BypassSequenceControlFlag::ExpeditedQoS;
primary_header.protocol_control_command_flag =
ProtocolControlCommandFlag::TfdfContainsProtocolInfo;
primary_header.ocf_flag = true;
primary_header.set_vc_frame_count(4, 0x12345678).unwrap();
// Virtual channel count 4.
assert_eq!(primary_header.write_to_be_bytes(&mut buf).unwrap(), 11);
common_basic_check(&buf);
// Bypass / Sequence Control Flag.
assert_eq!(
(buf[6] >> 7) & 0b1,
BypassSequenceControlFlag::ExpeditedQoS as u8
);
// Protocol Control Command Flag.
assert_eq!(
(buf[6] >> 6) & 0b1,
ProtocolControlCommandFlag::TfdfContainsProtocolInfo as u8
);
// OCF flag.
assert_eq!((buf[6] >> 3) & 0b1, true as u8);
// VCF count length.
assert_eq!(buf[6] & 0b111, 4);
assert_eq!(
u32::from_be_bytes(buf[7..11].try_into().unwrap()),
0x12345678
);
}
#[test]
fn test_reading_0() {
let mut buf: [u8; 8] = [0; 8];
let primary_header = PrimaryHeader::new(
0b10100101_11000011,
SourceOrDestField::Dest,
0b110101,
0b1010,
0x2345,
)
.unwrap();
assert_eq!(primary_header.write_to_be_bytes(&mut buf).unwrap(), 7);
let parsed_header = PrimaryHeader::from_bytes(&buf).unwrap();
assert_eq!(parsed_header, primary_header);
}
#[test]
fn test_reading_1() {
let mut buf: [u8; 16] = [0; 16];
let mut primary_header = PrimaryHeader::new(
0b10100101_11000011,
SourceOrDestField::Dest,
0b110101,
0b1010,
0x2345,
)
.unwrap();
primary_header.sequence_control_flag = BypassSequenceControlFlag::ExpeditedQoS;
primary_header.protocol_control_command_flag =
ProtocolControlCommandFlag::TfdfContainsProtocolInfo;
primary_header.ocf_flag = true;
primary_header.set_vc_frame_count(4, 0x12345678).unwrap();
assert_eq!(primary_header.write_to_be_bytes(&mut buf).unwrap(), 11);
let parsed_header = PrimaryHeader::from_bytes(&buf).unwrap();
assert_eq!(parsed_header, primary_header);
}
#[test]
fn test_invalid_vcid() {
let error = PrimaryHeader::new(
0b10100101_11000011,
SourceOrDestField::Dest,
0b1101011,
0b1010,
0x2345,
);
assert!(error.is_err());
let error = error.unwrap_err();
matches!(error, UslpError::InvalidVcid(0b1101011));
}
#[test]
fn test_invalid_mapid() {
let error = PrimaryHeader::new(
0b10100101_11000011,
SourceOrDestField::Dest,
0b110101,
0b10101,
0x2345,
);
assert!(error.is_err());
let error = error.unwrap_err();
matches!(error, UslpError::InvalidMapId(0b10101));
}
#[test]
fn test_invalid_vc_count() {
let mut primary_header = PrimaryHeader::new(
0b10100101_11000011,
SourceOrDestField::Dest,
0b110101,
0b1010,
0x2345,
)
.unwrap();
matches!(
primary_header.set_vc_frame_count(0, 1).unwrap_err(),
InvalidValueForLen { value: 1, len: 0 }
);
matches!(
primary_header.set_vc_frame_count(1, 256).unwrap_err(),
InvalidValueForLen { value: 256, len: 1 }
);
}
#[test]
fn test_frame_parser() {
let mut buf: [u8; 32] = [0; 32];
// Build a variable frame manually.
let mut primary_header =
PrimaryHeader::new(0x01, SourceOrDestField::Dest, 0b110101, 0b1010, 0).unwrap();
let header_len = primary_header.len_header();
buf[header_len] = ((ConstructionRule::NoSegmentation as u8) << 5)
| (UslpProtocolId::UserDefinedOctetStream as u8) & 0b11111;
buf[header_len + 1] = 0x42;
// 1 byte TFDH, 1 byte data, 2 bytes CRC.
primary_header.set_frame_len(header_len + 4);
primary_header.write_to_be_bytes(&mut buf).unwrap();
// Calculate and write CRC16.
let mut digest = CRC_CCITT_FALSE.digest();
digest.update(&buf[0..header_len + 2]);
buf[header_len + 2..header_len + 4].copy_from_slice(&digest.finalize().to_be_bytes());
println!("Buffer: {:x?}", buf);
// Now parse the frame.
let frame = TransferFrameReader::from_bytes(&buf, true).unwrap();
assert_eq!(frame.data().len(), 1);
assert_eq!(frame.data()[0], 0x42);
assert_eq!(
frame.data_field_header().uslp_protocol_id,
UslpProtocolId::UserDefinedOctetStream
);
assert_eq!(
frame.data_field_header().construction_rule,
ConstructionRule::NoSegmentation
);
assert!(frame.data_field_header().fhp_or_lvo().is_none());
assert_eq!(frame.len_frame(), 11);
}
}