Compare commits
28 Commits
v0.7.0-bet
...
v0.11.0-rc
Author | SHA1 | Date | |
---|---|---|---|
ea05a547ac | |||
0ab69b3ddc
|
|||
240f0bc267 | |||
00744a22fc
|
|||
c5aeeec19f
|
|||
d13cd28962 | |||
5641d9007e
|
|||
f39ea2f793 | |||
e4730d4b8f
|
|||
64ea7e609d
|
|||
ebaa6210a4
|
|||
d14f532f62 | |||
6ea18d3715 | |||
6056342334
|
|||
4e6dcc5afa | |||
200593bfb4
|
|||
60bf876dd3
|
|||
f47604346e | |||
0d0d7a256a
|
|||
2fd5860e18 | |||
7e8b71db6d
|
|||
c3cc6d5c73 | |||
d01309cccf
|
|||
92403738ca | |||
3353475261
|
|||
84c1c47fe1
|
|||
c4bbf91be8
|
|||
7200e10250
|
51
CHANGELOG.md
51
CHANGELOG.md
@ -8,6 +8,57 @@ and this project adheres to [Semantic Versioning](http://semver.org/).
|
||||
|
||||
# [unreleased]
|
||||
|
||||
# [v0.11.0-rc.0] 2024-03-04
|
||||
|
||||
## Added
|
||||
|
||||
- `From<$TY>` for the `EcssEnum$TY` ECSS enum type definitions.
|
||||
- `Sub` implementation for `UnixTimestamp` to calculate the duration between two timestamps.
|
||||
|
||||
## Changed
|
||||
|
||||
- `CcsdsTimeProvider` `subsecond_millis` function now returns `u16` instead of `Option<u16>`.
|
||||
- `UnixTimestamp` `subsecond_millis` function now returns `u16` instead of `Option<u16>`.
|
||||
|
||||
# [v0.10.0] 2024-02-17
|
||||
|
||||
## Added
|
||||
|
||||
- Added `value` and `to_vec` methods for the `UnsignedEnum` trait. The value is returned as
|
||||
as `u64`. Renamed former `value` method on `GenericUnsignedByteField` to `value_typed`.
|
||||
- Added `value_const` const function for `UnsignedByteField` type.
|
||||
- Added `value_typed` const functions for `GenericUnsignedByteField` and `GenericEcssEnumWrapper`.
|
||||
|
||||
# [v0.9.0] 2024-02-07
|
||||
|
||||
## Added
|
||||
|
||||
- `CcsdsPacket`, `PusPacket` and `GenericPusTmSecondaryHeader` implementation for
|
||||
`PusTmZeroCopyWriter`.
|
||||
- Additional length checks for `PusTmZeroCopyWriter`.
|
||||
|
||||
## Changed
|
||||
|
||||
- `PusTmZeroCopyWriter`: Added additional timestamp length argument for `new` constructor.
|
||||
|
||||
## Fixed
|
||||
|
||||
- Typo: `PUC_TM_MIN_HEADER_LEN` -> `PUS_TM_MIN_HEADER_LEN`
|
||||
|
||||
# [v0.8.1] 2024-02-05
|
||||
|
||||
## Fixed
|
||||
|
||||
- Added `pub` visibility for `PacketSequenceCtrl::const_new`.
|
||||
|
||||
# [v0.8.0] 2024-02-05
|
||||
|
||||
## Added
|
||||
|
||||
- Added `len_written` and `to_vec` methods to the `TimeWriter` trait.
|
||||
|
||||
# [v0.7.0] 2024-02-01
|
||||
|
||||
# [v0.7.0-beta.4] 2024-01-23
|
||||
|
||||
## Fixed
|
||||
|
@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "spacepackets"
|
||||
version = "0.7.0-beta.4"
|
||||
version = "0.11.0-rc.0"
|
||||
edition = "2021"
|
||||
rust-version = "1.61"
|
||||
authors = ["Robin Mueller <muellerr@irs.uni-stuttgart.de>"]
|
||||
@ -53,4 +53,4 @@ alloc = ["postcard/alloc", "chrono/alloc"]
|
||||
|
||||
[package.metadata.docs.rs]
|
||||
all-features = true
|
||||
rustdoc-args = ["--cfg", "doc_cfg"]
|
||||
rustdoc-args = ["--cfg", "doc_cfg", "--generate-link-to-definition"]
|
||||
|
@ -581,7 +581,7 @@ mod tests {
|
||||
assert_eq!(finished_pdu_vec.len(), 12);
|
||||
assert_eq!(finished_pdu_vec[9], TlvType::EntityId.into());
|
||||
assert_eq!(finished_pdu_vec[10], 1);
|
||||
assert_eq!(finished_pdu_vec[11], TEST_DEST_ID.value());
|
||||
assert_eq!(finished_pdu_vec[11], TEST_DEST_ID.value_typed());
|
||||
assert_eq!(
|
||||
finished_pdu.fault_location().unwrap().entity_id(),
|
||||
&TEST_DEST_ID.into()
|
||||
|
@ -315,15 +315,19 @@ pub trait EcssEnumerationExt: EcssEnumeration + Debug + Copy + Clone + PartialEq
|
||||
|
||||
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
|
||||
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
||||
pub struct GenericEcssEnumWrapper<TYPE: Copy> {
|
||||
pub struct GenericEcssEnumWrapper<TYPE: Copy + Into<u64>> {
|
||||
field: GenericUnsignedByteField<TYPE>,
|
||||
}
|
||||
|
||||
impl<TYPE: Copy> GenericEcssEnumWrapper<TYPE> {
|
||||
impl<TYPE: Copy + Into<u64>> GenericEcssEnumWrapper<TYPE> {
|
||||
pub const fn ptc() -> PacketTypeCodes {
|
||||
PacketTypeCodes::Enumerated
|
||||
}
|
||||
|
||||
pub const fn value_typed(&self) -> TYPE {
|
||||
self.field.value_typed()
|
||||
}
|
||||
|
||||
pub fn new(val: TYPE) -> Self {
|
||||
Self {
|
||||
field: GenericUnsignedByteField::new(val),
|
||||
@ -331,7 +335,7 @@ impl<TYPE: Copy> GenericEcssEnumWrapper<TYPE> {
|
||||
}
|
||||
}
|
||||
|
||||
impl<TYPE: Copy + ToBeBytes> UnsignedEnum for GenericEcssEnumWrapper<TYPE> {
|
||||
impl<TYPE: Copy + ToBeBytes + Into<u64>> UnsignedEnum for GenericEcssEnumWrapper<TYPE> {
|
||||
fn size(&self) -> usize {
|
||||
(self.pfc() / 8) as usize
|
||||
}
|
||||
@ -339,23 +343,45 @@ impl<TYPE: Copy + ToBeBytes> UnsignedEnum for GenericEcssEnumWrapper<TYPE> {
|
||||
fn write_to_be_bytes(&self, buf: &mut [u8]) -> Result<usize, ByteConversionError> {
|
||||
self.field.write_to_be_bytes(buf)
|
||||
}
|
||||
|
||||
fn value(&self) -> u64 {
|
||||
self.field.value()
|
||||
}
|
||||
}
|
||||
|
||||
impl<TYPE: Copy + ToBeBytes> EcssEnumeration for GenericEcssEnumWrapper<TYPE> {
|
||||
impl<TYPE: Copy + ToBeBytes + Into<u64>> EcssEnumeration for GenericEcssEnumWrapper<TYPE> {
|
||||
fn pfc(&self) -> u8 {
|
||||
size_of::<TYPE>() as u8 * 8_u8
|
||||
}
|
||||
}
|
||||
|
||||
impl<TYPE: Debug + Copy + Clone + PartialEq + Eq + ToBeBytes> EcssEnumerationExt
|
||||
impl<TYPE: Debug + Copy + Clone + PartialEq + Eq + ToBeBytes + Into<u64>> EcssEnumerationExt
|
||||
for GenericEcssEnumWrapper<TYPE>
|
||||
{
|
||||
}
|
||||
|
||||
pub type EcssEnumU8 = GenericEcssEnumWrapper<u8>;
|
||||
pub type EcssEnumU16 = GenericEcssEnumWrapper<u16>;
|
||||
pub type EcssEnumU32 = GenericEcssEnumWrapper<u32>;
|
||||
pub type EcssEnumU64 = GenericEcssEnumWrapper<u64>;
|
||||
macro_rules! generic_ecss_enum_typedefs_and_from_impls {
|
||||
($($ty:ty => $Enum:ident),*) => {
|
||||
$(
|
||||
pub type $Enum = GenericEcssEnumWrapper<$ty>;
|
||||
|
||||
impl From<$ty> for $Enum {
|
||||
fn from(value: $ty) -> Self {
|
||||
Self::new(value)
|
||||
}
|
||||
}
|
||||
)*
|
||||
};
|
||||
}
|
||||
|
||||
// Generates EcssEnum<$TY> type definitions as well as a From<$TY> for EcssEnum<$TY>
|
||||
// implementation.
|
||||
generic_ecss_enum_typedefs_and_from_impls! {
|
||||
u8 => EcssEnumU8,
|
||||
u16 => EcssEnumU16,
|
||||
u32 => EcssEnumU32,
|
||||
u64 => EcssEnumU64
|
||||
}
|
||||
|
||||
/// Generic trait for PUS packet abstractions which can written to a raw slice as their raw
|
||||
/// byte representation. This is especially useful for generic abstractions which depend only
|
||||
@ -396,6 +422,10 @@ mod tests {
|
||||
.write_to_be_bytes(&mut buf[1..2])
|
||||
.expect("To byte conversion of u8 failed");
|
||||
assert_eq!(buf[1], 1);
|
||||
assert_eq!(my_enum.value(), 1);
|
||||
assert_eq!(my_enum.value_typed(), 1);
|
||||
let vec = my_enum.to_vec();
|
||||
assert_eq!(vec, buf[1..2]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@ -409,6 +439,10 @@ mod tests {
|
||||
assert_eq!(my_enum.pfc(), 16);
|
||||
assert_eq!(buf[1], 0x1f);
|
||||
assert_eq!(buf[2], 0x2f);
|
||||
assert_eq!(my_enum.value(), 0x1f2f);
|
||||
assert_eq!(my_enum.value_typed(), 0x1f2f);
|
||||
let vec = my_enum.to_vec();
|
||||
assert_eq!(vec, buf[1..3]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@ -440,6 +474,10 @@ mod tests {
|
||||
assert_eq!(buf[2], 0x2f);
|
||||
assert_eq!(buf[3], 0x3f);
|
||||
assert_eq!(buf[4], 0x4f);
|
||||
assert_eq!(my_enum.value(), 0x1f2f3f4f);
|
||||
assert_eq!(my_enum.value_typed(), 0x1f2f3f4f);
|
||||
let vec = my_enum.to_vec();
|
||||
assert_eq!(vec, buf[1..5]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@ -460,6 +498,25 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_enum_u64() {
|
||||
let mut buf = [0; 8];
|
||||
let my_enum = EcssEnumU64::new(0x1f2f3f4f5f);
|
||||
my_enum
|
||||
.write_to_be_bytes(&mut buf)
|
||||
.expect("To byte conversion of u64 failed");
|
||||
assert_eq!(buf[3], 0x1f);
|
||||
assert_eq!(buf[4], 0x2f);
|
||||
assert_eq!(buf[5], 0x3f);
|
||||
assert_eq!(buf[6], 0x4f);
|
||||
assert_eq!(buf[7], 0x5f);
|
||||
assert_eq!(my_enum.value(), 0x1f2f3f4f5f);
|
||||
assert_eq!(my_enum.value_typed(), 0x1f2f3f4f5f);
|
||||
assert_eq!(u64::from_be_bytes(buf), 0x1f2f3f4f5f);
|
||||
let vec = my_enum.to_vec();
|
||||
assert_eq!(vec, buf);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_pus_error_display() {
|
||||
let unsupport_version = PusError::VersionNotSupported(super::PusVersion::EsaPus);
|
||||
|
213
src/ecss/tm.rs
213
src/ecss/tm.rs
@ -21,12 +21,14 @@ use delegate::delegate;
|
||||
use crate::time::{TimeWriter, TimestampError};
|
||||
pub use legacy_tm::*;
|
||||
|
||||
use self::zc::PusTmSecHeaderWithoutTimestamp;
|
||||
|
||||
pub trait IsPusTelemetry {}
|
||||
|
||||
/// Length without timestamp
|
||||
pub const PUC_TM_MIN_SEC_HEADER_LEN: usize = 7;
|
||||
pub const PUS_TM_MIN_SEC_HEADER_LEN: usize = 7;
|
||||
pub const PUS_TM_MIN_LEN_WITHOUT_SOURCE_DATA: usize =
|
||||
CCSDS_HEADER_LEN + PUC_TM_MIN_SEC_HEADER_LEN + size_of::<CrcType>();
|
||||
CCSDS_HEADER_LEN + PUS_TM_MIN_SEC_HEADER_LEN + size_of::<CrcType>();
|
||||
|
||||
pub trait GenericPusTmSecondaryHeader {
|
||||
fn pus_version(&self) -> PusVersion;
|
||||
@ -198,7 +200,7 @@ impl<'slice> TryFrom<zc::PusTmSecHeader<'slice>> for PusTmSecondaryHeader<'slice
|
||||
pub mod legacy_tm {
|
||||
use crate::ecss::tm::{
|
||||
zc, GenericPusTmSecondaryHeader, IsPusTelemetry, PusTmSecondaryHeader,
|
||||
PUC_TM_MIN_SEC_HEADER_LEN, PUS_TM_MIN_LEN_WITHOUT_SOURCE_DATA,
|
||||
PUS_TM_MIN_LEN_WITHOUT_SOURCE_DATA, PUS_TM_MIN_SEC_HEADER_LEN,
|
||||
};
|
||||
use crate::ecss::PusVersion;
|
||||
use crate::ecss::{
|
||||
@ -406,10 +408,10 @@ pub mod legacy_tm {
|
||||
.into());
|
||||
}
|
||||
let sec_header_zc = zc::PusTmSecHeaderWithoutTimestamp::from_bytes(
|
||||
&slice[current_idx..current_idx + PUC_TM_MIN_SEC_HEADER_LEN],
|
||||
&slice[current_idx..current_idx + PUS_TM_MIN_SEC_HEADER_LEN],
|
||||
)
|
||||
.ok_or(ByteConversionError::ZeroCopyFromError)?;
|
||||
current_idx += PUC_TM_MIN_SEC_HEADER_LEN;
|
||||
current_idx += PUS_TM_MIN_SEC_HEADER_LEN;
|
||||
let zc_sec_header_wrapper = zc::PusTmSecHeader {
|
||||
zc_header: sec_header_zc,
|
||||
timestamp: &slice[current_idx..current_idx + timestamp_len],
|
||||
@ -814,10 +816,10 @@ impl<'raw_data> PusTmReader<'raw_data> {
|
||||
.into());
|
||||
}
|
||||
let sec_header_zc = zc::PusTmSecHeaderWithoutTimestamp::from_bytes(
|
||||
&slice[current_idx..current_idx + PUC_TM_MIN_SEC_HEADER_LEN],
|
||||
&slice[current_idx..current_idx + PUS_TM_MIN_SEC_HEADER_LEN],
|
||||
)
|
||||
.ok_or(ByteConversionError::ZeroCopyFromError)?;
|
||||
current_idx += PUC_TM_MIN_SEC_HEADER_LEN;
|
||||
current_idx += PUS_TM_MIN_SEC_HEADER_LEN;
|
||||
let zc_sec_header_wrapper = zc::PusTmSecHeader {
|
||||
zc_header: sec_header_zc,
|
||||
timestamp: &slice[current_idx..current_idx + timestamp_len],
|
||||
@ -912,36 +914,40 @@ impl PartialEq<PusTmReader<'_>> for PusTmCreator<'_> {
|
||||
}
|
||||
|
||||
/// This is a helper class to update certain fields in a raw PUS telemetry packet directly in place.
|
||||
/// This can be more efficient than creating a full [PusTm], modifying the fields and then writing
|
||||
/// it back to another buffer.
|
||||
/// This can be more efficient than creating a full [PusTmReader], modifying the fields and then
|
||||
/// writing it back to another buffer.
|
||||
///
|
||||
/// Please note that the [Self::finish] method has to be called for the PUS TM CRC16 to be valid
|
||||
/// after changing fields of the TM packet. Furthermore, the constructor of this class will not
|
||||
/// do any checks except a length check to ensure that all relevant fields can be updated without
|
||||
/// a panic. If a full validity check of the PUS TM packet is required, it is recommended
|
||||
/// to construct a full [PusTm] object from the raw bytestream first.
|
||||
/// do any checks except basic length checks to ensure that all relevant fields can be updated and
|
||||
/// all methods can be called without a panic. If a full validity check of the PUS TM packet is
|
||||
/// required, it is recommended to construct a full [PusTmReader] object from the raw bytestream
|
||||
/// first.
|
||||
pub struct PusTmZeroCopyWriter<'raw> {
|
||||
raw_tm: &'raw mut [u8],
|
||||
timestamp_len: usize,
|
||||
}
|
||||
|
||||
impl<'raw> PusTmZeroCopyWriter<'raw> {
|
||||
/// This function will not do any other checks on the raw data other than a length check
|
||||
/// for all internal fields which can be updated. It is the responsibility of the user to ensure
|
||||
/// the raw slice contains a valid telemetry packet. The slice should have the exact length
|
||||
/// of the telemetry packet for this class to work properly.
|
||||
pub fn new(raw_tm: &'raw mut [u8]) -> Option<Self> {
|
||||
if raw_tm.len() < 13 {
|
||||
/// for all internal fields which can be updated.
|
||||
///
|
||||
/// It is the responsibility of the user to ensure the raw slice contains a valid telemetry
|
||||
/// packet.
|
||||
pub fn new(raw_tm: &'raw mut [u8], timestamp_len: usize) -> Option<Self> {
|
||||
let raw_tm_len = raw_tm.len();
|
||||
if raw_tm_len < CCSDS_HEADER_LEN + PUS_TM_MIN_SEC_HEADER_LEN + timestamp_len {
|
||||
return None;
|
||||
}
|
||||
Some(Self { raw_tm })
|
||||
}
|
||||
|
||||
pub fn service(&self) -> u8 {
|
||||
self.raw_tm[7]
|
||||
}
|
||||
|
||||
pub fn subservice(&self) -> u8 {
|
||||
self.raw_tm[8]
|
||||
let sp_header = crate::zc::SpHeader::from_bytes(&raw_tm[0..CCSDS_HEADER_LEN]).unwrap();
|
||||
if raw_tm_len < sp_header.total_len() {
|
||||
return None;
|
||||
}
|
||||
let writer = Self {
|
||||
raw_tm: &mut raw_tm[..sp_header.total_len()],
|
||||
timestamp_len,
|
||||
};
|
||||
Some(writer)
|
||||
}
|
||||
|
||||
/// Set the sequence count. Returns false and does not update the value if the passed value
|
||||
@ -967,6 +973,24 @@ impl<'raw> PusTmZeroCopyWriter<'raw> {
|
||||
self.raw_tm[11..13].copy_from_slice(&dest_id.to_be_bytes())
|
||||
}
|
||||
|
||||
/// Helper API to generate the space packet header portion of the PUS TM from the raw memory.
|
||||
#[inline]
|
||||
pub fn sp_header(&self) -> crate::zc::SpHeader {
|
||||
// Valid minimum length of packet was checked before.
|
||||
crate::zc::SpHeader::from_bytes(&self.raw_tm[0..CCSDS_HEADER_LEN]).unwrap()
|
||||
}
|
||||
|
||||
/// Helper API to generate the portion of the secondary header without a timestamp from the
|
||||
/// raw memory.
|
||||
#[inline]
|
||||
pub fn sec_header_without_timestamp(&self) -> PusTmSecHeaderWithoutTimestamp {
|
||||
// Valid minimum length of packet was checked before.
|
||||
PusTmSecHeaderWithoutTimestamp::from_bytes(
|
||||
&self.raw_tm[CCSDS_HEADER_LEN..CCSDS_HEADER_LEN + PUS_TM_MIN_SEC_HEADER_LEN],
|
||||
)
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
/// Set the sequence count. Returns false and does not update the value if the passed value
|
||||
/// exceeds [MAX_SEQ_COUNT].
|
||||
pub fn set_seq_count(&mut self, seq_count: u16) -> bool {
|
||||
@ -988,6 +1012,85 @@ impl<'raw> PusTmZeroCopyWriter<'raw> {
|
||||
}
|
||||
}
|
||||
|
||||
impl CcsdsPacket for PusTmZeroCopyWriter<'_> {
|
||||
#[inline]
|
||||
fn ccsds_version(&self) -> u8 {
|
||||
self.sp_header().ccsds_version()
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn packet_id(&self) -> crate::PacketId {
|
||||
self.sp_header().packet_id()
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn psc(&self) -> crate::PacketSequenceCtrl {
|
||||
self.sp_header().psc()
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn data_len(&self) -> u16 {
|
||||
self.sp_header().data_len()
|
||||
}
|
||||
}
|
||||
|
||||
impl PusPacket for PusTmZeroCopyWriter<'_> {
|
||||
#[inline]
|
||||
fn pus_version(&self) -> PusVersion {
|
||||
self.sec_header_without_timestamp().pus_version()
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn service(&self) -> u8 {
|
||||
self.raw_tm[7]
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn subservice(&self) -> u8 {
|
||||
self.raw_tm[8]
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn user_data(&self) -> &[u8] {
|
||||
&self.raw_tm[CCSDS_HEADER_LEN + PUS_TM_MIN_SEC_HEADER_LEN + self.timestamp_len
|
||||
..self.sp_header().total_len() - 2]
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn crc16(&self) -> Option<u16> {
|
||||
Some(u16::from_be_bytes(
|
||||
self.raw_tm[self.sp_header().total_len() - 2..self.sp_header().total_len()]
|
||||
.try_into()
|
||||
.unwrap(),
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
impl GenericPusTmSecondaryHeader for PusTmZeroCopyWriter<'_> {
|
||||
delegate! {
|
||||
to self.sec_header_without_timestamp() {
|
||||
#[inline]
|
||||
fn pus_version(&self) -> PusVersion;
|
||||
#[inline]
|
||||
fn sc_time_ref_status(&self) -> u8;
|
||||
#[inline]
|
||||
fn msg_counter(&self) -> u16;
|
||||
#[inline]
|
||||
fn dest_id(&self) -> u16;
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn service(&self) -> u8 {
|
||||
PusPacket::service(self)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn subservice(&self) -> u8 {
|
||||
PusPacket::subservice(self)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use alloc::string::ToString;
|
||||
@ -1001,11 +1104,18 @@ mod tests {
|
||||
#[cfg(feature = "serde")]
|
||||
use postcard::{from_bytes, to_allocvec};
|
||||
|
||||
const DUMMY_DATA: &[u8] = &[0, 1, 2];
|
||||
|
||||
fn base_ping_reply_full_ctor(timestamp: &[u8]) -> PusTmCreator {
|
||||
let mut sph = SpHeader::tm_unseg(0x123, 0x234, 0).unwrap();
|
||||
let tm_header = PusTmSecondaryHeader::new_simple(17, 2, timestamp);
|
||||
PusTmCreator::new_no_source_data(&mut sph, tm_header, true)
|
||||
}
|
||||
fn ping_reply_with_data(timestamp: &[u8]) -> PusTmCreator {
|
||||
let mut sph = SpHeader::tm_unseg(0x123, 0x234, 0).unwrap();
|
||||
let tm_header = PusTmSecondaryHeader::new_simple(17, 2, timestamp);
|
||||
PusTmCreator::new(&mut sph, tm_header, DUMMY_DATA, true)
|
||||
}
|
||||
|
||||
fn base_hk_reply<'a>(timestamp: &'a [u8], src_data: &'a [u8]) -> PusTmCreator<'a> {
|
||||
let mut sph = SpHeader::tm_unseg(0x123, 0x234, 0).unwrap();
|
||||
@ -1294,7 +1404,7 @@ mod tests {
|
||||
let tm_size = ping_tm
|
||||
.write_to_bytes(&mut buf)
|
||||
.expect("writing PUS ping TM failed");
|
||||
let mut writer = PusTmZeroCopyWriter::new(&mut buf[..tm_size])
|
||||
let mut writer = PusTmZeroCopyWriter::new(&mut buf[..tm_size], 7)
|
||||
.expect("Creating zero copy writer failed");
|
||||
writer.set_destination_id(55);
|
||||
writer.set_msg_count(100);
|
||||
@ -1302,8 +1412,6 @@ mod tests {
|
||||
writer.set_apid(MAX_APID);
|
||||
assert!(!writer.set_apid(MAX_APID + 1));
|
||||
assert!(!writer.set_apid(MAX_SEQ_COUNT + 1));
|
||||
assert_eq!(writer.service(), 17);
|
||||
assert_eq!(writer.subservice(), 2);
|
||||
writer.finish();
|
||||
// This performs all necessary checks, including the CRC check.
|
||||
let (tm_read_back, tm_size_read_back) =
|
||||
@ -1315,6 +1423,53 @@ mod tests {
|
||||
assert_eq!(tm_read_back.apid(), MAX_APID);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_zero_copy_writer_ccsds_api() {
|
||||
let ping_tm = base_ping_reply_full_ctor(dummy_timestamp());
|
||||
let mut buf: [u8; 64] = [0; 64];
|
||||
let tm_size = ping_tm
|
||||
.write_to_bytes(&mut buf)
|
||||
.expect("writing PUS ping TM failed");
|
||||
let mut writer = PusTmZeroCopyWriter::new(&mut buf[..tm_size], 7)
|
||||
.expect("Creating zero copy writer failed");
|
||||
writer.set_destination_id(55);
|
||||
writer.set_msg_count(100);
|
||||
writer.set_seq_count(MAX_SEQ_COUNT);
|
||||
writer.set_apid(MAX_APID);
|
||||
assert_eq!(PusPacket::service(&writer), 17);
|
||||
assert_eq!(PusPacket::subservice(&writer), 2);
|
||||
assert_eq!(writer.apid(), MAX_APID);
|
||||
assert_eq!(writer.seq_count(), MAX_SEQ_COUNT);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_zero_copy_pus_api() {
|
||||
let ping_tm = ping_reply_with_data(dummy_timestamp());
|
||||
let mut buf: [u8; 64] = [0; 64];
|
||||
let tm_size = ping_tm
|
||||
.write_to_bytes(&mut buf)
|
||||
.expect("writing PUS ping TM failed");
|
||||
let crc16_raw = u16::from_be_bytes(buf[tm_size - 2..tm_size].try_into().unwrap());
|
||||
let mut writer = PusTmZeroCopyWriter::new(&mut buf[..tm_size], 7)
|
||||
.expect("Creating zero copy writer failed");
|
||||
writer.set_destination_id(55);
|
||||
writer.set_msg_count(100);
|
||||
writer.set_seq_count(MAX_SEQ_COUNT);
|
||||
writer.set_apid(MAX_APID);
|
||||
assert_eq!(PusPacket::service(&writer), 17);
|
||||
assert_eq!(PusPacket::subservice(&writer), 2);
|
||||
assert_eq!(writer.dest_id(), 55);
|
||||
assert_eq!(writer.msg_counter(), 100);
|
||||
assert_eq!(writer.sec_header_without_timestamp().dest_id(), 55);
|
||||
assert_eq!(writer.sec_header_without_timestamp().msg_counter(), 100);
|
||||
assert_eq!(writer.user_data(), DUMMY_DATA);
|
||||
// Need to check crc16 before finish, because finish will update the CRC.
|
||||
let crc16 = writer.crc16();
|
||||
assert!(crc16.is_some());
|
||||
assert_eq!(crc16.unwrap(), crc16_raw);
|
||||
writer.finish();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_sec_header_without_stamp() {
|
||||
let sec_header = PusTmSecondaryHeader::new_simple_no_timestamp(17, 1);
|
||||
|
@ -311,7 +311,7 @@ pub struct PacketSequenceCtrl {
|
||||
impl PacketSequenceCtrl {
|
||||
/// const variant of [PacketSequenceCtrl::new], but panics if the sequence count exceeds
|
||||
/// [MAX_SEQ_COUNT].
|
||||
const fn const_new(seq_flags: SequenceFlags, seq_count: u16) -> PacketSequenceCtrl {
|
||||
pub const fn const_new(seq_flags: SequenceFlags, seq_count: u16) -> PacketSequenceCtrl {
|
||||
if seq_count > MAX_SEQ_COUNT {
|
||||
panic!("Sequence count too large");
|
||||
}
|
||||
|
@ -672,10 +672,8 @@ impl<ProvidesDaysLen: ProvidesDaysLength> TimeProvider<ProvidesDaysLen> {
|
||||
unix_stamp: &UnixTimestamp,
|
||||
days_len: LengthOfDaySegment,
|
||||
) -> Result<Self, TimestampError> {
|
||||
let conv_from_dt = ConversionFromUnix::new(
|
||||
unix_stamp.unix_seconds,
|
||||
unix_stamp.subsecond_millis.unwrap_or(0) as u32,
|
||||
)?;
|
||||
let conv_from_dt =
|
||||
ConversionFromUnix::new(unix_stamp.unix_seconds, unix_stamp.subsecond_millis as u32)?;
|
||||
Self::generic_from_conversion(days_len, conv_from_dt)
|
||||
}
|
||||
|
||||
@ -1148,7 +1146,7 @@ impl<ProvidesDaysLen: ProvidesDaysLength> CcsdsTimeProvider for TimeProvider<Pro
|
||||
self.unix_stamp.unix_seconds
|
||||
}
|
||||
#[inline]
|
||||
fn subsecond_millis(&self) -> Option<u16> {
|
||||
fn subsecond_millis(&self) -> u16 {
|
||||
self.unix_stamp.subsecond_millis
|
||||
}
|
||||
|
||||
@ -1201,6 +1199,10 @@ impl TimeWriter for TimeProvider<DaysLen16Bits> {
|
||||
}
|
||||
Ok(self.len_as_bytes())
|
||||
}
|
||||
|
||||
fn len_written(&self) -> usize {
|
||||
self.len_as_bytes()
|
||||
}
|
||||
}
|
||||
|
||||
impl TimeWriter for TimeProvider<DaysLen24Bits> {
|
||||
@ -1221,6 +1223,10 @@ impl TimeWriter for TimeProvider<DaysLen24Bits> {
|
||||
}
|
||||
Ok(self.len_as_bytes())
|
||||
}
|
||||
|
||||
fn len_written(&self) -> usize {
|
||||
self.len_as_bytes()
|
||||
}
|
||||
}
|
||||
|
||||
impl<DaysLenProvider: ProvidesDaysLength> PartialEq for TimeProvider<DaysLenProvider> {
|
||||
@ -1312,12 +1318,12 @@ mod tests {
|
||||
(DAYS_CCSDS_TO_UNIX * SECONDS_PER_DAY as i32) as i64
|
||||
);
|
||||
let subsecond_millis = unix_stamp.subsecond_millis;
|
||||
assert!(subsecond_millis.is_none());
|
||||
assert_eq!(subsecond_millis, 0);
|
||||
assert_eq!(
|
||||
time_stamper.submillis_precision(),
|
||||
SubmillisPrecision::Absent
|
||||
);
|
||||
assert!(time_stamper.subsecond_millis().is_none());
|
||||
assert_eq!(time_stamper.subsecond_millis(), 0);
|
||||
assert_eq!(time_stamper.ccdsd_time_code(), CcsdsTimeCodes::Cds);
|
||||
assert_eq!(
|
||||
time_stamper.p_field(),
|
||||
@ -1348,11 +1354,9 @@ mod tests {
|
||||
assert_eq!(date_time.minute(), 0);
|
||||
assert_eq!(date_time.second(), 0);
|
||||
let time_stamper = TimeProvider::new_with_u16_days((-DAYS_CCSDS_TO_UNIX) as u16, 40);
|
||||
assert!(time_stamper.subsecond_millis().is_some());
|
||||
assert_eq!(time_stamper.subsecond_millis().unwrap(), 40);
|
||||
assert_eq!(time_stamper.subsecond_millis(), 40);
|
||||
let time_stamper = TimeProvider::new_with_u16_days((-DAYS_CCSDS_TO_UNIX) as u16, 1040);
|
||||
assert!(time_stamper.subsecond_millis().is_some());
|
||||
assert_eq!(time_stamper.subsecond_millis().unwrap(), 40);
|
||||
assert_eq!(time_stamper.subsecond_millis(), 40);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@ -2270,4 +2274,22 @@ mod tests {
|
||||
assert_eq!(first, second);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_stamp_to_vec_u16() {
|
||||
let stamp = TimeProvider::new_with_u16_days(1, 1);
|
||||
let stamp_vec = stamp.to_vec().unwrap();
|
||||
let mut buf: [u8; 7] = [0; 7];
|
||||
stamp.write_to_bytes(&mut buf).unwrap();
|
||||
assert_eq!(stamp_vec, buf);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_stamp_to_vec_u24() {
|
||||
let stamp = TimeProvider::new_with_u24_days(1, 1).unwrap();
|
||||
let stamp_vec = stamp.to_vec().unwrap();
|
||||
let mut buf: [u8; 10] = [0; 10];
|
||||
stamp.write_to_bytes(&mut buf).unwrap();
|
||||
assert_eq!(stamp_vec, buf[..stamp.len_written()]);
|
||||
}
|
||||
}
|
||||
|
@ -297,10 +297,10 @@ impl TimeProviderCcsdsEpoch {
|
||||
unix_stamp.as_date_time().unwrap(),
|
||||
));
|
||||
}
|
||||
let mut fractions = None;
|
||||
if let Some(subsec_millis) = unix_stamp.subsecond_millis {
|
||||
fractions = fractional_part_from_subsec_ns(res, subsec_millis as u64 * 10_u64.pow(6));
|
||||
}
|
||||
let fractions = fractional_part_from_subsec_ns(
|
||||
res,
|
||||
unix_stamp.subsecond_millis() as u64 * 10_u64.pow(6),
|
||||
);
|
||||
Self::new_generic(WidthCounterPair(4, ccsds_epoch as u32), fractions).map_err(|e| e.into())
|
||||
}
|
||||
|
||||
@ -587,6 +587,10 @@ impl TimeWriter for TimeProviderCcsdsEpoch {
|
||||
}
|
||||
Ok(current_idx)
|
||||
}
|
||||
|
||||
fn len_written(&self) -> usize {
|
||||
self.len_as_bytes()
|
||||
}
|
||||
}
|
||||
|
||||
impl CcsdsTimeProvider for TimeProviderCcsdsEpoch {
|
||||
@ -606,15 +610,15 @@ impl CcsdsTimeProvider for TimeProviderCcsdsEpoch {
|
||||
self.unix_seconds()
|
||||
}
|
||||
|
||||
fn subsecond_millis(&self) -> Option<u16> {
|
||||
fn subsecond_millis(&self) -> u16 {
|
||||
if let Some(fractions) = self.fractions {
|
||||
if fractions.0 == FractionalResolution::Seconds {
|
||||
return None;
|
||||
return 0;
|
||||
}
|
||||
// Rounding down here is the correct approach.
|
||||
return Some((convert_fractional_part_to_ns(fractions) / 10_u32.pow(6) as u64) as u16);
|
||||
return (convert_fractional_part_to_ns(fractions) / 10_u32.pow(6) as u64) as u16;
|
||||
}
|
||||
None
|
||||
0
|
||||
}
|
||||
|
||||
fn date_time(&self) -> Option<DateTime<Utc>> {
|
||||
@ -759,7 +763,7 @@ mod tests {
|
||||
let zero_cuc = zero_cuc.unwrap();
|
||||
let res = zero_cuc.write_to_bytes(&mut buf);
|
||||
assert!(res.is_ok());
|
||||
assert!(zero_cuc.subsecond_millis().is_none());
|
||||
assert_eq!(zero_cuc.subsecond_millis(), 0);
|
||||
assert_eq!(zero_cuc.len_as_bytes(), 5);
|
||||
assert_eq!(pfield_len(buf[0]), 1);
|
||||
let written = res.unwrap();
|
||||
@ -1126,7 +1130,7 @@ mod tests {
|
||||
// What I would roughly expect
|
||||
assert_eq!(cuc_stamp2.counter.1, 203);
|
||||
assert!(cuc_stamp2.fractions.unwrap().1 < 100);
|
||||
assert!(cuc_stamp2.subsecond_millis().unwrap() <= 1);
|
||||
assert!(cuc_stamp2.subsecond_millis() <= 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@ -1226,4 +1230,13 @@ mod tests {
|
||||
panic!("unexpected error: {}", cuc_error);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_stamp_to_vec() {
|
||||
let stamp = TimeProviderCcsdsEpoch::new_u16_counter(100);
|
||||
let stamp_vec = stamp.to_vec().unwrap();
|
||||
let mut buf: [u8; 16] = [0; 16];
|
||||
stamp.write_to_bytes(&mut buf).unwrap();
|
||||
assert_eq!(stamp_vec, buf[..stamp.len_written()]);
|
||||
}
|
||||
}
|
||||
|
151
src/time/mod.rs
151
src/time/mod.rs
@ -3,7 +3,7 @@ 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::ops::{Add, AddAssign, Sub};
|
||||
use core::time::Duration;
|
||||
use core::u8;
|
||||
|
||||
@ -189,9 +189,19 @@ pub fn ms_of_day(seconds_since_epoch: f64) -> u32 {
|
||||
}
|
||||
|
||||
pub trait TimeWriter {
|
||||
fn len_written(&self) -> usize;
|
||||
|
||||
/// Generic function to convert write a timestamp into a raw buffer.
|
||||
/// Returns the number of written bytes on success.
|
||||
fn write_to_bytes(&self, bytes: &mut [u8]) -> Result<usize, TimestampError>;
|
||||
|
||||
#[cfg(feature = "alloc")]
|
||||
#[cfg_attr(doc_cfg, doc(cfg(feature = "alloc")))]
|
||||
fn to_vec(&self) -> Result<alloc::vec::Vec<u8>, TimestampError> {
|
||||
let mut vec = alloc::vec![0; self.len_written()];
|
||||
self.write_to_bytes(&mut vec)?;
|
||||
Ok(vec)
|
||||
}
|
||||
}
|
||||
|
||||
pub trait TimeReader {
|
||||
@ -215,12 +225,9 @@ pub trait CcsdsTimeProvider {
|
||||
fn ccdsd_time_code(&self) -> CcsdsTimeCodes;
|
||||
|
||||
fn unix_seconds(&self) -> i64;
|
||||
fn subsecond_millis(&self) -> Option<u16>;
|
||||
fn subsecond_millis(&self) -> u16;
|
||||
fn unix_stamp(&self) -> UnixTimestamp {
|
||||
if self.subsecond_millis().is_none() {
|
||||
return UnixTimestamp::new_only_seconds(self.unix_seconds());
|
||||
}
|
||||
UnixTimestamp::const_new(self.unix_seconds(), self.subsecond_millis().unwrap())
|
||||
UnixTimestamp::const_new(self.unix_seconds(), self.subsecond_millis())
|
||||
}
|
||||
|
||||
fn date_time(&self) -> Option<DateTime<Utc>>;
|
||||
@ -228,18 +235,16 @@ pub trait CcsdsTimeProvider {
|
||||
|
||||
/// UNIX timestamp: Elapsed seconds since 1970-01-01T00:00:00+00:00.
|
||||
///
|
||||
/// Also can optionally include subsecond millisecond for greater accuracy. Please note that a
|
||||
/// subsecond millisecond value of 0 gets converted to [None].
|
||||
/// Also can optionally include subsecond millisecond for greater accuracy.
|
||||
#[derive(Default, Debug, Copy, Clone, PartialEq, Eq)]
|
||||
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
||||
pub struct UnixTimestamp {
|
||||
pub unix_seconds: i64,
|
||||
subsecond_millis: Option<u16>,
|
||||
subsecond_millis: u16,
|
||||
}
|
||||
|
||||
impl UnixTimestamp {
|
||||
/// Returns none if the subsecond millisecond value is larger than 999. 0 is converted to
|
||||
/// a [None] value.
|
||||
/// Returns [None] if the subsecond millisecond value is larger than 999.
|
||||
pub fn new(unix_seconds: i64, subsec_millis: u16) -> Option<Self> {
|
||||
if subsec_millis > 999 {
|
||||
return None;
|
||||
@ -248,15 +253,10 @@ impl UnixTimestamp {
|
||||
}
|
||||
|
||||
/// Like [Self::new] but const. Panics if the subsecond value is larger than 999.
|
||||
pub const fn const_new(unix_seconds: i64, subsec_millis: u16) -> Self {
|
||||
if subsec_millis > 999 {
|
||||
pub const fn const_new(unix_seconds: i64, subsecond_millis: u16) -> Self {
|
||||
if subsecond_millis > 999 {
|
||||
panic!("subsec milliseconds exceeds 999");
|
||||
}
|
||||
let subsecond_millis = if subsec_millis == 0 {
|
||||
None
|
||||
} else {
|
||||
Some(subsec_millis)
|
||||
};
|
||||
Self {
|
||||
unix_seconds,
|
||||
subsecond_millis,
|
||||
@ -266,11 +266,11 @@ impl UnixTimestamp {
|
||||
pub fn new_only_seconds(unix_seconds: i64) -> Self {
|
||||
Self {
|
||||
unix_seconds,
|
||||
subsecond_millis: None,
|
||||
subsecond_millis: 0,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn subsecond_millis(&self) -> Option<u16> {
|
||||
pub fn subsecond_millis(&self) -> u16 {
|
||||
self.subsecond_millis
|
||||
}
|
||||
|
||||
@ -284,19 +284,28 @@ impl UnixTimestamp {
|
||||
|
||||
#[inline]
|
||||
pub fn unix_seconds_f64(&self) -> f64 {
|
||||
let mut secs = self.unix_seconds as f64;
|
||||
if let Some(subsec_millis) = self.subsecond_millis {
|
||||
secs += subsec_millis as f64 / 1000.0;
|
||||
}
|
||||
secs
|
||||
self.unix_seconds as f64 + (self.subsecond_millis as f64 / 1000.0)
|
||||
}
|
||||
|
||||
pub fn as_date_time(&self) -> LocalResult<DateTime<Utc>> {
|
||||
Utc.timestamp_opt(
|
||||
self.unix_seconds,
|
||||
self.subsecond_millis.unwrap_or(0) as u32 * 10_u32.pow(6),
|
||||
self.subsecond_millis as u32 * 10_u32.pow(6),
|
||||
)
|
||||
}
|
||||
|
||||
// Calculate the difference in milliseconds between two UnixTimestamps
|
||||
pub fn difference_in_millis(&self, other: &UnixTimestamp) -> i64 {
|
||||
let seconds_difference = self.unix_seconds - other.unix_seconds;
|
||||
// Convert seconds difference to milliseconds
|
||||
let milliseconds_difference = seconds_difference * 1000;
|
||||
|
||||
// Calculate the difference in subsecond milliseconds directly
|
||||
let subsecond_difference = self.subsecond_millis as i64 - other.subsecond_millis as i64;
|
||||
|
||||
// Combine the differences
|
||||
milliseconds_difference + subsecond_difference
|
||||
}
|
||||
}
|
||||
|
||||
impl From<DateTime<Utc>> for UnixTimestamp {
|
||||
@ -322,11 +331,7 @@ impl Ord for UnixTimestamp {
|
||||
_ => (),
|
||||
}
|
||||
|
||||
match self
|
||||
.subsecond_millis()
|
||||
.unwrap_or(0)
|
||||
.cmp(&other.subsecond_millis().unwrap_or(0))
|
||||
{
|
||||
match self.subsecond_millis().cmp(&other.subsecond_millis()) {
|
||||
Ordering::Less => {
|
||||
return if self.unix_seconds < 0 {
|
||||
Ordering::Greater
|
||||
@ -347,12 +352,38 @@ impl Ord for UnixTimestamp {
|
||||
}
|
||||
}
|
||||
|
||||
/// Difference between two UNIX timestamps. The [Duration] type can not contain negative durations,
|
||||
/// so the sign information is supplied separately.
|
||||
#[derive(Clone, Copy, PartialEq, Eq)]
|
||||
pub struct StampDiff {
|
||||
pub positive_duration: bool,
|
||||
pub duration_absolute: Duration,
|
||||
}
|
||||
|
||||
impl Sub for UnixTimestamp {
|
||||
type Output = StampDiff;
|
||||
|
||||
fn sub(self, rhs: Self) -> Self::Output {
|
||||
let difference = self.difference_in_millis(&rhs);
|
||||
if difference < 0 {
|
||||
StampDiff {
|
||||
positive_duration: false,
|
||||
duration_absolute: Duration::from_millis(-difference as u64),
|
||||
}
|
||||
} else {
|
||||
StampDiff {
|
||||
positive_duration: true,
|
||||
duration_absolute: Duration::from_millis(difference as u64),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn get_new_stamp_after_addition(
|
||||
current_stamp: &UnixTimestamp,
|
||||
duration: Duration,
|
||||
) -> UnixTimestamp {
|
||||
let mut new_subsec_millis =
|
||||
current_stamp.subsecond_millis().unwrap_or(0) + duration.subsec_millis() as u16;
|
||||
let mut new_subsec_millis = current_stamp.subsecond_millis() + duration.subsec_millis() as u16;
|
||||
let mut new_unix_seconds = current_stamp.unix_seconds;
|
||||
let mut increment_seconds = |value: u32| {
|
||||
if new_unix_seconds < 0 {
|
||||
@ -455,18 +486,17 @@ mod tests {
|
||||
fn basic_unix_stamp_test() {
|
||||
let stamp = UnixTimestamp::new_only_seconds(-200);
|
||||
assert_eq!(stamp.unix_seconds, -200);
|
||||
assert!(stamp.subsecond_millis().is_none());
|
||||
assert_eq!(stamp.subsecond_millis(), 0);
|
||||
let stamp = UnixTimestamp::new_only_seconds(250);
|
||||
assert_eq!(stamp.unix_seconds, 250);
|
||||
assert!(stamp.subsecond_millis().is_none());
|
||||
assert_eq!(stamp.subsecond_millis(), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn basic_float_unix_stamp_test() {
|
||||
let stamp = UnixTimestamp::new(500, 600).unwrap();
|
||||
assert!(stamp.subsecond_millis.is_some());
|
||||
assert_eq!(stamp.unix_seconds, 500);
|
||||
let subsec_millis = stamp.subsecond_millis().unwrap();
|
||||
let subsec_millis = stamp.subsecond_millis();
|
||||
assert_eq!(subsec_millis, 600);
|
||||
assert!((500.6 - stamp.unix_seconds_f64()).abs() < 0.0001);
|
||||
}
|
||||
@ -515,6 +545,7 @@ mod tests {
|
||||
assert!(stamp2 <= stamp1);
|
||||
}
|
||||
|
||||
#[allow(clippy::nonminimal_bool)]
|
||||
#[test]
|
||||
fn test_eq() {
|
||||
let stamp0 = UnixTimestamp::new(5, 0).unwrap();
|
||||
@ -531,11 +562,10 @@ mod tests {
|
||||
let mut stamp0 = UnixTimestamp::new_only_seconds(1);
|
||||
stamp0 += Duration::from_secs(5);
|
||||
assert_eq!(stamp0.unix_seconds, 6);
|
||||
assert!(stamp0.subsecond_millis().is_none());
|
||||
assert_eq!(stamp0.subsecond_millis(), 0);
|
||||
let stamp1 = stamp0 + Duration::from_millis(500);
|
||||
assert_eq!(stamp1.unix_seconds, 6);
|
||||
assert!(stamp1.subsecond_millis().is_some());
|
||||
assert_eq!(stamp1.subsecond_millis().unwrap(), 500);
|
||||
assert_eq!(stamp1.subsecond_millis(), 500);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@ -543,7 +573,7 @@ mod tests {
|
||||
let stamp0 = &UnixTimestamp::new(20, 500).unwrap();
|
||||
let stamp1 = stamp0 + Duration::from_millis(2500);
|
||||
assert_eq!(stamp1.unix_seconds, 23);
|
||||
assert!(stamp1.subsecond_millis().is_none());
|
||||
assert_eq!(stamp1.subsecond_millis(), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@ -565,15 +595,50 @@ mod tests {
|
||||
assert!(dt_now.year() >= 2020);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_stamp_diff_positive_0() {
|
||||
let stamp_later = UnixTimestamp::new(2, 0).unwrap();
|
||||
let StampDiff {
|
||||
positive_duration,
|
||||
duration_absolute,
|
||||
} = stamp_later - UnixTimestamp::new(1, 0).unwrap();
|
||||
assert!(positive_duration);
|
||||
assert_eq!(duration_absolute, Duration::from_secs(1));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_stamp_diff_positive_1() {
|
||||
let stamp_later = UnixTimestamp::new(3, 800).unwrap();
|
||||
let stamp_earlier = UnixTimestamp::new(1, 900).unwrap();
|
||||
let StampDiff {
|
||||
positive_duration,
|
||||
duration_absolute,
|
||||
} = stamp_later - stamp_earlier;
|
||||
assert!(positive_duration);
|
||||
assert_eq!(duration_absolute, Duration::from_millis(1900));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_stamp_diff_negative() {
|
||||
let stamp_later = UnixTimestamp::new(3, 800).unwrap();
|
||||
let stamp_earlier = UnixTimestamp::new(1, 900).unwrap();
|
||||
let StampDiff {
|
||||
positive_duration,
|
||||
duration_absolute,
|
||||
} = stamp_earlier - stamp_later;
|
||||
assert!(!positive_duration);
|
||||
assert_eq!(duration_absolute, Duration::from_millis(1900));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_addition_spillover() {
|
||||
let mut stamp0 = UnixTimestamp::new(1, 900).unwrap();
|
||||
stamp0 += Duration::from_millis(100);
|
||||
assert_eq!(stamp0.unix_seconds, 2);
|
||||
assert!(stamp0.subsecond_millis().is_none());
|
||||
assert_eq!(stamp0.subsecond_millis(), 0);
|
||||
stamp0 += Duration::from_millis(1100);
|
||||
assert_eq!(stamp0.unix_seconds, 3);
|
||||
assert_eq!(stamp0.subsecond_millis().unwrap(), 100);
|
||||
assert_eq!(stamp0.subsecond_millis(), 100);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
46
src/util.rs
46
src/util.rs
@ -73,6 +73,16 @@ pub trait UnsignedEnum {
|
||||
fn size(&self) -> usize;
|
||||
/// Write the unsigned enumeration to a raw buffer. Returns the written size on success.
|
||||
fn write_to_be_bytes(&self, buf: &mut [u8]) -> Result<usize, ByteConversionError>;
|
||||
|
||||
fn value(&self) -> u64;
|
||||
|
||||
#[cfg(feature = "alloc")]
|
||||
#[cfg_attr(doc_cfg, doc(cfg(feature = "alloc")))]
|
||||
fn to_vec(&self) -> alloc::vec::Vec<u8> {
|
||||
let mut buf = alloc::vec![0; self.size()];
|
||||
self.write_to_be_bytes(&mut buf).unwrap();
|
||||
buf
|
||||
}
|
||||
}
|
||||
|
||||
pub trait UnsignedEnumExt: UnsignedEnum + Debug + Copy + Clone + PartialEq + Eq {}
|
||||
@ -132,7 +142,7 @@ impl UnsignedByteField {
|
||||
Self { width, value }
|
||||
}
|
||||
|
||||
pub fn value(&self) -> u64 {
|
||||
pub const fn value_const(&self) -> u64 {
|
||||
self.value
|
||||
}
|
||||
|
||||
@ -172,6 +182,10 @@ impl UnsignedEnum for UnsignedByteField {
|
||||
self.width
|
||||
}
|
||||
|
||||
fn value(&self) -> u64 {
|
||||
self.value_const()
|
||||
}
|
||||
|
||||
fn write_to_be_bytes(&self, buf: &mut [u8]) -> Result<usize, ByteConversionError> {
|
||||
if buf.len() < self.size() {
|
||||
return Err(ByteConversionError::ToSliceTooSmall {
|
||||
@ -207,21 +221,21 @@ impl UnsignedEnum for UnsignedByteField {
|
||||
|
||||
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
|
||||
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
||||
pub struct GenericUnsignedByteField<TYPE: Copy> {
|
||||
pub struct GenericUnsignedByteField<TYPE: Copy + Into<u64>> {
|
||||
value: TYPE,
|
||||
}
|
||||
|
||||
impl<TYPE: Copy> GenericUnsignedByteField<TYPE> {
|
||||
impl<TYPE: Copy + Into<u64>> GenericUnsignedByteField<TYPE> {
|
||||
pub const fn new(val: TYPE) -> Self {
|
||||
Self { value: val }
|
||||
}
|
||||
|
||||
pub const fn value(&self) -> TYPE {
|
||||
pub const fn value_typed(&self) -> TYPE {
|
||||
self.value
|
||||
}
|
||||
}
|
||||
|
||||
impl<TYPE: Copy + ToBeBytes> UnsignedEnum for GenericUnsignedByteField<TYPE> {
|
||||
impl<TYPE: Copy + ToBeBytes + Into<u64>> UnsignedEnum for GenericUnsignedByteField<TYPE> {
|
||||
fn size(&self) -> usize {
|
||||
self.value.written_len()
|
||||
}
|
||||
@ -233,9 +247,13 @@ impl<TYPE: Copy + ToBeBytes> UnsignedEnum for GenericUnsignedByteField<TYPE> {
|
||||
expected: self.size(),
|
||||
});
|
||||
}
|
||||
buf[0..self.size()].copy_from_slice(self.value.to_be_bytes().as_ref());
|
||||
buf[..self.size()].copy_from_slice(self.value.to_be_bytes().as_ref());
|
||||
Ok(self.value.written_len())
|
||||
}
|
||||
|
||||
fn value(&self) -> u64 {
|
||||
self.value_typed().into()
|
||||
}
|
||||
}
|
||||
|
||||
pub type UnsignedByteFieldEmpty = GenericUnsignedByteField<()>;
|
||||
@ -351,6 +369,8 @@ pub mod tests {
|
||||
for val in buf.iter().skip(1) {
|
||||
assert_eq!(*val, 0);
|
||||
}
|
||||
assert_eq!(u8.value_typed(), 5);
|
||||
assert_eq!(u8.value(), 5);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@ -367,6 +387,8 @@ pub mod tests {
|
||||
for val in buf.iter().skip(2) {
|
||||
assert_eq!(*val, 0);
|
||||
}
|
||||
assert_eq!(u16.value_typed(), 3823);
|
||||
assert_eq!(u16.value(), 3823);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@ -383,6 +405,8 @@ pub mod tests {
|
||||
(4..8).for_each(|i| {
|
||||
assert_eq!(buf[i], 0);
|
||||
});
|
||||
assert_eq!(u32.value_typed(), 80932);
|
||||
assert_eq!(u32.value(), 80932);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@ -396,6 +420,8 @@ pub mod tests {
|
||||
assert_eq!(len, 8);
|
||||
let raw_val = u64::from_be_bytes(buf[0..8].try_into().unwrap());
|
||||
assert_eq!(raw_val, 5999999);
|
||||
assert_eq!(u64.value_typed(), 5999999);
|
||||
assert_eq!(u64.value(), 5999999);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@ -534,9 +560,9 @@ pub mod tests {
|
||||
u8.write_to_be_bytes(&mut buf)
|
||||
.expect("writing to raw buffer failed");
|
||||
assert_eq!(buf[0], 5);
|
||||
for i in 1..8 {
|
||||
(1..8).for_each(|i| {
|
||||
assert_eq!(buf[i], 0);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
@ -562,9 +588,9 @@ pub mod tests {
|
||||
.expect("writing to raw buffer failed");
|
||||
let raw_val = u32::from_be_bytes(buf[0..4].try_into().unwrap());
|
||||
assert_eq!(raw_val, 80932);
|
||||
for i in 4..8 {
|
||||
(4..8).for_each(|i| {
|
||||
assert_eq!(buf[i], 0);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
Reference in New Issue
Block a user