Compare commits
207 Commits
v0.11.0-rc
...
v0.16.0
Author | SHA1 | Date | |
---|---|---|---|
0aa41fee92 | |||
![]() |
d1516d669d
|
||
b1ebb4d7c4 | |||
![]() |
cd79af4440
|
||
6a760c8585 | |||
![]() |
5eb409f1ec
|
||
69d416d6ff | |||
![]() |
e2b239ae61
|
||
b06d7c1a87 | |||
![]() |
ec1ddbde81 | ||
7f4ada1734 | |||
![]() |
15f97e960b | ||
49b7c2d072 | |||
1ed23bd7ef | |||
a82cdb1e82 | |||
12e7062075 | |||
a1e40834f5 | |||
![]() |
3f6a5df8e7 | ||
a8d5fdf8d3 | |||
![]() |
62326da276 | ||
477890346a | |||
![]() |
9394beea38 | ||
6c425e137a | |||
24b91a7a83 | |||
a7c6ce7d44 | |||
![]() |
c68e71a25e
|
||
272a961a70 | |||
![]() |
6f4df7e3c2
|
||
15c477e810 | |||
![]() |
e5b10920a0
|
||
3f8434e1fa | |||
![]() |
ec3f462931 | ||
e6686caba1 | |||
![]() |
2a0b21983e | ||
4e153e0b68 | |||
![]() |
aaac15e3d0 | ||
89788c1341 | |||
![]() |
578be2da8f | ||
3a21daf8de | |||
![]() |
8fd46f6a30 | ||
c6b74fecbd | |||
![]() |
60e35559e5 | ||
e708f1b861 | |||
![]() |
91490b5dd6
|
||
e151b8e761 | |||
![]() |
2839174e5f | ||
6e2db87fa9 | |||
![]() |
e8a01dc6b2
|
||
20403bda32 | |||
![]() |
2cbd48331c
|
||
c1346f2b12 | |||
2e3a7849a7 | |||
86ebea8eb8 | |||
2c8c77acb8 | |||
63d74aa58b | |||
5a86f89c83 | |||
b8ae26c302 | |||
160b1dedf9 | |||
8eccf1fa29 | |||
![]() |
8445b7cc31
|
||
a2971f8f73 | |||
![]() |
ba3b66326d
|
||
de2675e602 | |||
![]() |
3d344c11cc | ||
6e2c35e0c0 | |||
![]() |
026e1a50b9
|
||
440b836b70 | |||
![]() |
00e28e4a96
|
||
4c1cad5b72 | |||
5cd5c1ce6d | |||
de99bb926a | |||
167f53cac7
|
|||
172227b843 | |||
1bbca6866b
|
|||
b569208d45 | |||
d9709ffd6c
|
|||
243dc64a78 | |||
a6dc173f7f | |||
86dddbeef5
|
|||
17d112e838 | |||
9c8467ccfe
|
|||
217a8c2cc7 | |||
349e34bed6
|
|||
d6a76ca360 | |||
8f4351771b | |||
b08c3329f4 | |||
08e0d39154
|
|||
ab97607024 | |||
60d1f77844 | |||
5a112b7f39 | |||
e774dd69d4 | |||
a03d26a49c | |||
026173514f | |||
2d7ccc0909 | |||
05d3bac927
|
|||
d58df5fee2 | |||
9d23ac5b9b | |||
c0b4653c01 | |||
f156833985
|
|||
9aea3dba00 | |||
48247a0a87 | |||
f70b957d9a | |||
fbf953df0e
|
|||
f135d54364 | |||
d8b2a3dfea
|
|||
448b76be91 | |||
027b01f00f
|
|||
bf15b22889 | |||
16f91b562d
|
|||
cd77b806fe | |||
43c88da3f2
|
|||
b19a61b859 | |||
8aa957b8bb
|
|||
190fa1befc | |||
175b61deca
|
|||
51c28b5cc6 | |||
45cc74daa7 | |||
191c6f8146 | |||
5449884b2e | |||
9c93c76193 | |||
043927c7ef | |||
f4dc5a0302 | |||
9166faa4ae | |||
ed808e69d4 | |||
d146b6cf57 | |||
ff0c9d8c70 | |||
c40bc855a2 | |||
81423fc6e8 | |||
a399b11a8e | |||
9d4c7446a3 | |||
b87f7d73b1 | |||
80744eea16 | |||
a5918bfd4a | |||
0e347b0e37 | |||
58dabb6f2f
|
|||
7fd65aa592
|
|||
0024afc83e | |||
c48bd848d3
|
|||
b8be9ae641 | |||
c2506dbba9 | |||
b842b9d11a | |||
374c034e92 | |||
791c7f6e02 | |||
8001938507 | |||
73ab7ff148 | |||
c59d01174f
|
|||
eb49bff0c9 | |||
af392d40d0
|
|||
b78bfe2114
|
|||
69a3b1d8f3
|
|||
e7b3ba9575 | |||
c515535ccd
|
|||
95158a8cd2 | |||
8b1ccb0cd0
|
|||
619b22e58f | |||
55222d92b3
|
|||
8e1934e604
|
|||
5f37978c56 | |||
97bbb14168 | |||
a65a98f43f | |||
e1a200e65b | |||
b55c7db3fc | |||
944bcf1320 | |||
8972dcbfc0
|
|||
04b671fa6f | |||
533afc33fa
|
|||
50c56f6504
|
|||
9e02e00d1a | |||
d8676ae711
|
|||
9711159969 | |||
57adb619b3
|
|||
fe52657d11 | |||
50b86939a1
|
|||
179984f258 | |||
deb89362a4 | |||
4cd40f37ce | |||
bbd66a6a8b
|
|||
0115461bb5
|
|||
ca90393d95 | |||
325e7d6ff3 | |||
228f198006 | |||
54f065ed74
|
|||
4ef65279ea
|
|||
f0af16dc29
|
|||
d05a1077e8 | |||
fc684a42a8
|
|||
e9ddc316c8 | |||
4da417dfd2
|
|||
cabb3a19ef
|
|||
5eef376351 | |||
538548b05e | |||
caaecdff0c | |||
3045a27d8c
|
|||
c7cf83d468
|
|||
ef37a84edc
|
|||
c1b32bca21 | |||
d9525674c3
|
|||
8b151d942d
|
|||
85a8eb3f4a
|
|||
fb71185b4a | |||
3e62d7d411
|
|||
3faffd52fc | |||
7476fc8096
|
|||
59c7ece126
|
|||
6f5254bdbd | |||
bd1927c5c2
|
|||
77862868d5
|
115
.github/workflows/ci.yml
vendored
115
.github/workflows/ci.yml
vendored
@@ -1,42 +1,39 @@
|
|||||||
on: [push]
|
|
||||||
|
|
||||||
name: ci
|
name: ci
|
||||||
|
on: [push, pull_request]
|
||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
check:
|
check:
|
||||||
name: Check
|
name: Check build
|
||||||
strategy:
|
strategy:
|
||||||
matrix:
|
matrix:
|
||||||
os: [ubuntu-latest, macos-latest, windows-latest]
|
os: [ubuntu-latest, macos-latest, windows-latest]
|
||||||
runs-on: ${{ matrix.os }}
|
runs-on: ${{ matrix.os }}
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v2
|
- uses: actions/checkout@v4
|
||||||
- uses: actions-rs/toolchain@v1
|
- uses: dtolnay/rust-toolchain@stable
|
||||||
with:
|
- run: cargo check --release
|
||||||
profile: minimal
|
|
||||||
toolchain: stable
|
|
||||||
- uses: actions-rs/cargo@v1
|
|
||||||
with:
|
|
||||||
command: check
|
|
||||||
args: --release
|
|
||||||
|
|
||||||
msrv:
|
test:
|
||||||
name: Check with MSRV
|
name: Run Tests
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v2
|
- uses: actions/checkout@v4
|
||||||
- uses: actions-rs/toolchain@v1
|
- uses: dtolnay/rust-toolchain@stable
|
||||||
with:
|
- name: Install nextest
|
||||||
toolchain: 1.61.0
|
uses: taiki-e/install-action@nextest
|
||||||
override: true
|
- run: cargo nextest run --all-features
|
||||||
profile: minimal
|
- run: cargo test --doc
|
||||||
- uses: actions-rs/cargo@v1
|
|
||||||
with:
|
msrv:
|
||||||
command: check
|
name: Check MSRV
|
||||||
args: --release
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v4
|
||||||
|
- uses: dtolnay/rust-toolchain@1.83
|
||||||
|
- run: cargo check --release
|
||||||
|
|
||||||
cross-check:
|
cross-check:
|
||||||
name: Check Cross
|
name: Check Cross-Compilation
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
strategy:
|
strategy:
|
||||||
matrix:
|
matrix:
|
||||||
@@ -44,70 +41,32 @@ jobs:
|
|||||||
- armv7-unknown-linux-gnueabihf
|
- armv7-unknown-linux-gnueabihf
|
||||||
- thumbv7em-none-eabihf
|
- thumbv7em-none-eabihf
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v2
|
- uses: actions/checkout@v4
|
||||||
- uses: actions-rs/toolchain@v1
|
- uses: dtolnay/rust-toolchain@stable
|
||||||
with:
|
with:
|
||||||
profile: minimal
|
targets: "armv7-unknown-linux-gnueabihf, thumbv7em-none-eabihf"
|
||||||
toolchain: stable
|
- run: cargo check --release --target=${{matrix.target}} --no-default-features
|
||||||
target: ${{ matrix.target }}
|
|
||||||
override: true
|
|
||||||
- uses: actions-rs/cargo@v1
|
|
||||||
with:
|
|
||||||
use-cross: true
|
|
||||||
command: check
|
|
||||||
args: --release --target=${{ matrix.target }} --no-default-features
|
|
||||||
|
|
||||||
fmt:
|
fmt:
|
||||||
name: Rustfmt
|
name: Check formatting
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v2
|
- uses: actions/checkout@v4
|
||||||
- uses: actions-rs/toolchain@v1
|
- uses: dtolnay/rust-toolchain@stable
|
||||||
with:
|
- run: cargo fmt --all -- --check
|
||||||
profile: minimal
|
|
||||||
toolchain: stable
|
|
||||||
override: true
|
|
||||||
- run: rustup component add rustfmt
|
|
||||||
- uses: actions-rs/cargo@v1
|
|
||||||
with:
|
|
||||||
command: fmt
|
|
||||||
args: --all -- --check
|
|
||||||
|
|
||||||
check-doc:
|
docs:
|
||||||
name: Check Documentation Build
|
name: Check Documentation Build
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v2
|
- uses: actions/checkout@v4
|
||||||
- uses: actions-rs/toolchain@v1
|
- uses: dtolnay/rust-toolchain@nightly
|
||||||
with:
|
- run: RUSTDOCFLAGS="--cfg docsrs --generate-link-to-definition -Z unstable-options" cargo +nightly doc --all-features
|
||||||
toolchain: nightly
|
|
||||||
override: true
|
|
||||||
profile: minimal
|
|
||||||
- uses: actions-rs/cargo@v1
|
|
||||||
with:
|
|
||||||
command: doc
|
|
||||||
args: --all-features
|
|
||||||
|
|
||||||
clippy:
|
clippy:
|
||||||
name: Clippy
|
name: Clippy
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v2
|
- uses: actions/checkout@v4
|
||||||
- uses: actions-rs/toolchain@v1
|
- uses: dtolnay/rust-toolchain@stable
|
||||||
with:
|
- run: cargo clippy -- -D warnings
|
||||||
profile: minimal
|
|
||||||
toolchain: stable
|
|
||||||
- run: rustup component add clippy
|
|
||||||
- uses: actions-rs/cargo@v1
|
|
||||||
with:
|
|
||||||
command: clippy
|
|
||||||
args: -- -D warnings
|
|
||||||
|
|
||||||
ci:
|
|
||||||
if: ${{ success() }}
|
|
||||||
# all new jobs must be added to this list
|
|
||||||
needs: [check, fmt, clippy]
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
steps:
|
|
||||||
- name: CI succeeded
|
|
||||||
run: exit 0
|
|
||||||
|
238
CHANGELOG.md
238
CHANGELOG.md
@@ -8,6 +8,236 @@ and this project adheres to [Semantic Versioning](http://semver.org/).
|
|||||||
|
|
||||||
# [unreleased]
|
# [unreleased]
|
||||||
|
|
||||||
|
# [v0.16.0] 2025-09-24
|
||||||
|
|
||||||
|
- Bump Rust MSRV to v1.83
|
||||||
|
|
||||||
|
## Changed
|
||||||
|
|
||||||
|
- `PusTcCreator` has its own `service`, `subservice` and `apid` methods and does not require trait
|
||||||
|
imports anymore.
|
||||||
|
- CFDP NAK PDU `SegmentRequestIter` is not generic over the file size anymore. Instead, the
|
||||||
|
iterator returns pairs of `u64` for both large and normal file size.
|
||||||
|
- `PusVersion::VersionNotSupported` contains raw version number instead of `PusVersion` enum now
|
||||||
|
to make it more flexible.
|
||||||
|
- `pus_version` API now returns a `Result<PusVersion, u8>` instead of a `PusVersion` to allow
|
||||||
|
modelling invalid version numbers properly.
|
||||||
|
- Renamed `CcsdsPacket::total_len` to `CcsdsPacket::packet_len`
|
||||||
|
- Renamed `SequenceCountProvider` to `SequenceCounter`
|
||||||
|
- Renamed `SeqCountProviderSimple` to `SequenceCounterSimple`
|
||||||
|
- Renamed `CcsdsSimpleSeqCountProvider` to `SequenceCounterCcsdsSimple`
|
||||||
|
- Renamed `SeqCountProviderSync` to `SequenceCounterSync`
|
||||||
|
- Renamed `PusPacket::opt_crc16` to `PusPacket::checksum`
|
||||||
|
- Renamed `PacketSequenceCtrl` to `PacketSequenceControl`
|
||||||
|
- ECSS checksum generation is now optional as specified in the standard. Added `has_checksum`
|
||||||
|
parameters for ECSS TM/TC creators and readers to reflect this.
|
||||||
|
- APID is represented by `arbitrary-int::u11` while the sequence count is represented by
|
||||||
|
`arbitrary-int::u14`. A lot of corresponding checks were removed because the type now ensure
|
||||||
|
value validity.
|
||||||
|
- ACK field changed from `u8` to `AckFlags` structure.
|
||||||
|
- PUS version raw representation is `u4` now.
|
||||||
|
- SC time reference status representation is `u4` now.
|
||||||
|
- Renamed `ptype` to `packet_type`
|
||||||
|
- Renamed `PduHeader::new_no_file_data` to `PduHeader::new_for_file_directive`
|
||||||
|
- Renamd `FinishedPduCreator::new_generic` to `new` and `new_default` to `new_no_error`
|
||||||
|
|
||||||
|
## Removed
|
||||||
|
|
||||||
|
- `PusVersion::Invalid`, which will be modelled with `Result<PusVersion, u8>` now.
|
||||||
|
|
||||||
|
## Added
|
||||||
|
|
||||||
|
- `cfdp::pdu::ack::InvalidAckedDirectiveCodeError` which is returned by the `AckPdu` constructor.
|
||||||
|
- `cfdp::pdu::nak::NakPduCreatorWithReservedSegReqsBuf` constructor which exposes the segment
|
||||||
|
request buffer mutably to avoid the need for a separate segment request buffer.
|
||||||
|
- `SpHeader::packet_len` direct method.
|
||||||
|
- `AckFlags` which is implemented with `bitbybit::bitfield`
|
||||||
|
- `ApidOutOfRangeError` and `SequenceCountOutOfRangeError`
|
||||||
|
- Added PUS A legacy support for telecommands inside the `ecss.tc_pus_a` module
|
||||||
|
- Added `SequenceCounter::increment_mut` and `SequenceCounter::get_and_increment_mut`
|
||||||
|
- Implemented `SequenceCounter` for `Atomic` unsigned types and references of them
|
||||||
|
- `PusPacket::has_checksum` and `WritablePusPacket::has_checksum`
|
||||||
|
- PUS TC builder API, either via `PusTcBuilder::new`, or `PusTcCreator::builder`
|
||||||
|
|
||||||
|
# [v0.15.0] 2025-07-18
|
||||||
|
|
||||||
|
## 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
|
||||||
|
|
||||||
|
- Moved CRC constants/implementations to dedicated `crc` module.
|
||||||
|
- `crc::CRC_CCITT_FALSE_NO_TABLE` and `crc::CRC_CCITT_FALSE_BIG_TABLE` variants.
|
||||||
|
- Renamed `PusPacket::crc16` to `PusPacket::opt_crc16`.
|
||||||
|
|
||||||
|
## Added
|
||||||
|
|
||||||
|
- `WritablePusPacket::write_to_bytes_crc_no_table` and `WritablePusPacket::write_to_bytes_no_crc`
|
||||||
|
variants.
|
||||||
|
- `PusTmReader::new_crc_no_table` and `PusTcReader::new_crc_no_table` variants.
|
||||||
|
- `crc16` methods for PUS TM and PUS TC reader.
|
||||||
|
- PUS TM and PUS TC reader now return the reader instance directly instead of a tuple of the reader
|
||||||
|
and the read size. The instance `total_len` method can be used to retrieve the read lenght.
|
||||||
|
|
||||||
|
# [v0.13.1] 2025-03-21
|
||||||
|
|
||||||
|
- Bugfix due to operator precendence for `PusTcSecondaryHeader::pus_version`,
|
||||||
|
`PusTcSecondaryHeaderWithoutTimestamp::pus_version`, `CdsTime::from_bytes_with_u16_days` and
|
||||||
|
`CdsTime::from_bytes_with_u24_days`
|
||||||
|
|
||||||
|
# [v0.13.0] 2024-11-08
|
||||||
|
|
||||||
|
- Bumped MSRV to 1.81.0
|
||||||
|
- Bump `zerocopy` to v0.8.0
|
||||||
|
- Bump `thiserror` to v2.0.0
|
||||||
|
|
||||||
|
## Changed
|
||||||
|
|
||||||
|
- Migrated all Error implementations to thiserror, improved some naming and error handling in
|
||||||
|
general
|
||||||
|
|
||||||
|
# [v0.12.0] 2024-09-10
|
||||||
|
|
||||||
|
- Bumped MSRV to 1.70.0
|
||||||
|
|
||||||
|
## Added
|
||||||
|
|
||||||
|
- Added new `cfdp::tlv::TlvOwned` type which erases the lifetime and is clonable.
|
||||||
|
- Dedicated `cfdp::tlv::TlvLvDataTooLarge` error struct for APIs where this is the only possible
|
||||||
|
API error.
|
||||||
|
- Added File Data PDU API which expects the expected file data size and then exposes the unwritten
|
||||||
|
file data field as a mutable slice. This allows to read data from the virtual file system
|
||||||
|
API to the file data buffer without an intermediate buffer.
|
||||||
|
- Generic `EofPdu::new` constructor.
|
||||||
|
- Added generic sequence counter module.
|
||||||
|
- Added `MsgToUserTlv::to_tlv` converter which reduced the type and converts
|
||||||
|
it to a generic `Tlv`.
|
||||||
|
- Implemented `From<MsgToUserTlv> for Tlv` converter trait.
|
||||||
|
- Added CFDP maximum file segment length calculator method `calculate_max_file_seg_len_for_max_packet_len_and_pdu_header`
|
||||||
|
|
||||||
|
## Added and Changed
|
||||||
|
|
||||||
|
- Added new `ReadableTlv` to avoid some boilerplate code and have a common abstraction implemented
|
||||||
|
for both `Tlv` and `TlvOwned` to read the raw TLV data field and its length.
|
||||||
|
- Replaced `cfdp::tlv::TlvLvError` by `cfdp::tlv::TlvLvDataTooLarge` where applicable.
|
||||||
|
|
||||||
|
## Fixed
|
||||||
|
|
||||||
|
- Fixed an error in the EOF writer which wrote the fault location to the wrong buffer position.
|
||||||
|
- cfdp `ConditionCode::CheckLimitReached` previous had the wrong numerical value of `0b1001` (9)
|
||||||
|
and now has the correct value of `0b1010` (10).
|
||||||
|
|
||||||
|
## Changed
|
||||||
|
|
||||||
|
- Minor documentation build updates.
|
||||||
|
- Increased delegate version range to v0.13
|
||||||
|
|
||||||
|
# [v0.11.2] 2024-05-19
|
||||||
|
|
||||||
|
- Bumped MSRV to 1.68.2
|
||||||
|
|
||||||
|
## Fixed
|
||||||
|
|
||||||
|
- Removed `defmt::Format` impl for `MetadataPduCreator` which seems to be problematic.
|
||||||
|
|
||||||
|
# [v0.11.1] 2024-04-22
|
||||||
|
|
||||||
|
## Fixed
|
||||||
|
|
||||||
|
- The default data length for for `SpHeader` constructors where the data field length is not
|
||||||
|
specified is now 0.
|
||||||
|
- The `SpHeader::new_from_fields` is public now.
|
||||||
|
|
||||||
|
## Added
|
||||||
|
|
||||||
|
- `SpHeader::to_vec` method.
|
||||||
|
|
||||||
|
# [v0.11.0] 2024-04-16
|
||||||
|
|
||||||
|
## Changed
|
||||||
|
|
||||||
|
- Moved `CCSDS_HEADER_LEN` constant to the crate root.
|
||||||
|
|
||||||
|
## Added
|
||||||
|
|
||||||
|
- Added `SpacePacketHeader` type alias for `SpHeader` type.
|
||||||
|
|
||||||
|
# [v0.11.0-rc.2] 2024-04-04
|
||||||
|
|
||||||
|
## Changed
|
||||||
|
|
||||||
|
- Renamed `PacketId` and `PacketSequenceCtrl` `new` method to `new_checked` and former
|
||||||
|
`new_const` method to `new`.
|
||||||
|
- Renamed `tc`, `tm`, `tc_unseg` and `tm_unseg` variants for `PacketId` and `SpHeader`
|
||||||
|
to `new_for_tc_checked`, `new_for_tm_checked`, `new_for_unseg_tc_checked` and
|
||||||
|
`new_for_unseg_tm_checked`.
|
||||||
|
- `PusTmCreator` and `PusTcCreator` now expect a regular instance of `SpHeader` instead of
|
||||||
|
a mutable reference.
|
||||||
|
|
||||||
|
## Added
|
||||||
|
|
||||||
|
- `SpHeader::new_from_apid` and `SpHeader::new_from_apid_checked` constructor.
|
||||||
|
- `#[inline]` attribute for a lot of small functions.
|
||||||
|
|
||||||
|
# [v0.11.0-rc.1] 2024-04-03
|
||||||
|
|
||||||
|
Major API changes for the time API. If you are using the time API, it is strongly recommended
|
||||||
|
to check all the API changes in the **Changed** chapter.
|
||||||
|
|
||||||
|
## Fixed
|
||||||
|
|
||||||
|
- CUC timestamp was fixed to include leap second corrections because it is based on the TAI
|
||||||
|
time reference. The default CUC time object do not implement `CcsdsTimeProvider` anymore
|
||||||
|
because the trait methods require cached leap second information. This task is now performed
|
||||||
|
by the `cuc::CucTimeWithLeapSecs` which implements the trait.
|
||||||
|
|
||||||
|
## Added
|
||||||
|
|
||||||
|
- `From<$EcssEnum$TY> from $TY` for the ECSS enum type definitions.
|
||||||
|
- Added basic support conversions to the `time` library. Introduce new `chrono` and `timelib`
|
||||||
|
feature gate.
|
||||||
|
- Added `CcsdsTimeProvider::timelib_date_time`.
|
||||||
|
- Optional support for `defmt` by adding optional `defmt::Format` derives for common types.
|
||||||
|
|
||||||
|
## Changed
|
||||||
|
|
||||||
|
- `PusTcCreator::new_simple` now expects a valid slice for the source data instead of an optional
|
||||||
|
slice. For telecommands without application data, `&[]` can be passed.
|
||||||
|
- `PusTmSecondaryHeader` constructors now expects a valid slice for the time stamp instead of an
|
||||||
|
optional slice.
|
||||||
|
- Renamed `CcsdsTimeProvider::date_time` to `CcsdsTimeProvider::chrono_date_time`
|
||||||
|
- Renamed `CcsdsTimeCodes` to `CcsdsTimeCode`
|
||||||
|
- Renamed `cds::TimeProvider` to `cds::CdsTime`
|
||||||
|
- Renamed `cuc::TimeProviderCcsdsEpoch` to `cuc::CucTime`
|
||||||
|
- `UnixTimestamp` renamed to `UnixTime`
|
||||||
|
- `UnixTime` seconds are now private and can be retrieved using the `secs` member method.
|
||||||
|
- `UnixTime::new` renamed to `UnixTime::new_checked`.
|
||||||
|
- `UnixTime::secs` renamed to `UnixTime::as_secs`.
|
||||||
|
- `UnixTime` now has a nanosecond subsecond precision. The `new` constructor now expects
|
||||||
|
nanoseconds as the second argument.
|
||||||
|
- Added new `UnixTime::new_subsec_millis` and `UnixTime::new_subsec_millis_checked` API
|
||||||
|
to still allow creating a timestamp with only millisecond subsecond resolution.
|
||||||
|
- `CcsdsTimeProvider` now has a new `subsec_nanos` method in addition to a default
|
||||||
|
implementation for the `subsec_millis` method.
|
||||||
|
- `CcsdsTimeProvider::date_time` renamed to `CcsdsTimeProvider::chrono_date_time`.
|
||||||
|
- Added `UnixTime::MIN`, `UnixTime::MAX` and `UnixTime::EPOCH`.
|
||||||
|
- Added `UnixTime::timelib_date_time`.
|
||||||
|
- Error handling for ECSS and time module is more granular now, with a new
|
||||||
|
`DateBeforeCcsdsEpochError` error and a `DateBeforeCcsdsEpoch` enum variant for both
|
||||||
|
`CdsError` and `CucError`.
|
||||||
|
- `PusTmCreator` now has two lifetimes: One for the raw source data buffer and one for the
|
||||||
|
raw timestamp.
|
||||||
|
- Time API `from_now*` API renamed to `now*`.
|
||||||
|
|
||||||
|
## Removed
|
||||||
|
|
||||||
|
- Legacy `PusTm` and `PusTc` objects.
|
||||||
|
|
||||||
# [v0.11.0-rc.0] 2024-03-04
|
# [v0.11.0-rc.0] 2024-03-04
|
||||||
|
|
||||||
## Added
|
## Added
|
||||||
@@ -413,3 +643,11 @@ The timestamp of `PusTm` is now optional. See Added and Changed section for deta
|
|||||||
|
|
||||||
Initial release with CCSDS Space Packet Primary Header implementation and basic PUS TC and TM
|
Initial release with CCSDS Space Packet Primary Header implementation and basic PUS TC and TM
|
||||||
implementations.
|
implementations.
|
||||||
|
|
||||||
|
[unreleased]: https://egit.irs.uni-stuttgart.de/rust/spacepackets/compare/v0.16.0...HEAD
|
||||||
|
[v0.16.0]: https://egit.irs.uni-stuttgart.de/rust/spacepackets/compare/v0.15.0...v0.16.0
|
||||||
|
[v0.15.0]: https://egit.irs.uni-stuttgart.de/rust/spacepackets/compare/v0.14.0...v0.15.0
|
||||||
|
[v0.14.0]: https://egit.irs.uni-stuttgart.de/rust/spacepackets/compare/v0.13.1...v0.14.0
|
||||||
|
[v0.13.1]: https://egit.irs.uni-stuttgart.de/rust/spacepackets/compare/v0.13.0...v0.13.1
|
||||||
|
[v0.13.0]: https://egit.irs.uni-stuttgart.de/rust/spacepackets/compare/v0.12.0...v0.13.0
|
||||||
|
[v0.12.0]: https://egit.irs.uni-stuttgart.de/rust/spacepackets/compare/v0.11.2...v0.12.0
|
||||||
|
60
Cargo.toml
60
Cargo.toml
@@ -1,8 +1,8 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "spacepackets"
|
name = "spacepackets"
|
||||||
version = "0.11.0-rc.0"
|
version = "0.16.0"
|
||||||
edition = "2021"
|
edition = "2021"
|
||||||
rust-version = "1.61"
|
rust-version = "1.83"
|
||||||
authors = ["Robin Mueller <muellerr@irs.uni-stuttgart.de>"]
|
authors = ["Robin Mueller <muellerr@irs.uni-stuttgart.de>"]
|
||||||
description = "Generic implementations for various CCSDS and ECSS packet standards"
|
description = "Generic implementations for various CCSDS and ECSS packet standards"
|
||||||
homepage = "https://egit.irs.uni-stuttgart.de/rust/spacepackets"
|
homepage = "https://egit.irs.uni-stuttgart.de/rust/spacepackets"
|
||||||
@@ -14,43 +14,33 @@ categories = ["aerospace", "aerospace::space-protocols", "no-std", "hardware-sup
|
|||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
crc = "3"
|
crc = "3"
|
||||||
delegate = ">=0.8, <0.11"
|
delegate = ">=0.8, <=0.13"
|
||||||
|
paste = "1"
|
||||||
|
zerocopy = { version = "0.8", features = ["derive"] }
|
||||||
|
thiserror = { version = "2", default-features = false }
|
||||||
|
num_enum = { version = ">0.5, <=0.7", default-features = false }
|
||||||
|
num-traits = { version = "0.2", default-features = false }
|
||||||
|
serde = { version = "1", optional = true, default-features = false, features = ["derive"] }
|
||||||
|
arbitrary-int = { version = "2" }
|
||||||
|
portable-atomic = "1"
|
||||||
|
bitbybit = "1.4"
|
||||||
|
|
||||||
[dependencies.zerocopy]
|
time = { version = "0.3", default-features = false, optional = true }
|
||||||
version = "0.7"
|
chrono = { version = "0.4", default-features = false, optional = true }
|
||||||
features = ["derive"]
|
defmt = { version = "1", default-features = false, optional = true }
|
||||||
|
|
||||||
[dependencies.thiserror]
|
|
||||||
version = "1"
|
|
||||||
optional = true
|
|
||||||
|
|
||||||
[dependencies.num_enum]
|
|
||||||
version = ">0.5, <=0.7"
|
|
||||||
default-features = false
|
|
||||||
|
|
||||||
[dependencies.serde]
|
|
||||||
version = "1"
|
|
||||||
optional = true
|
|
||||||
default-features = false
|
|
||||||
features = ["derive"]
|
|
||||||
|
|
||||||
[dependencies.chrono]
|
|
||||||
version = "0.4"
|
|
||||||
default-features = false
|
|
||||||
|
|
||||||
[dependencies.num-traits]
|
|
||||||
version = "0.2"
|
|
||||||
default-features = false
|
|
||||||
|
|
||||||
[dev-dependencies.postcard]
|
|
||||||
version = "1"
|
|
||||||
|
|
||||||
[features]
|
[features]
|
||||||
default = ["std"]
|
default = ["std"]
|
||||||
std = ["chrono/std", "chrono/clock", "alloc", "thiserror"]
|
std = ["alloc", "chrono/std", "chrono/clock", "thiserror/std"]
|
||||||
serde = ["dep:serde", "chrono/serde"]
|
defmt = ["dep:defmt", "arbitrary-int/defmt"]
|
||||||
alloc = ["postcard/alloc", "chrono/alloc"]
|
serde = ["dep:serde", "chrono?/serde", "arbitrary-int/serde"]
|
||||||
|
alloc = ["chrono?/alloc", "defmt?/alloc", "serde?/alloc"]
|
||||||
|
timelib = ["dep:time"]
|
||||||
|
|
||||||
|
[dev-dependencies]
|
||||||
|
postcard = { version = "1", features = ["alloc"] }
|
||||||
|
chrono = "0.4"
|
||||||
|
|
||||||
[package.metadata.docs.rs]
|
[package.metadata.docs.rs]
|
||||||
all-features = true
|
all-features = true
|
||||||
rustdoc-args = ["--cfg", "doc_cfg", "--generate-link-to-definition"]
|
rustdoc-args = ["--generate-link-to-definition"]
|
||||||
|
1
FUNDING.yml
Normal file
1
FUNDING.yml
Normal file
@@ -0,0 +1 @@
|
|||||||
|
github: robamu
|
30
README.md
30
README.md
@@ -1,7 +1,7 @@
|
|||||||
[](https://crates.io/crates/spacepackets)
|
[](https://crates.io/crates/spacepackets)
|
||||||
[](https://docs.rs/spacepackets)
|
[](https://docs.rs/spacepackets)
|
||||||
[](https://github.com/us-irs/spacepackets-rs/actions/workflows/ci.yml)
|
[](https://github.com/us-irs/spacepackets-rs/actions/workflows/ci.yml)
|
||||||
[](https://absatsw.irs.uni-stuttgart.de/projects/spacepackets/coverage-rs/latest/index.html)
|
[](https://matrix.to/#/#sat-rs:matrix.org)
|
||||||
|
|
||||||
ECSS and CCSDS Spacepackets
|
ECSS and CCSDS Spacepackets
|
||||||
======
|
======
|
||||||
@@ -29,10 +29,6 @@ Currently, this includes the following components:
|
|||||||
|
|
||||||
`spacepackets` supports various runtime environments and is also suitable for `no_std` environments.
|
`spacepackets` supports various runtime environments and is also suitable for `no_std` environments.
|
||||||
|
|
||||||
It also offers optional support for [`serde`](https://serde.rs/). This allows serializing and
|
|
||||||
deserializing them with an appropriate `serde` provider like
|
|
||||||
[`postcard`](https://github.com/jamesmunns/postcard).
|
|
||||||
|
|
||||||
## Default features
|
## Default features
|
||||||
|
|
||||||
- [`std`](https://doc.rust-lang.org/std/): Enables functionality relying on the standard library.
|
- [`std`](https://doc.rust-lang.org/std/): Enables functionality relying on the standard library.
|
||||||
@@ -43,6 +39,10 @@ deserializing them with an appropriate `serde` provider like
|
|||||||
## Optional Features
|
## Optional Features
|
||||||
|
|
||||||
- [`serde`](https://serde.rs/): Adds `serde` support for most types by adding `Serialize` and `Deserialize` `derive`s
|
- [`serde`](https://serde.rs/): Adds `serde` support for most types by adding `Serialize` and `Deserialize` `derive`s
|
||||||
|
- [`chrono`](https://crates.io/crates/chrono): Add basic support for the `chrono` time library.
|
||||||
|
- [`timelib`](https://crates.io/crates/time): Add basic support for the `time` time library.
|
||||||
|
- [`defmt`](https://defmt.ferrous-systems.com/): Add support for the `defmt` by adding the
|
||||||
|
[`defmt::Format`](https://defmt.ferrous-systems.com/format) derive on many types.
|
||||||
|
|
||||||
# Examples
|
# Examples
|
||||||
|
|
||||||
@@ -51,13 +51,21 @@ usage examples.
|
|||||||
|
|
||||||
# Coverage
|
# Coverage
|
||||||
|
|
||||||
Coverage was generated using [`grcov`](https://github.com/mozilla/grcov). If you have not done so
|
Coverage can be generated using [`llvm-cov`](https://github.com/taiki-e/cargo-llvm-cov). If you have not done so
|
||||||
already, install the `llvm-tools-preview`:
|
already, install the tool:
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
rustup component add llvm-tools-preview
|
cargo +stable install cargo-llvm-cov --locked
|
||||||
cargo install grcov --locked
|
|
||||||
```
|
```
|
||||||
|
|
||||||
After that, you can simply run `coverage.py` to test the project with coverage. You can optionally
|
After this, you can run `cargo llvm-cov nextest` to run all the tests and display coverage.
|
||||||
supply the `--open` flag to open the coverage report in your webbrowser.
|
|
||||||
|
# Miri
|
||||||
|
|
||||||
|
You can run the [`miri`](https://github.com/rust-lang/miri) tool on this library to check for
|
||||||
|
undefined behaviour (UB). This library does not use use any `unsafe` code blocks, but `miri` could
|
||||||
|
still catch UB from used libraries.
|
||||||
|
|
||||||
|
```sh
|
||||||
|
cargo +nightly miri nextest run --all-features
|
||||||
|
```
|
||||||
|
@@ -15,7 +15,10 @@ RUN rustup install nightly && \
|
|||||||
rustup target add thumbv7em-none-eabihf armv7-unknown-linux-gnueabihf && \
|
rustup target add thumbv7em-none-eabihf armv7-unknown-linux-gnueabihf && \
|
||||||
rustup component add rustfmt clippy llvm-tools-preview
|
rustup component add rustfmt clippy llvm-tools-preview
|
||||||
|
|
||||||
|
# Get grcov
|
||||||
RUN curl -sSL https://github.com/mozilla/grcov/releases/download/v0.8.19/grcov-x86_64-unknown-linux-gnu.tar.bz2 | tar -xj --directory /usr/local/bin
|
RUN curl -sSL https://github.com/mozilla/grcov/releases/download/v0.8.19/grcov-x86_64-unknown-linux-gnu.tar.bz2 | tar -xj --directory /usr/local/bin
|
||||||
|
# Get nextest
|
||||||
|
RUN curl -LsSf https://get.nexte.st/latest/linux | tar zxf - -C ${CARGO_HOME:-~/.cargo}/bin
|
||||||
|
|
||||||
# SSH stuff to allow deployment to doc server
|
# SSH stuff to allow deployment to doc server
|
||||||
RUN adduser --uid 114 jenkins
|
RUN adduser --uid 114 jenkins
|
||||||
|
7
automation/Jenkinsfile
vendored
7
automation/Jenkinsfile
vendored
@@ -21,7 +21,9 @@ pipeline {
|
|||||||
}
|
}
|
||||||
stage('Docs') {
|
stage('Docs') {
|
||||||
steps {
|
steps {
|
||||||
sh 'cargo +nightly doc --all-features'
|
sh """
|
||||||
|
RUSTDOCFLAGS="--cfg docsrs --generate-link-to-definition -Z unstable-options" cargo +nightly doc --all-features
|
||||||
|
"""
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
stage('Rustfmt') {
|
stage('Rustfmt') {
|
||||||
@@ -31,7 +33,8 @@ pipeline {
|
|||||||
}
|
}
|
||||||
stage('Test') {
|
stage('Test') {
|
||||||
steps {
|
steps {
|
||||||
sh 'cargo test --all-features'
|
sh 'cargo nextest r --all-features'
|
||||||
|
sh 'cargo test --doc'
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
stage('Check with all features') {
|
stage('Check with all features') {
|
||||||
|
54
coverage.py
54
coverage.py
@@ -1,54 +0,0 @@
|
|||||||
#!/usr/bin/env python3
|
|
||||||
import os
|
|
||||||
import logging
|
|
||||||
import argparse
|
|
||||||
import webbrowser
|
|
||||||
|
|
||||||
|
|
||||||
_LOGGER = logging.getLogger()
|
|
||||||
|
|
||||||
|
|
||||||
def generate_cov_report(open_report: bool, format: str):
|
|
||||||
logging.basicConfig(level=logging.INFO)
|
|
||||||
os.environ["RUSTFLAGS"] = "-Cinstrument-coverage"
|
|
||||||
os.environ["LLVM_PROFILE_FILE"] = "target/coverage/%p-%m.profraw"
|
|
||||||
_LOGGER.info("Executing tests with coverage")
|
|
||||||
os.system("cargo test --all-features")
|
|
||||||
|
|
||||||
out_path = "./target/debug/coverage"
|
|
||||||
if format == "lcov":
|
|
||||||
out_path = "./target/debug/lcov.info"
|
|
||||||
os.system(
|
|
||||||
f"grcov . -s . --binary-path ./target/debug/ -t {format} --branch --ignore-not-existing "
|
|
||||||
f"-o {out_path}"
|
|
||||||
)
|
|
||||||
if format == "lcov":
|
|
||||||
os.system(
|
|
||||||
"genhtml -o ./target/debug/coverage/ --show-details --highlight --ignore-errors source "
|
|
||||||
"--legend ./target/debug/lcov.info"
|
|
||||||
)
|
|
||||||
if open_report:
|
|
||||||
coverage_report_path = os.path.abspath("./target/debug/coverage/index.html")
|
|
||||||
webbrowser.open_new_tab(coverage_report_path)
|
|
||||||
_LOGGER.info("Done")
|
|
||||||
|
|
||||||
|
|
||||||
def main():
|
|
||||||
parser = argparse.ArgumentParser(
|
|
||||||
description="Generate coverage report and optionally open it in a browser"
|
|
||||||
)
|
|
||||||
parser.add_argument(
|
|
||||||
"--open", action="store_true", help="Open the coverage report in a browser"
|
|
||||||
)
|
|
||||||
parser.add_argument(
|
|
||||||
"--format",
|
|
||||||
choices=["html", "lcov"],
|
|
||||||
default="html",
|
|
||||||
help="Choose report format (html or lcov)",
|
|
||||||
)
|
|
||||||
args = parser.parse_args()
|
|
||||||
generate_cov_report(args.open, args.format)
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
|
||||||
main()
|
|
31
justfile
Normal file
31
justfile
Normal file
@@ -0,0 +1,31 @@
|
|||||||
|
all: check build test clippy fmt docs coverage
|
||||||
|
|
||||||
|
clippy:
|
||||||
|
cargo clippy -- -D warnings
|
||||||
|
|
||||||
|
fmt:
|
||||||
|
cargo fmt --all -- --check
|
||||||
|
|
||||||
|
check:
|
||||||
|
cargo check --all-features
|
||||||
|
|
||||||
|
test:
|
||||||
|
cargo nextest r --all-features
|
||||||
|
cargo test --doc
|
||||||
|
|
||||||
|
build:
|
||||||
|
cargo build --all-features
|
||||||
|
|
||||||
|
docs:
|
||||||
|
export RUSTDOCFLAGS="--cfg docsrs --generate-link-to-definition -Z unstable-options"
|
||||||
|
cargo +nightly doc --all-features
|
||||||
|
|
||||||
|
docs-html:
|
||||||
|
export RUSTDOCFLAGS="--cfg docsrs --generate-link-to-definition -Z unstable-options"
|
||||||
|
cargo +nightly doc --all-features --open
|
||||||
|
|
||||||
|
coverage:
|
||||||
|
cargo llvm-cov nextest
|
||||||
|
|
||||||
|
coverage-html:
|
||||||
|
cargo llvm-cov nextest --html --open
|
@@ -4,11 +4,14 @@ Checklist for new releases
|
|||||||
# Pre-Release
|
# Pre-Release
|
||||||
|
|
||||||
1. Make sure any new modules are documented sufficiently enough and check docs with
|
1. Make sure any new modules are documented sufficiently enough and check docs with
|
||||||
`cargo +nightly doc --all-features --config 'rustdocflags=["--cfg", "doc_cfg"]' --open`.
|
`RUSTDOCFLAGS="--cfg docsrs --generate-link-to-definition -Z unstable-options" cargo +nightly doc --all-features --open`
|
||||||
|
or `cargo +nightly doc --all-features --config 'build.rustdocflags=["--cfg", "docsrs" --generate-link-to-definition"]' --open`
|
||||||
|
(was problematic on more recent nightly versions).
|
||||||
2. Bump version specifier in `Cargo.toml`.
|
2. Bump version specifier in `Cargo.toml`.
|
||||||
3. Update `CHANGELOG.md`: Convert `unreleased` section into version section with date and add new
|
3. Update `CHANGELOG.md`: Convert `unreleased` section into version section with date and add new
|
||||||
`unreleased` section.
|
`unreleased` section.
|
||||||
4. Run `cargo test --all-features`.
|
4. Run `cargo test --all-features` or `cargo nextest r --all-features` together with
|
||||||
|
`cargo test --doc`.
|
||||||
5. Run `cargo fmt` and `cargo clippy`. Check `cargo msrv` against MSRV in `Cargo.toml`.
|
5. Run `cargo fmt` and `cargo clippy`. Check `cargo msrv` against MSRV in `Cargo.toml`.
|
||||||
6. Wait for CI/CD results for EGit and Github. These also check cross-compilation for bare-metal
|
6. Wait for CI/CD results for EGit and Github. These also check cross-compilation for bare-metal
|
||||||
targets.
|
targets.
|
||||||
|
@@ -1,5 +1,4 @@
|
|||||||
//! Generic CFDP length-value (LV) abstraction as specified in CFDP 5.1.8.
|
//! Generic CFDP length-value (LV) abstraction as specified in CFDP 5.1.8.
|
||||||
use crate::cfdp::TlvLvError;
|
|
||||||
use crate::ByteConversionError;
|
use crate::ByteConversionError;
|
||||||
use core::str::Utf8Error;
|
use core::str::Utf8Error;
|
||||||
#[cfg(feature = "serde")]
|
#[cfg(feature = "serde")]
|
||||||
@@ -7,6 +6,8 @@ use serde::{Deserialize, Serialize};
|
|||||||
#[cfg(feature = "std")]
|
#[cfg(feature = "std")]
|
||||||
use std::string::String;
|
use std::string::String;
|
||||||
|
|
||||||
|
use super::TlvLvDataTooLargeError;
|
||||||
|
|
||||||
pub const MIN_LV_LEN: usize = 1;
|
pub const MIN_LV_LEN: usize = 1;
|
||||||
|
|
||||||
/// Generic CFDP length-value (LV) abstraction as specified in CFDP 5.1.8.
|
/// Generic CFDP length-value (LV) abstraction as specified in CFDP 5.1.8.
|
||||||
@@ -20,6 +21,7 @@ pub const MIN_LV_LEN: usize = 1;
|
|||||||
/// this will be the lifetime of that data reference.
|
/// this will be the lifetime of that data reference.
|
||||||
#[derive(Debug, Copy, Clone, Eq)]
|
#[derive(Debug, Copy, Clone, Eq)]
|
||||||
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
||||||
|
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
|
||||||
pub struct Lv<'data> {
|
pub struct Lv<'data> {
|
||||||
data: &'data [u8],
|
data: &'data [u8],
|
||||||
// If the LV was generated from a raw bytestream, this will contain the start of the
|
// If the LV was generated from a raw bytestream, this will contain the start of the
|
||||||
@@ -61,9 +63,12 @@ pub(crate) fn generic_len_check_deserialization(
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl<'data> Lv<'data> {
|
impl<'data> Lv<'data> {
|
||||||
pub fn new(data: &[u8]) -> Result<Lv, TlvLvError> {
|
pub const MIN_LEN: usize = MIN_LV_LEN;
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
pub fn new(data: &[u8]) -> Result<Lv<'_>, TlvLvDataTooLargeError> {
|
||||||
if data.len() > u8::MAX as usize {
|
if data.len() > u8::MAX as usize {
|
||||||
return Err(TlvLvError::DataTooLarge(data.len()));
|
return Err(TlvLvDataTooLargeError(data.len()));
|
||||||
}
|
}
|
||||||
Ok(Lv {
|
Ok(Lv {
|
||||||
data,
|
data,
|
||||||
@@ -72,6 +77,7 @@ impl<'data> Lv<'data> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Creates a LV with an empty value field.
|
/// Creates a LV with an empty value field.
|
||||||
|
#[inline]
|
||||||
pub fn new_empty() -> Lv<'data> {
|
pub fn new_empty() -> Lv<'data> {
|
||||||
Lv {
|
Lv {
|
||||||
data: &[],
|
data: &[],
|
||||||
@@ -81,45 +87,52 @@ impl<'data> Lv<'data> {
|
|||||||
|
|
||||||
/// Helper function to build a string LV. This is especially useful for the file or directory
|
/// Helper function to build a string LV. This is especially useful for the file or directory
|
||||||
/// path LVs
|
/// path LVs
|
||||||
pub fn new_from_str(str_slice: &str) -> Result<Lv, TlvLvError> {
|
#[inline]
|
||||||
|
pub fn new_from_str(str_slice: &str) -> Result<Lv<'_>, TlvLvDataTooLargeError> {
|
||||||
Self::new(str_slice.as_bytes())
|
Self::new(str_slice.as_bytes())
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Helper function to build a string LV. This is especially useful for the file or directory
|
/// Helper function to build a string LV. This is especially useful for the file or directory
|
||||||
/// path LVs
|
/// path LVs
|
||||||
#[cfg(feature = "std")]
|
#[cfg(feature = "std")]
|
||||||
#[cfg_attr(doc_cfg, doc(cfg(feature = "std")))]
|
#[inline]
|
||||||
pub fn new_from_string(string: &'data String) -> Result<Lv<'data>, TlvLvError> {
|
pub fn new_from_string(string: &'data String) -> Result<Lv<'data>, TlvLvDataTooLargeError> {
|
||||||
Self::new(string.as_bytes())
|
Self::new(string.as_bytes())
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Returns the length of the value part, not including the length byte.
|
/// Returns the length of the value part, not including the length byte.
|
||||||
|
#[inline]
|
||||||
pub fn len_value(&self) -> usize {
|
pub fn len_value(&self) -> usize {
|
||||||
self.data.len()
|
self.data.len()
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Returns the full raw length, including the length byte.
|
/// Returns the full raw length, including the length byte.
|
||||||
|
#[inline]
|
||||||
pub fn len_full(&self) -> usize {
|
pub fn len_full(&self) -> usize {
|
||||||
self.len_value() + 1
|
self.len_value() + 1
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Checks whether the value field is empty.
|
/// Checks whether the value field is empty.
|
||||||
|
#[inline]
|
||||||
pub fn is_empty(&self) -> bool {
|
pub fn is_empty(&self) -> bool {
|
||||||
self.data.len() == 0
|
self.data.len() == 0
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
pub fn value(&self) -> &[u8] {
|
pub fn value(&self) -> &[u8] {
|
||||||
self.data
|
self.data
|
||||||
}
|
}
|
||||||
|
|
||||||
/// If the LV was generated from a raw bytestream using [Self::from_bytes], the raw start
|
/// 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.
|
/// of the LV can be retrieved with this method.
|
||||||
|
#[inline]
|
||||||
pub fn raw_data(&self) -> Option<&[u8]> {
|
pub fn raw_data(&self) -> Option<&[u8]> {
|
||||||
self.raw_data
|
self.raw_data
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Convenience function to extract the value as a [str]. This is useful if the LV is
|
/// 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.
|
/// known to contain a [str], for example being a file name.
|
||||||
|
#[inline]
|
||||||
pub fn value_as_str(&self) -> Option<Result<&'data str, Utf8Error>> {
|
pub fn value_as_str(&self) -> Option<Result<&'data str, Utf8Error>> {
|
||||||
if self.is_empty() {
|
if self.is_empty() {
|
||||||
return None;
|
return None;
|
||||||
@@ -135,6 +148,7 @@ impl<'data> Lv<'data> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Reads a LV from a raw buffer.
|
/// Reads a LV from a raw buffer.
|
||||||
|
#[inline]
|
||||||
pub fn from_bytes(buf: &'data [u8]) -> Result<Lv<'data>, ByteConversionError> {
|
pub fn from_bytes(buf: &'data [u8]) -> Result<Lv<'data>, ByteConversionError> {
|
||||||
generic_len_check_deserialization(buf, MIN_LV_LEN)?;
|
generic_len_check_deserialization(buf, MIN_LV_LEN)?;
|
||||||
Self::from_be_bytes_no_len_check(buf)
|
Self::from_be_bytes_no_len_check(buf)
|
||||||
@@ -151,6 +165,7 @@ impl<'data> Lv<'data> {
|
|||||||
MIN_LV_LEN + self.data.len()
|
MIN_LV_LEN + self.data.len()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
pub(crate) fn from_be_bytes_no_len_check(
|
pub(crate) fn from_be_bytes_no_len_check(
|
||||||
buf: &'data [u8],
|
buf: &'data [u8],
|
||||||
) -> Result<Lv<'data>, ByteConversionError> {
|
) -> Result<Lv<'data>, ByteConversionError> {
|
||||||
@@ -165,10 +180,10 @@ impl<'data> Lv<'data> {
|
|||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
pub mod tests {
|
pub mod tests {
|
||||||
use super::*;
|
|
||||||
use alloc::string::ToString;
|
use alloc::string::ToString;
|
||||||
|
|
||||||
use crate::cfdp::TlvLvError;
|
use super::*;
|
||||||
|
|
||||||
use crate::ByteConversionError;
|
use crate::ByteConversionError;
|
||||||
use std::string::String;
|
use std::string::String;
|
||||||
|
|
||||||
@@ -259,15 +274,11 @@ pub mod tests {
|
|||||||
let lv = Lv::new(&data_big);
|
let lv = Lv::new(&data_big);
|
||||||
assert!(lv.is_err());
|
assert!(lv.is_err());
|
||||||
let error = lv.unwrap_err();
|
let error = lv.unwrap_err();
|
||||||
if let TlvLvError::DataTooLarge(size) = error {
|
assert_eq!(error.0, u8::MAX as usize + 1);
|
||||||
assert_eq!(size, u8::MAX as usize + 1);
|
assert_eq!(
|
||||||
assert_eq!(
|
error.to_string(),
|
||||||
error.to_string(),
|
"data with size 256 larger than allowed 255 bytes"
|
||||||
"data with size 256 larger than allowed 255 bytes"
|
);
|
||||||
);
|
|
||||||
} else {
|
|
||||||
panic!("invalid exception {:?}", error)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
|
132
src/cfdp/mod.rs
132
src/cfdp/mod.rs
@@ -1,11 +1,8 @@
|
|||||||
//! Low-level CCSDS File Delivery Protocol (CFDP) support according to [CCSDS 727.0-B-5](https://public.ccsds.org/Pubs/727x0b5.pdf).
|
//! Low-level CCSDS File Delivery Protocol (CFDP) support according to [CCSDS 727.0-B-5](https://public.ccsds.org/Pubs/727x0b5.pdf).
|
||||||
use crate::ByteConversionError;
|
use crate::ByteConversionError;
|
||||||
use core::fmt::{Display, Formatter};
|
|
||||||
use num_enum::{IntoPrimitive, TryFromPrimitive};
|
use num_enum::{IntoPrimitive, TryFromPrimitive};
|
||||||
#[cfg(feature = "serde")]
|
#[cfg(feature = "serde")]
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
#[cfg(feature = "std")]
|
|
||||||
use std::error::Error;
|
|
||||||
|
|
||||||
pub mod lv;
|
pub mod lv;
|
||||||
pub mod pdu;
|
pub mod pdu;
|
||||||
@@ -16,32 +13,40 @@ pub const CFDP_VERSION_2_NAME: &str = "CCSDS 727.0-B-5";
|
|||||||
/// Currently, only this version is supported.
|
/// Currently, only this version is supported.
|
||||||
pub const CFDP_VERSION_2: u8 = 0b001;
|
pub const CFDP_VERSION_2: u8 = 0b001;
|
||||||
|
|
||||||
#[derive(Debug, Copy, Clone, PartialEq, Eq, TryFromPrimitive, IntoPrimitive)]
|
#[derive(Debug, PartialEq, Eq, TryFromPrimitive, IntoPrimitive)]
|
||||||
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
||||||
|
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
|
||||||
|
#[bitbybit::bitenum(u1, exhaustive = true)]
|
||||||
#[repr(u8)]
|
#[repr(u8)]
|
||||||
pub enum PduType {
|
pub enum PduType {
|
||||||
FileDirective = 0,
|
FileDirective = 0,
|
||||||
FileData = 1,
|
FileData = 1,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Copy, Clone, PartialEq, Eq, TryFromPrimitive, IntoPrimitive)]
|
#[derive(Debug, PartialEq, Eq, TryFromPrimitive, IntoPrimitive)]
|
||||||
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
||||||
|
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
|
||||||
|
#[bitbybit::bitenum(u1, exhaustive = true)]
|
||||||
#[repr(u8)]
|
#[repr(u8)]
|
||||||
pub enum Direction {
|
pub enum Direction {
|
||||||
TowardsReceiver = 0,
|
TowardsReceiver = 0,
|
||||||
TowardsSender = 1,
|
TowardsSender = 1,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Copy, Clone, PartialEq, Eq, TryFromPrimitive, IntoPrimitive)]
|
#[derive(Debug, PartialEq, Eq, TryFromPrimitive, IntoPrimitive)]
|
||||||
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
||||||
|
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
|
||||||
|
#[bitbybit::bitenum(u1, exhaustive = true)]
|
||||||
#[repr(u8)]
|
#[repr(u8)]
|
||||||
pub enum TransmissionMode {
|
pub enum TransmissionMode {
|
||||||
Acknowledged = 0,
|
Acknowledged = 0,
|
||||||
Unacknowledged = 1,
|
Unacknowledged = 1,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Copy, Clone, PartialEq, Eq, TryFromPrimitive, IntoPrimitive)]
|
#[derive(Debug, PartialEq, Eq, TryFromPrimitive, IntoPrimitive)]
|
||||||
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
||||||
|
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
|
||||||
|
#[bitbybit::bitenum(u1, exhaustive = true)]
|
||||||
#[repr(u8)]
|
#[repr(u8)]
|
||||||
pub enum CrcFlag {
|
pub enum CrcFlag {
|
||||||
NoCrc = 0,
|
NoCrc = 0,
|
||||||
@@ -67,8 +72,10 @@ impl From<CrcFlag> for bool {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Always 0 and ignored for File Directive PDUs (CCSDS 727.0-B-5 P.75)
|
/// Always 0 and ignored for File Directive PDUs (CCSDS 727.0-B-5 P.75)
|
||||||
#[derive(Debug, Copy, Clone, PartialEq, Eq, TryFromPrimitive, IntoPrimitive)]
|
#[derive(Debug, PartialEq, Eq, TryFromPrimitive, IntoPrimitive)]
|
||||||
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
||||||
|
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
|
||||||
|
#[bitbybit::bitenum(u1, exhaustive = true)]
|
||||||
#[repr(u8)]
|
#[repr(u8)]
|
||||||
pub enum SegmentMetadataFlag {
|
pub enum SegmentMetadataFlag {
|
||||||
NotPresent = 0,
|
NotPresent = 0,
|
||||||
@@ -76,16 +83,20 @@ pub enum SegmentMetadataFlag {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Always 0 and ignored for File Directive PDUs (CCSDS 727.0-B-5 P.75)
|
/// Always 0 and ignored for File Directive PDUs (CCSDS 727.0-B-5 P.75)
|
||||||
#[derive(Debug, Copy, Clone, PartialEq, Eq, TryFromPrimitive, IntoPrimitive)]
|
#[derive(Debug, PartialEq, Eq, TryFromPrimitive, IntoPrimitive)]
|
||||||
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
||||||
|
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
|
||||||
|
#[bitbybit::bitenum(u1, exhaustive = true)]
|
||||||
#[repr(u8)]
|
#[repr(u8)]
|
||||||
pub enum SegmentationControl {
|
pub enum SegmentationControl {
|
||||||
NoRecordBoundaryPreservation = 0,
|
NoRecordBoundaryPreservation = 0,
|
||||||
WithRecordBoundaryPreservation = 1,
|
WithRecordBoundaryPreservation = 1,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Copy, Clone, PartialEq, Eq, TryFromPrimitive, IntoPrimitive)]
|
#[derive(Debug, PartialEq, Eq, TryFromPrimitive, IntoPrimitive)]
|
||||||
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
||||||
|
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
|
||||||
|
#[bitbybit::bitenum(u3, exhaustive = false)]
|
||||||
#[repr(u8)]
|
#[repr(u8)]
|
||||||
pub enum FaultHandlerCode {
|
pub enum FaultHandlerCode {
|
||||||
NoticeOfCancellation = 0b0001,
|
NoticeOfCancellation = 0b0001,
|
||||||
@@ -94,8 +105,10 @@ pub enum FaultHandlerCode {
|
|||||||
AbandonTransaction = 0b0100,
|
AbandonTransaction = 0b0100,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Copy, Clone, PartialEq, Eq, TryFromPrimitive, IntoPrimitive)]
|
#[derive(Debug, PartialEq, Eq, TryFromPrimitive, IntoPrimitive)]
|
||||||
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
||||||
|
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
|
||||||
|
#[bitbybit::bitenum(u4, exhaustive = false)]
|
||||||
#[repr(u8)]
|
#[repr(u8)]
|
||||||
pub enum ConditionCode {
|
pub enum ConditionCode {
|
||||||
/// This is not an error condition for which a faulty handler override can be specified
|
/// This is not an error condition for which a faulty handler override can be specified
|
||||||
@@ -108,7 +121,7 @@ pub enum ConditionCode {
|
|||||||
FileSizeError = 0b0110,
|
FileSizeError = 0b0110,
|
||||||
NakLimitReached = 0b0111,
|
NakLimitReached = 0b0111,
|
||||||
InactivityDetected = 0b1000,
|
InactivityDetected = 0b1000,
|
||||||
CheckLimitReached = 0b1001,
|
CheckLimitReached = 0b1010,
|
||||||
UnsupportedChecksumType = 0b1011,
|
UnsupportedChecksumType = 0b1011,
|
||||||
/// Not an actual fault condition for which fault handler overrides can be specified
|
/// Not an actual fault condition for which fault handler overrides can be specified
|
||||||
SuspendRequestReceived = 0b1110,
|
SuspendRequestReceived = 0b1110,
|
||||||
@@ -116,8 +129,10 @@ pub enum ConditionCode {
|
|||||||
CancelRequestReceived = 0b1111,
|
CancelRequestReceived = 0b1111,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Copy, Clone, PartialEq, Eq, TryFromPrimitive, IntoPrimitive)]
|
#[derive(Debug, PartialEq, Eq, TryFromPrimitive, IntoPrimitive)]
|
||||||
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
||||||
|
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
|
||||||
|
#[bitbybit::bitenum(u1, exhaustive = true)]
|
||||||
#[repr(u8)]
|
#[repr(u8)]
|
||||||
pub enum LargeFileFlag {
|
pub enum LargeFileFlag {
|
||||||
/// 32 bit maximum file size and FSS size
|
/// 32 bit maximum file size and FSS size
|
||||||
@@ -127,8 +142,10 @@ pub enum LargeFileFlag {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Transaction status for the ACK PDU field according to chapter 5.2.4 of the CFDP standard.
|
/// Transaction status for the ACK PDU field according to chapter 5.2.4 of the CFDP standard.
|
||||||
#[derive(Debug, Copy, Clone, PartialEq, Eq, TryFromPrimitive, IntoPrimitive)]
|
#[derive(Debug, PartialEq, Eq, TryFromPrimitive, IntoPrimitive)]
|
||||||
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
||||||
|
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
|
||||||
|
#[bitbybit::bitenum(u2, exhaustive = true)]
|
||||||
#[repr(u8)]
|
#[repr(u8)]
|
||||||
pub enum TransactionStatus {
|
pub enum TransactionStatus {
|
||||||
/// Transaction is not currently active and the CFDP implementation does not retain a
|
/// Transaction is not currently active and the CFDP implementation does not retain a
|
||||||
@@ -146,6 +163,7 @@ pub enum TransactionStatus {
|
|||||||
/// [SANA Checksum Types registry](https://sanaregistry.org/r/checksum_identifiers/)
|
/// [SANA Checksum Types registry](https://sanaregistry.org/r/checksum_identifiers/)
|
||||||
#[derive(Debug, Copy, Clone, PartialEq, Eq, TryFromPrimitive, IntoPrimitive)]
|
#[derive(Debug, Copy, Clone, PartialEq, Eq, TryFromPrimitive, IntoPrimitive)]
|
||||||
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
||||||
|
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
|
||||||
#[repr(u8)]
|
#[repr(u8)]
|
||||||
pub enum ChecksumType {
|
pub enum ChecksumType {
|
||||||
/// Modular legacy checksum
|
/// Modular legacy checksum
|
||||||
@@ -165,75 +183,43 @@ impl Default for ChecksumType {
|
|||||||
|
|
||||||
pub const NULL_CHECKSUM_U32: [u8; 4] = [0; 4];
|
pub const NULL_CHECKSUM_U32: [u8; 4] = [0; 4];
|
||||||
|
|
||||||
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
|
#[derive(Debug, Copy, Clone, PartialEq, Eq, thiserror::Error)]
|
||||||
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
||||||
|
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
|
||||||
|
#[error("data with size {0} larger than allowed {max} bytes", max = u8::MAX)]
|
||||||
|
pub struct TlvLvDataTooLargeError(pub usize);
|
||||||
|
|
||||||
|
/// First value: Found value. Second value: Expected value if there is one.
|
||||||
|
#[derive(Debug, Copy, Clone, PartialEq, Eq, thiserror::Error)]
|
||||||
|
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
||||||
|
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
|
||||||
|
#[error("invalid TLV type field, found {found}, expected {expected:?}")]
|
||||||
|
pub struct InvalidTlvTypeFieldError {
|
||||||
|
found: u8,
|
||||||
|
expected: Option<u8>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Copy, Clone, PartialEq, Eq, thiserror::Error)]
|
||||||
|
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
||||||
|
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
|
||||||
pub enum TlvLvError {
|
pub enum TlvLvError {
|
||||||
DataTooLarge(usize),
|
#[error("{0}")]
|
||||||
ByteConversion(ByteConversionError),
|
DataTooLarge(#[from] TlvLvDataTooLargeError),
|
||||||
/// First value: Found value. Second value: Expected value if there is one.
|
#[error("byte conversion error: {0}")]
|
||||||
InvalidTlvTypeField {
|
ByteConversion(#[from] ByteConversionError),
|
||||||
found: u8,
|
#[error("{0}")]
|
||||||
expected: Option<u8>,
|
InvalidTlvTypeField(#[from] InvalidTlvTypeFieldError),
|
||||||
},
|
#[error("invalid value length {0}")]
|
||||||
/// Logically invalid value length detected. The value length may not exceed 255 bytes.
|
|
||||||
/// Depending on the concrete TLV type, the value length may also be logically invalid.
|
|
||||||
InvalidValueLength(usize),
|
InvalidValueLength(usize),
|
||||||
/// Only applies to filestore requests and responses. Second name was missing where one is
|
/// Only applies to filestore requests and responses. Second name was missing where one is
|
||||||
/// expected.
|
/// expected.
|
||||||
|
#[error("second name missing for filestore request or response")]
|
||||||
SecondNameMissing,
|
SecondNameMissing,
|
||||||
/// Invalid action code for filestore requests or responses.
|
/// Invalid action code for filestore requests or responses.
|
||||||
|
#[error("invalid action code {0}")]
|
||||||
InvalidFilestoreActionCode(u8),
|
InvalidFilestoreActionCode(u8),
|
||||||
}
|
}
|
||||||
|
|
||||||
impl From<ByteConversionError> for TlvLvError {
|
|
||||||
fn from(value: ByteConversionError) -> Self {
|
|
||||||
Self::ByteConversion(value)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Display for TlvLvError {
|
|
||||||
fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
|
|
||||||
match self {
|
|
||||||
TlvLvError::DataTooLarge(data_len) => {
|
|
||||||
write!(
|
|
||||||
f,
|
|
||||||
"data with size {} larger than allowed {} bytes",
|
|
||||||
data_len,
|
|
||||||
u8::MAX
|
|
||||||
)
|
|
||||||
}
|
|
||||||
TlvLvError::ByteConversion(e) => {
|
|
||||||
write!(f, "tlv or lv byte conversion: {}", e)
|
|
||||||
}
|
|
||||||
TlvLvError::InvalidTlvTypeField { found, expected } => {
|
|
||||||
write!(
|
|
||||||
f,
|
|
||||||
"invalid TLV type field, found {found}, expected {expected:?}"
|
|
||||||
)
|
|
||||||
}
|
|
||||||
TlvLvError::InvalidValueLength(len) => {
|
|
||||||
write!(f, "invalid value length {len}")
|
|
||||||
}
|
|
||||||
TlvLvError::SecondNameMissing => {
|
|
||||||
write!(f, "second name missing for filestore request or response")
|
|
||||||
}
|
|
||||||
TlvLvError::InvalidFilestoreActionCode(raw) => {
|
|
||||||
write!(f, "invalid filestore action code with raw value {raw}")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(feature = "std")]
|
|
||||||
impl Error for TlvLvError {
|
|
||||||
fn source(&self) -> Option<&(dyn Error + 'static)> {
|
|
||||||
match self {
|
|
||||||
TlvLvError::ByteConversion(e) => Some(e),
|
|
||||||
_ => None,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use super::*;
|
use super::*;
|
||||||
|
@@ -10,11 +10,16 @@ use super::{
|
|||||||
#[cfg(feature = "serde")]
|
#[cfg(feature = "serde")]
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
|
||||||
|
#[error("invalid directive code of acknowledged PDU")]
|
||||||
|
pub struct InvalidAckedDirectiveCodeError(pub FileDirectiveType);
|
||||||
|
|
||||||
/// ACK PDU abstraction.
|
/// ACK PDU abstraction.
|
||||||
///
|
///
|
||||||
/// For more information, refer to CFDP chapter 5.2.4.
|
/// For more information, refer to CFDP chapter 5.2.4.
|
||||||
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
|
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
|
||||||
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
||||||
|
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
|
||||||
pub struct AckPdu {
|
pub struct AckPdu {
|
||||||
pdu_header: PduHeader,
|
pdu_header: PduHeader,
|
||||||
directive_code_of_acked_pdu: FileDirectiveType,
|
directive_code_of_acked_pdu: FileDirectiveType,
|
||||||
@@ -28,16 +33,13 @@ impl AckPdu {
|
|||||||
directive_code_of_acked_pdu: FileDirectiveType,
|
directive_code_of_acked_pdu: FileDirectiveType,
|
||||||
condition_code: ConditionCode,
|
condition_code: ConditionCode,
|
||||||
transaction_status: TransactionStatus,
|
transaction_status: TransactionStatus,
|
||||||
) -> Result<Self, PduError> {
|
) -> Result<Self, InvalidAckedDirectiveCodeError> {
|
||||||
if directive_code_of_acked_pdu == FileDirectiveType::EofPdu {
|
if directive_code_of_acked_pdu == FileDirectiveType::EofPdu {
|
||||||
pdu_header.pdu_conf.direction = Direction::TowardsSender;
|
pdu_header.pdu_conf.direction = Direction::TowardsSender;
|
||||||
} else if directive_code_of_acked_pdu == FileDirectiveType::FinishedPdu {
|
} else if directive_code_of_acked_pdu == FileDirectiveType::FinishedPdu {
|
||||||
pdu_header.pdu_conf.direction = Direction::TowardsReceiver;
|
pdu_header.pdu_conf.direction = Direction::TowardsReceiver;
|
||||||
} else {
|
} else {
|
||||||
return Err(PduError::InvalidDirectiveType {
|
return Err(InvalidAckedDirectiveCodeError(directive_code_of_acked_pdu));
|
||||||
found: directive_code_of_acked_pdu as u8,
|
|
||||||
expected: None,
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
// Force correct direction flag.
|
// Force correct direction flag.
|
||||||
let mut ack_pdu = Self {
|
let mut ack_pdu = Self {
|
||||||
@@ -80,22 +82,27 @@ impl AckPdu {
|
|||||||
.unwrap()
|
.unwrap()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
pub fn pdu_header(&self) -> &PduHeader {
|
pub fn pdu_header(&self) -> &PduHeader {
|
||||||
&self.pdu_header
|
&self.pdu_header
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
pub fn directive_code_of_acked_pdu(&self) -> FileDirectiveType {
|
pub fn directive_code_of_acked_pdu(&self) -> FileDirectiveType {
|
||||||
self.directive_code_of_acked_pdu
|
self.directive_code_of_acked_pdu
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
pub fn condition_code(&self) -> ConditionCode {
|
pub fn condition_code(&self) -> ConditionCode {
|
||||||
self.condition_code
|
self.condition_code
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
pub fn transaction_status(&self) -> TransactionStatus {
|
pub fn transaction_status(&self) -> TransactionStatus {
|
||||||
self.transaction_status
|
self.transaction_status
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
fn calc_pdu_datafield_len(&self) -> usize {
|
fn calc_pdu_datafield_len(&self) -> usize {
|
||||||
if self.crc_flag() == CrcFlag::WithCrc {
|
if self.crc_flag() == CrcFlag::WithCrc {
|
||||||
return 5;
|
return 5;
|
||||||
@@ -139,27 +146,18 @@ impl AckPdu {
|
|||||||
let condition_code = ConditionCode::try_from((buf[current_idx] >> 4) & 0b1111)
|
let condition_code = ConditionCode::try_from((buf[current_idx] >> 4) & 0b1111)
|
||||||
.map_err(|_| PduError::InvalidConditionCode((buf[current_idx] >> 4) & 0b1111))?;
|
.map_err(|_| PduError::InvalidConditionCode((buf[current_idx] >> 4) & 0b1111))?;
|
||||||
let transaction_status = TransactionStatus::try_from(buf[current_idx] & 0b11).unwrap();
|
let transaction_status = TransactionStatus::try_from(buf[current_idx] & 0b11).unwrap();
|
||||||
Self::new(
|
// Unwrap okay, validity of acked directive code was checked.
|
||||||
|
Ok(Self::new(
|
||||||
pdu_header,
|
pdu_header,
|
||||||
acked_directive_type,
|
acked_directive_type,
|
||||||
condition_code,
|
condition_code,
|
||||||
transaction_status,
|
transaction_status,
|
||||||
)
|
)
|
||||||
}
|
.unwrap())
|
||||||
}
|
|
||||||
|
|
||||||
impl CfdpPdu for AckPdu {
|
|
||||||
fn pdu_header(&self) -> &PduHeader {
|
|
||||||
&self.pdu_header
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fn file_directive_type(&self) -> Option<FileDirectiveType> {
|
/// Write [Self] to the provided buffer and returns the written size.
|
||||||
Some(FileDirectiveType::AckPdu)
|
pub fn write_to_bytes(&self, buf: &mut [u8]) -> Result<usize, PduError> {
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl WritablePduPacket for AckPdu {
|
|
||||||
fn write_to_bytes(&self, buf: &mut [u8]) -> Result<usize, PduError> {
|
|
||||||
let expected_len = self.len_written();
|
let expected_len = self.len_written();
|
||||||
if buf.len() < expected_len {
|
if buf.len() < expected_len {
|
||||||
return Err(ByteConversionError::ToSliceTooSmall {
|
return Err(ByteConversionError::ToSliceTooSmall {
|
||||||
@@ -187,11 +185,33 @@ impl WritablePduPacket for AckPdu {
|
|||||||
Ok(current_idx)
|
Ok(current_idx)
|
||||||
}
|
}
|
||||||
|
|
||||||
fn len_written(&self) -> usize {
|
pub fn len_written(&self) -> usize {
|
||||||
self.pdu_header.header_len() + self.calc_pdu_datafield_len()
|
self.pdu_header.header_len() + self.calc_pdu_datafield_len()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
impl CfdpPdu for AckPdu {
|
||||||
|
#[inline]
|
||||||
|
fn pdu_header(&self) -> &PduHeader {
|
||||||
|
self.pdu_header()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
fn file_directive_type(&self) -> Option<FileDirectiveType> {
|
||||||
|
Some(FileDirectiveType::AckPdu)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl WritablePduPacket for AckPdu {
|
||||||
|
fn write_to_bytes(&self, buf: &mut [u8]) -> Result<usize, PduError> {
|
||||||
|
self.write_to_bytes(buf)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn len_written(&self) -> usize {
|
||||||
|
self.len_written()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use crate::cfdp::{
|
use crate::cfdp::{
|
||||||
@@ -224,7 +244,7 @@ mod tests {
|
|||||||
#[test]
|
#[test]
|
||||||
fn test_basic() {
|
fn test_basic() {
|
||||||
let pdu_conf = common_pdu_conf(CrcFlag::NoCrc, LargeFileFlag::Normal);
|
let pdu_conf = common_pdu_conf(CrcFlag::NoCrc, LargeFileFlag::Normal);
|
||||||
let pdu_header = PduHeader::new_no_file_data(pdu_conf, 0);
|
let pdu_header = PduHeader::new_for_file_directive(pdu_conf, 0);
|
||||||
let ack_pdu = AckPdu::new(
|
let ack_pdu = AckPdu::new(
|
||||||
pdu_header,
|
pdu_header,
|
||||||
FileDirectiveType::FinishedPdu,
|
FileDirectiveType::FinishedPdu,
|
||||||
@@ -244,7 +264,7 @@ mod tests {
|
|||||||
transaction_status: TransactionStatus,
|
transaction_status: TransactionStatus,
|
||||||
) {
|
) {
|
||||||
let pdu_conf = common_pdu_conf(CrcFlag::NoCrc, LargeFileFlag::Normal);
|
let pdu_conf = common_pdu_conf(CrcFlag::NoCrc, LargeFileFlag::Normal);
|
||||||
let pdu_header = PduHeader::new_no_file_data(pdu_conf, 0);
|
let pdu_header = PduHeader::new_for_file_directive(pdu_conf, 0);
|
||||||
let ack_pdu = AckPdu::new_for_finished_pdu(pdu_header, condition_code, transaction_status);
|
let ack_pdu = AckPdu::new_for_finished_pdu(pdu_header, condition_code, transaction_status);
|
||||||
let mut buf: [u8; 64] = [0; 64];
|
let mut buf: [u8; 64] = [0; 64];
|
||||||
let res = ack_pdu.write_to_bytes(&mut buf);
|
let res = ack_pdu.write_to_bytes(&mut buf);
|
||||||
@@ -266,15 +286,53 @@ mod tests {
|
|||||||
generic_serialization_test(ConditionCode::NoError, TransactionStatus::Active);
|
generic_serialization_test(ConditionCode::NoError, TransactionStatus::Active);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_serialization_too_small() {
|
||||||
|
let pdu_conf = common_pdu_conf(CrcFlag::NoCrc, LargeFileFlag::Normal);
|
||||||
|
let pdu_header = PduHeader::new_for_file_directive(pdu_conf, 0);
|
||||||
|
let ack_pdu = AckPdu::new(
|
||||||
|
pdu_header,
|
||||||
|
FileDirectiveType::FinishedPdu,
|
||||||
|
ConditionCode::NoError,
|
||||||
|
TransactionStatus::Active,
|
||||||
|
)
|
||||||
|
.expect("creating ACK PDU failed");
|
||||||
|
if let Err(PduError::ByteConversion(ByteConversionError::ToSliceTooSmall {
|
||||||
|
found,
|
||||||
|
expected,
|
||||||
|
})) = ack_pdu.write_to_bytes(&mut [0; 5])
|
||||||
|
{
|
||||||
|
assert_eq!(found, 5);
|
||||||
|
assert_eq!(expected, ack_pdu.len_written());
|
||||||
|
} else {
|
||||||
|
panic!("serialization should have failed");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_serialization_fs_error() {
|
fn test_serialization_fs_error() {
|
||||||
generic_serialization_test(ConditionCode::FileSizeError, TransactionStatus::Terminated);
|
generic_serialization_test(ConditionCode::FileSizeError, TransactionStatus::Terminated);
|
||||||
}
|
}
|
||||||
|
#[test]
|
||||||
|
fn test_invalid_directive_code_of_acked_pdu() {
|
||||||
|
let pdu_conf = common_pdu_conf(CrcFlag::NoCrc, LargeFileFlag::Normal);
|
||||||
|
let pdu_header = PduHeader::new_for_file_directive(pdu_conf, 0);
|
||||||
|
assert_eq!(
|
||||||
|
AckPdu::new(
|
||||||
|
pdu_header,
|
||||||
|
FileDirectiveType::MetadataPdu,
|
||||||
|
ConditionCode::NoError,
|
||||||
|
TransactionStatus::Active,
|
||||||
|
)
|
||||||
|
.unwrap_err(),
|
||||||
|
InvalidAckedDirectiveCodeError(FileDirectiveType::MetadataPdu)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_deserialization() {
|
fn test_deserialization() {
|
||||||
let pdu_conf = common_pdu_conf(CrcFlag::NoCrc, LargeFileFlag::Normal);
|
let pdu_conf = common_pdu_conf(CrcFlag::NoCrc, LargeFileFlag::Normal);
|
||||||
let pdu_header = PduHeader::new_no_file_data(pdu_conf, 0);
|
let pdu_header = PduHeader::new_for_file_directive(pdu_conf, 0);
|
||||||
let ack_pdu = AckPdu::new_for_finished_pdu(
|
let ack_pdu = AckPdu::new_for_finished_pdu(
|
||||||
pdu_header,
|
pdu_header,
|
||||||
ConditionCode::NoError,
|
ConditionCode::NoError,
|
||||||
@@ -289,7 +347,7 @@ mod tests {
|
|||||||
#[test]
|
#[test]
|
||||||
fn test_with_crc() {
|
fn test_with_crc() {
|
||||||
let pdu_conf = common_pdu_conf(CrcFlag::WithCrc, LargeFileFlag::Normal);
|
let pdu_conf = common_pdu_conf(CrcFlag::WithCrc, LargeFileFlag::Normal);
|
||||||
let pdu_header = PduHeader::new_no_file_data(pdu_conf, 0);
|
let pdu_header = PduHeader::new_for_file_directive(pdu_conf, 0);
|
||||||
let ack_pdu = AckPdu::new_for_finished_pdu(
|
let ack_pdu = AckPdu::new_for_finished_pdu(
|
||||||
pdu_header,
|
pdu_header,
|
||||||
ConditionCode::NoError,
|
ConditionCode::NoError,
|
||||||
@@ -306,7 +364,7 @@ mod tests {
|
|||||||
#[test]
|
#[test]
|
||||||
fn test_for_eof_pdu() {
|
fn test_for_eof_pdu() {
|
||||||
let pdu_conf = common_pdu_conf(CrcFlag::WithCrc, LargeFileFlag::Normal);
|
let pdu_conf = common_pdu_conf(CrcFlag::WithCrc, LargeFileFlag::Normal);
|
||||||
let pdu_header = PduHeader::new_no_file_data(pdu_conf, 0);
|
let pdu_header = PduHeader::new_for_file_directive(pdu_conf, 0);
|
||||||
let ack_pdu = AckPdu::new_for_eof_pdu(
|
let ack_pdu = AckPdu::new_for_eof_pdu(
|
||||||
pdu_header,
|
pdu_header,
|
||||||
ConditionCode::NoError,
|
ConditionCode::NoError,
|
||||||
@@ -323,7 +381,7 @@ mod tests {
|
|||||||
#[cfg(feature = "serde")]
|
#[cfg(feature = "serde")]
|
||||||
fn test_ack_pdu_serialization() {
|
fn test_ack_pdu_serialization() {
|
||||||
let pdu_conf = common_pdu_conf(CrcFlag::WithCrc, LargeFileFlag::Normal);
|
let pdu_conf = common_pdu_conf(CrcFlag::WithCrc, LargeFileFlag::Normal);
|
||||||
let pdu_header = PduHeader::new_no_file_data(pdu_conf, 0);
|
let pdu_header = PduHeader::new_for_file_directive(pdu_conf, 0);
|
||||||
let ack_pdu = AckPdu::new_for_eof_pdu(
|
let ack_pdu = AckPdu::new_for_eof_pdu(
|
||||||
pdu_header,
|
pdu_header,
|
||||||
ConditionCode::NoError,
|
ConditionCode::NoError,
|
||||||
|
@@ -15,6 +15,7 @@ use super::{CfdpPdu, WritablePduPacket};
|
|||||||
/// For more information, refer to CFDP chapter 5.2.2.
|
/// For more information, refer to CFDP chapter 5.2.2.
|
||||||
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
|
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
|
||||||
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
||||||
|
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
|
||||||
pub struct EofPdu {
|
pub struct EofPdu {
|
||||||
pdu_header: PduHeader,
|
pdu_header: PduHeader,
|
||||||
condition_code: ConditionCode,
|
condition_code: ConditionCode,
|
||||||
@@ -24,32 +25,52 @@ pub struct EofPdu {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl EofPdu {
|
impl EofPdu {
|
||||||
pub fn new_no_error(mut pdu_header: PduHeader, file_checksum: u32, file_size: u64) -> Self {
|
pub fn new(
|
||||||
|
mut pdu_header: PduHeader,
|
||||||
|
condition_code: ConditionCode,
|
||||||
|
file_checksum: u32,
|
||||||
|
file_size: u64,
|
||||||
|
fault_location: Option<EntityIdTlv>,
|
||||||
|
) -> Self {
|
||||||
// Force correct direction flag.
|
// Force correct direction flag.
|
||||||
pdu_header.pdu_conf.direction = Direction::TowardsReceiver;
|
pdu_header.pdu_conf.direction = Direction::TowardsReceiver;
|
||||||
let mut eof_pdu = Self {
|
let mut eof_pdu = Self {
|
||||||
pdu_header,
|
pdu_header,
|
||||||
condition_code: ConditionCode::NoError,
|
condition_code,
|
||||||
file_checksum,
|
file_checksum,
|
||||||
file_size,
|
file_size,
|
||||||
fault_location: None,
|
fault_location,
|
||||||
};
|
};
|
||||||
eof_pdu.pdu_header.pdu_datafield_len = eof_pdu.calc_pdu_datafield_len() as u16;
|
eof_pdu.pdu_header.pdu_datafield_len = eof_pdu.calc_pdu_datafield_len() as u16;
|
||||||
eof_pdu
|
eof_pdu
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub fn new_no_error(pdu_header: PduHeader, file_checksum: u32, file_size: u64) -> Self {
|
||||||
|
Self::new(
|
||||||
|
pdu_header,
|
||||||
|
ConditionCode::NoError,
|
||||||
|
file_checksum,
|
||||||
|
file_size,
|
||||||
|
None,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
pub fn pdu_header(&self) -> &PduHeader {
|
pub fn pdu_header(&self) -> &PduHeader {
|
||||||
&self.pdu_header
|
&self.pdu_header
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
pub fn condition_code(&self) -> ConditionCode {
|
pub fn condition_code(&self) -> ConditionCode {
|
||||||
self.condition_code
|
self.condition_code
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
pub fn file_checksum(&self) -> u32 {
|
pub fn file_checksum(&self) -> u32 {
|
||||||
self.file_checksum
|
self.file_checksum
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
pub fn file_size(&self) -> u64 {
|
pub fn file_size(&self) -> u64 {
|
||||||
self.file_size
|
self.file_size
|
||||||
}
|
}
|
||||||
@@ -112,20 +133,9 @@ impl EofPdu {
|
|||||||
fault_location,
|
fault_location,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
impl CfdpPdu for EofPdu {
|
/// Write [Self] to the provided buffer and returns the written size.
|
||||||
fn pdu_header(&self) -> &PduHeader {
|
pub fn write_to_bytes(&self, buf: &mut [u8]) -> Result<usize, PduError> {
|
||||||
&self.pdu_header
|
|
||||||
}
|
|
||||||
|
|
||||||
fn file_directive_type(&self) -> Option<FileDirectiveType> {
|
|
||||||
Some(FileDirectiveType::EofPdu)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl WritablePduPacket for EofPdu {
|
|
||||||
fn write_to_bytes(&self, buf: &mut [u8]) -> Result<usize, PduError> {
|
|
||||||
let expected_len = self.len_written();
|
let expected_len = self.len_written();
|
||||||
if buf.len() < expected_len {
|
if buf.len() < expected_len {
|
||||||
return Err(ByteConversionError::ToSliceTooSmall {
|
return Err(ByteConversionError::ToSliceTooSmall {
|
||||||
@@ -147,7 +157,7 @@ impl WritablePduPacket for EofPdu {
|
|||||||
&mut buf[current_idx..],
|
&mut buf[current_idx..],
|
||||||
)?;
|
)?;
|
||||||
if let Some(fault_location) = self.fault_location {
|
if let Some(fault_location) = self.fault_location {
|
||||||
current_idx += fault_location.write_to_bytes(buf)?;
|
current_idx += fault_location.write_to_bytes(&mut buf[current_idx..])?;
|
||||||
}
|
}
|
||||||
if self.crc_flag() == CrcFlag::WithCrc {
|
if self.crc_flag() == CrcFlag::WithCrc {
|
||||||
current_idx = add_pdu_crc(buf, current_idx);
|
current_idx = add_pdu_crc(buf, current_idx);
|
||||||
@@ -155,11 +165,33 @@ impl WritablePduPacket for EofPdu {
|
|||||||
Ok(current_idx)
|
Ok(current_idx)
|
||||||
}
|
}
|
||||||
|
|
||||||
fn len_written(&self) -> usize {
|
pub fn len_written(&self) -> usize {
|
||||||
self.pdu_header.header_len() + self.calc_pdu_datafield_len()
|
self.pdu_header.header_len() + self.calc_pdu_datafield_len()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
impl CfdpPdu for EofPdu {
|
||||||
|
#[inline]
|
||||||
|
fn pdu_header(&self) -> &PduHeader {
|
||||||
|
self.pdu_header()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
fn file_directive_type(&self) -> Option<FileDirectiveType> {
|
||||||
|
Some(FileDirectiveType::EofPdu)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl WritablePduPacket for EofPdu {
|
||||||
|
fn write_to_bytes(&self, buf: &mut [u8]) -> Result<usize, PduError> {
|
||||||
|
self.write_to_bytes(buf)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn len_written(&self) -> usize {
|
||||||
|
self.len_written()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use super::*;
|
use super::*;
|
||||||
@@ -170,13 +202,23 @@ mod tests {
|
|||||||
use crate::cfdp::{ConditionCode, CrcFlag, LargeFileFlag, PduType, TransmissionMode};
|
use crate::cfdp::{ConditionCode, CrcFlag, LargeFileFlag, PduType, TransmissionMode};
|
||||||
#[cfg(feature = "serde")]
|
#[cfg(feature = "serde")]
|
||||||
use crate::tests::generic_serde_test;
|
use crate::tests::generic_serde_test;
|
||||||
|
use crate::util::{UnsignedByteFieldU16, UnsignedEnum};
|
||||||
|
|
||||||
fn verify_state(&eof_pdu: &EofPdu, file_flag: LargeFileFlag) {
|
fn verify_state_no_error_no_crc(eof_pdu: &EofPdu, file_flag: LargeFileFlag) {
|
||||||
|
verify_state(eof_pdu, CrcFlag::NoCrc, file_flag, ConditionCode::NoError);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn verify_state(
|
||||||
|
eof_pdu: &EofPdu,
|
||||||
|
crc_flag: CrcFlag,
|
||||||
|
file_flag: LargeFileFlag,
|
||||||
|
cond_code: ConditionCode,
|
||||||
|
) {
|
||||||
assert_eq!(eof_pdu.file_checksum(), 0x01020304);
|
assert_eq!(eof_pdu.file_checksum(), 0x01020304);
|
||||||
assert_eq!(eof_pdu.file_size(), 12);
|
assert_eq!(eof_pdu.file_size(), 12);
|
||||||
assert_eq!(eof_pdu.condition_code(), ConditionCode::NoError);
|
assert_eq!(eof_pdu.condition_code(), cond_code);
|
||||||
|
|
||||||
assert_eq!(eof_pdu.crc_flag(), CrcFlag::NoCrc);
|
assert_eq!(eof_pdu.crc_flag(), crc_flag);
|
||||||
assert_eq!(eof_pdu.file_flag(), file_flag);
|
assert_eq!(eof_pdu.file_flag(), file_flag);
|
||||||
assert_eq!(eof_pdu.pdu_type(), PduType::FileDirective);
|
assert_eq!(eof_pdu.pdu_type(), PduType::FileDirective);
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
@@ -193,16 +235,16 @@ mod tests {
|
|||||||
#[test]
|
#[test]
|
||||||
fn test_basic() {
|
fn test_basic() {
|
||||||
let pdu_conf = common_pdu_conf(CrcFlag::NoCrc, LargeFileFlag::Normal);
|
let pdu_conf = common_pdu_conf(CrcFlag::NoCrc, LargeFileFlag::Normal);
|
||||||
let pdu_header = PduHeader::new_no_file_data(pdu_conf, 0);
|
let pdu_header = PduHeader::new_for_file_directive(pdu_conf, 0);
|
||||||
let eof_pdu = EofPdu::new_no_error(pdu_header, 0x01020304, 12);
|
let eof_pdu = EofPdu::new_no_error(pdu_header, 0x01020304, 12);
|
||||||
assert_eq!(eof_pdu.len_written(), pdu_header.header_len() + 2 + 4 + 4);
|
assert_eq!(eof_pdu.len_written(), pdu_header.header_len() + 2 + 4 + 4);
|
||||||
verify_state(&eof_pdu, LargeFileFlag::Normal);
|
verify_state_no_error_no_crc(&eof_pdu, LargeFileFlag::Normal);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_serialization() {
|
fn test_serialization() {
|
||||||
let pdu_conf = common_pdu_conf(CrcFlag::NoCrc, LargeFileFlag::Normal);
|
let pdu_conf = common_pdu_conf(CrcFlag::NoCrc, LargeFileFlag::Normal);
|
||||||
let pdu_header = PduHeader::new_no_file_data(pdu_conf, 0);
|
let pdu_header = PduHeader::new_for_file_directive(pdu_conf, 0);
|
||||||
let eof_pdu = EofPdu::new_no_error(pdu_header, 0x01020304, 12);
|
let eof_pdu = EofPdu::new_no_error(pdu_header, 0x01020304, 12);
|
||||||
let mut buf: [u8; 64] = [0; 64];
|
let mut buf: [u8; 64] = [0; 64];
|
||||||
let res = eof_pdu.write_to_bytes(&mut buf);
|
let res = eof_pdu.write_to_bytes(&mut buf);
|
||||||
@@ -234,7 +276,7 @@ mod tests {
|
|||||||
#[test]
|
#[test]
|
||||||
fn test_deserialization() {
|
fn test_deserialization() {
|
||||||
let pdu_conf = common_pdu_conf(CrcFlag::NoCrc, LargeFileFlag::Normal);
|
let pdu_conf = common_pdu_conf(CrcFlag::NoCrc, LargeFileFlag::Normal);
|
||||||
let pdu_header = PduHeader::new_no_file_data(pdu_conf, 0);
|
let pdu_header = PduHeader::new_for_file_directive(pdu_conf, 0);
|
||||||
let eof_pdu = EofPdu::new_no_error(pdu_header, 0x01020304, 12);
|
let eof_pdu = EofPdu::new_no_error(pdu_header, 0x01020304, 12);
|
||||||
let mut buf: [u8; 64] = [0; 64];
|
let mut buf: [u8; 64] = [0; 64];
|
||||||
eof_pdu.write_to_bytes(&mut buf).unwrap();
|
eof_pdu.write_to_bytes(&mut buf).unwrap();
|
||||||
@@ -249,7 +291,7 @@ mod tests {
|
|||||||
#[test]
|
#[test]
|
||||||
fn test_write_to_vec() {
|
fn test_write_to_vec() {
|
||||||
let pdu_conf = common_pdu_conf(CrcFlag::NoCrc, LargeFileFlag::Normal);
|
let pdu_conf = common_pdu_conf(CrcFlag::NoCrc, LargeFileFlag::Normal);
|
||||||
let pdu_header = PduHeader::new_no_file_data(pdu_conf, 0);
|
let pdu_header = PduHeader::new_for_file_directive(pdu_conf, 0);
|
||||||
let eof_pdu = EofPdu::new_no_error(pdu_header, 0x01020304, 12);
|
let eof_pdu = EofPdu::new_no_error(pdu_header, 0x01020304, 12);
|
||||||
let mut buf: [u8; 64] = [0; 64];
|
let mut buf: [u8; 64] = [0; 64];
|
||||||
let written = eof_pdu.write_to_bytes(&mut buf).unwrap();
|
let written = eof_pdu.write_to_bytes(&mut buf).unwrap();
|
||||||
@@ -260,7 +302,7 @@ mod tests {
|
|||||||
#[test]
|
#[test]
|
||||||
fn test_with_crc() {
|
fn test_with_crc() {
|
||||||
let pdu_conf = common_pdu_conf(CrcFlag::WithCrc, LargeFileFlag::Normal);
|
let pdu_conf = common_pdu_conf(CrcFlag::WithCrc, LargeFileFlag::Normal);
|
||||||
let pdu_header = PduHeader::new_no_file_data(pdu_conf, 0);
|
let pdu_header = PduHeader::new_for_file_directive(pdu_conf, 0);
|
||||||
let eof_pdu = EofPdu::new_no_error(pdu_header, 0x01020304, 12);
|
let eof_pdu = EofPdu::new_no_error(pdu_header, 0x01020304, 12);
|
||||||
let mut buf: [u8; 64] = [0; 64];
|
let mut buf: [u8; 64] = [0; 64];
|
||||||
let written = eof_pdu.write_to_bytes(&mut buf).unwrap();
|
let written = eof_pdu.write_to_bytes(&mut buf).unwrap();
|
||||||
@@ -270,7 +312,7 @@ mod tests {
|
|||||||
buf[written - 1] -= 1;
|
buf[written - 1] -= 1;
|
||||||
let crc: u16 = ((buf[written - 2] as u16) << 8) as u16 | buf[written - 1] as u16;
|
let crc: u16 = ((buf[written - 2] as u16) << 8) as u16 | buf[written - 1] as u16;
|
||||||
let error = EofPdu::from_bytes(&buf).unwrap_err();
|
let error = EofPdu::from_bytes(&buf).unwrap_err();
|
||||||
if let PduError::ChecksumError(e) = error {
|
if let PduError::Checksum(e) = error {
|
||||||
assert_eq!(e, crc);
|
assert_eq!(e, crc);
|
||||||
} else {
|
} else {
|
||||||
panic!("expected crc error");
|
panic!("expected crc error");
|
||||||
@@ -280,9 +322,9 @@ mod tests {
|
|||||||
#[test]
|
#[test]
|
||||||
fn test_with_large_file_flag() {
|
fn test_with_large_file_flag() {
|
||||||
let pdu_conf = common_pdu_conf(CrcFlag::NoCrc, LargeFileFlag::Large);
|
let pdu_conf = common_pdu_conf(CrcFlag::NoCrc, LargeFileFlag::Large);
|
||||||
let pdu_header = PduHeader::new_no_file_data(pdu_conf, 0);
|
let pdu_header = PduHeader::new_for_file_directive(pdu_conf, 0);
|
||||||
let eof_pdu = EofPdu::new_no_error(pdu_header, 0x01020304, 12);
|
let eof_pdu = EofPdu::new_no_error(pdu_header, 0x01020304, 12);
|
||||||
verify_state(&eof_pdu, LargeFileFlag::Large);
|
verify_state_no_error_no_crc(&eof_pdu, LargeFileFlag::Large);
|
||||||
assert_eq!(eof_pdu.len_written(), pdu_header.header_len() + 2 + 8 + 4);
|
assert_eq!(eof_pdu.len_written(), pdu_header.header_len() + 2 + 8 + 4);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -290,8 +332,52 @@ mod tests {
|
|||||||
#[cfg(feature = "serde")]
|
#[cfg(feature = "serde")]
|
||||||
fn test_eof_serde() {
|
fn test_eof_serde() {
|
||||||
let pdu_conf = common_pdu_conf(CrcFlag::NoCrc, LargeFileFlag::Normal);
|
let pdu_conf = common_pdu_conf(CrcFlag::NoCrc, LargeFileFlag::Normal);
|
||||||
let pdu_header = PduHeader::new_no_file_data(pdu_conf, 0);
|
let pdu_header = PduHeader::new_for_file_directive(pdu_conf, 0);
|
||||||
let eof_pdu = EofPdu::new_no_error(pdu_header, 0x01020304, 12);
|
let eof_pdu = EofPdu::new_no_error(pdu_header, 0x01020304, 12);
|
||||||
generic_serde_test(eof_pdu);
|
generic_serde_test(eof_pdu);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn generic_test_with_fault_location_and_error(crc: CrcFlag) {
|
||||||
|
let pdu_conf = common_pdu_conf(crc, LargeFileFlag::Normal);
|
||||||
|
let pdu_header = PduHeader::new_for_file_directive(pdu_conf, 0);
|
||||||
|
let eof_pdu = EofPdu::new(
|
||||||
|
pdu_header,
|
||||||
|
ConditionCode::FileChecksumFailure,
|
||||||
|
0x01020304,
|
||||||
|
12,
|
||||||
|
Some(EntityIdTlv::new(UnsignedByteFieldU16::new(5).into())),
|
||||||
|
);
|
||||||
|
let mut expected_len = pdu_header.header_len() + 2 + 4 + 4 + 4;
|
||||||
|
if crc == CrcFlag::WithCrc {
|
||||||
|
expected_len += 2;
|
||||||
|
}
|
||||||
|
// Entity ID TLV increaes length by 4.
|
||||||
|
assert_eq!(eof_pdu.len_written(), expected_len);
|
||||||
|
verify_state(
|
||||||
|
&eof_pdu,
|
||||||
|
crc,
|
||||||
|
LargeFileFlag::Normal,
|
||||||
|
ConditionCode::FileChecksumFailure,
|
||||||
|
);
|
||||||
|
let eof_vec = eof_pdu.to_vec().unwrap();
|
||||||
|
let eof_read_back = EofPdu::from_bytes(&eof_vec);
|
||||||
|
if let Err(e) = eof_read_back {
|
||||||
|
panic!("deserialization failed with: {e}")
|
||||||
|
}
|
||||||
|
let eof_read_back = eof_read_back.unwrap();
|
||||||
|
assert_eq!(eof_read_back, eof_pdu);
|
||||||
|
assert!(eof_read_back.fault_location.is_some());
|
||||||
|
assert_eq!(eof_read_back.fault_location.unwrap().entity_id().value(), 5);
|
||||||
|
assert_eq!(eof_read_back.fault_location.unwrap().entity_id().size(), 2);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_with_fault_location_and_error() {
|
||||||
|
generic_test_with_fault_location_and_error(CrcFlag::NoCrc);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_with_fault_location_and_error_and_crc() {
|
||||||
|
generic_test_with_fault_location_and_error(CrcFlag::WithCrc);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
@@ -10,8 +10,10 @@ use serde::{Deserialize, Serialize};
|
|||||||
|
|
||||||
use super::{CfdpPdu, FileDirectiveType, WritablePduPacket};
|
use super::{CfdpPdu, FileDirectiveType, WritablePduPacket};
|
||||||
|
|
||||||
#[derive(Debug, Copy, Clone, PartialEq, Eq, TryFromPrimitive, IntoPrimitive)]
|
#[derive(Debug, PartialEq, Eq, TryFromPrimitive, IntoPrimitive)]
|
||||||
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
||||||
|
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
|
||||||
|
#[bitbybit::bitenum(u2, exhaustive = true)]
|
||||||
#[repr(u8)]
|
#[repr(u8)]
|
||||||
pub enum RecordContinuationState {
|
pub enum RecordContinuationState {
|
||||||
NoStartNoEnd = 0b00,
|
NoStartNoEnd = 0b00,
|
||||||
@@ -43,24 +45,27 @@ impl<'seg_meta> SegmentMetadata<'seg_meta> {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
pub fn record_continuation_state(&self) -> RecordContinuationState {
|
pub fn record_continuation_state(&self) -> RecordContinuationState {
|
||||||
self.record_continuation_state
|
self.record_continuation_state
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
pub fn metadata(&self) -> Option<&'seg_meta [u8]> {
|
pub fn metadata(&self) -> Option<&'seg_meta [u8]> {
|
||||||
self.metadata
|
self.metadata
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn written_len(&self) -> usize {
|
#[inline]
|
||||||
|
pub fn len_written(&self) -> usize {
|
||||||
// Map empty metadata to 0 and slice to its length.
|
// Map empty metadata to 0 and slice to its length.
|
||||||
1 + self.metadata.map_or(0, |meta| meta.len())
|
1 + self.metadata.map_or(0, |meta| meta.len())
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(crate) fn write_to_bytes(&self, buf: &mut [u8]) -> Result<usize, ByteConversionError> {
|
pub(crate) fn write_to_bytes(&self, buf: &mut [u8]) -> Result<usize, ByteConversionError> {
|
||||||
if buf.len() < self.written_len() {
|
if buf.len() < self.len_written() {
|
||||||
return Err(ByteConversionError::ToSliceTooSmall {
|
return Err(ByteConversionError::ToSliceTooSmall {
|
||||||
found: buf.len(),
|
found: buf.len(),
|
||||||
expected: self.written_len(),
|
expected: self.len_written(),
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
buf[0] = ((self.record_continuation_state as u8) << 6)
|
buf[0] = ((self.record_continuation_state as u8) << 6)
|
||||||
@@ -68,7 +73,7 @@ impl<'seg_meta> SegmentMetadata<'seg_meta> {
|
|||||||
if let Some(metadata) = self.metadata {
|
if let Some(metadata) = self.metadata {
|
||||||
buf[1..1 + metadata.len()].copy_from_slice(metadata)
|
buf[1..1 + metadata.len()].copy_from_slice(metadata)
|
||||||
}
|
}
|
||||||
Ok(self.written_len())
|
Ok(self.len_written())
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(crate) fn from_bytes(buf: &'seg_meta [u8]) -> Result<Self, ByteConversionError> {
|
pub(crate) fn from_bytes(buf: &'seg_meta [u8]) -> Result<Self, ByteConversionError> {
|
||||||
@@ -92,16 +97,74 @@ impl<'seg_meta> SegmentMetadata<'seg_meta> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
|
||||||
|
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
||||||
|
struct FdPduBase<'seg_meta> {
|
||||||
|
pdu_header: PduHeader,
|
||||||
|
#[cfg_attr(feature = "serde", serde(borrow))]
|
||||||
|
segment_metadata: Option<SegmentMetadata<'seg_meta>>,
|
||||||
|
offset: u64,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl CfdpPdu for FdPduBase<'_> {
|
||||||
|
#[inline]
|
||||||
|
fn pdu_header(&self) -> &PduHeader {
|
||||||
|
self.pdu_header()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
fn file_directive_type(&self) -> Option<FileDirectiveType> {
|
||||||
|
None
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl FdPduBase<'_> {
|
||||||
|
fn calc_pdu_datafield_len(&self, file_data_len: u64) -> usize {
|
||||||
|
let mut len = core::mem::size_of::<u32>();
|
||||||
|
if self.pdu_header.pdu_conf.file_flag == LargeFileFlag::Large {
|
||||||
|
len += 4;
|
||||||
|
}
|
||||||
|
if self.segment_metadata.is_some() {
|
||||||
|
len += self.segment_metadata.as_ref().unwrap().len_written()
|
||||||
|
}
|
||||||
|
len += file_data_len as usize;
|
||||||
|
if self.crc_flag() == CrcFlag::WithCrc {
|
||||||
|
len += 2;
|
||||||
|
}
|
||||||
|
len
|
||||||
|
}
|
||||||
|
|
||||||
|
fn write_common_fields_to_bytes(&self, buf: &mut [u8]) -> Result<usize, PduError> {
|
||||||
|
let mut current_idx = self.pdu_header.write_to_bytes(buf)?;
|
||||||
|
if self.segment_metadata.is_some() {
|
||||||
|
current_idx += self
|
||||||
|
.segment_metadata
|
||||||
|
.as_ref()
|
||||||
|
.unwrap()
|
||||||
|
.write_to_bytes(&mut buf[current_idx..])?;
|
||||||
|
}
|
||||||
|
current_idx += write_fss_field(
|
||||||
|
self.pdu_header.common_pdu_conf().file_flag,
|
||||||
|
self.offset,
|
||||||
|
&mut buf[current_idx..],
|
||||||
|
)?;
|
||||||
|
Ok(current_idx)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
pub fn pdu_header(&self) -> &PduHeader {
|
||||||
|
&self.pdu_header
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// File Data PDU abstraction.
|
/// File Data PDU abstraction.
|
||||||
///
|
///
|
||||||
/// For more information, refer to CFDP chapter 5.3.
|
/// For more information, refer to CFDP chapter 5.3.
|
||||||
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
|
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
|
||||||
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
||||||
pub struct FileDataPdu<'seg_meta, 'file_data> {
|
pub struct FileDataPdu<'seg_meta, 'file_data> {
|
||||||
pdu_header: PduHeader,
|
|
||||||
#[cfg_attr(feature = "serde", serde(borrow))]
|
#[cfg_attr(feature = "serde", serde(borrow))]
|
||||||
segment_metadata: Option<SegmentMetadata<'seg_meta>>,
|
common: FdPduBase<'seg_meta>,
|
||||||
offset: u64,
|
|
||||||
file_data: &'file_data [u8],
|
file_data: &'file_data [u8],
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -134,42 +197,42 @@ impl<'seg_meta, 'file_data> FileDataPdu<'seg_meta, 'file_data> {
|
|||||||
pdu_header.seg_metadata_flag = SegmentMetadataFlag::Present;
|
pdu_header.seg_metadata_flag = SegmentMetadataFlag::Present;
|
||||||
}
|
}
|
||||||
let mut pdu = Self {
|
let mut pdu = Self {
|
||||||
pdu_header,
|
common: FdPduBase {
|
||||||
segment_metadata,
|
pdu_header,
|
||||||
offset,
|
segment_metadata,
|
||||||
|
offset,
|
||||||
|
},
|
||||||
file_data,
|
file_data,
|
||||||
};
|
};
|
||||||
pdu.pdu_header.pdu_datafield_len = pdu.calc_pdu_datafield_len() as u16;
|
pdu.common.pdu_header.pdu_datafield_len = pdu.calc_pdu_datafield_len() as u16;
|
||||||
pdu
|
pdu
|
||||||
}
|
}
|
||||||
|
|
||||||
fn calc_pdu_datafield_len(&self) -> usize {
|
fn calc_pdu_datafield_len(&self) -> usize {
|
||||||
let mut len = core::mem::size_of::<u32>();
|
self.common
|
||||||
if self.pdu_header.pdu_conf.file_flag == LargeFileFlag::Large {
|
.calc_pdu_datafield_len(self.file_data.len() as u64)
|
||||||
len += 4;
|
|
||||||
}
|
|
||||||
if self.segment_metadata.is_some() {
|
|
||||||
len += self.segment_metadata.as_ref().unwrap().written_len()
|
|
||||||
}
|
|
||||||
len += self.file_data.len();
|
|
||||||
if self.crc_flag() == CrcFlag::WithCrc {
|
|
||||||
len += 2;
|
|
||||||
}
|
|
||||||
len
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
pub fn segment_metadata(&self) -> Option<&SegmentMetadata<'_>> {
|
||||||
|
self.common.segment_metadata.as_ref()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
pub fn pdu_header(&self) -> &PduHeader {
|
||||||
|
self.common.pdu_header()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
pub fn offset(&self) -> u64 {
|
pub fn offset(&self) -> u64 {
|
||||||
self.offset
|
self.common.offset
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
pub fn file_data(&self) -> &'file_data [u8] {
|
pub fn file_data(&self) -> &'file_data [u8] {
|
||||||
self.file_data
|
self.file_data
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn segment_metadata(&self) -> Option<&SegmentMetadata> {
|
|
||||||
self.segment_metadata.as_ref()
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn from_bytes<'buf: 'seg_meta + 'file_data>(buf: &'buf [u8]) -> Result<Self, PduError> {
|
pub fn from_bytes<'buf: 'seg_meta + 'file_data>(buf: &'buf [u8]) -> Result<Self, PduError> {
|
||||||
let (pdu_header, mut current_idx) = PduHeader::from_bytes(buf)?;
|
let (pdu_header, mut current_idx) = PduHeader::from_bytes(buf)?;
|
||||||
let full_len_without_crc = pdu_header.verify_length_and_checksum(buf)?;
|
let full_len_without_crc = pdu_header.verify_length_and_checksum(buf)?;
|
||||||
@@ -178,7 +241,7 @@ impl<'seg_meta, 'file_data> FileDataPdu<'seg_meta, 'file_data> {
|
|||||||
let mut segment_metadata = None;
|
let mut segment_metadata = None;
|
||||||
if pdu_header.seg_metadata_flag == SegmentMetadataFlag::Present {
|
if pdu_header.seg_metadata_flag == SegmentMetadataFlag::Present {
|
||||||
segment_metadata = Some(SegmentMetadata::from_bytes(&buf[current_idx..])?);
|
segment_metadata = Some(SegmentMetadata::from_bytes(&buf[current_idx..])?);
|
||||||
current_idx += segment_metadata.as_ref().unwrap().written_len();
|
current_idx += segment_metadata.as_ref().unwrap().len_written();
|
||||||
}
|
}
|
||||||
let (fss, offset) = read_fss_field(pdu_header.pdu_conf.file_flag, &buf[current_idx..]);
|
let (fss, offset) = read_fss_field(pdu_header.pdu_conf.file_flag, &buf[current_idx..]);
|
||||||
current_idx += fss;
|
current_idx += fss;
|
||||||
@@ -190,25 +253,17 @@ impl<'seg_meta, 'file_data> FileDataPdu<'seg_meta, 'file_data> {
|
|||||||
.into());
|
.into());
|
||||||
}
|
}
|
||||||
Ok(Self {
|
Ok(Self {
|
||||||
pdu_header,
|
common: FdPduBase {
|
||||||
segment_metadata,
|
pdu_header,
|
||||||
offset,
|
segment_metadata,
|
||||||
|
offset,
|
||||||
|
},
|
||||||
file_data: &buf[current_idx..full_len_without_crc],
|
file_data: &buf[current_idx..full_len_without_crc],
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
|
||||||
impl CfdpPdu for FileDataPdu<'_, '_> {
|
|
||||||
fn pdu_header(&self) -> &PduHeader {
|
|
||||||
&self.pdu_header
|
|
||||||
}
|
|
||||||
|
|
||||||
fn file_directive_type(&self) -> Option<FileDirectiveType> {
|
/// Write [Self] to the provided buffer and returns the written size.
|
||||||
None
|
pub fn write_to_bytes(&self, buf: &mut [u8]) -> Result<usize, PduError> {
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl WritablePduPacket for FileDataPdu<'_, '_> {
|
|
||||||
fn write_to_bytes(&self, buf: &mut [u8]) -> Result<usize, PduError> {
|
|
||||||
if buf.len() < self.len_written() {
|
if buf.len() < self.len_written() {
|
||||||
return Err(ByteConversionError::ToSliceTooSmall {
|
return Err(ByteConversionError::ToSliceTooSmall {
|
||||||
found: buf.len(),
|
found: buf.len(),
|
||||||
@@ -216,19 +271,8 @@ impl WritablePduPacket for FileDataPdu<'_, '_> {
|
|||||||
}
|
}
|
||||||
.into());
|
.into());
|
||||||
}
|
}
|
||||||
let mut current_idx = self.pdu_header.write_to_bytes(buf)?;
|
|
||||||
if self.segment_metadata.is_some() {
|
let mut current_idx = self.common.write_common_fields_to_bytes(buf)?;
|
||||||
current_idx += self
|
|
||||||
.segment_metadata
|
|
||||||
.as_ref()
|
|
||||||
.unwrap()
|
|
||||||
.write_to_bytes(&mut buf[current_idx..])?;
|
|
||||||
}
|
|
||||||
current_idx += write_fss_field(
|
|
||||||
self.pdu_header.common_pdu_conf().file_flag,
|
|
||||||
self.offset,
|
|
||||||
&mut buf[current_idx..],
|
|
||||||
)?;
|
|
||||||
buf[current_idx..current_idx + self.file_data.len()].copy_from_slice(self.file_data);
|
buf[current_idx..current_idx + self.file_data.len()].copy_from_slice(self.file_data);
|
||||||
current_idx += self.file_data.len();
|
current_idx += self.file_data.len();
|
||||||
if self.crc_flag() == CrcFlag::WithCrc {
|
if self.crc_flag() == CrcFlag::WithCrc {
|
||||||
@@ -237,10 +281,188 @@ impl WritablePduPacket for FileDataPdu<'_, '_> {
|
|||||||
Ok(current_idx)
|
Ok(current_idx)
|
||||||
}
|
}
|
||||||
|
|
||||||
fn len_written(&self) -> usize {
|
pub fn len_written(&self) -> usize {
|
||||||
self.pdu_header.header_len() + self.calc_pdu_datafield_len()
|
self.common.pdu_header.header_len() + self.calc_pdu_datafield_len()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
impl CfdpPdu for FileDataPdu<'_, '_> {
|
||||||
|
#[inline]
|
||||||
|
fn pdu_header(&self) -> &PduHeader {
|
||||||
|
&self.common.pdu_header
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
fn file_directive_type(&self) -> Option<FileDirectiveType> {
|
||||||
|
None
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl WritablePduPacket for FileDataPdu<'_, '_> {
|
||||||
|
fn write_to_bytes(&self, buf: &mut [u8]) -> Result<usize, PduError> {
|
||||||
|
self.write_to_bytes(buf)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn len_written(&self) -> usize {
|
||||||
|
self.len_written()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// File Data PDU creator abstraction.
|
||||||
|
///
|
||||||
|
/// This special creator object allows to read into the file data buffer directly. This avoids
|
||||||
|
/// the need of an additional buffer to create a file data PDU. This structure therefore
|
||||||
|
/// does not implement the regular [WritablePduPacket] trait.
|
||||||
|
///
|
||||||
|
/// For more information, refer to CFDP chapter 5.3.
|
||||||
|
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
|
||||||
|
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
||||||
|
pub struct FileDataPduCreatorWithReservedDatafield<'seg_meta> {
|
||||||
|
#[cfg_attr(feature = "serde", serde(borrow))]
|
||||||
|
common: FdPduBase<'seg_meta>,
|
||||||
|
file_data_len: u64,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<'seg_meta> FileDataPduCreatorWithReservedDatafield<'seg_meta> {
|
||||||
|
pub fn new_with_seg_metadata(
|
||||||
|
pdu_header: PduHeader,
|
||||||
|
segment_metadata: SegmentMetadata<'seg_meta>,
|
||||||
|
offset: u64,
|
||||||
|
file_data_len: u64,
|
||||||
|
) -> Self {
|
||||||
|
Self::new_generic(pdu_header, Some(segment_metadata), offset, file_data_len)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn new_no_seg_metadata(pdu_header: PduHeader, offset: u64, file_data_len: u64) -> Self {
|
||||||
|
Self::new_generic(pdu_header, None, offset, file_data_len)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn new_generic(
|
||||||
|
mut pdu_header: PduHeader,
|
||||||
|
segment_metadata: Option<SegmentMetadata<'seg_meta>>,
|
||||||
|
offset: u64,
|
||||||
|
file_data_len: u64,
|
||||||
|
) -> Self {
|
||||||
|
pdu_header.pdu_type = PduType::FileData;
|
||||||
|
if segment_metadata.is_some() {
|
||||||
|
pdu_header.seg_metadata_flag = SegmentMetadataFlag::Present;
|
||||||
|
}
|
||||||
|
let mut pdu = Self {
|
||||||
|
common: FdPduBase {
|
||||||
|
pdu_header,
|
||||||
|
segment_metadata,
|
||||||
|
offset,
|
||||||
|
},
|
||||||
|
file_data_len,
|
||||||
|
};
|
||||||
|
pdu.common.pdu_header.pdu_datafield_len = pdu.calc_pdu_datafield_len() as u16;
|
||||||
|
pdu
|
||||||
|
}
|
||||||
|
|
||||||
|
fn calc_pdu_datafield_len(&self) -> usize {
|
||||||
|
self.common.calc_pdu_datafield_len(self.file_data_len)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn len_written(&self) -> usize {
|
||||||
|
self.common.pdu_header.header_len() + self.calc_pdu_datafield_len()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// This function performs a partial write by writing all data except the file data
|
||||||
|
/// and the CRC.
|
||||||
|
///
|
||||||
|
/// It returns a [FileDataPduCreatorWithUnwrittenData] which provides a mutable slice to
|
||||||
|
/// the reserved file data field. The user can read file data into this field directly and
|
||||||
|
/// then finish the PDU creation using the [FileDataPduCreatorWithUnwrittenData::finish] call.
|
||||||
|
pub fn write_to_bytes_partially<'buf>(
|
||||||
|
&self,
|
||||||
|
buf: &'buf mut [u8],
|
||||||
|
) -> Result<FileDataPduCreatorWithUnwrittenData<'buf>, PduError> {
|
||||||
|
if buf.len() < self.len_written() {
|
||||||
|
return Err(ByteConversionError::ToSliceTooSmall {
|
||||||
|
found: buf.len(),
|
||||||
|
expected: self.len_written(),
|
||||||
|
}
|
||||||
|
.into());
|
||||||
|
}
|
||||||
|
let mut current_idx = self.common.write_common_fields_to_bytes(buf)?;
|
||||||
|
let file_data_offset = current_idx as u64;
|
||||||
|
current_idx += self.file_data_len as usize;
|
||||||
|
if self.crc_flag() == CrcFlag::WithCrc {
|
||||||
|
current_idx += 2;
|
||||||
|
}
|
||||||
|
Ok(FileDataPduCreatorWithUnwrittenData {
|
||||||
|
write_buf: &mut buf[0..current_idx],
|
||||||
|
file_data_offset,
|
||||||
|
file_data_len: self.file_data_len,
|
||||||
|
needs_crc: self.crc_flag() == CrcFlag::WithCrc,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl CfdpPdu for FileDataPduCreatorWithReservedDatafield<'_> {
|
||||||
|
fn pdu_header(&self) -> &PduHeader {
|
||||||
|
&self.common.pdu_header
|
||||||
|
}
|
||||||
|
|
||||||
|
fn file_directive_type(&self) -> Option<FileDirectiveType> {
|
||||||
|
None
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// This structure is created with [FileDataPduCreatorWithReservedDatafield::write_to_bytes_partially]
|
||||||
|
/// and provides an API to read file data from the virtual filesystem into the file data PDU buffer
|
||||||
|
/// directly.
|
||||||
|
///
|
||||||
|
/// This structure provides a mutable slice to the reserved file data field. The user can read
|
||||||
|
/// file data into this field directly and then finish the PDU creation using the
|
||||||
|
/// [FileDataPduCreatorWithUnwrittenData::finish] call.
|
||||||
|
pub struct FileDataPduCreatorWithUnwrittenData<'buf> {
|
||||||
|
write_buf: &'buf mut [u8],
|
||||||
|
file_data_offset: u64,
|
||||||
|
file_data_len: u64,
|
||||||
|
needs_crc: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl FileDataPduCreatorWithUnwrittenData<'_> {
|
||||||
|
pub fn file_data_field_mut(&mut self) -> &mut [u8] {
|
||||||
|
&mut self.write_buf[self.file_data_offset as usize
|
||||||
|
..self.file_data_offset as usize + self.file_data_len as usize]
|
||||||
|
}
|
||||||
|
|
||||||
|
/// This functio needs to be called to add a CRC to the file data PDU where applicable.
|
||||||
|
///
|
||||||
|
/// It returns the full written size of the PDU.
|
||||||
|
pub fn finish(self) -> usize {
|
||||||
|
if self.needs_crc {
|
||||||
|
add_pdu_crc(
|
||||||
|
self.write_buf,
|
||||||
|
self.file_data_offset as usize + self.file_data_len as usize,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
self.write_buf.len()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// This function can be used to calculate the maximum allowed file segment size for
|
||||||
|
/// a given maximum packet length and the segment metadata if there is any.
|
||||||
|
pub fn calculate_max_file_seg_len_for_max_packet_len_and_pdu_header(
|
||||||
|
pdu_header: &PduHeader,
|
||||||
|
max_packet_len: usize,
|
||||||
|
segment_metadata: Option<&SegmentMetadata>,
|
||||||
|
) -> usize {
|
||||||
|
let mut subtract = pdu_header.header_len();
|
||||||
|
if let Some(segment_metadata) = segment_metadata {
|
||||||
|
subtract += 1 + segment_metadata.metadata().unwrap().len();
|
||||||
|
}
|
||||||
|
if pdu_header.common_pdu_conf().file_flag == LargeFileFlag::Large {
|
||||||
|
subtract += 8;
|
||||||
|
} else {
|
||||||
|
subtract += 4;
|
||||||
|
}
|
||||||
|
if pdu_header.common_pdu_conf().crc_flag == CrcFlag::WithCrc {
|
||||||
|
subtract += 2;
|
||||||
|
}
|
||||||
|
max_packet_len.saturating_sub(subtract)
|
||||||
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
@@ -263,7 +485,7 @@ mod tests {
|
|||||||
assert!(fd_pdu.segment_metadata().is_none());
|
assert!(fd_pdu.segment_metadata().is_none());
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
fd_pdu.len_written(),
|
fd_pdu.len_written(),
|
||||||
fd_pdu.pdu_header.header_len() + core::mem::size_of::<u32>() + 4
|
fd_pdu.pdu_header().header_len() + core::mem::size_of::<u32>() + 4
|
||||||
);
|
);
|
||||||
|
|
||||||
assert_eq!(fd_pdu.crc_flag(), CrcFlag::NoCrc);
|
assert_eq!(fd_pdu.crc_flag(), CrcFlag::NoCrc);
|
||||||
@@ -290,11 +512,11 @@ mod tests {
|
|||||||
let written = res.unwrap();
|
let written = res.unwrap();
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
written,
|
written,
|
||||||
fd_pdu.pdu_header.header_len() + core::mem::size_of::<u32>() + 4
|
fd_pdu.pdu_header().header_len() + core::mem::size_of::<u32>() + 4
|
||||||
);
|
);
|
||||||
let mut current_idx = fd_pdu.pdu_header.header_len();
|
let mut current_idx = fd_pdu.pdu_header().header_len();
|
||||||
let file_size = u32::from_be_bytes(
|
let file_size = u32::from_be_bytes(
|
||||||
buf[fd_pdu.pdu_header.header_len()..fd_pdu.pdu_header.header_len() + 4]
|
buf[fd_pdu.pdu_header().header_len()..fd_pdu.pdu_header().header_len() + 4]
|
||||||
.try_into()
|
.try_into()
|
||||||
.unwrap(),
|
.unwrap(),
|
||||||
);
|
);
|
||||||
@@ -353,7 +575,7 @@ mod tests {
|
|||||||
buf[written - 1] -= 1;
|
buf[written - 1] -= 1;
|
||||||
let crc: u16 = ((buf[written - 2] as u16) << 8) | buf[written - 1] as u16;
|
let crc: u16 = ((buf[written - 2] as u16) << 8) | buf[written - 1] as u16;
|
||||||
let error = FileDataPdu::from_bytes(&buf).unwrap_err();
|
let error = FileDataPdu::from_bytes(&buf).unwrap_err();
|
||||||
if let PduError::ChecksumError(e) = error {
|
if let PduError::Checksum(e) = error {
|
||||||
assert_eq!(e, crc);
|
assert_eq!(e, crc);
|
||||||
} else {
|
} else {
|
||||||
panic!("expected crc error");
|
panic!("expected crc error");
|
||||||
@@ -380,7 +602,7 @@ mod tests {
|
|||||||
assert_eq!(*fd_pdu.segment_metadata().unwrap(), segment_meta);
|
assert_eq!(*fd_pdu.segment_metadata().unwrap(), segment_meta);
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
fd_pdu.len_written(),
|
fd_pdu.len_written(),
|
||||||
fd_pdu.pdu_header.header_len()
|
fd_pdu.pdu_header().header_len()
|
||||||
+ 1
|
+ 1
|
||||||
+ seg_metadata.len()
|
+ seg_metadata.len()
|
||||||
+ core::mem::size_of::<u32>()
|
+ core::mem::size_of::<u32>()
|
||||||
@@ -390,7 +612,7 @@ mod tests {
|
|||||||
fd_pdu
|
fd_pdu
|
||||||
.write_to_bytes(&mut buf)
|
.write_to_bytes(&mut buf)
|
||||||
.expect("writing FD PDU failed");
|
.expect("writing FD PDU failed");
|
||||||
let mut current_idx = fd_pdu.pdu_header.header_len();
|
let mut current_idx = fd_pdu.pdu_header().header_len();
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
RecordContinuationState::try_from((buf[current_idx] >> 6) & 0b11).unwrap(),
|
RecordContinuationState::try_from((buf[current_idx] >> 6) & 0b11).unwrap(),
|
||||||
RecordContinuationState::StartAndEnd
|
RecordContinuationState::StartAndEnd
|
||||||
@@ -482,4 +704,142 @@ mod tests {
|
|||||||
let output_converted_back: FileDataPdu = from_bytes(&output).unwrap();
|
let output_converted_back: FileDataPdu = from_bytes(&output).unwrap();
|
||||||
assert_eq!(output_converted_back, fd_pdu);
|
assert_eq!(output_converted_back, fd_pdu);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_fd_pdu_creator_with_reserved_field_no_crc() {
|
||||||
|
let common_conf =
|
||||||
|
CommonPduConfig::new_with_byte_fields(TEST_SRC_ID, TEST_DEST_ID, TEST_SEQ_NUM).unwrap();
|
||||||
|
let pdu_header = PduHeader::new_for_file_data_default(common_conf, 0);
|
||||||
|
let test_str = "hello world!";
|
||||||
|
let fd_pdu = FileDataPduCreatorWithReservedDatafield::new_no_seg_metadata(
|
||||||
|
pdu_header,
|
||||||
|
10,
|
||||||
|
test_str.len() as u64,
|
||||||
|
);
|
||||||
|
let mut write_buf: [u8; 64] = [0; 64];
|
||||||
|
let mut pdu_unwritten = fd_pdu
|
||||||
|
.write_to_bytes_partially(&mut write_buf)
|
||||||
|
.expect("partial write failed");
|
||||||
|
pdu_unwritten
|
||||||
|
.file_data_field_mut()
|
||||||
|
.copy_from_slice(test_str.as_bytes());
|
||||||
|
pdu_unwritten.finish();
|
||||||
|
|
||||||
|
let pdu_reader = FileDataPdu::from_bytes(&write_buf).expect("reading file data PDU failed");
|
||||||
|
assert_eq!(
|
||||||
|
core::str::from_utf8(pdu_reader.file_data()).expect("reading utf8 string failed"),
|
||||||
|
"hello world!"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_fd_pdu_creator_with_reserved_field_with_crc() {
|
||||||
|
let mut common_conf =
|
||||||
|
CommonPduConfig::new_with_byte_fields(TEST_SRC_ID, TEST_DEST_ID, TEST_SEQ_NUM).unwrap();
|
||||||
|
common_conf.crc_flag = true.into();
|
||||||
|
let pdu_header = PduHeader::new_for_file_data_default(common_conf, 0);
|
||||||
|
let test_str = "hello world!";
|
||||||
|
let fd_pdu = FileDataPduCreatorWithReservedDatafield::new_no_seg_metadata(
|
||||||
|
pdu_header,
|
||||||
|
10,
|
||||||
|
test_str.len() as u64,
|
||||||
|
);
|
||||||
|
let mut write_buf: [u8; 64] = [0; 64];
|
||||||
|
let mut pdu_unwritten = fd_pdu
|
||||||
|
.write_to_bytes_partially(&mut write_buf)
|
||||||
|
.expect("partial write failed");
|
||||||
|
pdu_unwritten
|
||||||
|
.file_data_field_mut()
|
||||||
|
.copy_from_slice(test_str.as_bytes());
|
||||||
|
pdu_unwritten.finish();
|
||||||
|
|
||||||
|
let pdu_reader = FileDataPdu::from_bytes(&write_buf).expect("reading file data PDU failed");
|
||||||
|
assert_eq!(
|
||||||
|
core::str::from_utf8(pdu_reader.file_data()).expect("reading utf8 string failed"),
|
||||||
|
"hello world!"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_fd_pdu_creator_with_reserved_field_with_crc_without_finish_fails() {
|
||||||
|
let mut common_conf =
|
||||||
|
CommonPduConfig::new_with_byte_fields(TEST_SRC_ID, TEST_DEST_ID, TEST_SEQ_NUM).unwrap();
|
||||||
|
common_conf.crc_flag = true.into();
|
||||||
|
let pdu_header = PduHeader::new_for_file_data_default(common_conf, 0);
|
||||||
|
let test_str = "hello world!";
|
||||||
|
let fd_pdu = FileDataPduCreatorWithReservedDatafield::new_no_seg_metadata(
|
||||||
|
pdu_header,
|
||||||
|
10,
|
||||||
|
test_str.len() as u64,
|
||||||
|
);
|
||||||
|
let mut write_buf: [u8; 64] = [0; 64];
|
||||||
|
let mut pdu_unwritten = fd_pdu
|
||||||
|
.write_to_bytes_partially(&mut write_buf)
|
||||||
|
.expect("partial write failed");
|
||||||
|
pdu_unwritten
|
||||||
|
.file_data_field_mut()
|
||||||
|
.copy_from_slice(test_str.as_bytes());
|
||||||
|
|
||||||
|
let pdu_reader_error = FileDataPdu::from_bytes(&write_buf);
|
||||||
|
assert!(pdu_reader_error.is_err());
|
||||||
|
let error = pdu_reader_error.unwrap_err();
|
||||||
|
match error {
|
||||||
|
PduError::Checksum(_) => (),
|
||||||
|
_ => {
|
||||||
|
panic!("unexpected PDU error {}", error)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_max_file_seg_calculator_0() {
|
||||||
|
let pdu_header = PduHeader::new_for_file_data_default(CommonPduConfig::default(), 0);
|
||||||
|
assert_eq!(
|
||||||
|
calculate_max_file_seg_len_for_max_packet_len_and_pdu_header(&pdu_header, 64, None),
|
||||||
|
53
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_max_file_seg_calculator_1() {
|
||||||
|
let common_conf = CommonPduConfig {
|
||||||
|
crc_flag: CrcFlag::WithCrc,
|
||||||
|
..Default::default()
|
||||||
|
};
|
||||||
|
let pdu_header = PduHeader::new_for_file_data_default(common_conf, 0);
|
||||||
|
assert_eq!(
|
||||||
|
calculate_max_file_seg_len_for_max_packet_len_and_pdu_header(&pdu_header, 64, None),
|
||||||
|
51
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_max_file_seg_calculator_2() {
|
||||||
|
let common_conf = CommonPduConfig {
|
||||||
|
file_flag: LargeFileFlag::Large,
|
||||||
|
..Default::default()
|
||||||
|
};
|
||||||
|
let pdu_header = PduHeader::new_for_file_data_default(common_conf, 0);
|
||||||
|
assert_eq!(
|
||||||
|
calculate_max_file_seg_len_for_max_packet_len_and_pdu_header(&pdu_header, 64, None),
|
||||||
|
49
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_max_file_seg_calculator_saturating_sub() {
|
||||||
|
let common_conf = CommonPduConfig {
|
||||||
|
file_flag: LargeFileFlag::Large,
|
||||||
|
..Default::default()
|
||||||
|
};
|
||||||
|
let pdu_header = PduHeader::new_for_file_data_default(common_conf, 0);
|
||||||
|
assert_eq!(
|
||||||
|
calculate_max_file_seg_len_for_max_packet_len_and_pdu_header(&pdu_header, 15, None),
|
||||||
|
0
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
calculate_max_file_seg_len_for_max_packet_len_and_pdu_header(&pdu_header, 14, None),
|
||||||
|
0
|
||||||
|
);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
@@ -4,16 +4,18 @@ use crate::cfdp::pdu::{
|
|||||||
use crate::cfdp::tlv::{
|
use crate::cfdp::tlv::{
|
||||||
EntityIdTlv, FilestoreResponseTlv, GenericTlv, Tlv, TlvType, TlvTypeField, WritableTlv,
|
EntityIdTlv, FilestoreResponseTlv, GenericTlv, Tlv, TlvType, TlvTypeField, WritableTlv,
|
||||||
};
|
};
|
||||||
use crate::cfdp::{ConditionCode, CrcFlag, Direction, PduType, TlvLvError};
|
use crate::cfdp::{ConditionCode, CrcFlag, Direction, PduType};
|
||||||
use crate::ByteConversionError;
|
use crate::ByteConversionError;
|
||||||
use num_enum::{IntoPrimitive, TryFromPrimitive};
|
use num_enum::{IntoPrimitive, TryFromPrimitive};
|
||||||
#[cfg(feature = "serde")]
|
#[cfg(feature = "serde")]
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
use super::{CfdpPdu, WritablePduPacket};
|
use super::tlv::ReadableTlv;
|
||||||
|
use super::{CfdpPdu, InvalidTlvTypeFieldError, WritablePduPacket};
|
||||||
|
|
||||||
#[derive(Debug, Copy, Clone, PartialEq, Eq, TryFromPrimitive, IntoPrimitive)]
|
#[derive(Debug, Copy, Clone, PartialEq, Eq, TryFromPrimitive, IntoPrimitive)]
|
||||||
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
||||||
|
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
|
||||||
#[repr(u8)]
|
#[repr(u8)]
|
||||||
pub enum DeliveryCode {
|
pub enum DeliveryCode {
|
||||||
Complete = 0,
|
Complete = 0,
|
||||||
@@ -22,6 +24,7 @@ pub enum DeliveryCode {
|
|||||||
|
|
||||||
#[derive(Debug, Copy, Clone, PartialEq, Eq, TryFromPrimitive, IntoPrimitive)]
|
#[derive(Debug, Copy, Clone, PartialEq, Eq, TryFromPrimitive, IntoPrimitive)]
|
||||||
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
||||||
|
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
|
||||||
#[repr(u8)]
|
#[repr(u8)]
|
||||||
pub enum FileStatus {
|
pub enum FileStatus {
|
||||||
DiscardDeliberately = 0b00,
|
DiscardDeliberately = 0b00,
|
||||||
@@ -34,6 +37,7 @@ pub enum FileStatus {
|
|||||||
///
|
///
|
||||||
/// For more information, refer to CFDP chapter 5.2.3.
|
/// For more information, refer to CFDP chapter 5.2.3.
|
||||||
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
|
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
|
||||||
|
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
|
||||||
pub struct FinishedPduCreator<'fs_responses> {
|
pub struct FinishedPduCreator<'fs_responses> {
|
||||||
pdu_header: PduHeader,
|
pdu_header: PduHeader,
|
||||||
condition_code: ConditionCode,
|
condition_code: ConditionCode,
|
||||||
@@ -46,12 +50,12 @@ pub struct FinishedPduCreator<'fs_responses> {
|
|||||||
|
|
||||||
impl<'fs_responses> FinishedPduCreator<'fs_responses> {
|
impl<'fs_responses> FinishedPduCreator<'fs_responses> {
|
||||||
/// Default finished PDU: No error (no fault location field) and no filestore responses.
|
/// Default finished PDU: No error (no fault location field) and no filestore responses.
|
||||||
pub fn new_default(
|
pub fn new_no_error(
|
||||||
pdu_header: PduHeader,
|
pdu_header: PduHeader,
|
||||||
delivery_code: DeliveryCode,
|
delivery_code: DeliveryCode,
|
||||||
file_status: FileStatus,
|
file_status: FileStatus,
|
||||||
) -> Self {
|
) -> Self {
|
||||||
Self::new_generic(
|
Self::new(
|
||||||
pdu_header,
|
pdu_header,
|
||||||
ConditionCode::NoError,
|
ConditionCode::NoError,
|
||||||
delivery_code,
|
delivery_code,
|
||||||
@@ -68,7 +72,7 @@ impl<'fs_responses> FinishedPduCreator<'fs_responses> {
|
|||||||
file_status: FileStatus,
|
file_status: FileStatus,
|
||||||
fault_location: EntityIdTlv,
|
fault_location: EntityIdTlv,
|
||||||
) -> Self {
|
) -> Self {
|
||||||
Self::new_generic(
|
Self::new(
|
||||||
pdu_header,
|
pdu_header,
|
||||||
condition_code,
|
condition_code,
|
||||||
delivery_code,
|
delivery_code,
|
||||||
@@ -78,7 +82,7 @@ impl<'fs_responses> FinishedPduCreator<'fs_responses> {
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn new_generic(
|
pub fn new(
|
||||||
mut pdu_header: PduHeader,
|
mut pdu_header: PduHeader,
|
||||||
condition_code: ConditionCode,
|
condition_code: ConditionCode,
|
||||||
delivery_code: DeliveryCode,
|
delivery_code: DeliveryCode,
|
||||||
@@ -105,23 +109,33 @@ impl<'fs_responses> FinishedPduCreator<'fs_responses> {
|
|||||||
finished_pdu
|
finished_pdu
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
pub fn pdu_header(&self) -> &PduHeader {
|
||||||
|
&self.pdu_header
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
pub fn condition_code(&self) -> ConditionCode {
|
pub fn condition_code(&self) -> ConditionCode {
|
||||||
self.condition_code
|
self.condition_code
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
pub fn delivery_code(&self) -> DeliveryCode {
|
pub fn delivery_code(&self) -> DeliveryCode {
|
||||||
self.delivery_code
|
self.delivery_code
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
pub fn file_status(&self) -> FileStatus {
|
pub fn file_status(&self) -> FileStatus {
|
||||||
self.file_status
|
self.file_status
|
||||||
}
|
}
|
||||||
|
|
||||||
// If there are no filestore responses, an empty slice will be returned.
|
// If there are no filestore responses, an empty slice will be returned.
|
||||||
|
#[inline]
|
||||||
pub fn filestore_responses(&self) -> &[FilestoreResponseTlv<'_, '_, '_>] {
|
pub fn filestore_responses(&self) -> &[FilestoreResponseTlv<'_, '_, '_>] {
|
||||||
self.fs_responses
|
self.fs_responses
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
pub fn fault_location(&self) -> Option<EntityIdTlv> {
|
pub fn fault_location(&self) -> Option<EntityIdTlv> {
|
||||||
self.fault_location
|
self.fault_location
|
||||||
}
|
}
|
||||||
@@ -139,20 +153,9 @@ impl<'fs_responses> FinishedPduCreator<'fs_responses> {
|
|||||||
}
|
}
|
||||||
datafield_len
|
datafield_len
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
impl CfdpPdu for FinishedPduCreator<'_> {
|
/// Write [Self] to the provided buffer and returns the written size.
|
||||||
fn pdu_header(&self) -> &PduHeader {
|
pub fn write_to_bytes(&self, buf: &mut [u8]) -> Result<usize, PduError> {
|
||||||
&self.pdu_header
|
|
||||||
}
|
|
||||||
|
|
||||||
fn file_directive_type(&self) -> Option<FileDirectiveType> {
|
|
||||||
Some(FileDirectiveType::FinishedPdu)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl WritablePduPacket for FinishedPduCreator<'_> {
|
|
||||||
fn write_to_bytes(&self, buf: &mut [u8]) -> Result<usize, PduError> {
|
|
||||||
let expected_len = self.len_written();
|
let expected_len = self.len_written();
|
||||||
if buf.len() < expected_len {
|
if buf.len() < expected_len {
|
||||||
return Err(ByteConversionError::ToSliceTooSmall {
|
return Err(ByteConversionError::ToSliceTooSmall {
|
||||||
@@ -181,11 +184,33 @@ impl WritablePduPacket for FinishedPduCreator<'_> {
|
|||||||
Ok(current_idx)
|
Ok(current_idx)
|
||||||
}
|
}
|
||||||
|
|
||||||
fn len_written(&self) -> usize {
|
pub fn len_written(&self) -> usize {
|
||||||
self.pdu_header.header_len() + self.calc_pdu_datafield_len()
|
self.pdu_header.header_len() + self.calc_pdu_datafield_len()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
impl CfdpPdu for FinishedPduCreator<'_> {
|
||||||
|
#[inline]
|
||||||
|
fn pdu_header(&self) -> &PduHeader {
|
||||||
|
self.pdu_header()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
fn file_directive_type(&self) -> Option<FileDirectiveType> {
|
||||||
|
Some(FileDirectiveType::FinishedPdu)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl WritablePduPacket for FinishedPduCreator<'_> {
|
||||||
|
fn write_to_bytes(&self, buf: &mut [u8]) -> Result<usize, PduError> {
|
||||||
|
self.write_to_bytes(buf)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn len_written(&self) -> usize {
|
||||||
|
self.len_written()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// Helper structure to loop through all filestore responses of a read Finished PDU. It should be
|
/// Helper structure to loop through all filestore responses of a read Finished PDU. It should be
|
||||||
/// noted that iterators in Rust are not fallible, but the TLV creation can fail, for example if
|
/// noted that iterators in Rust are not fallible, but the TLV creation can fail, for example if
|
||||||
/// the raw TLV data is invalid for some reason. In that case, the iterator will yield [None]
|
/// the raw TLV data is invalid for some reason. In that case, the iterator will yield [None]
|
||||||
@@ -219,6 +244,7 @@ impl<'buf> Iterator for FilestoreResponseIterator<'buf> {
|
|||||||
|
|
||||||
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
|
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
|
||||||
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
||||||
|
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
|
||||||
pub struct FinishedPduReader<'buf> {
|
pub struct FinishedPduReader<'buf> {
|
||||||
pdu_header: PduHeader,
|
pdu_header: PduHeader,
|
||||||
condition_code: ConditionCode,
|
condition_code: ConditionCode,
|
||||||
@@ -271,10 +297,12 @@ impl<'buf> FinishedPduReader<'buf> {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
pub fn fs_responses_raw(&self) -> &[u8] {
|
pub fn fs_responses_raw(&self) -> &[u8] {
|
||||||
self.fs_responses_raw
|
self.fs_responses_raw
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
pub fn fs_responses_iter(&self) -> FilestoreResponseIterator<'_> {
|
pub fn fs_responses_iter(&self) -> FilestoreResponseIterator<'_> {
|
||||||
FilestoreResponseIterator {
|
FilestoreResponseIterator {
|
||||||
responses_buf: self.fs_responses_raw,
|
responses_buf: self.fs_responses_raw,
|
||||||
@@ -282,22 +310,31 @@ impl<'buf> FinishedPduReader<'buf> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
pub fn condition_code(&self) -> ConditionCode {
|
pub fn condition_code(&self) -> ConditionCode {
|
||||||
self.condition_code
|
self.condition_code
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
pub fn delivery_code(&self) -> DeliveryCode {
|
pub fn delivery_code(&self) -> DeliveryCode {
|
||||||
self.delivery_code
|
self.delivery_code
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
pub fn file_status(&self) -> FileStatus {
|
pub fn file_status(&self) -> FileStatus {
|
||||||
self.file_status
|
self.file_status
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
pub fn fault_location(&self) -> Option<EntityIdTlv> {
|
pub fn fault_location(&self) -> Option<EntityIdTlv> {
|
||||||
self.fault_location
|
self.fault_location
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
pub fn pdu_header(&self) -> &PduHeader {
|
||||||
|
&self.pdu_header
|
||||||
|
}
|
||||||
|
|
||||||
fn parse_tlv_fields(
|
fn parse_tlv_fields(
|
||||||
mut current_idx: usize,
|
mut current_idx: usize,
|
||||||
full_len_without_crc: usize,
|
full_len_without_crc: usize,
|
||||||
@@ -327,22 +364,26 @@ impl<'buf> FinishedPduReader<'buf> {
|
|||||||
// last TLV, everything else would break the whole handling of the packet
|
// last TLV, everything else would break the whole handling of the packet
|
||||||
// TLVs.
|
// TLVs.
|
||||||
if current_idx != full_len_without_crc {
|
if current_idx != full_len_without_crc {
|
||||||
return Err(PduError::FormatError);
|
return Err(PduError::Format);
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
return Err(TlvLvError::InvalidTlvTypeField {
|
return Err(PduError::TlvLv(
|
||||||
found: tlv_type.into(),
|
InvalidTlvTypeFieldError {
|
||||||
expected: Some(TlvType::FilestoreResponse.into()),
|
found: tlv_type.into(),
|
||||||
}
|
expected: Some(TlvType::FilestoreResponse.into()),
|
||||||
.into());
|
}
|
||||||
|
.into(),
|
||||||
|
));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
TlvTypeField::Custom(raw) => {
|
TlvTypeField::Custom(raw) => {
|
||||||
return Err(TlvLvError::InvalidTlvTypeField {
|
return Err(PduError::TlvLv(
|
||||||
found: raw,
|
InvalidTlvTypeFieldError {
|
||||||
expected: None,
|
found: raw,
|
||||||
}
|
expected: None,
|
||||||
.into());
|
}
|
||||||
|
.into(),
|
||||||
|
));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -351,10 +392,12 @@ impl<'buf> FinishedPduReader<'buf> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl CfdpPdu for FinishedPduReader<'_> {
|
impl CfdpPdu for FinishedPduReader<'_> {
|
||||||
|
#[inline]
|
||||||
fn pdu_header(&self) -> &PduHeader {
|
fn pdu_header(&self) -> &PduHeader {
|
||||||
&self.pdu_header
|
self.pdu_header()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
fn file_directive_type(&self) -> Option<FileDirectiveType> {
|
fn file_directive_type(&self) -> Option<FileDirectiveType> {
|
||||||
Some(FileDirectiveType::FinishedPdu)
|
Some(FileDirectiveType::FinishedPdu)
|
||||||
}
|
}
|
||||||
@@ -397,8 +440,8 @@ mod tests {
|
|||||||
delivery_code: DeliveryCode,
|
delivery_code: DeliveryCode,
|
||||||
file_status: FileStatus,
|
file_status: FileStatus,
|
||||||
) -> FinishedPduCreator<'static> {
|
) -> FinishedPduCreator<'static> {
|
||||||
let pdu_header = PduHeader::new_no_file_data(common_pdu_conf(crc_flag, fss), 0);
|
let pdu_header = PduHeader::new_for_file_directive(common_pdu_conf(crc_flag, fss), 0);
|
||||||
FinishedPduCreator::new_default(pdu_header, delivery_code, file_status)
|
FinishedPduCreator::new_no_error(pdu_header, delivery_code, file_status)
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
@@ -559,7 +602,7 @@ mod tests {
|
|||||||
buf[written - 1] -= 1;
|
buf[written - 1] -= 1;
|
||||||
let crc: u16 = ((buf[written - 2] as u16) << 8) as u16 | buf[written - 1] as u16;
|
let crc: u16 = ((buf[written - 2] as u16) << 8) as u16 | buf[written - 1] as u16;
|
||||||
let error = FinishedPduReader::new(&buf).unwrap_err();
|
let error = FinishedPduReader::new(&buf).unwrap_err();
|
||||||
if let PduError::ChecksumError(e) = error {
|
if let PduError::Checksum(e) = error {
|
||||||
assert_eq!(e, crc);
|
assert_eq!(e, crc);
|
||||||
} else {
|
} else {
|
||||||
panic!("expected crc error");
|
panic!("expected crc error");
|
||||||
@@ -568,8 +611,10 @@ mod tests {
|
|||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_with_fault_location() {
|
fn test_with_fault_location() {
|
||||||
let pdu_header =
|
let pdu_header = PduHeader::new_for_file_directive(
|
||||||
PduHeader::new_no_file_data(common_pdu_conf(CrcFlag::NoCrc, LargeFileFlag::Normal), 0);
|
common_pdu_conf(CrcFlag::NoCrc, LargeFileFlag::Normal),
|
||||||
|
0,
|
||||||
|
);
|
||||||
let finished_pdu = FinishedPduCreator::new_with_error(
|
let finished_pdu = FinishedPduCreator::new_with_error(
|
||||||
pdu_header,
|
pdu_header,
|
||||||
ConditionCode::NakLimitReached,
|
ConditionCode::NakLimitReached,
|
||||||
@@ -590,8 +635,10 @@ mod tests {
|
|||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_deserialization_with_fault_location() {
|
fn test_deserialization_with_fault_location() {
|
||||||
let pdu_header =
|
let pdu_header = PduHeader::new_for_file_directive(
|
||||||
PduHeader::new_no_file_data(common_pdu_conf(CrcFlag::NoCrc, LargeFileFlag::Normal), 0);
|
common_pdu_conf(CrcFlag::NoCrc, LargeFileFlag::Normal),
|
||||||
|
0,
|
||||||
|
);
|
||||||
let entity_id_tlv = EntityIdTlv::new(TEST_DEST_ID.into());
|
let entity_id_tlv = EntityIdTlv::new(TEST_DEST_ID.into());
|
||||||
let finished_pdu = FinishedPduCreator::new_with_error(
|
let finished_pdu = FinishedPduCreator::new_with_error(
|
||||||
pdu_header,
|
pdu_header,
|
||||||
@@ -626,9 +673,11 @@ mod tests {
|
|||||||
.unwrap();
|
.unwrap();
|
||||||
let fs_responses = &[fs_response_0, fs_response_1];
|
let fs_responses = &[fs_response_0, fs_response_1];
|
||||||
|
|
||||||
let pdu_header =
|
let pdu_header = PduHeader::new_for_file_directive(
|
||||||
PduHeader::new_no_file_data(common_pdu_conf(CrcFlag::NoCrc, LargeFileFlag::Normal), 0);
|
common_pdu_conf(CrcFlag::NoCrc, LargeFileFlag::Normal),
|
||||||
let finished_pdu = FinishedPduCreator::new_generic(
|
0,
|
||||||
|
);
|
||||||
|
let finished_pdu = FinishedPduCreator::new(
|
||||||
pdu_header,
|
pdu_header,
|
||||||
ConditionCode::NakLimitReached,
|
ConditionCode::NakLimitReached,
|
||||||
DeliveryCode::Incomplete,
|
DeliveryCode::Incomplete,
|
||||||
@@ -661,9 +710,11 @@ mod tests {
|
|||||||
.unwrap();
|
.unwrap();
|
||||||
let fs_responses = &[fs_response_0, fs_response_1];
|
let fs_responses = &[fs_response_0, fs_response_1];
|
||||||
|
|
||||||
let pdu_header =
|
let pdu_header = PduHeader::new_for_file_directive(
|
||||||
PduHeader::new_no_file_data(common_pdu_conf(CrcFlag::NoCrc, LargeFileFlag::Normal), 0);
|
common_pdu_conf(CrcFlag::NoCrc, LargeFileFlag::Normal),
|
||||||
let finished_pdu = FinishedPduCreator::new_generic(
|
0,
|
||||||
|
);
|
||||||
|
let finished_pdu = FinishedPduCreator::new(
|
||||||
pdu_header,
|
pdu_header,
|
||||||
ConditionCode::NakLimitReached,
|
ConditionCode::NakLimitReached,
|
||||||
DeliveryCode::Incomplete,
|
DeliveryCode::Incomplete,
|
||||||
|
@@ -1,3 +1,5 @@
|
|||||||
|
#[cfg(feature = "alloc")]
|
||||||
|
use super::tlv::TlvOwned;
|
||||||
use crate::cfdp::lv::Lv;
|
use crate::cfdp::lv::Lv;
|
||||||
use crate::cfdp::pdu::{
|
use crate::cfdp::pdu::{
|
||||||
add_pdu_crc, generic_length_checks_pdu_deserialization, read_fss_field, write_fss_field,
|
add_pdu_crc, generic_length_checks_pdu_deserialization, read_fss_field, write_fss_field,
|
||||||
@@ -11,10 +13,12 @@ use alloc::vec::Vec;
|
|||||||
#[cfg(feature = "serde")]
|
#[cfg(feature = "serde")]
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
|
use super::tlv::ReadableTlv;
|
||||||
use super::{CfdpPdu, WritablePduPacket};
|
use super::{CfdpPdu, WritablePduPacket};
|
||||||
|
|
||||||
#[derive(Default, Debug, Copy, Clone, PartialEq, Eq)]
|
#[derive(Default, Debug, Copy, Clone, PartialEq, Eq)]
|
||||||
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
||||||
|
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
|
||||||
pub struct MetadataGenericParams {
|
pub struct MetadataGenericParams {
|
||||||
pub closure_requested: bool,
|
pub closure_requested: bool,
|
||||||
pub checksum_type: ChecksumType,
|
pub checksum_type: ChecksumType,
|
||||||
@@ -50,6 +54,15 @@ pub fn build_metadata_opts_from_vec(
|
|||||||
build_metadata_opts_from_slice(buf, tlvs.as_slice())
|
build_metadata_opts_from_slice(buf, tlvs.as_slice())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[cfg(feature = "alloc")]
|
||||||
|
pub fn build_metadata_opts_from_owned_slice(tlvs: &[TlvOwned]) -> Vec<u8> {
|
||||||
|
let mut sum_vec = Vec::new();
|
||||||
|
for tlv in tlvs {
|
||||||
|
sum_vec.extend(tlv.to_vec());
|
||||||
|
}
|
||||||
|
sum_vec
|
||||||
|
}
|
||||||
|
|
||||||
/// Metadata PDU creator abstraction.
|
/// Metadata PDU creator abstraction.
|
||||||
///
|
///
|
||||||
/// This abstraction exposes a specialized API for creating metadata PDUs as specified in
|
/// This abstraction exposes a specialized API for creating metadata PDUs as specified in
|
||||||
@@ -60,7 +73,7 @@ pub struct MetadataPduCreator<'src_name, 'dest_name, 'opts> {
|
|||||||
metadata_params: MetadataGenericParams,
|
metadata_params: MetadataGenericParams,
|
||||||
src_file_name: Lv<'src_name>,
|
src_file_name: Lv<'src_name>,
|
||||||
dest_file_name: Lv<'dest_name>,
|
dest_file_name: Lv<'dest_name>,
|
||||||
options: &'opts [Tlv<'opts>],
|
options: &'opts [u8],
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<'src_name, 'dest_name, 'opts> MetadataPduCreator<'src_name, 'dest_name, 'opts> {
|
impl<'src_name, 'dest_name, 'opts> MetadataPduCreator<'src_name, 'dest_name, 'opts> {
|
||||||
@@ -84,7 +97,7 @@ impl<'src_name, 'dest_name, 'opts> MetadataPduCreator<'src_name, 'dest_name, 'op
|
|||||||
metadata_params: MetadataGenericParams,
|
metadata_params: MetadataGenericParams,
|
||||||
src_file_name: Lv<'src_name>,
|
src_file_name: Lv<'src_name>,
|
||||||
dest_file_name: Lv<'dest_name>,
|
dest_file_name: Lv<'dest_name>,
|
||||||
options: &'opts [Tlv<'opts>],
|
options: &'opts [u8],
|
||||||
) -> Self {
|
) -> Self {
|
||||||
Self::new(
|
Self::new(
|
||||||
pdu_header,
|
pdu_header,
|
||||||
@@ -100,7 +113,7 @@ impl<'src_name, 'dest_name, 'opts> MetadataPduCreator<'src_name, 'dest_name, 'op
|
|||||||
metadata_params: MetadataGenericParams,
|
metadata_params: MetadataGenericParams,
|
||||||
src_file_name: Lv<'src_name>,
|
src_file_name: Lv<'src_name>,
|
||||||
dest_file_name: Lv<'dest_name>,
|
dest_file_name: Lv<'dest_name>,
|
||||||
options: &'opts [Tlv<'opts>],
|
options: &'opts [u8],
|
||||||
) -> Self {
|
) -> Self {
|
||||||
pdu_header.pdu_type = PduType::FileDirective;
|
pdu_header.pdu_type = PduType::FileDirective;
|
||||||
pdu_header.pdu_conf.direction = Direction::TowardsReceiver;
|
pdu_header.pdu_conf.direction = Direction::TowardsReceiver;
|
||||||
@@ -115,22 +128,40 @@ impl<'src_name, 'dest_name, 'opts> MetadataPduCreator<'src_name, 'dest_name, 'op
|
|||||||
pdu
|
pdu
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
pub fn metadata_params(&self) -> &MetadataGenericParams {
|
pub fn metadata_params(&self) -> &MetadataGenericParams {
|
||||||
&self.metadata_params
|
&self.metadata_params
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
pub fn src_file_name(&self) -> Lv<'src_name> {
|
pub fn src_file_name(&self) -> Lv<'src_name> {
|
||||||
self.src_file_name
|
self.src_file_name
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
pub fn dest_file_name(&self) -> Lv<'dest_name> {
|
pub fn dest_file_name(&self) -> Lv<'dest_name> {
|
||||||
self.dest_file_name
|
self.dest_file_name
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn options(&self) -> &'opts [Tlv<'opts>] {
|
#[inline]
|
||||||
|
pub fn pdu_header(&self) -> &PduHeader {
|
||||||
|
&self.pdu_header
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
pub fn options(&self) -> &'opts [u8] {
|
||||||
self.options
|
self.options
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Yield an iterator which can be used to loop through all options. Returns [None] if the
|
||||||
|
/// options field is empty.
|
||||||
|
pub fn options_iter(&self) -> OptionsIter<'_> {
|
||||||
|
OptionsIter {
|
||||||
|
opt_buf: self.options,
|
||||||
|
current_idx: 0,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
fn calc_pdu_datafield_len(&self) -> usize {
|
fn calc_pdu_datafield_len(&self) -> usize {
|
||||||
// One directve type octet and one byte of the directive parameter field.
|
// One directve type octet and one byte of the directive parameter field.
|
||||||
let mut len = 2;
|
let mut len = 2;
|
||||||
@@ -141,28 +172,15 @@ impl<'src_name, 'dest_name, 'opts> MetadataPduCreator<'src_name, 'dest_name, 'op
|
|||||||
}
|
}
|
||||||
len += self.src_file_name.len_full();
|
len += self.src_file_name.len_full();
|
||||||
len += self.dest_file_name.len_full();
|
len += self.dest_file_name.len_full();
|
||||||
for tlv in self.options() {
|
len += self.options().len();
|
||||||
len += tlv.len_full()
|
|
||||||
}
|
|
||||||
if self.crc_flag() == CrcFlag::WithCrc {
|
if self.crc_flag() == CrcFlag::WithCrc {
|
||||||
len += 2;
|
len += 2;
|
||||||
}
|
}
|
||||||
len
|
len
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
impl CfdpPdu for MetadataPduCreator<'_, '_, '_> {
|
/// Write [Self] to the provided buffer and returns the written size.
|
||||||
fn pdu_header(&self) -> &PduHeader {
|
pub fn write_to_bytes(&self, buf: &mut [u8]) -> Result<usize, PduError> {
|
||||||
&self.pdu_header
|
|
||||||
}
|
|
||||||
|
|
||||||
fn file_directive_type(&self) -> Option<FileDirectiveType> {
|
|
||||||
Some(FileDirectiveType::MetadataPdu)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl WritablePduPacket for MetadataPduCreator<'_, '_, '_> {
|
|
||||||
fn write_to_bytes(&self, buf: &mut [u8]) -> Result<usize, PduError> {
|
|
||||||
let expected_len = self.len_written();
|
let expected_len = self.len_written();
|
||||||
if buf.len() < expected_len {
|
if buf.len() < expected_len {
|
||||||
return Err(ByteConversionError::ToSliceTooSmall {
|
return Err(ByteConversionError::ToSliceTooSmall {
|
||||||
@@ -189,21 +207,41 @@ impl WritablePduPacket for MetadataPduCreator<'_, '_, '_> {
|
|||||||
current_idx += self
|
current_idx += self
|
||||||
.dest_file_name
|
.dest_file_name
|
||||||
.write_to_be_bytes(&mut buf[current_idx..])?;
|
.write_to_be_bytes(&mut buf[current_idx..])?;
|
||||||
for opt in self.options() {
|
buf[current_idx..current_idx + self.options.len()].copy_from_slice(self.options);
|
||||||
opt.write_to_bytes(&mut buf[current_idx..current_idx + opt.len_full()])?;
|
current_idx += self.options.len();
|
||||||
current_idx += opt.len_full();
|
|
||||||
}
|
|
||||||
if self.crc_flag() == CrcFlag::WithCrc {
|
if self.crc_flag() == CrcFlag::WithCrc {
|
||||||
current_idx = add_pdu_crc(buf, current_idx);
|
current_idx = add_pdu_crc(buf, current_idx);
|
||||||
}
|
}
|
||||||
Ok(current_idx)
|
Ok(current_idx)
|
||||||
}
|
}
|
||||||
|
|
||||||
fn len_written(&self) -> usize {
|
pub fn len_written(&self) -> usize {
|
||||||
self.pdu_header.header_len() + self.calc_pdu_datafield_len()
|
self.pdu_header.header_len() + self.calc_pdu_datafield_len()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
impl CfdpPdu for MetadataPduCreator<'_, '_, '_> {
|
||||||
|
#[inline]
|
||||||
|
fn pdu_header(&self) -> &PduHeader {
|
||||||
|
self.pdu_header()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
fn file_directive_type(&self) -> Option<FileDirectiveType> {
|
||||||
|
Some(FileDirectiveType::MetadataPdu)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl WritablePduPacket for MetadataPduCreator<'_, '_, '_> {
|
||||||
|
fn write_to_bytes(&self, buf: &mut [u8]) -> Result<usize, PduError> {
|
||||||
|
self.write_to_bytes(buf)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn len_written(&self) -> usize {
|
||||||
|
self.len_written()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// Helper structure to loop through all options of a metadata PDU. It should be noted that
|
/// Helper structure to loop through all options of a metadata PDU. It should be noted that
|
||||||
/// iterators in Rust are not fallible, but the TLV creation can fail, for example if the raw TLV
|
/// iterators in Rust are not fallible, but the TLV creation can fail, for example if the raw TLV
|
||||||
/// data is invalid for some reason. In that case, the iterator will yield [None] because there
|
/// data is invalid for some reason. In that case, the iterator will yield [None] because there
|
||||||
@@ -241,6 +279,7 @@ impl<'opts> Iterator for OptionsIter<'opts> {
|
|||||||
/// involved.
|
/// involved.
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
||||||
|
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
|
||||||
pub struct MetadataPduReader<'buf> {
|
pub struct MetadataPduReader<'buf> {
|
||||||
pdu_header: PduHeader,
|
pdu_header: PduHeader,
|
||||||
metadata_params: MetadataGenericParams,
|
metadata_params: MetadataGenericParams,
|
||||||
@@ -311,26 +350,36 @@ impl<'raw> MetadataPduReader<'raw> {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
pub fn pdu_header(&self) -> &PduHeader {
|
||||||
|
&self.pdu_header
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
pub fn options(&self) -> &'raw [u8] {
|
pub fn options(&self) -> &'raw [u8] {
|
||||||
self.options
|
self.options
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
pub fn metadata_params(&self) -> &MetadataGenericParams {
|
pub fn metadata_params(&self) -> &MetadataGenericParams {
|
||||||
&self.metadata_params
|
&self.metadata_params
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn src_file_name(&self) -> Lv {
|
#[inline]
|
||||||
|
pub fn src_file_name(&self) -> Lv<'_> {
|
||||||
self.src_file_name
|
self.src_file_name
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn dest_file_name(&self) -> Lv {
|
#[inline]
|
||||||
|
pub fn dest_file_name(&self) -> Lv<'_> {
|
||||||
self.dest_file_name
|
self.dest_file_name
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl CfdpPdu for MetadataPduReader<'_> {
|
impl CfdpPdu for MetadataPduReader<'_> {
|
||||||
|
#[inline]
|
||||||
fn pdu_header(&self) -> &PduHeader {
|
fn pdu_header(&self) -> &PduHeader {
|
||||||
&self.pdu_header
|
self.pdu_header()
|
||||||
}
|
}
|
||||||
|
|
||||||
fn file_directive_type(&self) -> Option<FileDirectiveType> {
|
fn file_directive_type(&self) -> Option<FileDirectiveType> {
|
||||||
@@ -352,7 +401,7 @@ pub mod tests {
|
|||||||
};
|
};
|
||||||
use crate::cfdp::pdu::{CfdpPdu, PduError, WritablePduPacket};
|
use crate::cfdp::pdu::{CfdpPdu, PduError, WritablePduPacket};
|
||||||
use crate::cfdp::pdu::{FileDirectiveType, PduHeader};
|
use crate::cfdp::pdu::{FileDirectiveType, PduHeader};
|
||||||
use crate::cfdp::tlv::{Tlv, TlvType};
|
use crate::cfdp::tlv::{ReadableTlv, Tlv, TlvOwned, TlvType, WritableTlv};
|
||||||
use crate::cfdp::{
|
use crate::cfdp::{
|
||||||
ChecksumType, CrcFlag, Direction, LargeFileFlag, PduType, SegmentMetadataFlag,
|
ChecksumType, CrcFlag, Direction, LargeFileFlag, PduType, SegmentMetadataFlag,
|
||||||
SegmentationControl, TransmissionMode,
|
SegmentationControl, TransmissionMode,
|
||||||
@@ -362,18 +411,18 @@ pub mod tests {
|
|||||||
const SRC_FILENAME: &str = "hello-world.txt";
|
const SRC_FILENAME: &str = "hello-world.txt";
|
||||||
const DEST_FILENAME: &str = "hello-world2.txt";
|
const DEST_FILENAME: &str = "hello-world2.txt";
|
||||||
|
|
||||||
fn generic_metadata_pdu<'opts>(
|
fn generic_metadata_pdu(
|
||||||
crc_flag: CrcFlag,
|
crc_flag: CrcFlag,
|
||||||
checksum_type: ChecksumType,
|
checksum_type: ChecksumType,
|
||||||
closure_requested: bool,
|
closure_requested: bool,
|
||||||
fss: LargeFileFlag,
|
fss: LargeFileFlag,
|
||||||
opts: &'opts [Tlv],
|
opts: &[u8],
|
||||||
) -> (
|
) -> (
|
||||||
Lv<'static>,
|
Lv<'static>,
|
||||||
Lv<'static>,
|
Lv<'static>,
|
||||||
MetadataPduCreator<'static, 'static, 'opts>,
|
MetadataPduCreator<'static, 'static, '_>,
|
||||||
) {
|
) {
|
||||||
let pdu_header = PduHeader::new_no_file_data(common_pdu_conf(crc_flag, fss), 0);
|
let pdu_header = PduHeader::new_for_file_directive(common_pdu_conf(crc_flag, fss), 0);
|
||||||
let metadata_params = MetadataGenericParams::new(closure_requested, checksum_type, 0x1010);
|
let metadata_params = MetadataGenericParams::new(closure_requested, checksum_type, 0x1010);
|
||||||
let src_filename = Lv::new_from_str(SRC_FILENAME).expect("Generating string LV failed");
|
let src_filename = Lv::new_from_str(SRC_FILENAME).expect("Generating string LV failed");
|
||||||
let dest_filename =
|
let dest_filename =
|
||||||
@@ -541,9 +590,9 @@ pub mod tests {
|
|||||||
assert_eq!(written.metadata_params(), read.metadata_params());
|
assert_eq!(written.metadata_params(), read.metadata_params());
|
||||||
assert_eq!(written.src_file_name(), read.src_file_name());
|
assert_eq!(written.src_file_name(), read.src_file_name());
|
||||||
assert_eq!(written.dest_file_name(), read.dest_file_name());
|
assert_eq!(written.dest_file_name(), read.dest_file_name());
|
||||||
let opts = written.options();
|
let opts = written.options_iter();
|
||||||
for (tlv_written, tlv_read) in opts.iter().zip(read.options_iter().unwrap()) {
|
for (tlv_written, tlv_read) in opts.zip(read.options_iter().unwrap()) {
|
||||||
assert_eq!(tlv_written, &tlv_read);
|
assert_eq!(&tlv_written, &tlv_read);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -658,14 +707,14 @@ pub mod tests {
|
|||||||
let tlv1 = Tlv::new_empty(TlvType::FlowLabel);
|
let tlv1 = Tlv::new_empty(TlvType::FlowLabel);
|
||||||
let msg_to_user: [u8; 4] = [1, 2, 3, 4];
|
let msg_to_user: [u8; 4] = [1, 2, 3, 4];
|
||||||
let tlv2 = Tlv::new(TlvType::MsgToUser, &msg_to_user).unwrap();
|
let tlv2 = Tlv::new(TlvType::MsgToUser, &msg_to_user).unwrap();
|
||||||
let tlv_vec = vec![tlv1, tlv2];
|
let mut tlv_buf: [u8; 64] = [0; 64];
|
||||||
let opts_len = tlv1.len_full() + tlv2.len_full();
|
let opts_len = build_metadata_opts_from_slice(&mut tlv_buf, &[tlv1, tlv2]).unwrap();
|
||||||
let (src_filename, dest_filename, metadata_pdu) = generic_metadata_pdu(
|
let (src_filename, dest_filename, metadata_pdu) = generic_metadata_pdu(
|
||||||
CrcFlag::NoCrc,
|
CrcFlag::NoCrc,
|
||||||
ChecksumType::Crc32,
|
ChecksumType::Crc32,
|
||||||
false,
|
false,
|
||||||
LargeFileFlag::Normal,
|
LargeFileFlag::Normal,
|
||||||
&tlv_vec,
|
&tlv_buf[0..opts_len],
|
||||||
);
|
);
|
||||||
let mut buf: [u8; 128] = [0; 128];
|
let mut buf: [u8; 128] = [0; 128];
|
||||||
let write_res = metadata_pdu.write_to_bytes(&mut buf);
|
let write_res = metadata_pdu.write_to_bytes(&mut buf);
|
||||||
@@ -688,7 +737,55 @@ pub mod tests {
|
|||||||
let opts_iter = opts_iter.unwrap();
|
let opts_iter = opts_iter.unwrap();
|
||||||
let mut accumulated_len = 0;
|
let mut accumulated_len = 0;
|
||||||
for (idx, opt) in opts_iter.enumerate() {
|
for (idx, opt) in opts_iter.enumerate() {
|
||||||
assert_eq!(tlv_vec[idx], opt);
|
if idx == 0 {
|
||||||
|
assert_eq!(tlv1, opt);
|
||||||
|
} else if idx == 1 {
|
||||||
|
assert_eq!(tlv2, opt);
|
||||||
|
}
|
||||||
|
accumulated_len += opt.len_full();
|
||||||
|
}
|
||||||
|
assert_eq!(accumulated_len, pdu_read_back.options().len());
|
||||||
|
}
|
||||||
|
#[test]
|
||||||
|
fn test_with_owned_opts() {
|
||||||
|
let tlv1 = TlvOwned::new_empty(TlvType::FlowLabel);
|
||||||
|
let msg_to_user: [u8; 4] = [1, 2, 3, 4];
|
||||||
|
let tlv2 = TlvOwned::new(TlvType::MsgToUser, &msg_to_user);
|
||||||
|
let mut all_tlvs = tlv1.to_vec();
|
||||||
|
all_tlvs.extend(tlv2.to_vec());
|
||||||
|
let (src_filename, dest_filename, metadata_pdu) = generic_metadata_pdu(
|
||||||
|
CrcFlag::NoCrc,
|
||||||
|
ChecksumType::Crc32,
|
||||||
|
false,
|
||||||
|
LargeFileFlag::Normal,
|
||||||
|
&all_tlvs,
|
||||||
|
);
|
||||||
|
let mut buf: [u8; 128] = [0; 128];
|
||||||
|
let write_res = metadata_pdu.write_to_bytes(&mut buf);
|
||||||
|
assert!(write_res.is_ok());
|
||||||
|
let written = write_res.unwrap();
|
||||||
|
assert_eq!(
|
||||||
|
written,
|
||||||
|
metadata_pdu.pdu_header.header_len()
|
||||||
|
+ 1
|
||||||
|
+ 1
|
||||||
|
+ 4
|
||||||
|
+ src_filename.len_full()
|
||||||
|
+ dest_filename.len_full()
|
||||||
|
+ all_tlvs.len()
|
||||||
|
);
|
||||||
|
let pdu_read_back = MetadataPduReader::from_bytes(&buf).unwrap();
|
||||||
|
compare_read_pdu_to_written_pdu(&metadata_pdu, &pdu_read_back);
|
||||||
|
let opts_iter = pdu_read_back.options_iter();
|
||||||
|
assert!(opts_iter.is_some());
|
||||||
|
let opts_iter = opts_iter.unwrap();
|
||||||
|
let mut accumulated_len = 0;
|
||||||
|
for (idx, opt) in opts_iter.enumerate() {
|
||||||
|
if idx == 0 {
|
||||||
|
assert_eq!(tlv1, opt);
|
||||||
|
} else if idx == 1 {
|
||||||
|
assert_eq!(tlv2, opt);
|
||||||
|
}
|
||||||
accumulated_len += opt.len_full();
|
accumulated_len += opt.len_full();
|
||||||
}
|
}
|
||||||
assert_eq!(accumulated_len, pdu_read_back.options().len());
|
assert_eq!(accumulated_len, pdu_read_back.options().len());
|
||||||
@@ -713,7 +810,7 @@ pub mod tests {
|
|||||||
assert_eq!(expected, Some(FileDirectiveType::MetadataPdu));
|
assert_eq!(expected, Some(FileDirectiveType::MetadataPdu));
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
error.to_string(),
|
error.to_string(),
|
||||||
"invalid directive type value 255, expected Some(MetadataPdu)"
|
"invalid directive type, found 255, expected Some(MetadataPdu)"
|
||||||
);
|
);
|
||||||
} else {
|
} else {
|
||||||
panic!("Expected InvalidDirectiveType error, got {:?}", error);
|
panic!("Expected InvalidDirectiveType error, got {:?}", error);
|
||||||
@@ -739,7 +836,7 @@ pub mod tests {
|
|||||||
assert_eq!(expected, FileDirectiveType::MetadataPdu);
|
assert_eq!(expected, FileDirectiveType::MetadataPdu);
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
error.to_string(),
|
error.to_string(),
|
||||||
"found directive type EofPdu, expected MetadataPdu"
|
"wrong directive type, found EofPdu, expected MetadataPdu"
|
||||||
);
|
);
|
||||||
} else {
|
} else {
|
||||||
panic!("Expected InvalidDirectiveType error, got {:?}", error);
|
panic!("Expected InvalidDirectiveType error, got {:?}", error);
|
||||||
|
@@ -1,13 +1,12 @@
|
|||||||
//! CFDP Packet Data Unit (PDU) support.
|
//! CFDP Packet Data Unit (PDU) support.
|
||||||
|
use crate::cfdp::pdu::ack::InvalidAckedDirectiveCodeError;
|
||||||
|
use crate::cfdp::pdu::nak::InvalidStartOrEndOfScopeError;
|
||||||
use crate::cfdp::*;
|
use crate::cfdp::*;
|
||||||
|
use crate::crc::CRC_CCITT_FALSE;
|
||||||
use crate::util::{UnsignedByteField, UnsignedByteFieldU8, UnsignedEnum};
|
use crate::util::{UnsignedByteField, UnsignedByteFieldU8, UnsignedEnum};
|
||||||
use crate::ByteConversionError;
|
use crate::ByteConversionError;
|
||||||
use crate::CRC_CCITT_FALSE;
|
|
||||||
#[cfg(feature = "alloc")]
|
#[cfg(feature = "alloc")]
|
||||||
use alloc::vec::Vec;
|
use alloc::vec::Vec;
|
||||||
use core::fmt::{Display, Formatter};
|
|
||||||
#[cfg(feature = "std")]
|
|
||||||
use std::error::Error;
|
|
||||||
|
|
||||||
pub mod ack;
|
pub mod ack;
|
||||||
pub mod eof;
|
pub mod eof;
|
||||||
@@ -18,6 +17,7 @@ pub mod nak;
|
|||||||
|
|
||||||
#[derive(Debug, Copy, Clone, PartialEq, Eq, TryFromPrimitive, IntoPrimitive)]
|
#[derive(Debug, Copy, Clone, PartialEq, Eq, TryFromPrimitive, IntoPrimitive)]
|
||||||
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
||||||
|
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
|
||||||
#[repr(u8)]
|
#[repr(u8)]
|
||||||
pub enum FileDirectiveType {
|
pub enum FileDirectiveType {
|
||||||
EofPdu = 0x04,
|
EofPdu = 0x04,
|
||||||
@@ -29,137 +29,73 @@ pub enum FileDirectiveType {
|
|||||||
KeepAlivePdu = 0x0c,
|
KeepAlivePdu = 0x0c,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
|
#[derive(Debug, Copy, Clone, PartialEq, Eq, thiserror::Error)]
|
||||||
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
||||||
|
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
|
||||||
pub enum PduError {
|
pub enum PduError {
|
||||||
ByteConversion(ByteConversionError),
|
#[error("byte conversion error: {0}")]
|
||||||
/// Found version ID invalid, not equal to [CFDP_VERSION_2].
|
ByteConversion(#[from] ByteConversionError),
|
||||||
|
/// Found version ID invalid, not equal to [super::CFDP_VERSION_2].
|
||||||
|
#[error("CFDP version missmatch, found {0}, expected {ver}", ver = super::CFDP_VERSION_2)]
|
||||||
CfdpVersionMissmatch(u8),
|
CfdpVersionMissmatch(u8),
|
||||||
/// Invalid length for the entity ID detected. Only the values 1, 2, 4 and 8 are supported.
|
/// Invalid length for the entity ID detected. Only the values 1, 2, 4 and 8 are supported.
|
||||||
|
#[error("invalid PDU entity ID length {0}, only [1, 2, 4, 8] are allowed")]
|
||||||
InvalidEntityLen(u8),
|
InvalidEntityLen(u8),
|
||||||
/// Invalid length for the entity ID detected. Only the values 1, 2, 4 and 8 are supported.
|
/// Invalid length for the entity ID detected. Only the values 1, 2, 4 and 8 are supported.
|
||||||
|
#[error("invalid transaction ID length {0}")]
|
||||||
InvalidTransactionSeqNumLen(u8),
|
InvalidTransactionSeqNumLen(u8),
|
||||||
|
#[error(
|
||||||
|
"missmatch of PDU source ID length {src_id_len} and destination ID length {dest_id_len}"
|
||||||
|
)]
|
||||||
SourceDestIdLenMissmatch {
|
SourceDestIdLenMissmatch {
|
||||||
src_id_len: usize,
|
src_id_len: usize,
|
||||||
dest_id_len: usize,
|
dest_id_len: usize,
|
||||||
},
|
},
|
||||||
/// Wrong directive type, for example when parsing the directive field for a file directive
|
/// Wrong directive type, for example when parsing the directive field for a file directive
|
||||||
/// PDU.
|
/// PDU.
|
||||||
|
#[error("wrong directive type, found {found:?}, expected {expected:?}")]
|
||||||
WrongDirectiveType {
|
WrongDirectiveType {
|
||||||
found: FileDirectiveType,
|
found: FileDirectiveType,
|
||||||
expected: FileDirectiveType,
|
expected: FileDirectiveType,
|
||||||
},
|
},
|
||||||
/// The directive type field contained a value not in the range of permitted values. This can
|
/// The directive type field contained a value not in the range of permitted values. This can
|
||||||
/// also happen if an invalid value is passed to the ACK PDU constructor.
|
/// also happen if an invalid value is passed to the ACK PDU reader.
|
||||||
|
#[error("invalid directive type, found {found:?}, expected {expected:?}")]
|
||||||
InvalidDirectiveType {
|
InvalidDirectiveType {
|
||||||
found: u8,
|
found: u8,
|
||||||
expected: Option<FileDirectiveType>,
|
expected: Option<FileDirectiveType>,
|
||||||
},
|
},
|
||||||
InvalidStartOrEndOfScopeValue,
|
#[error("nak pdu: {0}")]
|
||||||
|
InvalidStartOrEndOfScope(#[from] InvalidStartOrEndOfScopeError),
|
||||||
/// Invalid condition code. Contains the raw detected value.
|
/// Invalid condition code. Contains the raw detected value.
|
||||||
|
#[error("invalid condition code {0}")]
|
||||||
InvalidConditionCode(u8),
|
InvalidConditionCode(u8),
|
||||||
/// Invalid checksum type which is not part of the checksums listed in the
|
/// Invalid checksum type which is not part of the checksums listed in the
|
||||||
/// [SANA Checksum Types registry](https://sanaregistry.org/r/checksum_identifiers/).
|
/// [SANA Checksum Types registry](https://sanaregistry.org/r/checksum_identifiers/).
|
||||||
|
#[error("invalid checksum type {0}")]
|
||||||
InvalidChecksumType(u8),
|
InvalidChecksumType(u8),
|
||||||
|
#[error("file size {0} too large")]
|
||||||
FileSizeTooLarge(u64),
|
FileSizeTooLarge(u64),
|
||||||
/// If the CRC flag for a PDU is enabled and the checksum check fails. Contains raw 16-bit CRC.
|
/// If the CRC flag for a PDU is enabled and the checksum check fails. Contains raw 16-bit CRC.
|
||||||
ChecksumError(u16),
|
#[error("checksum error for checksum {0}")]
|
||||||
|
Checksum(u16),
|
||||||
/// Generic error for invalid PDU formats.
|
/// Generic error for invalid PDU formats.
|
||||||
FormatError,
|
#[error("generic PDU format error")]
|
||||||
|
Format,
|
||||||
/// Error handling a TLV field.
|
/// Error handling a TLV field.
|
||||||
TlvLvError(TlvLvError),
|
#[error("PDU error: {0}")]
|
||||||
|
TlvLv(#[from] TlvLvError),
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Display for PduError {
|
impl From<InvalidAckedDirectiveCodeError> for PduError {
|
||||||
fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
|
fn from(value: InvalidAckedDirectiveCodeError) -> Self {
|
||||||
match self {
|
Self::InvalidDirectiveType {
|
||||||
PduError::InvalidEntityLen(raw_id) => {
|
found: value.0 as u8,
|
||||||
write!(
|
expected: None,
|
||||||
f,
|
|
||||||
"invalid PDU entity ID length {raw_id}, only [1, 2, 4, 8] are allowed"
|
|
||||||
)
|
|
||||||
}
|
|
||||||
PduError::InvalidStartOrEndOfScopeValue => {
|
|
||||||
write!(f, "invalid start or end of scope for NAK PDU")
|
|
||||||
}
|
|
||||||
PduError::InvalidTransactionSeqNumLen(raw_id) => {
|
|
||||||
write!(
|
|
||||||
f,
|
|
||||||
"invalid PDUtransaction seq num length {raw_id}, only [1, 2, 4, 8] are allowed"
|
|
||||||
)
|
|
||||||
}
|
|
||||||
PduError::CfdpVersionMissmatch(raw) => {
|
|
||||||
write!(
|
|
||||||
f,
|
|
||||||
"cfdp version missmatch, found {raw}, expected {CFDP_VERSION_2}"
|
|
||||||
)
|
|
||||||
}
|
|
||||||
PduError::SourceDestIdLenMissmatch {
|
|
||||||
src_id_len,
|
|
||||||
dest_id_len,
|
|
||||||
} => {
|
|
||||||
write!(
|
|
||||||
f,
|
|
||||||
"missmatch of PDU source length {src_id_len} and destination length {dest_id_len}"
|
|
||||||
)
|
|
||||||
}
|
|
||||||
PduError::ByteConversion(e) => {
|
|
||||||
write!(f, "{}", e)
|
|
||||||
}
|
|
||||||
PduError::FileSizeTooLarge(value) => {
|
|
||||||
write!(f, "file size value {value} exceeds allowed 32 bit width")
|
|
||||||
}
|
|
||||||
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 } => {
|
|
||||||
write!(
|
|
||||||
f,
|
|
||||||
"invalid directive type value {found}, expected {expected:?}"
|
|
||||||
)
|
|
||||||
}
|
|
||||||
PduError::InvalidChecksumType(checksum_type) => {
|
|
||||||
write!(f, "invalid checksum type {checksum_type}")
|
|
||||||
}
|
|
||||||
PduError::ChecksumError(checksum) => {
|
|
||||||
write!(f, "checksum error for CRC {checksum:#04x}")
|
|
||||||
}
|
|
||||||
PduError::TlvLvError(error) => {
|
|
||||||
write!(f, "pdu tlv error: {error}")
|
|
||||||
}
|
|
||||||
PduError::FormatError => {
|
|
||||||
write!(f, "generic PDU format error")
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(feature = "std")]
|
|
||||||
impl Error for PduError {
|
|
||||||
fn source(&self) -> Option<&(dyn Error + 'static)> {
|
|
||||||
match self {
|
|
||||||
PduError::ByteConversion(e) => Some(e),
|
|
||||||
PduError::TlvLvError(e) => Some(e),
|
|
||||||
_ => None,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl From<ByteConversionError> for PduError {
|
|
||||||
fn from(value: ByteConversionError) -> Self {
|
|
||||||
Self::ByteConversion(value)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl From<TlvLvError> for PduError {
|
|
||||||
fn from(e: TlvLvError) -> Self {
|
|
||||||
Self::TlvLvError(e)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub trait WritablePduPacket {
|
pub trait WritablePduPacket {
|
||||||
fn len_written(&self) -> usize;
|
fn len_written(&self) -> usize;
|
||||||
fn write_to_bytes(&self, buf: &mut [u8]) -> Result<usize, PduError>;
|
fn write_to_bytes(&self, buf: &mut [u8]) -> Result<usize, PduError>;
|
||||||
@@ -178,33 +114,42 @@ pub trait WritablePduPacket {
|
|||||||
pub trait CfdpPdu {
|
pub trait CfdpPdu {
|
||||||
fn pdu_header(&self) -> &PduHeader;
|
fn pdu_header(&self) -> &PduHeader;
|
||||||
|
|
||||||
|
#[inline]
|
||||||
fn source_id(&self) -> UnsignedByteField {
|
fn source_id(&self) -> UnsignedByteField {
|
||||||
self.pdu_header().common_pdu_conf().source_entity_id
|
self.pdu_header().common_pdu_conf().source_entity_id
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
fn dest_id(&self) -> UnsignedByteField {
|
fn dest_id(&self) -> UnsignedByteField {
|
||||||
self.pdu_header().common_pdu_conf().dest_entity_id
|
self.pdu_header().common_pdu_conf().dest_entity_id
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
fn transaction_seq_num(&self) -> UnsignedByteField {
|
fn transaction_seq_num(&self) -> UnsignedByteField {
|
||||||
self.pdu_header().common_pdu_conf().transaction_seq_num
|
self.pdu_header().common_pdu_conf().transaction_seq_num
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
fn transmission_mode(&self) -> TransmissionMode {
|
fn transmission_mode(&self) -> TransmissionMode {
|
||||||
self.pdu_header().common_pdu_conf().trans_mode
|
self.pdu_header().common_pdu_conf().trans_mode
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
fn direction(&self) -> Direction {
|
fn direction(&self) -> Direction {
|
||||||
self.pdu_header().common_pdu_conf().direction
|
self.pdu_header().common_pdu_conf().direction
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
fn crc_flag(&self) -> CrcFlag {
|
fn crc_flag(&self) -> CrcFlag {
|
||||||
self.pdu_header().common_pdu_conf().crc_flag
|
self.pdu_header().common_pdu_conf().crc_flag
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
fn file_flag(&self) -> LargeFileFlag {
|
fn file_flag(&self) -> LargeFileFlag {
|
||||||
self.pdu_header().common_pdu_conf().file_flag
|
self.pdu_header().common_pdu_conf().file_flag
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
fn pdu_type(&self) -> PduType {
|
fn pdu_type(&self) -> PduType {
|
||||||
self.pdu_header().pdu_type()
|
self.pdu_header().pdu_type()
|
||||||
}
|
}
|
||||||
@@ -220,6 +165,7 @@ pub trait CfdpPdu {
|
|||||||
/// same.
|
/// same.
|
||||||
#[derive(Debug, Copy, Clone, Eq)]
|
#[derive(Debug, Copy, Clone, Eq)]
|
||||||
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
||||||
|
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
|
||||||
pub struct CommonPduConfig {
|
pub struct CommonPduConfig {
|
||||||
source_entity_id: UnsignedByteField,
|
source_entity_id: UnsignedByteField,
|
||||||
dest_entity_id: UnsignedByteField,
|
dest_entity_id: UnsignedByteField,
|
||||||
@@ -232,6 +178,7 @@ pub struct CommonPduConfig {
|
|||||||
|
|
||||||
// TODO: Builder pattern might be applicable here..
|
// TODO: Builder pattern might be applicable here..
|
||||||
impl CommonPduConfig {
|
impl CommonPduConfig {
|
||||||
|
#[inline]
|
||||||
pub fn new(
|
pub fn new(
|
||||||
source_id: impl Into<UnsignedByteField>,
|
source_id: impl Into<UnsignedByteField>,
|
||||||
dest_id: impl Into<UnsignedByteField>,
|
dest_id: impl Into<UnsignedByteField>,
|
||||||
@@ -263,6 +210,7 @@ impl CommonPduConfig {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
pub fn new_with_byte_fields(
|
pub fn new_with_byte_fields(
|
||||||
source_id: impl Into<UnsignedByteField>,
|
source_id: impl Into<UnsignedByteField>,
|
||||||
dest_id: impl Into<UnsignedByteField>,
|
dest_id: impl Into<UnsignedByteField>,
|
||||||
@@ -279,10 +227,12 @@ impl CommonPduConfig {
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
pub fn source_id(&self) -> UnsignedByteField {
|
pub fn source_id(&self) -> UnsignedByteField {
|
||||||
self.source_entity_id
|
self.source_entity_id
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
fn source_dest_id_check(
|
fn source_dest_id_check(
|
||||||
source_id: impl Into<UnsignedByteField>,
|
source_id: impl Into<UnsignedByteField>,
|
||||||
dest_id: impl Into<UnsignedByteField>,
|
dest_id: impl Into<UnsignedByteField>,
|
||||||
@@ -305,6 +255,7 @@ impl CommonPduConfig {
|
|||||||
Ok((source_id, dest_id))
|
Ok((source_id, dest_id))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
pub fn set_source_and_dest_id(
|
pub fn set_source_and_dest_id(
|
||||||
&mut self,
|
&mut self,
|
||||||
source_id: impl Into<UnsignedByteField>,
|
source_id: impl Into<UnsignedByteField>,
|
||||||
@@ -316,6 +267,7 @@ impl CommonPduConfig {
|
|||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
pub fn dest_id(&self) -> UnsignedByteField {
|
pub fn dest_id(&self) -> UnsignedByteField {
|
||||||
self.dest_entity_id
|
self.dest_entity_id
|
||||||
}
|
}
|
||||||
@@ -324,6 +276,7 @@ impl CommonPduConfig {
|
|||||||
impl Default for CommonPduConfig {
|
impl Default for CommonPduConfig {
|
||||||
/// The defaults for the source ID, destination ID and the transaction sequence number is the
|
/// The defaults for the source ID, destination ID and the transaction sequence number is the
|
||||||
/// [UnsignedByteFieldU8] with an intitial value of 0
|
/// [UnsignedByteFieldU8] with an intitial value of 0
|
||||||
|
#[inline]
|
||||||
fn default() -> Self {
|
fn default() -> Self {
|
||||||
// The new function can not fail for these input parameters.
|
// The new function can not fail for these input parameters.
|
||||||
Self::new(
|
Self::new(
|
||||||
@@ -340,6 +293,7 @@ impl Default for CommonPduConfig {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl PartialEq for CommonPduConfig {
|
impl PartialEq for CommonPduConfig {
|
||||||
|
#[inline]
|
||||||
fn eq(&self, other: &Self) -> bool {
|
fn eq(&self, other: &Self) -> bool {
|
||||||
self.source_entity_id.value() == other.source_entity_id.value()
|
self.source_entity_id.value() == other.source_entity_id.value()
|
||||||
&& self.dest_entity_id.value() == other.dest_entity_id.value()
|
&& self.dest_entity_id.value() == other.dest_entity_id.value()
|
||||||
@@ -358,6 +312,7 @@ pub const FIXED_HEADER_LEN: usize = 4;
|
|||||||
/// For detailed information, refer to chapter 5.1 of the CFDP standard.
|
/// For detailed information, refer to chapter 5.1 of the CFDP standard.
|
||||||
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
|
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
|
||||||
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
||||||
|
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
|
||||||
pub struct PduHeader {
|
pub struct PduHeader {
|
||||||
pdu_type: PduType,
|
pdu_type: PduType,
|
||||||
pdu_conf: CommonPduConfig,
|
pdu_conf: CommonPduConfig,
|
||||||
@@ -367,6 +322,9 @@ pub struct PduHeader {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl PduHeader {
|
impl PduHeader {
|
||||||
|
pub const FIXED_LEN: usize = FIXED_HEADER_LEN;
|
||||||
|
|
||||||
|
#[inline]
|
||||||
pub fn new_for_file_data(
|
pub fn new_for_file_data(
|
||||||
pdu_conf: CommonPduConfig,
|
pdu_conf: CommonPduConfig,
|
||||||
pdu_datafield_len: u16,
|
pdu_datafield_len: u16,
|
||||||
@@ -382,6 +340,7 @@ impl PduHeader {
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
pub fn new_for_file_data_default(pdu_conf: CommonPduConfig, pdu_datafield_len: u16) -> Self {
|
pub fn new_for_file_data_default(pdu_conf: CommonPduConfig, pdu_datafield_len: u16) -> Self {
|
||||||
Self::new_generic(
|
Self::new_generic(
|
||||||
PduType::FileData,
|
PduType::FileData,
|
||||||
@@ -391,7 +350,9 @@ impl PduHeader {
|
|||||||
SegmentationControl::NoRecordBoundaryPreservation,
|
SegmentationControl::NoRecordBoundaryPreservation,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
pub fn new_no_file_data(pdu_conf: CommonPduConfig, pdu_datafield_len: u16) -> Self {
|
|
||||||
|
#[inline]
|
||||||
|
pub fn new_for_file_directive(pdu_conf: CommonPduConfig, pdu_datafield_len: u16) -> Self {
|
||||||
Self::new_generic(
|
Self::new_generic(
|
||||||
PduType::FileDirective,
|
PduType::FileDirective,
|
||||||
pdu_conf,
|
pdu_conf,
|
||||||
@@ -401,6 +362,18 @@ impl PduHeader {
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
pub fn from_pdu_conf_for_file_directive(pdu_conf: CommonPduConfig) -> Self {
|
||||||
|
Self::new_generic(
|
||||||
|
PduType::FileDirective,
|
||||||
|
pdu_conf,
|
||||||
|
0,
|
||||||
|
SegmentMetadataFlag::NotPresent,
|
||||||
|
SegmentationControl::NoRecordBoundaryPreservation,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
pub fn new_generic(
|
pub fn new_generic(
|
||||||
pdu_type: PduType,
|
pdu_type: PduType,
|
||||||
pdu_conf: CommonPduConfig,
|
pdu_conf: CommonPduConfig,
|
||||||
@@ -418,6 +391,7 @@ impl PduHeader {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Returns only the length of the PDU header when written to a raw buffer.
|
/// Returns only the length of the PDU header when written to a raw buffer.
|
||||||
|
#[inline]
|
||||||
pub fn header_len(&self) -> usize {
|
pub fn header_len(&self) -> usize {
|
||||||
FIXED_HEADER_LEN
|
FIXED_HEADER_LEN
|
||||||
+ self.pdu_conf.source_entity_id.size()
|
+ self.pdu_conf.source_entity_id.size()
|
||||||
@@ -425,25 +399,26 @@ impl PduHeader {
|
|||||||
+ self.pdu_conf.dest_entity_id.size()
|
+ self.pdu_conf.dest_entity_id.size()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
pub fn pdu_datafield_len(&self) -> usize {
|
pub fn pdu_datafield_len(&self) -> usize {
|
||||||
self.pdu_datafield_len.into()
|
self.pdu_datafield_len.into()
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Returns the full length of the PDU when written to a raw buffer, which is the header length
|
/// Returns the full length of the PDU when written to a raw buffer, which is the header length
|
||||||
/// plus the PDU datafield length.
|
/// plus the PDU datafield length.
|
||||||
|
#[inline]
|
||||||
pub fn pdu_len(&self) -> usize {
|
pub fn pdu_len(&self) -> usize {
|
||||||
self.header_len() + self.pdu_datafield_len as usize
|
self.header_len() + self.pdu_datafield_len as usize
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn write_to_bytes(&self, buf: &mut [u8]) -> Result<usize, PduError> {
|
pub fn write_to_bytes(&self, buf: &mut [u8]) -> Result<usize, ByteConversionError> {
|
||||||
// Internal note: There is currently no way to pass a PDU configuration like this, but
|
// The API does not allow passing entity IDs with different sizes, so this should
|
||||||
// this check is still kept for defensive programming.
|
// never happen.
|
||||||
if self.pdu_conf.source_entity_id.size() != self.pdu_conf.dest_entity_id.size() {
|
assert_eq!(
|
||||||
return Err(PduError::SourceDestIdLenMissmatch {
|
self.pdu_conf.source_entity_id.size(),
|
||||||
src_id_len: self.pdu_conf.source_entity_id.size(),
|
self.pdu_conf.dest_entity_id.size(),
|
||||||
dest_id_len: self.pdu_conf.dest_entity_id.size(),
|
"unexpected missmatch of source and destination entity ID length"
|
||||||
});
|
);
|
||||||
}
|
|
||||||
if buf.len()
|
if buf.len()
|
||||||
< FIXED_HEADER_LEN
|
< FIXED_HEADER_LEN
|
||||||
+ self.pdu_conf.source_entity_id.size()
|
+ self.pdu_conf.source_entity_id.size()
|
||||||
@@ -452,8 +427,7 @@ impl PduHeader {
|
|||||||
return Err(ByteConversionError::ToSliceTooSmall {
|
return Err(ByteConversionError::ToSliceTooSmall {
|
||||||
found: buf.len(),
|
found: buf.len(),
|
||||||
expected: FIXED_HEADER_LEN,
|
expected: FIXED_HEADER_LEN,
|
||||||
}
|
});
|
||||||
.into());
|
|
||||||
}
|
}
|
||||||
let mut current_idx = 0;
|
let mut current_idx = 0;
|
||||||
buf[current_idx] = (CFDP_VERSION_2 << 5)
|
buf[current_idx] = (CFDP_VERSION_2 << 5)
|
||||||
@@ -503,7 +477,7 @@ impl PduHeader {
|
|||||||
let mut digest = CRC_CCITT_FALSE.digest();
|
let mut digest = CRC_CCITT_FALSE.digest();
|
||||||
digest.update(&buf[..self.pdu_len()]);
|
digest.update(&buf[..self.pdu_len()]);
|
||||||
if digest.finalize() != 0 {
|
if digest.finalize() != 0 {
|
||||||
return Err(PduError::ChecksumError(u16::from_be_bytes(
|
return Err(PduError::Checksum(u16::from_be_bytes(
|
||||||
buf[self.pdu_len() - 2..self.pdu_len()].try_into().unwrap(),
|
buf[self.pdu_len() - 2..self.pdu_len()].try_into().unwrap(),
|
||||||
)));
|
)));
|
||||||
}
|
}
|
||||||
@@ -603,17 +577,23 @@ impl PduHeader {
|
|||||||
current_idx,
|
current_idx,
|
||||||
))
|
))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
pub fn pdu_type(&self) -> PduType {
|
pub fn pdu_type(&self) -> PduType {
|
||||||
self.pdu_type
|
self.pdu_type
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
pub fn common_pdu_conf(&self) -> &CommonPduConfig {
|
pub fn common_pdu_conf(&self) -> &CommonPduConfig {
|
||||||
&self.pdu_conf
|
&self.pdu_conf
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
pub fn seg_metadata_flag(&self) -> SegmentMetadataFlag {
|
pub fn seg_metadata_flag(&self) -> SegmentMetadataFlag {
|
||||||
self.seg_metadata_flag
|
self.seg_metadata_flag
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
pub fn seg_ctrl(&self) -> SegmentationControl {
|
pub fn seg_ctrl(&self) -> SegmentationControl {
|
||||||
self.seg_ctrl
|
self.seg_ctrl
|
||||||
}
|
}
|
||||||
@@ -778,7 +758,7 @@ mod tests {
|
|||||||
let transaction_id = UnsignedByteFieldU8::new(3);
|
let transaction_id = UnsignedByteFieldU8::new(3);
|
||||||
let common_pdu_cfg = CommonPduConfig::new_with_byte_fields(src_id, dest_id, transaction_id)
|
let common_pdu_cfg = CommonPduConfig::new_with_byte_fields(src_id, dest_id, transaction_id)
|
||||||
.expect("common config creation failed");
|
.expect("common config creation failed");
|
||||||
let pdu_header = PduHeader::new_no_file_data(common_pdu_cfg, 5);
|
let pdu_header = PduHeader::new_for_file_directive(common_pdu_cfg, 5);
|
||||||
assert_eq!(pdu_header.pdu_type(), PduType::FileDirective);
|
assert_eq!(pdu_header.pdu_type(), PduType::FileDirective);
|
||||||
let common_conf_ref = pdu_header.common_pdu_conf();
|
let common_conf_ref = pdu_header.common_pdu_conf();
|
||||||
assert_eq!(*common_conf_ref, common_pdu_cfg);
|
assert_eq!(*common_conf_ref, common_pdu_cfg);
|
||||||
@@ -844,7 +824,7 @@ mod tests {
|
|||||||
let transaction_id = UnsignedByteFieldU8::new(3);
|
let transaction_id = UnsignedByteFieldU8::new(3);
|
||||||
let common_pdu_cfg = CommonPduConfig::new_with_byte_fields(src_id, dest_id, transaction_id)
|
let common_pdu_cfg = CommonPduConfig::new_with_byte_fields(src_id, dest_id, transaction_id)
|
||||||
.expect("common config creation failed");
|
.expect("common config creation failed");
|
||||||
let pdu_header = PduHeader::new_no_file_data(common_pdu_cfg, 5);
|
let pdu_header = PduHeader::new_for_file_directive(common_pdu_cfg, 5);
|
||||||
let mut buf: [u8; 7] = [0; 7];
|
let mut buf: [u8; 7] = [0; 7];
|
||||||
let res = pdu_header.write_to_bytes(&mut buf);
|
let res = pdu_header.write_to_bytes(&mut buf);
|
||||||
assert!(res.is_ok());
|
assert!(res.is_ok());
|
||||||
@@ -861,7 +841,7 @@ mod tests {
|
|||||||
let transaction_id = UnsignedByteFieldU8::new(3);
|
let transaction_id = UnsignedByteFieldU8::new(3);
|
||||||
let common_pdu_cfg = CommonPduConfig::new_with_byte_fields(src_id, dest_id, transaction_id)
|
let common_pdu_cfg = CommonPduConfig::new_with_byte_fields(src_id, dest_id, transaction_id)
|
||||||
.expect("common config creation failed");
|
.expect("common config creation failed");
|
||||||
let pdu_header = PduHeader::new_no_file_data(common_pdu_cfg, 5);
|
let pdu_header = PduHeader::new_for_file_directive(common_pdu_cfg, 5);
|
||||||
let mut buf: [u8; 7] = [0; 7];
|
let mut buf: [u8; 7] = [0; 7];
|
||||||
let res = pdu_header.write_to_bytes(&mut buf);
|
let res = pdu_header.write_to_bytes(&mut buf);
|
||||||
assert!(res.is_ok());
|
assert!(res.is_ok());
|
||||||
@@ -934,7 +914,7 @@ mod tests {
|
|||||||
let transaction_id = UnsignedByteFieldU8::new(3);
|
let transaction_id = UnsignedByteFieldU8::new(3);
|
||||||
let common_pdu_cfg = CommonPduConfig::new_with_byte_fields(src_id, dest_id, transaction_id)
|
let common_pdu_cfg = CommonPduConfig::new_with_byte_fields(src_id, dest_id, transaction_id)
|
||||||
.expect("common config creation failed");
|
.expect("common config creation failed");
|
||||||
let pdu_header = PduHeader::new_no_file_data(common_pdu_cfg, 5);
|
let pdu_header = PduHeader::new_for_file_directive(common_pdu_cfg, 5);
|
||||||
let mut buf: [u8; 7] = [0; 7];
|
let mut buf: [u8; 7] = [0; 7];
|
||||||
let res = pdu_header.write_to_bytes(&mut buf);
|
let res = pdu_header.write_to_bytes(&mut buf);
|
||||||
assert!(res.is_ok());
|
assert!(res.is_ok());
|
||||||
@@ -947,7 +927,7 @@ mod tests {
|
|||||||
assert_eq!(raw_version, CFDP_VERSION_2 + 1);
|
assert_eq!(raw_version, CFDP_VERSION_2 + 1);
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
error.to_string(),
|
error.to_string(),
|
||||||
"cfdp version missmatch, found 2, expected 1"
|
"CFDP version missmatch, found 2, expected 1"
|
||||||
);
|
);
|
||||||
} else {
|
} else {
|
||||||
panic!("invalid exception: {}", error);
|
panic!("invalid exception: {}", error);
|
||||||
@@ -979,7 +959,7 @@ mod tests {
|
|||||||
let transaction_id = UnsignedByteFieldU8::new(3);
|
let transaction_id = UnsignedByteFieldU8::new(3);
|
||||||
let common_pdu_cfg = CommonPduConfig::new_with_byte_fields(src_id, dest_id, transaction_id)
|
let common_pdu_cfg = CommonPduConfig::new_with_byte_fields(src_id, dest_id, transaction_id)
|
||||||
.expect("common config creation failed");
|
.expect("common config creation failed");
|
||||||
let pdu_header = PduHeader::new_no_file_data(common_pdu_cfg, 5);
|
let pdu_header = PduHeader::new_for_file_directive(common_pdu_cfg, 5);
|
||||||
let mut buf: [u8; 7] = [0; 7];
|
let mut buf: [u8; 7] = [0; 7];
|
||||||
let res = pdu_header.write_to_bytes(&mut buf);
|
let res = pdu_header.write_to_bytes(&mut buf);
|
||||||
assert!(res.is_ok());
|
assert!(res.is_ok());
|
||||||
@@ -995,7 +975,7 @@ mod tests {
|
|||||||
assert_eq!(expected, 7);
|
assert_eq!(expected, 7);
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
error.to_string(),
|
error.to_string(),
|
||||||
"source slice with size 6 too small, expected at least 7 bytes"
|
"byte conversion error: source slice with size 6 too small, expected at least 7 bytes"
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1050,7 +1030,7 @@ mod tests {
|
|||||||
assert_eq!(dest_id_len, 2);
|
assert_eq!(dest_id_len, 2);
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
error.to_string(),
|
error.to_string(),
|
||||||
"missmatch of PDU source length 1 and destination length 2"
|
"missmatch of PDU source ID length 1 and destination ID length 2"
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1062,7 +1042,7 @@ mod tests {
|
|||||||
let transaction_id = UnsignedByteFieldU8::new(3);
|
let transaction_id = UnsignedByteFieldU8::new(3);
|
||||||
let common_pdu_cfg = CommonPduConfig::new_with_byte_fields(src_id, dest_id, transaction_id)
|
let common_pdu_cfg = CommonPduConfig::new_with_byte_fields(src_id, dest_id, transaction_id)
|
||||||
.expect("common config creation failed");
|
.expect("common config creation failed");
|
||||||
let pdu_header = PduHeader::new_no_file_data(common_pdu_cfg, 5);
|
let pdu_header = PduHeader::new_for_file_directive(common_pdu_cfg, 5);
|
||||||
let mut buf: [u8; 7] = [0; 7];
|
let mut buf: [u8; 7] = [0; 7];
|
||||||
let res = pdu_header.write_to_bytes(&mut buf);
|
let res = pdu_header.write_to_bytes(&mut buf);
|
||||||
assert!(res.is_ok());
|
assert!(res.is_ok());
|
||||||
@@ -1086,7 +1066,7 @@ mod tests {
|
|||||||
let transaction_id = UnsignedByteFieldU8::new(3);
|
let transaction_id = UnsignedByteFieldU8::new(3);
|
||||||
let common_pdu_cfg = CommonPduConfig::new_with_byte_fields(src_id, dest_id, transaction_id)
|
let common_pdu_cfg = CommonPduConfig::new_with_byte_fields(src_id, dest_id, transaction_id)
|
||||||
.expect("common config creation failed");
|
.expect("common config creation failed");
|
||||||
let pdu_header = PduHeader::new_no_file_data(common_pdu_cfg, 5);
|
let pdu_header = PduHeader::new_for_file_directive(common_pdu_cfg, 5);
|
||||||
let mut buf: [u8; 7] = [0; 7];
|
let mut buf: [u8; 7] = [0; 7];
|
||||||
let res = pdu_header.write_to_bytes(&mut buf);
|
let res = pdu_header.write_to_bytes(&mut buf);
|
||||||
assert!(res.is_ok());
|
assert!(res.is_ok());
|
||||||
@@ -1118,4 +1098,12 @@ mod tests {
|
|||||||
let common_pdu_cfg_1 = common_pdu_cfg_0;
|
let common_pdu_cfg_1 = common_pdu_cfg_0;
|
||||||
assert_eq!(common_pdu_cfg_0, common_pdu_cfg_1);
|
assert_eq!(common_pdu_cfg_0, common_pdu_cfg_1);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_ctor_from_pdu_conf() {
|
||||||
|
assert_eq!(
|
||||||
|
PduHeader::from_pdu_conf_for_file_directive(CommonPduConfig::default()),
|
||||||
|
PduHeader::new_for_file_directive(CommonPduConfig::default(), 0)
|
||||||
|
);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
1021
src/cfdp/pdu/nak.rs
1021
src/cfdp/pdu/nak.rs
File diff suppressed because it is too large
Load Diff
@@ -9,10 +9,14 @@ use crate::ByteConversionError;
|
|||||||
use alloc::vec;
|
use alloc::vec;
|
||||||
#[cfg(feature = "alloc")]
|
#[cfg(feature = "alloc")]
|
||||||
use alloc::vec::Vec;
|
use alloc::vec::Vec;
|
||||||
|
#[cfg(feature = "alloc")]
|
||||||
|
pub use alloc_mod::*;
|
||||||
use num_enum::{IntoPrimitive, TryFromPrimitive};
|
use num_enum::{IntoPrimitive, TryFromPrimitive};
|
||||||
#[cfg(feature = "serde")]
|
#[cfg(feature = "serde")]
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
|
use super::{InvalidTlvTypeFieldError, TlvLvDataTooLargeError};
|
||||||
|
|
||||||
pub mod msg_to_user;
|
pub mod msg_to_user;
|
||||||
|
|
||||||
pub const MIN_TLV_LEN: usize = 2;
|
pub const MIN_TLV_LEN: usize = 2;
|
||||||
@@ -22,6 +26,7 @@ pub trait GenericTlv {
|
|||||||
|
|
||||||
/// Checks whether the type field contains one of the standard types specified in the CFDP
|
/// Checks whether the type field contains one of the standard types specified in the CFDP
|
||||||
/// standard and is part of the [TlvType] enum.
|
/// standard and is part of the [TlvType] enum.
|
||||||
|
#[inline]
|
||||||
fn is_standard_tlv(&self) -> bool {
|
fn is_standard_tlv(&self) -> bool {
|
||||||
if let TlvTypeField::Standard(_) = self.tlv_type_field() {
|
if let TlvTypeField::Standard(_) = self.tlv_type_field() {
|
||||||
return true;
|
return true;
|
||||||
@@ -30,6 +35,7 @@ pub trait GenericTlv {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Returns the standard TLV type if the TLV field is not a custom field
|
/// Returns the standard TLV type if the TLV field is not a custom field
|
||||||
|
#[inline]
|
||||||
fn tlv_type(&self) -> Option<TlvType> {
|
fn tlv_type(&self) -> Option<TlvType> {
|
||||||
if let TlvTypeField::Standard(tlv_type) = self.tlv_type_field() {
|
if let TlvTypeField::Standard(tlv_type) = self.tlv_type_field() {
|
||||||
Some(tlv_type)
|
Some(tlv_type)
|
||||||
@@ -39,6 +45,29 @@ pub trait GenericTlv {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub trait ReadableTlv {
|
||||||
|
fn value(&self) -> &[u8];
|
||||||
|
|
||||||
|
/// Checks whether the value field is empty.
|
||||||
|
#[inline]
|
||||||
|
fn is_empty(&self) -> bool {
|
||||||
|
self.value().is_empty()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Helper method to retrieve the length of the value. Simply calls the [slice::len] method of
|
||||||
|
/// [Self::value]
|
||||||
|
#[inline]
|
||||||
|
fn len_value(&self) -> usize {
|
||||||
|
self.value().len()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Returns the full raw length, including the length byte.
|
||||||
|
#[inline]
|
||||||
|
fn len_full(&self) -> usize {
|
||||||
|
self.len_value() + 2
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
pub trait WritableTlv {
|
pub trait WritableTlv {
|
||||||
fn write_to_bytes(&self, buf: &mut [u8]) -> Result<usize, ByteConversionError>;
|
fn write_to_bytes(&self, buf: &mut [u8]) -> Result<usize, ByteConversionError>;
|
||||||
fn len_written(&self) -> usize;
|
fn len_written(&self) -> usize;
|
||||||
@@ -52,6 +81,7 @@ pub trait WritableTlv {
|
|||||||
|
|
||||||
#[derive(Debug, Copy, Clone, PartialEq, Eq, TryFromPrimitive, IntoPrimitive)]
|
#[derive(Debug, Copy, Clone, PartialEq, Eq, TryFromPrimitive, IntoPrimitive)]
|
||||||
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
||||||
|
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
|
||||||
#[repr(u8)]
|
#[repr(u8)]
|
||||||
pub enum TlvType {
|
pub enum TlvType {
|
||||||
FilestoreRequest = 0x00,
|
FilestoreRequest = 0x00,
|
||||||
@@ -64,6 +94,7 @@ pub enum TlvType {
|
|||||||
|
|
||||||
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
|
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
|
||||||
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
||||||
|
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
|
||||||
pub enum TlvTypeField {
|
pub enum TlvTypeField {
|
||||||
Standard(TlvType),
|
Standard(TlvType),
|
||||||
Custom(u8),
|
Custom(u8),
|
||||||
@@ -71,6 +102,7 @@ pub enum TlvTypeField {
|
|||||||
|
|
||||||
#[derive(Debug, Copy, Clone, PartialEq, Eq, TryFromPrimitive, IntoPrimitive)]
|
#[derive(Debug, Copy, Clone, PartialEq, Eq, TryFromPrimitive, IntoPrimitive)]
|
||||||
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
||||||
|
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
|
||||||
#[repr(u8)]
|
#[repr(u8)]
|
||||||
pub enum FilestoreActionCode {
|
pub enum FilestoreActionCode {
|
||||||
CreateFile = 0b0000,
|
CreateFile = 0b0000,
|
||||||
@@ -118,6 +150,7 @@ impl From<TlvTypeField> for u8 {
|
|||||||
/// this will be the lifetime of that data reference.
|
/// this will be the lifetime of that data reference.
|
||||||
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
|
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
|
||||||
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
||||||
|
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
|
||||||
pub struct Tlv<'data> {
|
pub struct Tlv<'data> {
|
||||||
tlv_type_field: TlvTypeField,
|
tlv_type_field: TlvTypeField,
|
||||||
#[cfg_attr(feature = "serde", serde(borrow))]
|
#[cfg_attr(feature = "serde", serde(borrow))]
|
||||||
@@ -125,14 +158,19 @@ pub struct Tlv<'data> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl<'data> Tlv<'data> {
|
impl<'data> Tlv<'data> {
|
||||||
pub fn new(tlv_type: TlvType, data: &[u8]) -> Result<Tlv, TlvLvError> {
|
pub const MIN_LEN: usize = MIN_TLV_LEN;
|
||||||
|
|
||||||
|
pub fn new(tlv_type: TlvType, data: &[u8]) -> Result<Tlv<'_>, TlvLvDataTooLargeError> {
|
||||||
Ok(Tlv {
|
Ok(Tlv {
|
||||||
tlv_type_field: TlvTypeField::Standard(tlv_type),
|
tlv_type_field: TlvTypeField::Standard(tlv_type),
|
||||||
lv: Lv::new(data)?,
|
lv: Lv::new(data)?,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn new_with_custom_type(tlv_type: u8, data: &[u8]) -> Result<Tlv, TlvLvError> {
|
pub fn new_with_custom_type(
|
||||||
|
tlv_type: u8,
|
||||||
|
data: &[u8],
|
||||||
|
) -> Result<Tlv<'_>, TlvLvDataTooLargeError> {
|
||||||
Ok(Tlv {
|
Ok(Tlv {
|
||||||
tlv_type_field: TlvTypeField::Custom(tlv_type),
|
tlv_type_field: TlvTypeField::Custom(tlv_type),
|
||||||
lv: Lv::new(data)?,
|
lv: Lv::new(data)?,
|
||||||
@@ -147,31 +185,11 @@ impl<'data> Tlv<'data> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn value(&self) -> &[u8] {
|
|
||||||
self.lv.value()
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Checks whether the value field is empty.
|
|
||||||
pub fn is_empty(&self) -> bool {
|
|
||||||
self.value().is_empty()
|
|
||||||
}
|
|
||||||
|
|
||||||
/// 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.value().len()
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Returns the full raw length, including the length byte.
|
|
||||||
pub fn len_full(&self) -> usize {
|
|
||||||
self.len_value() + 2
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Creates a TLV give a raw bytestream. Please note that is is not necessary to pass the
|
/// Creates a TLV give a raw bytestream. Please note that is is not necessary to pass the
|
||||||
/// bytestream with the exact size of the expected TLV. This function will take care
|
/// bytestream with the exact size of the expected TLV. This function will take care
|
||||||
/// of parsing the length byte, and the length of the parsed TLV can be retrieved using
|
/// of parsing the length byte, and the length of the parsed TLV can be retrieved using
|
||||||
/// [Self::len_full].
|
/// [Self::len_full].
|
||||||
pub fn from_bytes(buf: &'data [u8]) -> Result<Tlv<'data>, TlvLvError> {
|
pub fn from_bytes(buf: &'data [u8]) -> Result<Tlv<'data>, ByteConversionError> {
|
||||||
generic_len_check_deserialization(buf, MIN_TLV_LEN)?;
|
generic_len_check_deserialization(buf, MIN_TLV_LEN)?;
|
||||||
let mut tlv = Self {
|
let mut tlv = Self {
|
||||||
tlv_type_field: TlvTypeField::from(buf[0]),
|
tlv_type_field: TlvTypeField::from(buf[0]),
|
||||||
@@ -185,9 +203,31 @@ impl<'data> Tlv<'data> {
|
|||||||
|
|
||||||
/// If the TLV was generated from a raw bytestream using [Self::from_bytes], the raw start
|
/// 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.
|
/// of the TLV can be retrieved with this method.
|
||||||
|
#[inline]
|
||||||
pub fn raw_data(&self) -> Option<&[u8]> {
|
pub fn raw_data(&self) -> Option<&[u8]> {
|
||||||
self.lv.raw_data()
|
self.lv.raw_data()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[cfg(feature = "alloc")]
|
||||||
|
pub fn to_owned(&self) -> TlvOwned {
|
||||||
|
TlvOwned {
|
||||||
|
tlv_type_field: self.tlv_type_field,
|
||||||
|
data: self.value().to_vec(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(feature = "alloc")]
|
||||||
|
impl PartialEq<TlvOwned> for Tlv<'_> {
|
||||||
|
fn eq(&self, other: &TlvOwned) -> bool {
|
||||||
|
self.tlv_type_field == other.tlv_type_field && self.value() == other.value()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ReadableTlv for Tlv<'_> {
|
||||||
|
fn value(&self) -> &[u8] {
|
||||||
|
self.lv.value()
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl WritableTlv for Tlv<'_> {
|
impl WritableTlv for Tlv<'_> {
|
||||||
@@ -197,38 +237,127 @@ impl WritableTlv for Tlv<'_> {
|
|||||||
self.lv.write_to_be_bytes_no_len_check(&mut buf[1..]);
|
self.lv.write_to_be_bytes_no_len_check(&mut buf[1..]);
|
||||||
Ok(self.len_full())
|
Ok(self.len_full())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
fn len_written(&self) -> usize {
|
fn len_written(&self) -> usize {
|
||||||
self.len_full()
|
self.len_full()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl GenericTlv for Tlv<'_> {
|
impl GenericTlv for Tlv<'_> {
|
||||||
|
#[inline]
|
||||||
fn tlv_type_field(&self) -> TlvTypeField {
|
fn tlv_type_field(&self) -> TlvTypeField {
|
||||||
self.tlv_type_field
|
self.tlv_type_field
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(crate) fn verify_tlv_type(raw_type: u8, expected_tlv_type: TlvType) -> Result<(), TlvLvError> {
|
#[cfg(feature = "alloc")]
|
||||||
let tlv_type = TlvType::try_from(raw_type).map_err(|_| TlvLvError::InvalidTlvTypeField {
|
pub mod alloc_mod {
|
||||||
found: raw_type,
|
use super::*;
|
||||||
expected: Some(expected_tlv_type.into()),
|
|
||||||
})?;
|
/// Owned variant of [Tlv] which is consequently [Clone]able and does not have a lifetime
|
||||||
if tlv_type != expected_tlv_type {
|
/// associated to a data slice.
|
||||||
return Err(TlvLvError::InvalidTlvTypeField {
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
found: tlv_type as u8,
|
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||||
expected: Some(expected_tlv_type as u8),
|
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
|
||||||
});
|
pub struct TlvOwned {
|
||||||
|
pub(crate) tlv_type_field: TlvTypeField,
|
||||||
|
pub(crate) data: Vec<u8>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl TlvOwned {
|
||||||
|
pub fn new(tlv_type: TlvType, data: &[u8]) -> Self {
|
||||||
|
Self {
|
||||||
|
tlv_type_field: TlvTypeField::Standard(tlv_type),
|
||||||
|
data: data.to_vec(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn new_with_custom_type(tlv_type: u8, data: &[u8]) -> Self {
|
||||||
|
Self {
|
||||||
|
tlv_type_field: TlvTypeField::Custom(tlv_type),
|
||||||
|
data: data.to_vec(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Creates a TLV with an empty value field.
|
||||||
|
pub fn new_empty(tlv_type: TlvType) -> Self {
|
||||||
|
Self {
|
||||||
|
tlv_type_field: TlvTypeField::Standard(tlv_type),
|
||||||
|
data: Vec::new(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn write_to_bytes(&self, buf: &mut [u8]) -> Result<usize, ByteConversionError> {
|
||||||
|
generic_len_check_data_serialization(buf, self.data.len(), MIN_TLV_LEN)?;
|
||||||
|
buf[0] = self.tlv_type_field.into();
|
||||||
|
buf[1] = self.data.len() as u8;
|
||||||
|
buf[2..2 + self.data.len()].copy_from_slice(&self.data);
|
||||||
|
Ok(self.len_written())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
fn len_written(&self) -> usize {
|
||||||
|
self.data.len() + 2
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn as_tlv(&self) -> Tlv<'_> {
|
||||||
|
Tlv {
|
||||||
|
tlv_type_field: self.tlv_type_field,
|
||||||
|
// The API should ensure that the data length is never to large, so the unwrap for the
|
||||||
|
// LV creation should never be an issue.
|
||||||
|
lv: Lv::new(&self.data).expect("lv creation failed unexpectedly"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ReadableTlv for TlvOwned {
|
||||||
|
#[inline]
|
||||||
|
fn value(&self) -> &[u8] {
|
||||||
|
&self.data
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl WritableTlv for TlvOwned {
|
||||||
|
fn write_to_bytes(&self, buf: &mut [u8]) -> Result<usize, ByteConversionError> {
|
||||||
|
self.write_to_bytes(buf)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
fn len_written(&self) -> usize {
|
||||||
|
self.len_written()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl GenericTlv for TlvOwned {
|
||||||
|
#[inline]
|
||||||
|
fn tlv_type_field(&self) -> TlvTypeField {
|
||||||
|
self.tlv_type_field
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl From<Tlv<'_>> for TlvOwned {
|
||||||
|
fn from(value: Tlv<'_>) -> Self {
|
||||||
|
value.to_owned()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl PartialEq<Tlv<'_>> for TlvOwned {
|
||||||
|
fn eq(&self, other: &Tlv) -> bool {
|
||||||
|
self.tlv_type_field == other.tlv_type_field && self.data == other.value()
|
||||||
|
}
|
||||||
}
|
}
|
||||||
Ok(())
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
|
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
|
||||||
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
||||||
|
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
|
||||||
pub struct EntityIdTlv {
|
pub struct EntityIdTlv {
|
||||||
entity_id: UnsignedByteField,
|
entity_id: UnsignedByteField,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl EntityIdTlv {
|
impl EntityIdTlv {
|
||||||
|
#[inline]
|
||||||
pub fn new(entity_id: UnsignedByteField) -> Self {
|
pub fn new(entity_id: UnsignedByteField) -> Self {
|
||||||
Self { entity_id }
|
Self { entity_id }
|
||||||
}
|
}
|
||||||
@@ -243,14 +372,17 @@ impl EntityIdTlv {
|
|||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
pub fn entity_id(&self) -> &UnsignedByteField {
|
pub fn entity_id(&self) -> &UnsignedByteField {
|
||||||
&self.entity_id
|
&self.entity_id
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
pub fn len_value(&self) -> usize {
|
pub fn len_value(&self) -> usize {
|
||||||
self.entity_id.size()
|
self.entity_id.size()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
pub fn len_full(&self) -> usize {
|
pub fn len_full(&self) -> usize {
|
||||||
2 + self.entity_id.size()
|
2 + self.entity_id.size()
|
||||||
}
|
}
|
||||||
@@ -268,19 +400,14 @@ impl EntityIdTlv {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Convert to a generic [Tlv], which also erases the programmatic type information.
|
/// Convert to a generic [Tlv], which also erases the programmatic type information.
|
||||||
pub fn to_tlv(self, buf: &mut [u8]) -> Result<Tlv, ByteConversionError> {
|
pub fn to_tlv(self, buf: &mut [u8]) -> Result<Tlv<'_>, ByteConversionError> {
|
||||||
Self::len_check(buf)?;
|
Self::len_check(buf)?;
|
||||||
self.entity_id
|
self.entity_id
|
||||||
.write_to_be_bytes(&mut buf[2..2 + self.entity_id.size()])?;
|
.write_to_be_bytes(&mut buf[2..2 + self.entity_id.size()])?;
|
||||||
Tlv::new(TlvType::EntityId, &buf[2..2 + self.entity_id.size()]).map_err(|e| match e {
|
// Can't fail.
|
||||||
TlvLvError::ByteConversion(e) => e,
|
Ok(Tlv::new(TlvType::EntityId, &buf[2..2 + self.entity_id.size()]).unwrap())
|
||||||
// All other errors are impossible.
|
|
||||||
_ => panic!("unexpected TLV error"),
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
impl WritableTlv for EntityIdTlv {
|
|
||||||
fn write_to_bytes(&self, buf: &mut [u8]) -> Result<usize, ByteConversionError> {
|
fn write_to_bytes(&self, buf: &mut [u8]) -> Result<usize, ByteConversionError> {
|
||||||
Self::len_check(buf)?;
|
Self::len_check(buf)?;
|
||||||
buf[0] = TlvType::EntityId as u8;
|
buf[0] = TlvType::EntityId as u8;
|
||||||
@@ -288,35 +415,50 @@ impl WritableTlv for EntityIdTlv {
|
|||||||
Ok(2 + self.entity_id.write_to_be_bytes(&mut buf[2..])?)
|
Ok(2 + self.entity_id.write_to_be_bytes(&mut buf[2..])?)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
fn len_written(&self) -> usize {
|
fn len_written(&self) -> usize {
|
||||||
self.len_full()
|
self.len_full()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
impl WritableTlv for EntityIdTlv {
|
||||||
|
fn write_to_bytes(&self, buf: &mut [u8]) -> Result<usize, ByteConversionError> {
|
||||||
|
self.write_to_bytes(buf)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
fn len_written(&self) -> usize {
|
||||||
|
self.len_written()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
impl GenericTlv for EntityIdTlv {
|
impl GenericTlv for EntityIdTlv {
|
||||||
|
#[inline]
|
||||||
fn tlv_type_field(&self) -> TlvTypeField {
|
fn tlv_type_field(&self) -> TlvTypeField {
|
||||||
TlvTypeField::Standard(TlvType::EntityId)
|
TlvTypeField::Standard(TlvType::EntityId)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<'data> TryFrom<Tlv<'data>> for EntityIdTlv {
|
impl TryFrom<Tlv<'_>> for EntityIdTlv {
|
||||||
type Error = TlvLvError;
|
type Error = TlvLvError;
|
||||||
|
|
||||||
fn try_from(value: Tlv) -> Result<Self, Self::Error> {
|
fn try_from(value: Tlv) -> Result<Self, TlvLvError> {
|
||||||
match value.tlv_type_field {
|
match value.tlv_type_field {
|
||||||
TlvTypeField::Standard(tlv_type) => {
|
TlvTypeField::Standard(tlv_type) => {
|
||||||
if tlv_type != TlvType::EntityId {
|
if tlv_type != TlvType::EntityId {
|
||||||
return Err(TlvLvError::InvalidTlvTypeField {
|
return Err(InvalidTlvTypeFieldError {
|
||||||
found: tlv_type as u8,
|
found: tlv_type as u8,
|
||||||
expected: Some(TlvType::EntityId as u8),
|
expected: Some(TlvType::EntityId as u8),
|
||||||
});
|
}
|
||||||
|
.into());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
TlvTypeField::Custom(val) => {
|
TlvTypeField::Custom(val) => {
|
||||||
return Err(TlvLvError::InvalidTlvTypeField {
|
return Err(InvalidTlvTypeFieldError {
|
||||||
found: val,
|
found: val,
|
||||||
expected: Some(TlvType::EntityId as u8),
|
expected: Some(TlvType::EntityId as u8),
|
||||||
});
|
}
|
||||||
|
.into());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
let len_value = value.value().len();
|
let len_value = value.value().len();
|
||||||
@@ -336,6 +478,7 @@ impl<'data> TryFrom<Tlv<'data>> for EntityIdTlv {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
pub fn fs_request_has_second_filename(action_code: FilestoreActionCode) -> bool {
|
pub fn fs_request_has_second_filename(action_code: FilestoreActionCode) -> bool {
|
||||||
if action_code == FilestoreActionCode::RenameFile
|
if action_code == FilestoreActionCode::RenameFile
|
||||||
|| action_code == FilestoreActionCode::AppendFile
|
|| action_code == FilestoreActionCode::AppendFile
|
||||||
@@ -348,6 +491,7 @@ pub fn fs_request_has_second_filename(action_code: FilestoreActionCode) -> bool
|
|||||||
|
|
||||||
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
|
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
|
||||||
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
||||||
|
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
|
||||||
struct FilestoreTlvBase<'first_name, 'second_name> {
|
struct FilestoreTlvBase<'first_name, 'second_name> {
|
||||||
pub action_code: FilestoreActionCode,
|
pub action_code: FilestoreActionCode,
|
||||||
#[cfg_attr(feature = "serde", serde(borrow))]
|
#[cfg_attr(feature = "serde", serde(borrow))]
|
||||||
@@ -357,6 +501,7 @@ struct FilestoreTlvBase<'first_name, 'second_name> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl FilestoreTlvBase<'_, '_> {
|
impl FilestoreTlvBase<'_, '_> {
|
||||||
|
#[inline]
|
||||||
fn base_len_value(&self) -> usize {
|
fn base_len_value(&self) -> usize {
|
||||||
let mut len = 1 + self.first_name.len_full();
|
let mut len = 1 + self.first_name.len_full();
|
||||||
if let Some(second_name) = self.second_name {
|
if let Some(second_name) = self.second_name {
|
||||||
@@ -466,22 +611,27 @@ impl<'first_name, 'second_name> FilestoreRequestTlv<'first_name, 'second_name> {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
pub fn action_code(&self) -> FilestoreActionCode {
|
pub fn action_code(&self) -> FilestoreActionCode {
|
||||||
self.base.action_code
|
self.base.action_code
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
pub fn first_name(&self) -> Lv<'first_name> {
|
pub fn first_name(&self) -> Lv<'first_name> {
|
||||||
self.base.first_name
|
self.base.first_name
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
pub fn second_name(&self) -> Option<Lv<'second_name>> {
|
pub fn second_name(&self) -> Option<Lv<'second_name>> {
|
||||||
self.base.second_name
|
self.base.second_name
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
pub fn len_value(&self) -> usize {
|
pub fn len_value(&self) -> usize {
|
||||||
self.base.base_len_value()
|
self.base.base_len_value()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
pub fn len_full(&self) -> usize {
|
pub fn len_full(&self) -> usize {
|
||||||
2 + self.len_value()
|
2 + self.len_value()
|
||||||
}
|
}
|
||||||
@@ -520,9 +670,7 @@ impl<'first_name, 'second_name> FilestoreRequestTlv<'first_name, 'second_name> {
|
|||||||
},
|
},
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
impl WritableTlv for FilestoreRequestTlv<'_, '_> {
|
|
||||||
fn write_to_bytes(&self, buf: &mut [u8]) -> Result<usize, ByteConversionError> {
|
fn write_to_bytes(&self, buf: &mut [u8]) -> Result<usize, ByteConversionError> {
|
||||||
if buf.len() < self.len_full() {
|
if buf.len() < self.len_full() {
|
||||||
return Err(ByteConversionError::ToSliceTooSmall {
|
return Err(ByteConversionError::ToSliceTooSmall {
|
||||||
@@ -548,12 +696,25 @@ impl WritableTlv for FilestoreRequestTlv<'_, '_> {
|
|||||||
Ok(current_idx)
|
Ok(current_idx)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
fn len_written(&self) -> usize {
|
fn len_written(&self) -> usize {
|
||||||
self.len_full()
|
self.len_full()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
impl WritableTlv for FilestoreRequestTlv<'_, '_> {
|
||||||
|
fn write_to_bytes(&self, buf: &mut [u8]) -> Result<usize, ByteConversionError> {
|
||||||
|
self.write_to_bytes(buf)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
fn len_written(&self) -> usize {
|
||||||
|
self.len_written()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
impl GenericTlv for FilestoreRequestTlv<'_, '_> {
|
impl GenericTlv for FilestoreRequestTlv<'_, '_> {
|
||||||
|
#[inline]
|
||||||
fn tlv_type_field(&self) -> TlvTypeField {
|
fn tlv_type_field(&self) -> TlvTypeField {
|
||||||
TlvTypeField::Standard(TlvType::FilestoreRequest)
|
TlvTypeField::Standard(TlvType::FilestoreRequest)
|
||||||
}
|
}
|
||||||
@@ -561,6 +722,7 @@ impl GenericTlv for FilestoreRequestTlv<'_, '_> {
|
|||||||
|
|
||||||
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
|
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
|
||||||
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
||||||
|
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
|
||||||
pub struct FilestoreResponseTlv<'first_name, 'second_name, 'fs_msg> {
|
pub struct FilestoreResponseTlv<'first_name, 'second_name, 'fs_msg> {
|
||||||
#[cfg_attr(feature = "serde", serde(borrow))]
|
#[cfg_attr(feature = "serde", serde(borrow))]
|
||||||
base: FilestoreTlvBase<'first_name, 'second_name>,
|
base: FilestoreTlvBase<'first_name, 'second_name>,
|
||||||
@@ -627,26 +789,32 @@ impl<'first_name, 'second_name, 'fs_msg> FilestoreResponseTlv<'first_name, 'seco
|
|||||||
false
|
false
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
pub fn action_code(&self) -> FilestoreActionCode {
|
pub fn action_code(&self) -> FilestoreActionCode {
|
||||||
self.base.action_code
|
self.base.action_code
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
pub fn status_code(&self) -> u8 {
|
pub fn status_code(&self) -> u8 {
|
||||||
self.status_code
|
self.status_code
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
pub fn first_name(&self) -> Lv<'first_name> {
|
pub fn first_name(&self) -> Lv<'first_name> {
|
||||||
self.base.first_name
|
self.base.first_name
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
pub fn second_name(&self) -> Option<Lv<'second_name>> {
|
pub fn second_name(&self) -> Option<Lv<'second_name>> {
|
||||||
self.base.second_name
|
self.base.second_name
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
pub fn len_value(&self) -> usize {
|
pub fn len_value(&self) -> usize {
|
||||||
self.base.base_len_value() + self.filestore_message.len_full()
|
self.base.base_len_value() + self.filestore_message.len_full()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
pub fn len_full(&self) -> usize {
|
pub fn len_full(&self) -> usize {
|
||||||
2 + self.len_value()
|
2 + self.len_value()
|
||||||
}
|
}
|
||||||
@@ -704,9 +872,7 @@ impl<'first_name, 'second_name, 'fs_msg> FilestoreResponseTlv<'first_name, 'seco
|
|||||||
filestore_message,
|
filestore_message,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
impl WritableTlv for FilestoreResponseTlv<'_, '_, '_> {
|
|
||||||
fn write_to_bytes(&self, buf: &mut [u8]) -> Result<usize, ByteConversionError> {
|
fn write_to_bytes(&self, buf: &mut [u8]) -> Result<usize, ByteConversionError> {
|
||||||
if buf.len() < self.len_full() {
|
if buf.len() < self.len_full() {
|
||||||
return Err(ByteConversionError::ToSliceTooSmall {
|
return Err(ByteConversionError::ToSliceTooSmall {
|
||||||
@@ -739,12 +905,41 @@ impl WritableTlv for FilestoreResponseTlv<'_, '_, '_> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
impl WritableTlv for FilestoreResponseTlv<'_, '_, '_> {
|
||||||
|
fn write_to_bytes(&self, buf: &mut [u8]) -> Result<usize, ByteConversionError> {
|
||||||
|
self.write_to_bytes(buf)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
fn len_written(&self) -> usize {
|
||||||
|
self.len_written()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
impl GenericTlv for FilestoreResponseTlv<'_, '_, '_> {
|
impl GenericTlv for FilestoreResponseTlv<'_, '_, '_> {
|
||||||
|
#[inline]
|
||||||
fn tlv_type_field(&self) -> TlvTypeField {
|
fn tlv_type_field(&self) -> TlvTypeField {
|
||||||
TlvTypeField::Standard(TlvType::FilestoreResponse)
|
TlvTypeField::Standard(TlvType::FilestoreResponse)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub(crate) fn verify_tlv_type(
|
||||||
|
raw_type: u8,
|
||||||
|
expected_tlv_type: TlvType,
|
||||||
|
) -> Result<(), InvalidTlvTypeFieldError> {
|
||||||
|
let tlv_type = TlvType::try_from(raw_type).map_err(|_| InvalidTlvTypeFieldError {
|
||||||
|
found: raw_type,
|
||||||
|
expected: Some(expected_tlv_type.into()),
|
||||||
|
})?;
|
||||||
|
if tlv_type != expected_tlv_type {
|
||||||
|
return Err(InvalidTlvTypeFieldError {
|
||||||
|
found: tlv_type as u8,
|
||||||
|
expected: Some(expected_tlv_type as u8),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use super::*;
|
use super::*;
|
||||||
@@ -932,14 +1127,14 @@ mod tests {
|
|||||||
let tlv_res = Tlv::new(TlvType::MsgToUser, &buf_too_large);
|
let tlv_res = Tlv::new(TlvType::MsgToUser, &buf_too_large);
|
||||||
assert!(tlv_res.is_err());
|
assert!(tlv_res.is_err());
|
||||||
let error = tlv_res.unwrap_err();
|
let error = tlv_res.unwrap_err();
|
||||||
if let TlvLvError::DataTooLarge(size) = error {
|
match error {
|
||||||
assert_eq!(size, u8::MAX as usize + 1);
|
TlvLvDataTooLargeError(size) => {
|
||||||
assert_eq!(
|
assert_eq!(size, u8::MAX as usize + 1);
|
||||||
error.to_string(),
|
assert_eq!(
|
||||||
"data with size 256 larger than allowed 255 bytes"
|
error.to_string(),
|
||||||
);
|
"data with size 256 larger than allowed 255 bytes"
|
||||||
} else {
|
);
|
||||||
panic!("unexpected error {:?}", error);
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1249,7 +1444,8 @@ mod tests {
|
|||||||
let error = EntityIdTlv::try_from(msg_to_user_tlv);
|
let error = EntityIdTlv::try_from(msg_to_user_tlv);
|
||||||
assert!(error.is_err());
|
assert!(error.is_err());
|
||||||
let error = error.unwrap_err();
|
let error = error.unwrap_err();
|
||||||
if let TlvLvError::InvalidTlvTypeField { found, expected } = error {
|
if let TlvLvError::InvalidTlvTypeField(InvalidTlvTypeFieldError { found, expected }) = error
|
||||||
|
{
|
||||||
assert_eq!(found, TlvType::MsgToUser as u8);
|
assert_eq!(found, TlvType::MsgToUser as u8);
|
||||||
assert_eq!(expected, Some(TlvType::EntityId as u8));
|
assert_eq!(expected, Some(TlvType::EntityId as u8));
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
@@ -1293,4 +1489,71 @@ mod tests {
|
|||||||
assert_eq!(tlv_as_vec[0], 20);
|
assert_eq!(tlv_as_vec[0], 20);
|
||||||
assert_eq!(tlv_as_vec[1], 0);
|
assert_eq!(tlv_as_vec[1], 0);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_tlv_to_owned() {
|
||||||
|
let entity_id = UbfU8::new(5);
|
||||||
|
let mut buf: [u8; 4] = [0; 4];
|
||||||
|
assert!(entity_id.write_to_be_bytes(&mut buf).is_ok());
|
||||||
|
let tlv_res = Tlv::new(TlvType::EntityId, &buf[0..1]);
|
||||||
|
assert!(tlv_res.is_ok());
|
||||||
|
let tlv_res = tlv_res.unwrap();
|
||||||
|
let tlv_owned = tlv_res.to_owned();
|
||||||
|
assert_eq!(tlv_res, tlv_owned);
|
||||||
|
let tlv_owned_from_conversion: TlvOwned = tlv_res.into();
|
||||||
|
assert_eq!(tlv_owned_from_conversion, tlv_owned);
|
||||||
|
assert_eq!(tlv_owned_from_conversion, tlv_res);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_owned_tlv() {
|
||||||
|
let entity_id = UbfU8::new(5);
|
||||||
|
let mut buf: [u8; 4] = [0; 4];
|
||||||
|
assert!(entity_id.write_to_be_bytes(&mut buf).is_ok());
|
||||||
|
let tlv_res = TlvOwned::new(TlvType::EntityId, &buf[0..1]);
|
||||||
|
assert_eq!(
|
||||||
|
tlv_res.tlv_type_field(),
|
||||||
|
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_eq!(tlv_res.value()[0], 5);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_owned_tlv_empty() {
|
||||||
|
let tlv_res = TlvOwned::new_empty(TlvType::FlowLabel);
|
||||||
|
assert_eq!(
|
||||||
|
tlv_res.tlv_type_field(),
|
||||||
|
TlvTypeField::Standard(TlvType::FlowLabel)
|
||||||
|
);
|
||||||
|
assert_eq!(tlv_res.len_full(), 2);
|
||||||
|
assert_eq!(tlv_res.value().len(), 0);
|
||||||
|
assert_eq!(tlv_res.len_value(), 0);
|
||||||
|
assert!(tlv_res.is_empty());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_owned_tlv_custom_type() {
|
||||||
|
let tlv_res = TlvOwned::new_with_custom_type(32, &[]);
|
||||||
|
assert_eq!(tlv_res.tlv_type_field(), TlvTypeField::Custom(32));
|
||||||
|
assert_eq!(tlv_res.len_full(), 2);
|
||||||
|
assert_eq!(tlv_res.value().len(), 0);
|
||||||
|
assert_eq!(tlv_res.len_value(), 0);
|
||||||
|
assert!(tlv_res.is_empty());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_owned_tlv_conversion_to_bytes() {
|
||||||
|
let entity_id = UbfU8::new(5);
|
||||||
|
let mut buf: [u8; 4] = [0; 4];
|
||||||
|
assert!(entity_id.write_to_be_bytes(&mut buf).is_ok());
|
||||||
|
let tlv_res = Tlv::new(TlvType::EntityId, &buf[0..1]);
|
||||||
|
assert!(tlv_res.is_ok());
|
||||||
|
let tlv_res = tlv_res.unwrap();
|
||||||
|
let tlv_owned_from_conversion: TlvOwned = tlv_res.into();
|
||||||
|
assert_eq!(tlv_res.to_vec(), tlv_owned_from_conversion.to_vec());
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
@@ -1,6 +1,11 @@
|
|||||||
//! Abstractions for the Message to User CFDP TLV subtype.
|
//! Abstractions for the Message to User CFDP TLV subtype.
|
||||||
use super::{GenericTlv, Tlv, TlvLvError, TlvType, TlvTypeField, WritableTlv};
|
#[cfg(feature = "alloc")]
|
||||||
use crate::ByteConversionError;
|
use super::TlvOwned;
|
||||||
|
use super::{GenericTlv, ReadableTlv, Tlv, TlvLvError, TlvType, TlvTypeField, WritableTlv};
|
||||||
|
use crate::{
|
||||||
|
cfdp::{InvalidTlvTypeFieldError, TlvLvDataTooLargeError},
|
||||||
|
ByteConversionError,
|
||||||
|
};
|
||||||
use delegate::delegate;
|
use delegate::delegate;
|
||||||
|
|
||||||
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
|
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
|
||||||
@@ -10,7 +15,7 @@ pub struct MsgToUserTlv<'data> {
|
|||||||
|
|
||||||
impl<'data> MsgToUserTlv<'data> {
|
impl<'data> MsgToUserTlv<'data> {
|
||||||
/// Create a new message to user TLV where the type field is set correctly.
|
/// Create a new message to user TLV where the type field is set correctly.
|
||||||
pub fn new(value: &'data [u8]) -> Result<MsgToUserTlv<'data>, TlvLvError> {
|
pub fn new(value: &'data [u8]) -> Result<MsgToUserTlv<'data>, TlvLvDataTooLargeError> {
|
||||||
Ok(Self {
|
Ok(Self {
|
||||||
tlv: Tlv::new(TlvType::MsgToUser, value)?,
|
tlv: Tlv::new(TlvType::MsgToUser, value)?,
|
||||||
})
|
})
|
||||||
@@ -32,10 +37,12 @@ impl<'data> MsgToUserTlv<'data> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
pub fn is_standard_tlv(&self) -> bool {
|
pub fn is_standard_tlv(&self) -> bool {
|
||||||
true
|
true
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
pub fn tlv_type(&self) -> Option<TlvType> {
|
pub fn tlv_type(&self) -> Option<TlvType> {
|
||||||
Some(TlvType::MsgToUser)
|
Some(TlvType::MsgToUser)
|
||||||
}
|
}
|
||||||
@@ -60,36 +67,65 @@ impl<'data> MsgToUserTlv<'data> {
|
|||||||
match msg_to_user.tlv.tlv_type_field() {
|
match msg_to_user.tlv.tlv_type_field() {
|
||||||
TlvTypeField::Standard(tlv_type) => {
|
TlvTypeField::Standard(tlv_type) => {
|
||||||
if tlv_type != TlvType::MsgToUser {
|
if tlv_type != TlvType::MsgToUser {
|
||||||
return Err(TlvLvError::InvalidTlvTypeField {
|
return Err(InvalidTlvTypeFieldError {
|
||||||
found: tlv_type as u8,
|
found: tlv_type as u8,
|
||||||
expected: Some(TlvType::MsgToUser as u8),
|
expected: Some(TlvType::MsgToUser as u8),
|
||||||
});
|
}
|
||||||
|
.into());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
TlvTypeField::Custom(raw) => {
|
TlvTypeField::Custom(raw) => {
|
||||||
return Err(TlvLvError::InvalidTlvTypeField {
|
return Err(InvalidTlvTypeFieldError {
|
||||||
found: raw,
|
found: raw,
|
||||||
expected: Some(TlvType::MsgToUser as u8),
|
expected: Some(TlvType::MsgToUser as u8),
|
||||||
});
|
}
|
||||||
|
.into());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Ok(msg_to_user)
|
Ok(msg_to_user)
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
impl WritableTlv for MsgToUserTlv<'_> {
|
#[inline]
|
||||||
|
pub fn to_tlv(&self) -> Tlv<'data> {
|
||||||
|
self.tlv
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(feature = "alloc")]
|
||||||
|
pub fn to_owned(&self) -> TlvOwned {
|
||||||
|
self.tlv.to_owned()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
fn len_written(&self) -> usize {
|
fn len_written(&self) -> usize {
|
||||||
self.len_full()
|
self.len_full()
|
||||||
}
|
}
|
||||||
|
|
||||||
delegate!(
|
delegate!(
|
||||||
to self.tlv {
|
to self.tlv {
|
||||||
fn write_to_bytes(&self, buf: &mut [u8]) -> Result<usize, ByteConversionError>;
|
pub fn write_to_bytes(&self, buf: &mut [u8]) -> Result<usize, ByteConversionError>;
|
||||||
}
|
}
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
impl<'a> From<MsgToUserTlv<'a>> for Tlv<'a> {
|
||||||
|
fn from(value: MsgToUserTlv<'a>) -> Tlv<'a> {
|
||||||
|
value.to_tlv()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl WritableTlv for MsgToUserTlv<'_> {
|
||||||
|
#[inline]
|
||||||
|
fn len_written(&self) -> usize {
|
||||||
|
self.len_written()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn write_to_bytes(&self, buf: &mut [u8]) -> Result<usize, ByteConversionError> {
|
||||||
|
self.tlv.write_to_bytes(buf)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
impl GenericTlv for MsgToUserTlv<'_> {
|
impl GenericTlv for MsgToUserTlv<'_> {
|
||||||
|
#[inline]
|
||||||
fn tlv_type_field(&self) -> TlvTypeField {
|
fn tlv_type_field(&self) -> TlvTypeField {
|
||||||
self.tlv.tlv_type_field()
|
self.tlv.tlv_type_field()
|
||||||
}
|
}
|
||||||
@@ -139,6 +175,40 @@ mod tests {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_msg_to_user_type_reduction() {
|
||||||
|
let custom_value: [u8; 4] = [1, 2, 3, 4];
|
||||||
|
let msg_to_user = MsgToUserTlv::new(&custom_value).unwrap();
|
||||||
|
let tlv = msg_to_user.to_tlv();
|
||||||
|
assert_eq!(
|
||||||
|
tlv.tlv_type_field(),
|
||||||
|
TlvTypeField::Standard(TlvType::MsgToUser)
|
||||||
|
);
|
||||||
|
|
||||||
|
assert_eq!(tlv.value(), custom_value);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_msg_to_user_to_tlv() {
|
||||||
|
let custom_value: [u8; 4] = [1, 2, 3, 4];
|
||||||
|
let msg_to_user = MsgToUserTlv::new(&custom_value).unwrap();
|
||||||
|
let tlv: Tlv = msg_to_user.into();
|
||||||
|
assert_eq!(msg_to_user.to_tlv(), tlv);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_msg_to_user_owner_converter() {
|
||||||
|
let custom_value: [u8; 4] = [1, 2, 3, 4];
|
||||||
|
let msg_to_user = MsgToUserTlv::new(&custom_value).unwrap();
|
||||||
|
let tlv = msg_to_user.to_owned();
|
||||||
|
assert_eq!(
|
||||||
|
tlv.tlv_type_field(),
|
||||||
|
TlvTypeField::Standard(TlvType::MsgToUser)
|
||||||
|
);
|
||||||
|
|
||||||
|
assert_eq!(tlv.value(), custom_value);
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_reserved_msg_deserialization() {
|
fn test_reserved_msg_deserialization() {
|
||||||
let custom_value: [u8; 3] = [1, 2, 3];
|
let custom_value: [u8; 3] = [1, 2, 3];
|
||||||
@@ -154,9 +224,9 @@ mod tests {
|
|||||||
fn test_reserved_msg_deserialization_invalid_type() {
|
fn test_reserved_msg_deserialization_invalid_type() {
|
||||||
let trash: [u8; 5] = [TlvType::FlowLabel as u8, 3, 1, 2, 3];
|
let trash: [u8; 5] = [TlvType::FlowLabel as u8, 3, 1, 2, 3];
|
||||||
let error = MsgToUserTlv::from_bytes(&trash).unwrap_err();
|
let error = MsgToUserTlv::from_bytes(&trash).unwrap_err();
|
||||||
if let TlvLvError::InvalidTlvTypeField { found, expected } = error {
|
if let TlvLvError::InvalidTlvTypeField(inner) = error {
|
||||||
assert_eq!(found, TlvType::FlowLabel as u8);
|
assert_eq!(inner.found, TlvType::FlowLabel as u8);
|
||||||
assert_eq!(expected, Some(TlvType::MsgToUser as u8));
|
assert_eq!(inner.expected, Some(TlvType::MsgToUser as u8));
|
||||||
} else {
|
} else {
|
||||||
panic!("Wrong error type returned: {:?}", error);
|
panic!("Wrong error type returned: {:?}", error);
|
||||||
}
|
}
|
||||||
|
11
src/crc.rs
Normal file
11
src/crc.rs
Normal file
@@ -0,0 +1,11 @@
|
|||||||
|
/// CRC algorithm used by the PUS standard, the CCSDS TC standard and the CFDP standard, using
|
||||||
|
/// a [crc::NoTable] as the CRC implementation.
|
||||||
|
pub const CRC_CCITT_FALSE_NO_TABLE: crc::Crc<u16, crc::NoTable> =
|
||||||
|
crc::Crc::<u16, crc::NoTable>::new(&crc::CRC_16_IBM_3740);
|
||||||
|
/// CRC algorithm used by the PUS standard, the CCSDS TC standard and the CFDP standard, using
|
||||||
|
/// [crc::Table<1>] as the CRC implementation.
|
||||||
|
pub const CRC_CCITT_FALSE: crc::Crc<u16> = crc::Crc::<u16>::new(&crc::CRC_16_IBM_3740);
|
||||||
|
/// CRC algorithm used by the PUS standard, the CCSDS TC standard and the CFDP standard, using
|
||||||
|
/// a [crc::Table<16>] large table as the CRC implementation.
|
||||||
|
pub const CRC_CCITT_FALSE_BIG_TABLE: crc::Crc<u16, crc::Table<16>> =
|
||||||
|
crc::Crc::<u16, crc::Table<16>>::new(&crc::CRC_16_IBM_3740);
|
@@ -5,6 +5,7 @@ use serde::{Deserialize, Serialize};
|
|||||||
|
|
||||||
#[derive(Debug, Eq, PartialEq, Copy, Clone, IntoPrimitive, TryFromPrimitive)]
|
#[derive(Debug, Eq, PartialEq, Copy, Clone, IntoPrimitive, TryFromPrimitive)]
|
||||||
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
||||||
|
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
|
||||||
#[repr(u8)]
|
#[repr(u8)]
|
||||||
pub enum Subservice {
|
pub enum Subservice {
|
||||||
// Regular HK
|
// Regular HK
|
||||||
|
269
src/ecss/mod.rs
269
src/ecss/mod.rs
@@ -1,31 +1,35 @@
|
|||||||
//! Common definitions and helpers required to create PUS TMTC packets according to
|
//! Common definitions and helpers required to create PUS TMTC packets according to
|
||||||
//! [ECSS-E-ST-70-41C](https://ecss.nl/standard/ecss-e-st-70-41c-space-engineering-telemetry-and-telecommand-packet-utilization-15-april-2016/)
|
//! [ECSS-E-ST-70-41C](https://ecss.nl/standard/ecss-e-st-70-41c-space-engineering-telemetry-and-telecommand-packet-utilization-15-april-2016/)
|
||||||
//!
|
//!
|
||||||
//! You can find the PUS telecommand definitions in the [tc] module and ithe PUS telemetry definitions
|
//! You can find the PUS telecommand types in the [tc] module and the the PUS telemetry
|
||||||
//! inside the [tm] module.
|
//! types inside the [tm] module.
|
||||||
use crate::{ByteConversionError, CcsdsPacket, CRC_CCITT_FALSE};
|
use crate::{
|
||||||
|
crc::{CRC_CCITT_FALSE, CRC_CCITT_FALSE_NO_TABLE},
|
||||||
|
ByteConversionError, CcsdsPacket,
|
||||||
|
};
|
||||||
#[cfg(feature = "alloc")]
|
#[cfg(feature = "alloc")]
|
||||||
use alloc::vec::Vec;
|
use alloc::vec::Vec;
|
||||||
use core::fmt::{Debug, Display, Formatter};
|
use arbitrary_int::u4;
|
||||||
|
use core::fmt::Debug;
|
||||||
use core::mem::size_of;
|
use core::mem::size_of;
|
||||||
use num_enum::{IntoPrimitive, TryFromPrimitive};
|
use num_enum::{IntoPrimitive, TryFromPrimitive};
|
||||||
#[cfg(feature = "serde")]
|
#[cfg(feature = "serde")]
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
#[cfg(feature = "std")]
|
|
||||||
use std::error::Error;
|
|
||||||
|
|
||||||
pub mod event;
|
pub mod event;
|
||||||
pub mod hk;
|
pub mod hk;
|
||||||
pub mod scheduling;
|
pub mod scheduling;
|
||||||
pub mod tc;
|
pub mod tc;
|
||||||
|
pub mod tc_pus_a;
|
||||||
pub mod tm;
|
pub mod tm;
|
||||||
|
pub mod tm_pus_a;
|
||||||
pub mod verification;
|
pub mod verification;
|
||||||
|
|
||||||
pub type CrcType = u16;
|
pub type CrcType = u16;
|
||||||
pub const CCSDS_HEADER_LEN: usize = size_of::<crate::zc::SpHeader>();
|
|
||||||
|
|
||||||
#[derive(Debug, Copy, Clone, Eq, PartialEq, IntoPrimitive, TryFromPrimitive)]
|
#[derive(Debug, Copy, Clone, Eq, PartialEq, IntoPrimitive, TryFromPrimitive)]
|
||||||
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
||||||
|
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
|
||||||
#[repr(u8)]
|
#[repr(u8)]
|
||||||
#[non_exhaustive]
|
#[non_exhaustive]
|
||||||
pub enum PusServiceId {
|
pub enum PusServiceId {
|
||||||
@@ -72,25 +76,27 @@ pub enum PusServiceId {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// All PUS versions. Only PUS C is supported by this library.
|
/// All PUS versions. Only PUS C is supported by this library.
|
||||||
#[derive(PartialEq, Eq, Copy, Clone, Debug)]
|
#[derive(PartialEq, Eq, Debug, num_enum::TryFromPrimitive)]
|
||||||
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
||||||
|
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
|
||||||
|
#[bitbybit::bitenum(u4, exhaustive = false)]
|
||||||
|
#[repr(u8)]
|
||||||
#[non_exhaustive]
|
#[non_exhaustive]
|
||||||
pub enum PusVersion {
|
pub enum PusVersion {
|
||||||
EsaPus = 0,
|
EsaPus = 0,
|
||||||
PusA = 1,
|
PusA = 1,
|
||||||
PusC = 2,
|
PusC = 2,
|
||||||
Invalid = 0b1111,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl TryFrom<u8> for PusVersion {
|
impl TryFrom<u4> for PusVersion {
|
||||||
type Error = ();
|
type Error = u4;
|
||||||
|
|
||||||
fn try_from(value: u8) -> Result<Self, Self::Error> {
|
fn try_from(value: u4) -> Result<Self, Self::Error> {
|
||||||
match value {
|
match value {
|
||||||
x if x == PusVersion::EsaPus as u8 => Ok(PusVersion::EsaPus),
|
x if x == PusVersion::EsaPus.raw_value() => Ok(PusVersion::EsaPus),
|
||||||
x if x == PusVersion::PusA as u8 => Ok(PusVersion::PusA),
|
x if x == PusVersion::PusA.raw_value() => Ok(PusVersion::PusA),
|
||||||
x if x == PusVersion::PusC as u8 => Ok(PusVersion::PusC),
|
x if x == PusVersion::PusC.raw_value() => Ok(PusVersion::PusC),
|
||||||
_ => Err(()),
|
_ => Err(value),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -98,6 +104,7 @@ impl TryFrom<u8> for PusVersion {
|
|||||||
/// ECSS Packet Type Codes (PTC)s.
|
/// ECSS Packet Type Codes (PTC)s.
|
||||||
#[derive(Debug, Copy, Clone, Eq, PartialEq, IntoPrimitive, TryFromPrimitive)]
|
#[derive(Debug, Copy, Clone, Eq, PartialEq, IntoPrimitive, TryFromPrimitive)]
|
||||||
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
||||||
|
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
|
||||||
#[repr(u8)]
|
#[repr(u8)]
|
||||||
pub enum PacketTypeCodes {
|
pub enum PacketTypeCodes {
|
||||||
Boolean = 1,
|
Boolean = 1,
|
||||||
@@ -119,6 +126,7 @@ pub type Ptc = PacketTypeCodes;
|
|||||||
/// ECSS Packet Field Codes (PFC)s for the unsigned [Ptc].
|
/// ECSS Packet Field Codes (PFC)s for the unsigned [Ptc].
|
||||||
#[derive(Debug, Copy, Clone, Eq, PartialEq, IntoPrimitive, TryFromPrimitive)]
|
#[derive(Debug, Copy, Clone, Eq, PartialEq, IntoPrimitive, TryFromPrimitive)]
|
||||||
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
||||||
|
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
|
||||||
#[repr(u8)]
|
#[repr(u8)]
|
||||||
pub enum PfcUnsigned {
|
pub enum PfcUnsigned {
|
||||||
OneByte = 4,
|
OneByte = 4,
|
||||||
@@ -136,6 +144,7 @@ pub enum PfcUnsigned {
|
|||||||
/// ECSS Packet Field Codes (PFC)s for the real (floating point) [Ptc].
|
/// ECSS Packet Field Codes (PFC)s for the real (floating point) [Ptc].
|
||||||
#[derive(Debug, Copy, Clone, Eq, PartialEq, IntoPrimitive, TryFromPrimitive)]
|
#[derive(Debug, Copy, Clone, Eq, PartialEq, IntoPrimitive, TryFromPrimitive)]
|
||||||
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
||||||
|
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
|
||||||
#[repr(u8)]
|
#[repr(u8)]
|
||||||
pub enum PfcReal {
|
pub enum PfcReal {
|
||||||
/// 4 octets simple precision format (IEEE)
|
/// 4 octets simple precision format (IEEE)
|
||||||
@@ -148,70 +157,42 @@ pub enum PfcReal {
|
|||||||
DoubleMilStd = 4,
|
DoubleMilStd = 4,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
|
#[derive(Debug, Copy, Clone, PartialEq, Eq, thiserror::Error)]
|
||||||
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
||||||
|
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
|
||||||
pub enum PusError {
|
pub enum PusError {
|
||||||
VersionNotSupported(PusVersion),
|
#[error("PUS version {0:?} not supported")]
|
||||||
|
VersionNotSupported(u4),
|
||||||
|
#[error("checksum verification for crc16 {0:#06x} failed")]
|
||||||
ChecksumFailure(u16),
|
ChecksumFailure(u16),
|
||||||
/// CRC16 needs to be calculated first
|
/// CRC16 needs to be calculated first
|
||||||
CrcCalculationMissing,
|
//#[error("crc16 was not calculated")]
|
||||||
ByteConversion(ByteConversionError),
|
//CrcCalculationMissing,
|
||||||
}
|
#[error("pus error: {0}")]
|
||||||
|
ByteConversion(#[from] ByteConversionError),
|
||||||
impl Display for PusError {
|
|
||||||
fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
|
|
||||||
match self {
|
|
||||||
PusError::VersionNotSupported(v) => {
|
|
||||||
write!(f, "PUS version {v:?} not supported")
|
|
||||||
}
|
|
||||||
PusError::ChecksumFailure(crc) => {
|
|
||||||
write!(f, "checksum verification for crc16 {crc:#06x} failed")
|
|
||||||
}
|
|
||||||
PusError::CrcCalculationMissing => {
|
|
||||||
write!(f, "crc16 was not calculated")
|
|
||||||
}
|
|
||||||
PusError::ByteConversion(e) => {
|
|
||||||
write!(f, "pus error: {e}")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(feature = "std")]
|
|
||||||
impl Error for PusError {
|
|
||||||
fn source(&self) -> Option<&(dyn Error + 'static)> {
|
|
||||||
if let PusError::ByteConversion(e) = self {
|
|
||||||
return Some(e);
|
|
||||||
}
|
|
||||||
None
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl From<ByteConversionError> for PusError {
|
|
||||||
fn from(e: ByteConversionError) -> Self {
|
|
||||||
PusError::ByteConversion(e)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Generic trait to describe common attributes for both PUS Telecommands (TC) and PUS Telemetry
|
/// Generic trait to describe common attributes for both PUS Telecommands (TC) and PUS Telemetry
|
||||||
/// (TM) packets. All PUS packets are also a special type of [CcsdsPacket]s.
|
/// (TM) packets. All PUS packets are also a special type of [CcsdsPacket]s.
|
||||||
pub trait PusPacket: CcsdsPacket {
|
pub trait PusPacket: CcsdsPacket {
|
||||||
const PUS_VERSION: PusVersion = PusVersion::PusC;
|
fn pus_version(&self) -> Result<PusVersion, u4>;
|
||||||
|
|
||||||
fn pus_version(&self) -> PusVersion;
|
|
||||||
fn service(&self) -> u8;
|
fn service(&self) -> u8;
|
||||||
fn subservice(&self) -> u8;
|
fn subservice(&self) -> u8;
|
||||||
fn user_data(&self) -> &[u8];
|
fn user_data(&self) -> &[u8];
|
||||||
fn crc16(&self) -> Option<u16>;
|
/// CRC-16-CCITT checksum.
|
||||||
|
fn checksum(&self) -> Option<u16>;
|
||||||
|
/// The presence of the CRC-16-CCITT checksum is optional.
|
||||||
|
fn has_checksum(&self) -> bool {
|
||||||
|
self.checksum().is_some()
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(crate) fn crc_from_raw_data(raw_data: &[u8]) -> Result<u16, PusError> {
|
pub(crate) fn crc_from_raw_data(raw_data: &[u8]) -> Result<u16, ByteConversionError> {
|
||||||
if raw_data.len() < 2 {
|
if raw_data.len() < 2 {
|
||||||
return Err(ByteConversionError::FromSliceTooSmall {
|
return Err(ByteConversionError::FromSliceTooSmall {
|
||||||
found: raw_data.len(),
|
found: raw_data.len(),
|
||||||
expected: 2,
|
expected: 2,
|
||||||
}
|
});
|
||||||
.into());
|
|
||||||
}
|
}
|
||||||
Ok(u16::from_be_bytes(
|
Ok(u16::from_be_bytes(
|
||||||
raw_data[raw_data.len() - 2..raw_data.len()]
|
raw_data[raw_data.len() - 2..raw_data.len()]
|
||||||
@@ -226,49 +207,45 @@ pub(crate) fn calc_pus_crc16(bytes: &[u8]) -> u16 {
|
|||||||
digest.finalize()
|
digest.finalize()
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(crate) fn crc_procedure(
|
|
||||||
calc_on_serialization: bool,
|
|
||||||
cached_crc16: &Option<u16>,
|
|
||||||
start_idx: usize,
|
|
||||||
curr_idx: usize,
|
|
||||||
slice: &[u8],
|
|
||||||
) -> Result<u16, PusError> {
|
|
||||||
let crc16;
|
|
||||||
if calc_on_serialization {
|
|
||||||
crc16 = calc_pus_crc16(&slice[start_idx..curr_idx])
|
|
||||||
} else if cached_crc16.is_none() {
|
|
||||||
return Err(PusError::CrcCalculationMissing);
|
|
||||||
} else {
|
|
||||||
crc16 = cached_crc16.unwrap();
|
|
||||||
}
|
|
||||||
Ok(crc16)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(crate) fn user_data_from_raw(
|
pub(crate) fn user_data_from_raw(
|
||||||
current_idx: usize,
|
current_idx: usize,
|
||||||
total_len: usize,
|
total_len: usize,
|
||||||
slice: &[u8],
|
slice: &[u8],
|
||||||
) -> Result<&[u8], PusError> {
|
has_checksum: bool,
|
||||||
match current_idx {
|
) -> Result<&[u8], ByteConversionError> {
|
||||||
_ if current_idx > total_len - 2 => Err(ByteConversionError::FromSliceTooSmall {
|
if has_checksum {
|
||||||
found: total_len - 2,
|
if current_idx > total_len - 2 {
|
||||||
expected: current_idx,
|
return Err(ByteConversionError::FromSliceTooSmall {
|
||||||
|
found: total_len - 2,
|
||||||
|
expected: current_idx,
|
||||||
|
});
|
||||||
}
|
}
|
||||||
.into()),
|
Ok(&slice[current_idx..total_len - 2])
|
||||||
_ => Ok(&slice[current_idx..total_len - 2]),
|
} else {
|
||||||
|
Ok(&slice[current_idx..total_len])
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(crate) fn verify_crc16_ccitt_false_from_raw_to_pus_error(
|
pub fn verify_crc16_ccitt_false_from_raw_to_pus_error(
|
||||||
raw_data: &[u8],
|
raw_data: &[u8],
|
||||||
crc16: u16,
|
crc16: u16,
|
||||||
) -> Result<(), PusError> {
|
) -> Result<(), PusError> {
|
||||||
verify_crc16_ccitt_false_from_raw(raw_data)
|
verify_crc16_ccitt_false_from_raw(raw_data)
|
||||||
.then(|| ())
|
.then_some(())
|
||||||
.ok_or(PusError::ChecksumFailure(crc16))
|
.ok_or(PusError::ChecksumFailure(crc16))
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(crate) fn verify_crc16_ccitt_false_from_raw(raw_data: &[u8]) -> bool {
|
pub fn verify_crc16_ccitt_false_from_raw_to_pus_error_no_table(
|
||||||
|
raw_data: &[u8],
|
||||||
|
crc16: u16,
|
||||||
|
) -> Result<(), PusError> {
|
||||||
|
verify_crc16_ccitt_false_from_raw_no_table(raw_data)
|
||||||
|
.then_some(())
|
||||||
|
.ok_or(PusError::ChecksumFailure(crc16))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Verify the CRC16 of a raw packet.
|
||||||
|
pub fn verify_crc16_ccitt_false_from_raw(raw_data: &[u8]) -> bool {
|
||||||
let mut digest = CRC_CCITT_FALSE.digest();
|
let mut digest = CRC_CCITT_FALSE.digest();
|
||||||
digest.update(raw_data);
|
digest.update(raw_data);
|
||||||
if digest.finalize() == 0 {
|
if digest.finalize() == 0 {
|
||||||
@@ -277,29 +254,30 @@ pub(crate) fn verify_crc16_ccitt_false_from_raw(raw_data: &[u8]) -> bool {
|
|||||||
false
|
false
|
||||||
}
|
}
|
||||||
|
|
||||||
macro_rules! ccsds_impl {
|
/// Verify the CRC16 of a raw packet, using the table-less implementation.
|
||||||
() => {
|
pub fn verify_crc16_ccitt_false_from_raw_no_table(raw_data: &[u8]) -> bool {
|
||||||
delegate!(to self.sp_header {
|
let mut digest = CRC_CCITT_FALSE_NO_TABLE.digest();
|
||||||
fn ccsds_version(&self) -> u8;
|
digest.update(raw_data);
|
||||||
fn packet_id(&self) -> crate::PacketId;
|
if digest.finalize() == 0 {
|
||||||
fn psc(&self) -> crate::PacketSequenceCtrl;
|
return true;
|
||||||
fn data_len(&self) -> u16;
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
false
|
||||||
}
|
}
|
||||||
|
|
||||||
macro_rules! sp_header_impls {
|
macro_rules! sp_header_impls {
|
||||||
() => {
|
() => {
|
||||||
delegate!(to self.sp_header {
|
delegate!(to self.sp_header {
|
||||||
pub fn set_apid(&mut self, apid: u16) -> bool;
|
#[inline]
|
||||||
pub fn set_seq_count(&mut self, seq_count: u16) -> bool;
|
pub fn set_apid(&mut self, apid: u11);
|
||||||
|
#[inline]
|
||||||
|
pub fn set_seq_count(&mut self, seq_count: u14);
|
||||||
|
#[inline]
|
||||||
pub fn set_seq_flags(&mut self, seq_flag: SequenceFlags);
|
pub fn set_seq_flags(&mut self, seq_flag: SequenceFlags);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
use crate::util::{GenericUnsignedByteField, ToBeBytes, UnsignedEnum};
|
use crate::util::{GenericUnsignedByteField, ToBeBytes, UnsignedEnum};
|
||||||
pub(crate) use ccsds_impl;
|
|
||||||
pub(crate) use sp_header_impls;
|
pub(crate) use sp_header_impls;
|
||||||
|
|
||||||
/// Generic trait for ECSS enumeration which consist of a PFC field denoting their bit length
|
/// Generic trait for ECSS enumeration which consist of a PFC field denoting their bit length
|
||||||
@@ -360,14 +338,20 @@ impl<TYPE: Debug + Copy + Clone + PartialEq + Eq + ToBeBytes + Into<u64>> EcssEn
|
|||||||
{
|
{
|
||||||
}
|
}
|
||||||
|
|
||||||
|
impl<T: Copy + Into<u64>> From<T> for GenericEcssEnumWrapper<T> {
|
||||||
|
fn from(value: T) -> Self {
|
||||||
|
Self::new(value)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
macro_rules! generic_ecss_enum_typedefs_and_from_impls {
|
macro_rules! generic_ecss_enum_typedefs_and_from_impls {
|
||||||
($($ty:ty => $Enum:ident),*) => {
|
($($ty:ty => $Enum:ident),*) => {
|
||||||
$(
|
$(
|
||||||
pub type $Enum = GenericEcssEnumWrapper<$ty>;
|
pub type $Enum = GenericEcssEnumWrapper<$ty>;
|
||||||
|
|
||||||
impl From<$ty> for $Enum {
|
impl From<$Enum> for $ty {
|
||||||
fn from(value: $ty) -> Self {
|
fn from(value: $Enum) -> Self {
|
||||||
Self::new(value)
|
value.value_typed()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
)*
|
)*
|
||||||
@@ -387,8 +371,47 @@ generic_ecss_enum_typedefs_and_from_impls! {
|
|||||||
/// byte representation. This is especially useful for generic abstractions which depend only
|
/// byte representation. This is especially useful for generic abstractions which depend only
|
||||||
/// on the serialization of those packets.
|
/// on the serialization of those packets.
|
||||||
pub trait WritablePusPacket {
|
pub trait WritablePusPacket {
|
||||||
|
/// The length here also includes the CRC length.
|
||||||
fn len_written(&self) -> usize;
|
fn len_written(&self) -> usize;
|
||||||
fn write_to_bytes(&self, slice: &mut [u8]) -> Result<usize, PusError>;
|
|
||||||
|
/// Checksum generation is enabled for the packet.
|
||||||
|
fn has_checksum(&self) -> bool;
|
||||||
|
|
||||||
|
/// Writes the packet to the given slice without writing the CRC checksum.
|
||||||
|
///
|
||||||
|
/// The returned size is the written size WITHOUT the CRC checksum.
|
||||||
|
/// If the checksum generation is disabled, this function is identical to the APIs which
|
||||||
|
/// generate a checksum.
|
||||||
|
fn write_to_bytes_no_checksum(&self, slice: &mut [u8]) -> Result<usize, PusError>;
|
||||||
|
|
||||||
|
/// First uses [Self::write_to_bytes_no_checksum] to write the packet to the given slice and
|
||||||
|
/// then uses the [CRC_CCITT_FALSE] to calculate the CRC and write it to the slice if the
|
||||||
|
/// packet is configured to include a checksum.
|
||||||
|
fn write_to_bytes(&self, slice: &mut [u8]) -> Result<usize, PusError> {
|
||||||
|
let mut curr_idx = self.write_to_bytes_no_checksum(slice)?;
|
||||||
|
if self.has_checksum() {
|
||||||
|
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)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// First uses [Self::write_to_bytes_no_checksum] to write the packet to the given slice and then
|
||||||
|
/// uses the [CRC_CCITT_FALSE_NO_TABLE] to calculate the CRC and write it to the slice if
|
||||||
|
/// the paket is configured to include a checksum.
|
||||||
|
fn write_to_bytes_checksum_no_table(&self, slice: &mut [u8]) -> Result<usize, PusError> {
|
||||||
|
let mut curr_idx = self.write_to_bytes_no_checksum(slice)?;
|
||||||
|
if self.has_checksum() {
|
||||||
|
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)
|
||||||
|
}
|
||||||
|
|
||||||
#[cfg(feature = "alloc")]
|
#[cfg(feature = "alloc")]
|
||||||
fn to_vec(&self) -> Result<Vec<u8>, PusError> {
|
fn to_vec(&self) -> Result<Vec<u8>, PusError> {
|
||||||
// This is the correct way to do this. See
|
// This is the correct way to do this. See
|
||||||
@@ -400,6 +423,25 @@ pub trait WritablePusPacket {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||||
|
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
||||||
|
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
|
||||||
|
pub struct CreatorConfig {
|
||||||
|
/// Set the CCSDS data length field on construction.
|
||||||
|
pub set_ccsds_len: bool,
|
||||||
|
/// CRC-16-CCITT Checksum is present.
|
||||||
|
pub has_checksum: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Default for CreatorConfig {
|
||||||
|
fn default() -> Self {
|
||||||
|
Self {
|
||||||
|
set_ccsds_len: true,
|
||||||
|
has_checksum: true,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use alloc::string::ToString;
|
use alloc::string::ToString;
|
||||||
@@ -424,6 +466,8 @@ mod tests {
|
|||||||
assert_eq!(buf[1], 1);
|
assert_eq!(buf[1], 1);
|
||||||
assert_eq!(my_enum.value(), 1);
|
assert_eq!(my_enum.value(), 1);
|
||||||
assert_eq!(my_enum.value_typed(), 1);
|
assert_eq!(my_enum.value_typed(), 1);
|
||||||
|
let enum_as_u8: u8 = my_enum.into();
|
||||||
|
assert_eq!(enum_as_u8, 1);
|
||||||
let vec = my_enum.to_vec();
|
let vec = my_enum.to_vec();
|
||||||
assert_eq!(vec, buf[1..2]);
|
assert_eq!(vec, buf[1..2]);
|
||||||
}
|
}
|
||||||
@@ -441,6 +485,8 @@ mod tests {
|
|||||||
assert_eq!(buf[2], 0x2f);
|
assert_eq!(buf[2], 0x2f);
|
||||||
assert_eq!(my_enum.value(), 0x1f2f);
|
assert_eq!(my_enum.value(), 0x1f2f);
|
||||||
assert_eq!(my_enum.value_typed(), 0x1f2f);
|
assert_eq!(my_enum.value_typed(), 0x1f2f);
|
||||||
|
let enum_as_raw: u16 = my_enum.into();
|
||||||
|
assert_eq!(enum_as_raw, 0x1f2f);
|
||||||
let vec = my_enum.to_vec();
|
let vec = my_enum.to_vec();
|
||||||
assert_eq!(vec, buf[1..3]);
|
assert_eq!(vec, buf[1..3]);
|
||||||
}
|
}
|
||||||
@@ -476,6 +522,8 @@ mod tests {
|
|||||||
assert_eq!(buf[4], 0x4f);
|
assert_eq!(buf[4], 0x4f);
|
||||||
assert_eq!(my_enum.value(), 0x1f2f3f4f);
|
assert_eq!(my_enum.value(), 0x1f2f3f4f);
|
||||||
assert_eq!(my_enum.value_typed(), 0x1f2f3f4f);
|
assert_eq!(my_enum.value_typed(), 0x1f2f3f4f);
|
||||||
|
let enum_as_raw: u32 = my_enum.into();
|
||||||
|
assert_eq!(enum_as_raw, 0x1f2f3f4f);
|
||||||
let vec = my_enum.to_vec();
|
let vec = my_enum.to_vec();
|
||||||
assert_eq!(vec, buf[1..5]);
|
assert_eq!(vec, buf[1..5]);
|
||||||
}
|
}
|
||||||
@@ -512,6 +560,8 @@ mod tests {
|
|||||||
assert_eq!(buf[7], 0x5f);
|
assert_eq!(buf[7], 0x5f);
|
||||||
assert_eq!(my_enum.value(), 0x1f2f3f4f5f);
|
assert_eq!(my_enum.value(), 0x1f2f3f4f5f);
|
||||||
assert_eq!(my_enum.value_typed(), 0x1f2f3f4f5f);
|
assert_eq!(my_enum.value_typed(), 0x1f2f3f4f5f);
|
||||||
|
let enum_as_raw: u64 = my_enum.into();
|
||||||
|
assert_eq!(enum_as_raw, 0x1f2f3f4f5f);
|
||||||
assert_eq!(u64::from_be_bytes(buf), 0x1f2f3f4f5f);
|
assert_eq!(u64::from_be_bytes(buf), 0x1f2f3f4f5f);
|
||||||
let vec = my_enum.to_vec();
|
let vec = my_enum.to_vec();
|
||||||
assert_eq!(vec, buf);
|
assert_eq!(vec, buf);
|
||||||
@@ -519,9 +569,10 @@ mod tests {
|
|||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_pus_error_display() {
|
fn test_pus_error_display() {
|
||||||
let unsupport_version = PusError::VersionNotSupported(super::PusVersion::EsaPus);
|
let unsupport_version =
|
||||||
|
PusError::VersionNotSupported(super::PusVersion::EsaPus.raw_value());
|
||||||
let write_str = unsupport_version.to_string();
|
let write_str = unsupport_version.to_string();
|
||||||
assert_eq!(write_str, "PUS version EsaPus not supported")
|
assert_eq!(write_str, "PUS version 0 not supported")
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
@@ -555,8 +606,8 @@ mod tests {
|
|||||||
#[test]
|
#[test]
|
||||||
fn test_pus_error_eq_impl() {
|
fn test_pus_error_eq_impl() {
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
PusError::VersionNotSupported(PusVersion::EsaPus),
|
PusError::VersionNotSupported(PusVersion::EsaPus.raw_value()),
|
||||||
PusError::VersionNotSupported(PusVersion::EsaPus)
|
PusError::VersionNotSupported(PusVersion::EsaPus.raw_value())
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@@ -5,6 +5,7 @@ use serde::{Deserialize, Serialize};
|
|||||||
|
|
||||||
#[derive(Debug, PartialEq, Eq, Copy, Clone, IntoPrimitive, TryFromPrimitive)]
|
#[derive(Debug, PartialEq, Eq, Copy, Clone, IntoPrimitive, TryFromPrimitive)]
|
||||||
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
||||||
|
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
|
||||||
#[repr(u8)]
|
#[repr(u8)]
|
||||||
pub enum Subservice {
|
pub enum Subservice {
|
||||||
// Core subservices
|
// Core subservices
|
||||||
@@ -47,6 +48,7 @@ pub enum Subservice {
|
|||||||
|
|
||||||
/// This status applies to sub-schedules and groups as well as specified in ECSS-E-ST-70-41C 8.11.3
|
/// This status applies to sub-schedules and groups as well as specified in ECSS-E-ST-70-41C 8.11.3
|
||||||
#[derive(Debug, PartialEq, Eq, Copy, Clone)]
|
#[derive(Debug, PartialEq, Eq, Copy, Clone)]
|
||||||
|
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
|
||||||
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
||||||
pub enum SchedStatus {
|
pub enum SchedStatus {
|
||||||
Disabled = 0,
|
Disabled = 0,
|
||||||
@@ -54,6 +56,7 @@ pub enum SchedStatus {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl From<bool> for SchedStatus {
|
impl From<bool> for SchedStatus {
|
||||||
|
#[inline]
|
||||||
fn from(value: bool) -> Self {
|
fn from(value: bool) -> Self {
|
||||||
if value {
|
if value {
|
||||||
SchedStatus::Enabled
|
SchedStatus::Enabled
|
||||||
@@ -65,6 +68,7 @@ impl From<bool> for SchedStatus {
|
|||||||
|
|
||||||
/// Time window types as specified in ECSS-E-ST-70-41C 8.11.3
|
/// Time window types as specified in ECSS-E-ST-70-41C 8.11.3
|
||||||
#[derive(Debug, PartialEq, Eq, Copy, Clone)]
|
#[derive(Debug, PartialEq, Eq, Copy, Clone)]
|
||||||
|
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
|
||||||
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
||||||
pub enum TimeWindowType {
|
pub enum TimeWindowType {
|
||||||
SelectAll = 0,
|
SelectAll = 0,
|
||||||
|
1486
src/ecss/tc.rs
1486
src/ecss/tc.rs
File diff suppressed because it is too large
Load Diff
1376
src/ecss/tc_pus_a.rs
Normal file
1376
src/ecss/tc_pus_a.rs
Normal file
File diff suppressed because it is too large
Load Diff
1826
src/ecss/tm.rs
1826
src/ecss/tm.rs
File diff suppressed because it is too large
Load Diff
1996
src/ecss/tm_pus_a.rs
Normal file
1996
src/ecss/tm_pus_a.rs
Normal file
File diff suppressed because it is too large
Load Diff
@@ -5,6 +5,7 @@ use serde::{Deserialize, Serialize};
|
|||||||
|
|
||||||
#[derive(Debug, Eq, PartialEq, Copy, Clone, IntoPrimitive, TryFromPrimitive)]
|
#[derive(Debug, Eq, PartialEq, Copy, Clone, IntoPrimitive, TryFromPrimitive)]
|
||||||
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
||||||
|
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
|
||||||
#[repr(u8)]
|
#[repr(u8)]
|
||||||
pub enum Subservice {
|
pub enum Subservice {
|
||||||
TmAcceptanceSuccess = 1,
|
TmAcceptanceSuccess = 1,
|
||||||
|
770
src/lib.rs
770
src/lib.rs
File diff suppressed because it is too large
Load Diff
437
src/seq_count.rs
Normal file
437
src/seq_count.rs
Normal file
@@ -0,0 +1,437 @@
|
|||||||
|
use crate::MAX_SEQ_COUNT;
|
||||||
|
use arbitrary_int::traits::Integer;
|
||||||
|
use core::cell::Cell;
|
||||||
|
use paste::paste;
|
||||||
|
|
||||||
|
/// Core trait for objects which can provide a sequence count.
|
||||||
|
///
|
||||||
|
/// The core functions are not mutable on purpose to allow easier usage with
|
||||||
|
/// static structs when using the interior mutability pattern. This can be achieved by using
|
||||||
|
/// [Cell], [core::cell::RefCell] or atomic types.
|
||||||
|
pub trait SequenceCounter {
|
||||||
|
type Raw: Into<u64>;
|
||||||
|
const MAX_BIT_WIDTH: usize;
|
||||||
|
|
||||||
|
fn get(&self) -> Self::Raw;
|
||||||
|
|
||||||
|
fn increment(&self);
|
||||||
|
|
||||||
|
fn increment_mut(&mut self) {
|
||||||
|
self.increment();
|
||||||
|
}
|
||||||
|
|
||||||
|
fn get_and_increment(&self) -> Self::Raw {
|
||||||
|
let val = self.get();
|
||||||
|
self.increment();
|
||||||
|
val
|
||||||
|
}
|
||||||
|
|
||||||
|
fn get_and_increment_mut(&mut self) -> Self::Raw {
|
||||||
|
self.get_and_increment()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone)]
|
||||||
|
pub struct SequenceCounterSimple<T: Copy> {
|
||||||
|
seq_count: Cell<T>,
|
||||||
|
// The maximum value
|
||||||
|
max_val: T,
|
||||||
|
}
|
||||||
|
|
||||||
|
macro_rules! impl_for_primitives {
|
||||||
|
($($ty: ident,)+) => {
|
||||||
|
$(
|
||||||
|
paste! {
|
||||||
|
impl SequenceCounterSimple<$ty> {
|
||||||
|
pub fn [<new_custom_max_val_ $ty>](max_val: $ty) -> Self {
|
||||||
|
Self {
|
||||||
|
seq_count: Cell::new(0),
|
||||||
|
max_val,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
pub fn [<new_ $ty>]() -> Self {
|
||||||
|
Self {
|
||||||
|
seq_count: Cell::new(0),
|
||||||
|
max_val: $ty::MAX
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Default for SequenceCounterSimple<$ty> {
|
||||||
|
fn default() -> Self {
|
||||||
|
Self::[<new_ $ty>]()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl SequenceCounter for SequenceCounterSimple<$ty> {
|
||||||
|
type Raw = $ty;
|
||||||
|
const MAX_BIT_WIDTH: usize = core::mem::size_of::<Self::Raw>() * 8;
|
||||||
|
|
||||||
|
fn get(&self) -> Self::Raw {
|
||||||
|
self.seq_count.get()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn increment(&self) {
|
||||||
|
self.get_and_increment();
|
||||||
|
}
|
||||||
|
|
||||||
|
fn get_and_increment(&self) -> Self::Raw {
|
||||||
|
let curr_count = self.seq_count.get();
|
||||||
|
|
||||||
|
if curr_count == self.max_val {
|
||||||
|
self.seq_count.set(0);
|
||||||
|
} else {
|
||||||
|
self.seq_count.set(curr_count + 1);
|
||||||
|
}
|
||||||
|
curr_count
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
)+
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl_for_primitives!(u8, u16, u32, u64,);
|
||||||
|
|
||||||
|
/// This is a sequence count provider which wraps around at [MAX_SEQ_COUNT].
|
||||||
|
#[derive(Clone)]
|
||||||
|
pub struct SequenceCounterCcsdsSimple {
|
||||||
|
provider: SequenceCounterSimple<u16>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Default for SequenceCounterCcsdsSimple {
|
||||||
|
fn default() -> Self {
|
||||||
|
Self {
|
||||||
|
provider: SequenceCounterSimple::new_custom_max_val_u16(MAX_SEQ_COUNT.as_u16()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl SequenceCounter for SequenceCounterCcsdsSimple {
|
||||||
|
type Raw = u16;
|
||||||
|
const MAX_BIT_WIDTH: usize = core::mem::size_of::<Self::Raw>() * 8;
|
||||||
|
delegate::delegate! {
|
||||||
|
to self.provider {
|
||||||
|
fn get(&self) -> u16;
|
||||||
|
fn increment(&self);
|
||||||
|
fn get_and_increment(&self) -> u16;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl SequenceCounter for core::sync::atomic::AtomicU8 {
|
||||||
|
type Raw = u8;
|
||||||
|
|
||||||
|
const MAX_BIT_WIDTH: usize = 8;
|
||||||
|
|
||||||
|
fn get(&self) -> Self::Raw {
|
||||||
|
self.load(core::sync::atomic::Ordering::Relaxed)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn increment(&self) {
|
||||||
|
self.fetch_add(1, core::sync::atomic::Ordering::Relaxed);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl SequenceCounter for core::sync::atomic::AtomicU16 {
|
||||||
|
type Raw = u16;
|
||||||
|
|
||||||
|
const MAX_BIT_WIDTH: usize = 16;
|
||||||
|
|
||||||
|
fn get(&self) -> Self::Raw {
|
||||||
|
self.load(core::sync::atomic::Ordering::Relaxed)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn increment(&self) {
|
||||||
|
self.fetch_add(1, core::sync::atomic::Ordering::Relaxed);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl SequenceCounter for core::sync::atomic::AtomicU32 {
|
||||||
|
type Raw = u32;
|
||||||
|
|
||||||
|
const MAX_BIT_WIDTH: usize = 32;
|
||||||
|
|
||||||
|
fn get(&self) -> Self::Raw {
|
||||||
|
self.load(core::sync::atomic::Ordering::Relaxed)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn increment(&self) {
|
||||||
|
self.fetch_add(1, core::sync::atomic::Ordering::Relaxed);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(target_has_atomic = "64")]
|
||||||
|
impl SequenceCounter for core::sync::atomic::AtomicU64 {
|
||||||
|
type Raw = u64;
|
||||||
|
|
||||||
|
const MAX_BIT_WIDTH: usize = 64;
|
||||||
|
|
||||||
|
fn get(&self) -> Self::Raw {
|
||||||
|
self.load(core::sync::atomic::Ordering::Relaxed)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn increment(&self) {
|
||||||
|
self.fetch_add(1, core::sync::atomic::Ordering::Relaxed);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl SequenceCounter for portable_atomic::AtomicU8 {
|
||||||
|
type Raw = u8;
|
||||||
|
|
||||||
|
const MAX_BIT_WIDTH: usize = 8;
|
||||||
|
|
||||||
|
fn get(&self) -> Self::Raw {
|
||||||
|
self.load(core::sync::atomic::Ordering::Relaxed)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn increment(&self) {
|
||||||
|
self.fetch_add(1, core::sync::atomic::Ordering::Relaxed);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl SequenceCounter for portable_atomic::AtomicU16 {
|
||||||
|
type Raw = u16;
|
||||||
|
|
||||||
|
const MAX_BIT_WIDTH: usize = 16;
|
||||||
|
|
||||||
|
fn get(&self) -> Self::Raw {
|
||||||
|
self.load(core::sync::atomic::Ordering::Relaxed)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn increment(&self) {
|
||||||
|
self.fetch_add(1, core::sync::atomic::Ordering::Relaxed);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl SequenceCounter for portable_atomic::AtomicU32 {
|
||||||
|
type Raw = u32;
|
||||||
|
|
||||||
|
const MAX_BIT_WIDTH: usize = 32;
|
||||||
|
|
||||||
|
fn get(&self) -> Self::Raw {
|
||||||
|
self.load(core::sync::atomic::Ordering::Relaxed)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn increment(&self) {
|
||||||
|
self.fetch_add(1, core::sync::atomic::Ordering::Relaxed);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl SequenceCounter for portable_atomic::AtomicU64 {
|
||||||
|
type Raw = u64;
|
||||||
|
|
||||||
|
const MAX_BIT_WIDTH: usize = 64;
|
||||||
|
|
||||||
|
fn get(&self) -> Self::Raw {
|
||||||
|
self.load(core::sync::atomic::Ordering::Relaxed)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn increment(&self) {
|
||||||
|
self.fetch_add(1, core::sync::atomic::Ordering::Relaxed);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T: SequenceCounter + ?Sized> SequenceCounter for &T {
|
||||||
|
type Raw = T::Raw;
|
||||||
|
const MAX_BIT_WIDTH: usize = T::MAX_BIT_WIDTH;
|
||||||
|
|
||||||
|
fn get(&self) -> Self::Raw {
|
||||||
|
(**self).get()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn increment(&self) {
|
||||||
|
(**self).increment()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
macro_rules! sync_clonable_seq_counter_impl {
|
||||||
|
($ty: ident) => {
|
||||||
|
paste::paste! {
|
||||||
|
/// This can be used if a custom wrap value is required when using a thread-safe
|
||||||
|
/// atomic based sequence counter.
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub struct [<SequenceCounterSyncCustomWrap $ty:upper>] {
|
||||||
|
seq_count: core::sync::atomic::[<Atomic $ty:upper>],
|
||||||
|
max_val: $ty,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl [<SequenceCounterSyncCustomWrap $ty:upper>] {
|
||||||
|
pub fn new(max_val: $ty) -> Self {
|
||||||
|
Self {
|
||||||
|
seq_count: core::sync::atomic::[<Atomic $ty:upper>]::new(0),
|
||||||
|
max_val,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl SequenceCounter for [<SequenceCounterSyncCustomWrap $ty:upper>] {
|
||||||
|
type Raw = $ty;
|
||||||
|
const MAX_BIT_WIDTH: usize = core::mem::size_of::<Self::Raw>() * 8;
|
||||||
|
|
||||||
|
fn get(&self) -> $ty {
|
||||||
|
self.seq_count.load(core::sync::atomic::Ordering::Relaxed)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn increment(&self) {
|
||||||
|
self.get_and_increment();
|
||||||
|
}
|
||||||
|
|
||||||
|
fn get_and_increment(&self) -> $ty {
|
||||||
|
self.seq_count.fetch_update(
|
||||||
|
core::sync::atomic::Ordering::Relaxed,
|
||||||
|
core::sync::atomic::Ordering::Relaxed,
|
||||||
|
|cur| {
|
||||||
|
// compute the next value, wrapping at MAX_VAL
|
||||||
|
let next = if cur == self.max_val { 0 } else { cur + 1 };
|
||||||
|
Some(next)
|
||||||
|
},
|
||||||
|
).unwrap()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(target_has_atomic = "8")]
|
||||||
|
sync_clonable_seq_counter_impl!(u8);
|
||||||
|
#[cfg(target_has_atomic = "16")]
|
||||||
|
sync_clonable_seq_counter_impl!(u16);
|
||||||
|
#[cfg(target_has_atomic = "32")]
|
||||||
|
sync_clonable_seq_counter_impl!(u32);
|
||||||
|
#[cfg(target_has_atomic = "64")]
|
||||||
|
sync_clonable_seq_counter_impl!(u64);
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use core::sync::atomic::{AtomicU16, AtomicU32, AtomicU64, AtomicU8};
|
||||||
|
|
||||||
|
use crate::seq_count::{
|
||||||
|
SequenceCounter, SequenceCounterCcsdsSimple, SequenceCounterSimple,
|
||||||
|
SequenceCounterSyncCustomWrapU8,
|
||||||
|
};
|
||||||
|
use crate::MAX_SEQ_COUNT;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_u8_counter() {
|
||||||
|
let u8_counter = SequenceCounterSimple::<u8>::default();
|
||||||
|
assert_eq!(u8_counter.get(), 0);
|
||||||
|
assert_eq!(u8_counter.get_and_increment(), 0);
|
||||||
|
assert_eq!(u8_counter.get_and_increment(), 1);
|
||||||
|
assert_eq!(u8_counter.get(), 2);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_u8_counter_overflow() {
|
||||||
|
let u8_counter = SequenceCounterSimple::new_u8();
|
||||||
|
for _ in 0..256 {
|
||||||
|
u8_counter.increment();
|
||||||
|
}
|
||||||
|
assert_eq!(u8_counter.get(), 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_ccsds_counter() {
|
||||||
|
let ccsds_counter = SequenceCounterCcsdsSimple::default();
|
||||||
|
assert_eq!(ccsds_counter.get(), 0);
|
||||||
|
assert_eq!(ccsds_counter.get_and_increment(), 0);
|
||||||
|
assert_eq!(ccsds_counter.get_and_increment(), 1);
|
||||||
|
assert_eq!(ccsds_counter.get(), 2);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_ccsds_counter_overflow() {
|
||||||
|
let ccsds_counter = SequenceCounterCcsdsSimple::default();
|
||||||
|
for _ in 0..MAX_SEQ_COUNT.value() + 1 {
|
||||||
|
ccsds_counter.increment();
|
||||||
|
}
|
||||||
|
assert_eq!(ccsds_counter.get(), 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn common_counter_test(seq_counter: &mut impl SequenceCounter) {
|
||||||
|
assert_eq!(seq_counter.get().into(), 0);
|
||||||
|
assert_eq!(seq_counter.get_and_increment().into(), 0);
|
||||||
|
assert_eq!(seq_counter.get_and_increment().into(), 1);
|
||||||
|
assert_eq!(seq_counter.get().into(), 2);
|
||||||
|
seq_counter.increment_mut();
|
||||||
|
assert_eq!(seq_counter.get().into(), 3);
|
||||||
|
assert_eq!(seq_counter.get_and_increment_mut().into(), 3);
|
||||||
|
assert_eq!(seq_counter.get().into(), 4);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_atomic_counter_u8() {
|
||||||
|
let mut sync_u8_counter = AtomicU8::new(0);
|
||||||
|
common_counter_test(&mut sync_u8_counter);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_atomic_counter_u16() {
|
||||||
|
let mut sync_u16_counter = AtomicU16::new(0);
|
||||||
|
common_counter_test(&mut sync_u16_counter);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_atomic_counter_u32() {
|
||||||
|
let mut sync_u32_counter = AtomicU32::new(0);
|
||||||
|
common_counter_test(&mut sync_u32_counter);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_atomic_counter_u64() {
|
||||||
|
let mut sync_u64_counter = AtomicU64::new(0);
|
||||||
|
common_counter_test(&mut sync_u64_counter);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_portable_atomic_counter_u8() {
|
||||||
|
let mut sync_u8_counter = portable_atomic::AtomicU8::new(0);
|
||||||
|
common_counter_test(&mut sync_u8_counter);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_portable_atomic_counter_u16() {
|
||||||
|
let mut sync_u16_counter = portable_atomic::AtomicU16::new(0);
|
||||||
|
common_counter_test(&mut sync_u16_counter);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_portable_atomic_counter_u32() {
|
||||||
|
let mut sync_u32_counter = portable_atomic::AtomicU32::new(0);
|
||||||
|
common_counter_test(&mut sync_u32_counter);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_portable_atomic_counter_u64() {
|
||||||
|
let mut sync_u64_counter = portable_atomic::AtomicU64::new(0);
|
||||||
|
common_counter_test(&mut sync_u64_counter);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn common_overflow_test_u8(seq_counter: &impl SequenceCounter) {
|
||||||
|
for _ in 0..u8::MAX as u16 + 1 {
|
||||||
|
seq_counter.increment();
|
||||||
|
}
|
||||||
|
assert_eq!(seq_counter.get().into(), 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_atomic_u8_counter_overflow() {
|
||||||
|
let sync_u8_counter = AtomicU8::new(0);
|
||||||
|
common_overflow_test_u8(&sync_u8_counter);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_portable_atomic_u8_counter_overflow() {
|
||||||
|
let sync_u8_counter = portable_atomic::AtomicU8::new(0);
|
||||||
|
common_overflow_test_u8(&sync_u8_counter);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_atomic_ref_counters_overflow_custom_max_val() {
|
||||||
|
let sync_u8_counter = SequenceCounterSyncCustomWrapU8::new(128);
|
||||||
|
for _ in 0..129 {
|
||||||
|
sync_u8_counter.increment();
|
||||||
|
}
|
||||||
|
assert_eq!(sync_u8_counter.get(), 0);
|
||||||
|
}
|
||||||
|
}
|
@@ -2,11 +2,8 @@
|
|||||||
//! [CCSDS 301.0-B-4](https://public.ccsds.org/Pubs/301x0b4e1.pdf) section 3.5 .
|
//! [CCSDS 301.0-B-4](https://public.ccsds.org/Pubs/301x0b4e1.pdf) section 3.5 .
|
||||||
//! See [chrono::DateTime::format] for a usage example of the generated
|
//! See [chrono::DateTime::format] for a usage example of the generated
|
||||||
//! [chrono::format::DelayedFormat] structs.
|
//! [chrono::format::DelayedFormat] structs.
|
||||||
#[cfg(feature = "alloc")]
|
#[cfg(all(feature = "alloc", feature = "chrono"))]
|
||||||
use chrono::{
|
pub use alloc_mod_chrono::*;
|
||||||
format::{DelayedFormat, StrftimeItems},
|
|
||||||
DateTime, Utc,
|
|
||||||
};
|
|
||||||
|
|
||||||
/// Tuple of format string and formatted size for time code A.
|
/// Tuple of format string and formatted size for time code A.
|
||||||
///
|
///
|
||||||
@@ -34,36 +31,37 @@ pub const FMT_STR_CODE_B_WITH_SIZE: (&str, usize) = ("%Y-%jT%T%.3f", 21);
|
|||||||
/// Three digits are used for the decimal fraction and a terminator is added at the end.
|
/// Three digits are used for the decimal fraction and a terminator is added at the end.
|
||||||
pub const FMT_STR_CODE_B_TERMINATED_WITH_SIZE: (&str, usize) = ("%Y-%jT%T%.3fZ", 22);
|
pub const FMT_STR_CODE_B_TERMINATED_WITH_SIZE: (&str, usize) = ("%Y-%jT%T%.3fZ", 22);
|
||||||
|
|
||||||
/// Generates a time code formatter using the [FMT_STR_CODE_A_WITH_SIZE] format.
|
#[cfg(all(feature = "alloc", feature = "chrono"))]
|
||||||
#[cfg(feature = "alloc")]
|
pub mod alloc_mod_chrono {
|
||||||
#[cfg_attr(doc_cfg, doc(cfg(feature = "alloc")))]
|
use super::*;
|
||||||
pub fn generate_time_code_a(date: &DateTime<Utc>) -> DelayedFormat<StrftimeItems<'static>> {
|
use chrono::{
|
||||||
date.format(FMT_STR_CODE_A_WITH_SIZE.0)
|
format::{DelayedFormat, StrftimeItems},
|
||||||
}
|
DateTime, Utc,
|
||||||
|
};
|
||||||
|
|
||||||
/// Generates a time code formatter using the [FMT_STR_CODE_A_TERMINATED_WITH_SIZE] format.
|
/// Generates a time code formatter using the [FMT_STR_CODE_A_WITH_SIZE] format.
|
||||||
#[cfg(feature = "alloc")]
|
pub fn generate_time_code_a(date: &DateTime<Utc>) -> DelayedFormat<StrftimeItems<'static>> {
|
||||||
#[cfg_attr(doc_cfg, doc(cfg(feature = "alloc")))]
|
date.format(FMT_STR_CODE_A_WITH_SIZE.0)
|
||||||
pub fn generate_time_code_a_terminated(
|
}
|
||||||
date: &DateTime<Utc>,
|
|
||||||
) -> DelayedFormat<StrftimeItems<'static>> {
|
|
||||||
date.format(FMT_STR_CODE_A_TERMINATED_WITH_SIZE.0)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Generates a time code formatter using the [FMT_STR_CODE_B_WITH_SIZE] format.
|
/// Generates a time code formatter using the [FMT_STR_CODE_A_TERMINATED_WITH_SIZE] format.
|
||||||
#[cfg(feature = "alloc")]
|
pub fn generate_time_code_a_terminated(
|
||||||
#[cfg_attr(doc_cfg, doc(cfg(feature = "alloc")))]
|
date: &DateTime<Utc>,
|
||||||
pub fn generate_time_code_b(date: &DateTime<Utc>) -> DelayedFormat<StrftimeItems<'static>> {
|
) -> DelayedFormat<StrftimeItems<'static>> {
|
||||||
date.format(FMT_STR_CODE_B_WITH_SIZE.0)
|
date.format(FMT_STR_CODE_A_TERMINATED_WITH_SIZE.0)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Generates a time code formatter using the [FMT_STR_CODE_B_TERMINATED_WITH_SIZE] format.
|
/// Generates a time code formatter using the [FMT_STR_CODE_B_WITH_SIZE] format.
|
||||||
#[cfg(feature = "alloc")]
|
pub fn generate_time_code_b(date: &DateTime<Utc>) -> DelayedFormat<StrftimeItems<'static>> {
|
||||||
#[cfg_attr(doc_cfg, doc(cfg(feature = "alloc")))]
|
date.format(FMT_STR_CODE_B_WITH_SIZE.0)
|
||||||
pub fn generate_time_code_b_terminated(
|
}
|
||||||
date: &DateTime<Utc>,
|
|
||||||
) -> DelayedFormat<StrftimeItems<'static>> {
|
/// Generates a time code formatter using the [FMT_STR_CODE_B_TERMINATED_WITH_SIZE] format.
|
||||||
date.format(FMT_STR_CODE_B_TERMINATED_WITH_SIZE.0)
|
pub fn generate_time_code_b_terminated(
|
||||||
|
date: &DateTime<Utc>,
|
||||||
|
) -> DelayedFormat<StrftimeItems<'static>> {
|
||||||
|
date.format(FMT_STR_CODE_B_TERMINATED_WITH_SIZE.0)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
@@ -73,25 +71,54 @@ mod tests {
|
|||||||
use std::format;
|
use std::format;
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_ascii_timestamp_a_unterminated() {
|
fn test_ascii_timestamp_a_unterminated_epoch() {
|
||||||
let date = Utc::now();
|
let date = chrono::DateTime::UNIX_EPOCH;
|
||||||
let stamp_formatter = generate_time_code_a(&date);
|
let stamp_formatter = generate_time_code_a(&date);
|
||||||
let stamp = format!("{}", stamp_formatter);
|
let stamp = format!("{}", stamp_formatter);
|
||||||
let t_sep = stamp.find("T");
|
let t_sep = stamp.find('T');
|
||||||
assert!(t_sep.is_some());
|
assert!(t_sep.is_some());
|
||||||
assert_eq!(t_sep.unwrap(), 10);
|
assert_eq!(t_sep.unwrap(), 10);
|
||||||
assert_eq!(stamp.len(), FMT_STR_CODE_A_WITH_SIZE.1);
|
assert_eq!(stamp.len(), FMT_STR_CODE_A_WITH_SIZE.1);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_ascii_timestamp_a_terminated() {
|
#[cfg_attr(miri, ignore)]
|
||||||
|
fn test_ascii_timestamp_a_unterminated_now() {
|
||||||
|
let date = Utc::now();
|
||||||
|
let stamp_formatter = generate_time_code_a(&date);
|
||||||
|
let stamp = format!("{}", stamp_formatter);
|
||||||
|
let t_sep = stamp.find('T');
|
||||||
|
assert!(t_sep.is_some());
|
||||||
|
assert_eq!(t_sep.unwrap(), 10);
|
||||||
|
assert_eq!(stamp.len(), FMT_STR_CODE_A_WITH_SIZE.1);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_ascii_timestamp_a_terminated_epoch() {
|
||||||
|
let date = chrono::DateTime::UNIX_EPOCH;
|
||||||
|
let stamp_formatter = generate_time_code_a_terminated(&date);
|
||||||
|
let stamp = format!("{}", stamp_formatter);
|
||||||
|
let t_sep = stamp.find('T');
|
||||||
|
assert!(t_sep.is_some());
|
||||||
|
assert_eq!(t_sep.unwrap(), 10);
|
||||||
|
let z_terminator = stamp.find('Z');
|
||||||
|
assert!(z_terminator.is_some());
|
||||||
|
assert_eq!(
|
||||||
|
z_terminator.unwrap(),
|
||||||
|
FMT_STR_CODE_A_TERMINATED_WITH_SIZE.1 - 1
|
||||||
|
);
|
||||||
|
assert_eq!(stamp.len(), FMT_STR_CODE_A_TERMINATED_WITH_SIZE.1);
|
||||||
|
}
|
||||||
|
#[test]
|
||||||
|
#[cfg_attr(miri, ignore)]
|
||||||
|
fn test_ascii_timestamp_a_terminated_now() {
|
||||||
let date = Utc::now();
|
let date = Utc::now();
|
||||||
let stamp_formatter = generate_time_code_a_terminated(&date);
|
let stamp_formatter = generate_time_code_a_terminated(&date);
|
||||||
let stamp = format!("{}", stamp_formatter);
|
let stamp = format!("{}", stamp_formatter);
|
||||||
let t_sep = stamp.find("T");
|
let t_sep = stamp.find('T');
|
||||||
assert!(t_sep.is_some());
|
assert!(t_sep.is_some());
|
||||||
assert_eq!(t_sep.unwrap(), 10);
|
assert_eq!(t_sep.unwrap(), 10);
|
||||||
let z_terminator = stamp.find("Z");
|
let z_terminator = stamp.find('Z');
|
||||||
assert!(z_terminator.is_some());
|
assert!(z_terminator.is_some());
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
z_terminator.unwrap(),
|
z_terminator.unwrap(),
|
||||||
@@ -101,25 +128,55 @@ mod tests {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_ascii_timestamp_b_unterminated() {
|
fn test_ascii_timestamp_b_unterminated_epoch() {
|
||||||
let date = Utc::now();
|
let date = chrono::DateTime::UNIX_EPOCH;
|
||||||
let stamp_formatter = generate_time_code_b(&date);
|
let stamp_formatter = generate_time_code_b(&date);
|
||||||
let stamp = format!("{}", stamp_formatter);
|
let stamp = format!("{}", stamp_formatter);
|
||||||
let t_sep = stamp.find("T");
|
let t_sep = stamp.find('T');
|
||||||
assert!(t_sep.is_some());
|
assert!(t_sep.is_some());
|
||||||
assert_eq!(t_sep.unwrap(), 8);
|
assert_eq!(t_sep.unwrap(), 8);
|
||||||
assert_eq!(stamp.len(), FMT_STR_CODE_B_WITH_SIZE.1);
|
assert_eq!(stamp.len(), FMT_STR_CODE_B_WITH_SIZE.1);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_ascii_timestamp_b_terminated() {
|
#[cfg_attr(miri, ignore)]
|
||||||
|
fn test_ascii_timestamp_b_unterminated_now() {
|
||||||
|
let date = Utc::now();
|
||||||
|
let stamp_formatter = generate_time_code_b(&date);
|
||||||
|
let stamp = format!("{}", stamp_formatter);
|
||||||
|
let t_sep = stamp.find('T');
|
||||||
|
assert!(t_sep.is_some());
|
||||||
|
assert_eq!(t_sep.unwrap(), 8);
|
||||||
|
assert_eq!(stamp.len(), FMT_STR_CODE_B_WITH_SIZE.1);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_ascii_timestamp_b_terminated_epoch() {
|
||||||
|
let date = chrono::DateTime::UNIX_EPOCH;
|
||||||
|
let stamp_formatter = generate_time_code_b_terminated(&date);
|
||||||
|
let stamp = format!("{}", stamp_formatter);
|
||||||
|
let t_sep = stamp.find('T');
|
||||||
|
assert!(t_sep.is_some());
|
||||||
|
assert_eq!(t_sep.unwrap(), 8);
|
||||||
|
let z_terminator = stamp.find('Z');
|
||||||
|
assert!(z_terminator.is_some());
|
||||||
|
assert_eq!(
|
||||||
|
z_terminator.unwrap(),
|
||||||
|
FMT_STR_CODE_B_TERMINATED_WITH_SIZE.1 - 1
|
||||||
|
);
|
||||||
|
assert_eq!(stamp.len(), FMT_STR_CODE_B_TERMINATED_WITH_SIZE.1);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
#[cfg_attr(miri, ignore)]
|
||||||
|
fn test_ascii_timestamp_b_terminated_now() {
|
||||||
let date = Utc::now();
|
let date = Utc::now();
|
||||||
let stamp_formatter = generate_time_code_b_terminated(&date);
|
let stamp_formatter = generate_time_code_b_terminated(&date);
|
||||||
let stamp = format!("{}", stamp_formatter);
|
let stamp = format!("{}", stamp_formatter);
|
||||||
let t_sep = stamp.find("T");
|
let t_sep = stamp.find('T');
|
||||||
assert!(t_sep.is_some());
|
assert!(t_sep.is_some());
|
||||||
assert_eq!(t_sep.unwrap(), 8);
|
assert_eq!(t_sep.unwrap(), 8);
|
||||||
let z_terminator = stamp.find("Z");
|
let z_terminator = stamp.find('Z');
|
||||||
assert!(z_terminator.is_some());
|
assert!(z_terminator.is_some());
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
z_terminator.unwrap(),
|
z_terminator.unwrap(),
|
||||||
|
944
src/time/cds.rs
944
src/time/cds.rs
File diff suppressed because it is too large
Load Diff
952
src/time/cuc.rs
952
src/time/cuc.rs
File diff suppressed because it is too large
Load Diff
477
src/time/mod.rs
477
src/time/mod.rs
@@ -1,11 +1,10 @@
|
|||||||
//! CCSDS Time Code Formats according to [CCSDS 301.0-B-4](https://public.ccsds.org/Pubs/301x0b4e1.pdf)
|
//! CCSDS Time Code Formats according to [CCSDS 301.0-B-4](https://public.ccsds.org/Pubs/301x0b4e1.pdf)
|
||||||
use crate::ByteConversionError;
|
use crate::ByteConversionError;
|
||||||
use chrono::{DateTime, LocalResult, TimeZone, Utc};
|
#[cfg(feature = "chrono")]
|
||||||
|
use chrono::{TimeZone, Utc};
|
||||||
use core::cmp::Ordering;
|
use core::cmp::Ordering;
|
||||||
use core::fmt::{Display, Formatter};
|
|
||||||
use core::ops::{Add, AddAssign, Sub};
|
use core::ops::{Add, AddAssign, Sub};
|
||||||
use core::time::Duration;
|
use core::time::Duration;
|
||||||
use core::u8;
|
|
||||||
|
|
||||||
#[allow(unused_imports)]
|
#[allow(unused_imports)]
|
||||||
#[cfg(not(feature = "std"))]
|
#[cfg(not(feature = "std"))]
|
||||||
@@ -13,8 +12,7 @@ use num_traits::float::FloatCore;
|
|||||||
|
|
||||||
#[cfg(feature = "serde")]
|
#[cfg(feature = "serde")]
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
#[cfg(feature = "std")]
|
|
||||||
use std::error::Error;
|
|
||||||
#[cfg(feature = "std")]
|
#[cfg(feature = "std")]
|
||||||
use std::time::{SystemTime, SystemTimeError};
|
use std::time::{SystemTime, SystemTimeError};
|
||||||
#[cfg(feature = "std")]
|
#[cfg(feature = "std")]
|
||||||
@@ -27,10 +25,12 @@ pub mod cuc;
|
|||||||
pub const DAYS_CCSDS_TO_UNIX: i32 = -4383;
|
pub const DAYS_CCSDS_TO_UNIX: i32 = -4383;
|
||||||
pub const SECONDS_PER_DAY: u32 = 86400;
|
pub const SECONDS_PER_DAY: u32 = 86400;
|
||||||
pub const MS_PER_DAY: u32 = SECONDS_PER_DAY * 1000;
|
pub const MS_PER_DAY: u32 = SECONDS_PER_DAY * 1000;
|
||||||
|
pub const NANOS_PER_SECOND: u32 = 1_000_000_000;
|
||||||
|
|
||||||
#[derive(Debug, PartialEq, Eq, Copy, Clone)]
|
#[derive(Debug, PartialEq, Eq, Copy, Clone)]
|
||||||
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
||||||
pub enum CcsdsTimeCodes {
|
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
|
||||||
|
pub enum CcsdsTimeCode {
|
||||||
CucCcsdsEpoch = 0b001,
|
CucCcsdsEpoch = 0b001,
|
||||||
CucAgencyEpoch = 0b010,
|
CucAgencyEpoch = 0b010,
|
||||||
Cds = 0b100,
|
Cds = 0b100,
|
||||||
@@ -38,16 +38,16 @@ pub enum CcsdsTimeCodes {
|
|||||||
AgencyDefined = 0b110,
|
AgencyDefined = 0b110,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl TryFrom<u8> for CcsdsTimeCodes {
|
impl TryFrom<u8> for CcsdsTimeCode {
|
||||||
type Error = ();
|
type Error = ();
|
||||||
|
|
||||||
fn try_from(value: u8) -> Result<Self, Self::Error> {
|
fn try_from(value: u8) -> Result<Self, Self::Error> {
|
||||||
match value {
|
match value {
|
||||||
x if x == CcsdsTimeCodes::CucCcsdsEpoch as u8 => Ok(CcsdsTimeCodes::CucCcsdsEpoch),
|
x if x == CcsdsTimeCode::CucCcsdsEpoch as u8 => Ok(CcsdsTimeCode::CucCcsdsEpoch),
|
||||||
x if x == CcsdsTimeCodes::CucAgencyEpoch as u8 => Ok(CcsdsTimeCodes::CucAgencyEpoch),
|
x if x == CcsdsTimeCode::CucAgencyEpoch as u8 => Ok(CcsdsTimeCode::CucAgencyEpoch),
|
||||||
x if x == CcsdsTimeCodes::Cds as u8 => Ok(CcsdsTimeCodes::Cds),
|
x if x == CcsdsTimeCode::Cds as u8 => Ok(CcsdsTimeCode::Cds),
|
||||||
x if x == CcsdsTimeCodes::Ccs as u8 => Ok(CcsdsTimeCodes::Ccs),
|
x if x == CcsdsTimeCode::Ccs as u8 => Ok(CcsdsTimeCode::Ccs),
|
||||||
x if x == CcsdsTimeCodes::AgencyDefined as u8 => Ok(CcsdsTimeCodes::AgencyDefined),
|
x if x == CcsdsTimeCode::AgencyDefined as u8 => Ok(CcsdsTimeCode::AgencyDefined),
|
||||||
_ => Err(()),
|
_ => Err(()),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -55,76 +55,35 @@ impl TryFrom<u8> for CcsdsTimeCodes {
|
|||||||
|
|
||||||
/// Retrieve the CCSDS time code from the p-field. If no valid time code identifier is found, the
|
/// Retrieve the CCSDS time code from the p-field. If no valid time code identifier is found, the
|
||||||
/// value of the raw time code identification field is returned.
|
/// value of the raw time code identification field is returned.
|
||||||
pub fn ccsds_time_code_from_p_field(pfield: u8) -> Result<CcsdsTimeCodes, u8> {
|
pub fn ccsds_time_code_from_p_field(pfield: u8) -> Result<CcsdsTimeCode, u8> {
|
||||||
let raw_bits = (pfield >> 4) & 0b111;
|
let raw_bits = (pfield >> 4) & 0b111;
|
||||||
CcsdsTimeCodes::try_from(raw_bits).map_err(|_| raw_bits)
|
CcsdsTimeCode::try_from(raw_bits).map_err(|_| raw_bits)
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, PartialEq, Eq, Copy, Clone)]
|
#[derive(Debug, PartialEq, Eq, Copy, Clone, thiserror::Error)]
|
||||||
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
||||||
|
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
|
||||||
|
#[error("date before ccsds epoch: {0:?}")]
|
||||||
|
pub struct DateBeforeCcsdsEpochError(UnixTime);
|
||||||
|
|
||||||
|
#[derive(Debug, PartialEq, Eq, Copy, Clone, thiserror::Error)]
|
||||||
|
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
||||||
|
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
|
||||||
#[non_exhaustive]
|
#[non_exhaustive]
|
||||||
pub enum TimestampError {
|
pub enum TimestampError {
|
||||||
InvalidTimeCode { expected: CcsdsTimeCodes, found: u8 },
|
#[error("invalid time code, expected {expected:?}, found {found}")]
|
||||||
ByteConversion(ByteConversionError),
|
InvalidTimeCode { expected: CcsdsTimeCode, found: u8 },
|
||||||
Cds(cds::CdsError),
|
#[error("time stamp: byte conversion error: {0}")]
|
||||||
Cuc(cuc::CucError),
|
ByteConversion(#[from] ByteConversionError),
|
||||||
DateBeforeCcsdsEpoch(DateTime<Utc>),
|
#[error("CDS error: {0}")]
|
||||||
|
Cds(#[from] cds::CdsError),
|
||||||
|
#[error("CUC error: {0}")]
|
||||||
|
Cuc(#[from] cuc::CucError),
|
||||||
|
#[error("custom epoch not supported")]
|
||||||
CustomEpochNotSupported,
|
CustomEpochNotSupported,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Display for TimestampError {
|
|
||||||
fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
|
|
||||||
match self {
|
|
||||||
TimestampError::InvalidTimeCode { expected, found } => {
|
|
||||||
write!(
|
|
||||||
f,
|
|
||||||
"invalid raw time code value {found} for time code {expected:?}"
|
|
||||||
)
|
|
||||||
}
|
|
||||||
TimestampError::Cds(e) => {
|
|
||||||
write!(f, "cds error: {e}")
|
|
||||||
}
|
|
||||||
TimestampError::Cuc(e) => {
|
|
||||||
write!(f, "cuc error: {e}")
|
|
||||||
}
|
|
||||||
TimestampError::ByteConversion(e) => {
|
|
||||||
write!(f, "time stamp: {e}")
|
|
||||||
}
|
|
||||||
TimestampError::DateBeforeCcsdsEpoch(e) => {
|
|
||||||
write!(f, "datetime with date before ccsds epoch: {e}")
|
|
||||||
}
|
|
||||||
TimestampError::CustomEpochNotSupported => {
|
|
||||||
write!(f, "custom epochs are not supported")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(feature = "std")]
|
#[cfg(feature = "std")]
|
||||||
impl Error for TimestampError {
|
|
||||||
fn source(&self) -> Option<&(dyn Error + 'static)> {
|
|
||||||
match self {
|
|
||||||
TimestampError::ByteConversion(e) => Some(e),
|
|
||||||
TimestampError::Cds(e) => Some(e),
|
|
||||||
TimestampError::Cuc(e) => Some(e),
|
|
||||||
_ => None,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
impl From<cds::CdsError> for TimestampError {
|
|
||||||
fn from(e: cds::CdsError) -> Self {
|
|
||||||
TimestampError::Cds(e)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl From<cuc::CucError> for TimestampError {
|
|
||||||
fn from(e: cuc::CucError) -> Self {
|
|
||||||
TimestampError::Cuc(e)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(feature = "std")]
|
|
||||||
#[cfg_attr(doc_cfg, doc(cfg(feature = "std")))]
|
|
||||||
pub mod std_mod {
|
pub mod std_mod {
|
||||||
use crate::time::TimestampError;
|
use crate::time::TimestampError;
|
||||||
use std::time::SystemTimeError;
|
use std::time::SystemTimeError;
|
||||||
@@ -132,7 +91,7 @@ pub mod std_mod {
|
|||||||
|
|
||||||
#[derive(Debug, Clone, Error)]
|
#[derive(Debug, Clone, Error)]
|
||||||
pub enum StdTimestampError {
|
pub enum StdTimestampError {
|
||||||
#[error("system time error: {0}")]
|
#[error("system time error: {0:?}")]
|
||||||
SystemTime(#[from] SystemTimeError),
|
SystemTime(#[from] SystemTimeError),
|
||||||
#[error("timestamp error: {0}")]
|
#[error("timestamp error: {0}")]
|
||||||
Timestamp(#[from] TimestampError),
|
Timestamp(#[from] TimestampError),
|
||||||
@@ -140,7 +99,6 @@ pub mod std_mod {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(feature = "std")]
|
#[cfg(feature = "std")]
|
||||||
#[cfg_attr(doc_cfg, doc(cfg(feature = "std")))]
|
|
||||||
pub fn seconds_since_epoch() -> f64 {
|
pub fn seconds_since_epoch() -> f64 {
|
||||||
SystemTime::now()
|
SystemTime::now()
|
||||||
.duration_since(SystemTime::UNIX_EPOCH)
|
.duration_since(SystemTime::UNIX_EPOCH)
|
||||||
@@ -152,6 +110,7 @@ pub fn seconds_since_epoch() -> f64 {
|
|||||||
///
|
///
|
||||||
/// - CCSDS epoch: 1958-01-01T00:00:00+00:00
|
/// - CCSDS epoch: 1958-01-01T00:00:00+00:00
|
||||||
/// - UNIX Epoch: 1970-01-01T00:00:00+00:00
|
/// - UNIX Epoch: 1970-01-01T00:00:00+00:00
|
||||||
|
#[inline]
|
||||||
pub const fn unix_to_ccsds_days(unix_days: i64) -> i64 {
|
pub const fn unix_to_ccsds_days(unix_days: i64) -> i64 {
|
||||||
unix_days - DAYS_CCSDS_TO_UNIX as i64
|
unix_days - DAYS_CCSDS_TO_UNIX as i64
|
||||||
}
|
}
|
||||||
@@ -160,22 +119,24 @@ pub const fn unix_to_ccsds_days(unix_days: i64) -> i64 {
|
|||||||
///
|
///
|
||||||
/// - CCSDS epoch: 1958-01-01T00:00:00+00:00
|
/// - CCSDS epoch: 1958-01-01T00:00:00+00:00
|
||||||
/// - UNIX Epoch: 1970-01-01T00:00:00+00:00
|
/// - UNIX Epoch: 1970-01-01T00:00:00+00:00
|
||||||
|
#[inline]
|
||||||
pub const fn ccsds_to_unix_days(ccsds_days: i64) -> i64 {
|
pub const fn ccsds_to_unix_days(ccsds_days: i64) -> i64 {
|
||||||
ccsds_days + DAYS_CCSDS_TO_UNIX as i64
|
ccsds_days + DAYS_CCSDS_TO_UNIX as i64
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Similar to [unix_to_ccsds_days] but converts the epoch instead, which is the number of elpased
|
/// Similar to [unix_to_ccsds_days] but converts the epoch instead, which is the number of elpased
|
||||||
/// seconds since the CCSDS and UNIX epoch times.
|
/// seconds since the CCSDS and UNIX epoch times.
|
||||||
|
#[inline]
|
||||||
pub const fn unix_epoch_to_ccsds_epoch(unix_epoch: i64) -> i64 {
|
pub const fn unix_epoch_to_ccsds_epoch(unix_epoch: i64) -> i64 {
|
||||||
unix_epoch - (DAYS_CCSDS_TO_UNIX as i64 * SECONDS_PER_DAY as i64)
|
unix_epoch - (DAYS_CCSDS_TO_UNIX as i64 * SECONDS_PER_DAY as i64)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
pub const fn ccsds_epoch_to_unix_epoch(ccsds_epoch: i64) -> i64 {
|
pub const fn ccsds_epoch_to_unix_epoch(ccsds_epoch: i64) -> i64 {
|
||||||
ccsds_epoch + (DAYS_CCSDS_TO_UNIX as i64 * SECONDS_PER_DAY as i64)
|
ccsds_epoch + (DAYS_CCSDS_TO_UNIX as i64 * SECONDS_PER_DAY as i64)
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(feature = "std")]
|
#[cfg(feature = "std")]
|
||||||
#[cfg_attr(doc_cfg, doc(cfg(feature = "std")))]
|
|
||||||
pub fn ms_of_day_using_sysclock() -> u32 {
|
pub fn ms_of_day_using_sysclock() -> u32 {
|
||||||
ms_of_day(seconds_since_epoch())
|
ms_of_day(seconds_since_epoch())
|
||||||
}
|
}
|
||||||
@@ -196,7 +157,6 @@ pub trait TimeWriter {
|
|||||||
fn write_to_bytes(&self, bytes: &mut [u8]) -> Result<usize, TimestampError>;
|
fn write_to_bytes(&self, bytes: &mut [u8]) -> Result<usize, TimestampError>;
|
||||||
|
|
||||||
#[cfg(feature = "alloc")]
|
#[cfg(feature = "alloc")]
|
||||||
#[cfg_attr(doc_cfg, doc(cfg(feature = "alloc")))]
|
|
||||||
fn to_vec(&self) -> Result<alloc::vec::Vec<u8>, TimestampError> {
|
fn to_vec(&self) -> Result<alloc::vec::Vec<u8>, TimestampError> {
|
||||||
let mut vec = alloc::vec![0; self.len_written()];
|
let mut vec = alloc::vec![0; self.len_written()];
|
||||||
self.write_to_bytes(&mut vec)?;
|
self.write_to_bytes(&mut vec)?;
|
||||||
@@ -204,16 +164,15 @@ pub trait TimeWriter {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub trait TimeReader {
|
pub trait TimeReader: Sized {
|
||||||
fn from_bytes(buf: &[u8]) -> Result<Self, TimestampError>
|
fn from_bytes(buf: &[u8]) -> Result<Self, TimestampError>;
|
||||||
where
|
|
||||||
Self: Sized;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Trait for generic CCSDS time providers.
|
/// Trait for generic CCSDS time providers.
|
||||||
///
|
///
|
||||||
/// The UNIX helper methods and the [Self::date_time] method are not strictly necessary but extremely
|
/// The UNIX helper methods and the helper method are not strictly necessary but extremely
|
||||||
/// practical because they are a very common and simple exchange format for time information.
|
/// practical because they are a very common and simple exchange format for time information.
|
||||||
|
/// Therefore, it was decided to keep them in this trait as well.
|
||||||
pub trait CcsdsTimeProvider {
|
pub trait CcsdsTimeProvider {
|
||||||
fn len_as_bytes(&self) -> usize;
|
fn len_as_bytes(&self) -> usize;
|
||||||
|
|
||||||
@@ -222,125 +181,203 @@ pub trait CcsdsTimeProvider {
|
|||||||
/// entry denotes the length of the pfield and the second entry is the value of the pfield
|
/// entry denotes the length of the pfield and the second entry is the value of the pfield
|
||||||
/// in big endian format.
|
/// in big endian format.
|
||||||
fn p_field(&self) -> (usize, [u8; 2]);
|
fn p_field(&self) -> (usize, [u8; 2]);
|
||||||
fn ccdsd_time_code(&self) -> CcsdsTimeCodes;
|
fn ccdsd_time_code(&self) -> CcsdsTimeCode;
|
||||||
|
|
||||||
fn unix_seconds(&self) -> i64;
|
fn unix_secs(&self) -> i64;
|
||||||
fn subsecond_millis(&self) -> u16;
|
fn subsec_nanos(&self) -> u32;
|
||||||
fn unix_stamp(&self) -> UnixTimestamp {
|
|
||||||
UnixTimestamp::const_new(self.unix_seconds(), self.subsecond_millis())
|
fn subsec_millis(&self) -> u16 {
|
||||||
|
(self.subsec_nanos() / 1_000_000) as u16
|
||||||
}
|
}
|
||||||
|
|
||||||
fn date_time(&self) -> Option<DateTime<Utc>>;
|
fn unix_time(&self) -> UnixTime {
|
||||||
|
UnixTime::new(self.unix_secs(), self.subsec_nanos())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(feature = "chrono")]
|
||||||
|
fn chrono_date_time(&self) -> chrono::LocalResult<chrono::DateTime<chrono::Utc>> {
|
||||||
|
chrono::Utc.timestamp_opt(self.unix_secs(), self.subsec_nanos())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(feature = "timelib")]
|
||||||
|
fn timelib_date_time(&self) -> Result<time::OffsetDateTime, time::error::ComponentRange> {
|
||||||
|
Ok(time::OffsetDateTime::from_unix_timestamp(self.unix_secs())?
|
||||||
|
+ time::Duration::nanoseconds(self.subsec_nanos().into()))
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// UNIX timestamp: Elapsed seconds since 1970-01-01T00:00:00+00:00.
|
/// UNIX time: Elapsed non-leap seconds since 1970-01-01T00:00:00+00:00 UTC.
|
||||||
///
|
///
|
||||||
/// Also can optionally include subsecond millisecond for greater accuracy.
|
/// This is a commonly used time format and can therefore also be used as a generic format to
|
||||||
|
/// convert other CCSDS time formats to and from. The subsecond precision is in nanoseconds
|
||||||
|
/// similarly to other common time formats and libraries.
|
||||||
#[derive(Default, Debug, Copy, Clone, PartialEq, Eq)]
|
#[derive(Default, Debug, Copy, Clone, PartialEq, Eq)]
|
||||||
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
||||||
pub struct UnixTimestamp {
|
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
|
||||||
pub unix_seconds: i64,
|
pub struct UnixTime {
|
||||||
subsecond_millis: u16,
|
secs: i64,
|
||||||
|
subsec_nanos: u32,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl UnixTimestamp {
|
impl UnixTime {
|
||||||
/// Returns [None] if the subsecond millisecond value is larger than 999.
|
/// The UNIX epoch time: 1970-01-01T00:00:00+00:00 UTC.
|
||||||
pub fn new(unix_seconds: i64, subsec_millis: u16) -> Option<Self> {
|
pub const EPOCH: Self = Self {
|
||||||
if subsec_millis > 999 {
|
secs: 0,
|
||||||
|
subsec_nanos: 0,
|
||||||
|
};
|
||||||
|
|
||||||
|
/// The minimum possible `UnixTime`.
|
||||||
|
pub const MIN: Self = Self {
|
||||||
|
secs: i64::MIN,
|
||||||
|
subsec_nanos: 0,
|
||||||
|
};
|
||||||
|
|
||||||
|
/// The maximum possible `UnixTime`.
|
||||||
|
pub const MAX: Self = Self {
|
||||||
|
secs: i64::MAX,
|
||||||
|
subsec_nanos: NANOS_PER_SECOND - 1,
|
||||||
|
};
|
||||||
|
|
||||||
|
/// Returns [None] if the subsecond nanosecond value is invalid (larger than fraction of a
|
||||||
|
/// second)
|
||||||
|
pub fn new_checked(unix_seconds: i64, subsec_nanos: u32) -> Option<Self> {
|
||||||
|
if subsec_nanos >= NANOS_PER_SECOND {
|
||||||
return None;
|
return None;
|
||||||
}
|
}
|
||||||
Some(Self::const_new(unix_seconds, subsec_millis))
|
Some(Self::new(unix_seconds, subsec_nanos))
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Like [Self::new] but const. Panics if the subsecond value is larger than 999.
|
/// Returns [None] if the subsecond millisecond value is invalid (larger than fraction of a
|
||||||
pub const fn const_new(unix_seconds: i64, subsecond_millis: u16) -> Self {
|
/// second)
|
||||||
if subsecond_millis > 999 {
|
pub fn new_subsec_millis_checked(unix_seconds: i64, subsec_millis: u16) -> Option<Self> {
|
||||||
panic!("subsec milliseconds exceeds 999");
|
if subsec_millis >= 1000 {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
Self::new_checked(unix_seconds, subsec_millis as u32 * 1_000_000)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// This function will panic if the subsecond value is larger than the fraction of a second.
|
||||||
|
/// Use [Self::new_checked] if you want to handle this case without a panic.
|
||||||
|
pub const fn new(unix_seconds: i64, subsecond_nanos: u32) -> Self {
|
||||||
|
if subsecond_nanos >= NANOS_PER_SECOND {
|
||||||
|
panic!("invalid subsecond nanos value");
|
||||||
}
|
}
|
||||||
Self {
|
Self {
|
||||||
unix_seconds,
|
secs: unix_seconds,
|
||||||
subsecond_millis,
|
subsec_nanos: subsecond_nanos,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn new_only_seconds(unix_seconds: i64) -> Self {
|
/// This function will panic if the subsecond value is larger than the fraction of a second.
|
||||||
|
/// Use [Self::new_subsec_millis_checked] if you want to handle this case without a panic.
|
||||||
|
pub const fn new_subsec_millis(unix_seconds: i64, subsecond_millis: u16) -> Self {
|
||||||
|
if subsecond_millis >= 1000 {
|
||||||
|
panic!("invalid subsecond millisecond value");
|
||||||
|
}
|
||||||
Self {
|
Self {
|
||||||
unix_seconds,
|
secs: unix_seconds,
|
||||||
subsecond_millis: 0,
|
subsec_nanos: subsecond_millis as u32 * 1_000_000,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn subsecond_millis(&self) -> u16 {
|
pub fn new_only_secs(unix_seconds: i64) -> Self {
|
||||||
self.subsecond_millis
|
Self {
|
||||||
}
|
secs: unix_seconds,
|
||||||
|
subsec_nanos: 0,
|
||||||
#[cfg(feature = "std")]
|
}
|
||||||
#[cfg_attr(doc_cfg, doc(cfg(feature = "std")))]
|
|
||||||
pub fn from_now() -> Result<Self, SystemTimeError> {
|
|
||||||
let now = SystemTime::now().duration_since(SystemTime::UNIX_EPOCH)?;
|
|
||||||
let epoch = now.as_secs();
|
|
||||||
Ok(Self::const_new(epoch as i64, now.subsec_millis() as u16))
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[inline]
|
#[inline]
|
||||||
pub fn unix_seconds_f64(&self) -> f64 {
|
pub fn subsec_millis(&self) -> u16 {
|
||||||
self.unix_seconds as f64 + (self.subsecond_millis as f64 / 1000.0)
|
(self.subsec_nanos / 1_000_000) as u16
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn as_date_time(&self) -> LocalResult<DateTime<Utc>> {
|
pub fn subsec_nanos(&self) -> u32 {
|
||||||
Utc.timestamp_opt(
|
self.subsec_nanos
|
||||||
self.unix_seconds,
|
}
|
||||||
self.subsecond_millis as u32 * 10_u32.pow(6),
|
|
||||||
)
|
#[cfg(feature = "std")]
|
||||||
|
pub fn now() -> Result<Self, SystemTimeError> {
|
||||||
|
let now = SystemTime::now().duration_since(SystemTime::UNIX_EPOCH)?;
|
||||||
|
let epoch = now.as_secs();
|
||||||
|
Ok(Self::new(epoch as i64, now.subsec_nanos()))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
pub fn unix_secs_f64(&self) -> f64 {
|
||||||
|
self.secs as f64 + (self.subsec_nanos as f64 / 1_000_000_000.0)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn as_secs(&self) -> i64 {
|
||||||
|
self.secs
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(feature = "chrono")]
|
||||||
|
pub fn chrono_date_time(&self) -> chrono::LocalResult<chrono::DateTime<chrono::Utc>> {
|
||||||
|
Utc.timestamp_opt(self.secs, self.subsec_nanos)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(feature = "timelib")]
|
||||||
|
pub fn timelib_date_time(&self) -> Result<time::OffsetDateTime, time::error::ComponentRange> {
|
||||||
|
Ok(time::OffsetDateTime::from_unix_timestamp(self.as_secs())?
|
||||||
|
+ time::Duration::nanoseconds(self.subsec_nanos().into()))
|
||||||
}
|
}
|
||||||
|
|
||||||
// Calculate the difference in milliseconds between two UnixTimestamps
|
// Calculate the difference in milliseconds between two UnixTimestamps
|
||||||
pub fn difference_in_millis(&self, other: &UnixTimestamp) -> i64 {
|
pub fn diff_in_millis(&self, other: &UnixTime) -> Option<i64> {
|
||||||
let seconds_difference = self.unix_seconds - other.unix_seconds;
|
let seconds_difference = self.secs.checked_sub(other.secs)?;
|
||||||
// Convert seconds difference to milliseconds
|
// Convert seconds difference to milliseconds
|
||||||
let milliseconds_difference = seconds_difference * 1000;
|
let milliseconds_difference = seconds_difference.checked_mul(1000)?;
|
||||||
|
|
||||||
// Calculate the difference in subsecond milliseconds directly
|
// Calculate the difference in subsecond milliseconds directly
|
||||||
let subsecond_difference = self.subsecond_millis as i64 - other.subsecond_millis as i64;
|
let subsecond_difference_nanos = self.subsec_nanos as i64 - other.subsec_nanos as i64;
|
||||||
|
|
||||||
// Combine the differences
|
// Combine the differences
|
||||||
milliseconds_difference + subsecond_difference
|
Some(milliseconds_difference + (subsecond_difference_nanos / 1_000_000))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl From<DateTime<Utc>> for UnixTimestamp {
|
#[cfg(feature = "chrono")]
|
||||||
fn from(value: DateTime<Utc>) -> Self {
|
impl From<chrono::DateTime<chrono::Utc>> for UnixTime {
|
||||||
Self::const_new(value.timestamp(), value.timestamp_subsec_millis() as u16)
|
fn from(value: chrono::DateTime<chrono::Utc>) -> Self {
|
||||||
|
Self::new(value.timestamp(), value.timestamp_subsec_nanos())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl PartialOrd for UnixTimestamp {
|
#[cfg(feature = "timelib")]
|
||||||
|
impl From<time::OffsetDateTime> for UnixTime {
|
||||||
|
fn from(value: time::OffsetDateTime) -> Self {
|
||||||
|
Self::new(value.unix_timestamp(), value.nanosecond())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl PartialOrd for UnixTime {
|
||||||
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
|
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
|
||||||
Some(self.cmp(other))
|
Some(self.cmp(other))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Ord for UnixTimestamp {
|
impl Ord for UnixTime {
|
||||||
fn cmp(&self, other: &Self) -> Ordering {
|
fn cmp(&self, other: &Self) -> Ordering {
|
||||||
if self == other {
|
if self == other {
|
||||||
return Ordering::Equal;
|
return Ordering::Equal;
|
||||||
}
|
}
|
||||||
match self.unix_seconds.cmp(&other.unix_seconds) {
|
match self.secs.cmp(&other.secs) {
|
||||||
Ordering::Less => return Ordering::Less,
|
Ordering::Less => return Ordering::Less,
|
||||||
Ordering::Greater => return Ordering::Greater,
|
Ordering::Greater => return Ordering::Greater,
|
||||||
_ => (),
|
_ => (),
|
||||||
}
|
}
|
||||||
|
|
||||||
match self.subsecond_millis().cmp(&other.subsecond_millis()) {
|
match self.subsec_millis().cmp(&other.subsec_millis()) {
|
||||||
Ordering::Less => {
|
Ordering::Less => {
|
||||||
return if self.unix_seconds < 0 {
|
return if self.secs < 0 {
|
||||||
Ordering::Greater
|
Ordering::Greater
|
||||||
} else {
|
} else {
|
||||||
Ordering::Less
|
Ordering::Less
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Ordering::Greater => {
|
Ordering::Greater => {
|
||||||
return if self.unix_seconds < 0 {
|
return if self.secs < 0 {
|
||||||
Ordering::Less
|
Ordering::Less
|
||||||
} else {
|
} else {
|
||||||
Ordering::Greater
|
Ordering::Greater
|
||||||
@@ -360,12 +397,12 @@ pub struct StampDiff {
|
|||||||
pub duration_absolute: Duration,
|
pub duration_absolute: Duration,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Sub for UnixTimestamp {
|
impl Sub for UnixTime {
|
||||||
type Output = StampDiff;
|
type Output = Option<StampDiff>;
|
||||||
|
|
||||||
fn sub(self, rhs: Self) -> Self::Output {
|
fn sub(self, rhs: Self) -> Self::Output {
|
||||||
let difference = self.difference_in_millis(&rhs);
|
let difference = self.diff_in_millis(&rhs)?;
|
||||||
if difference < 0 {
|
Some(if difference < 0 {
|
||||||
StampDiff {
|
StampDiff {
|
||||||
positive_duration: false,
|
positive_duration: false,
|
||||||
duration_absolute: Duration::from_millis(-difference as u64),
|
duration_absolute: Duration::from_millis(-difference as u64),
|
||||||
@@ -375,16 +412,13 @@ impl Sub for UnixTimestamp {
|
|||||||
positive_duration: true,
|
positive_duration: true,
|
||||||
duration_absolute: Duration::from_millis(difference as u64),
|
duration_absolute: Duration::from_millis(difference as u64),
|
||||||
}
|
}
|
||||||
}
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn get_new_stamp_after_addition(
|
fn get_new_stamp_after_addition(current_stamp: &UnixTime, duration: Duration) -> UnixTime {
|
||||||
current_stamp: &UnixTimestamp,
|
let mut new_subsec_nanos = current_stamp.subsec_nanos() + duration.subsec_nanos();
|
||||||
duration: Duration,
|
let mut new_unix_seconds = current_stamp.secs;
|
||||||
) -> UnixTimestamp {
|
|
||||||
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| {
|
let mut increment_seconds = |value: u32| {
|
||||||
if new_unix_seconds < 0 {
|
if new_unix_seconds < 0 {
|
||||||
new_unix_seconds = new_unix_seconds
|
new_unix_seconds = new_unix_seconds
|
||||||
@@ -396,8 +430,8 @@ fn get_new_stamp_after_addition(
|
|||||||
.expect("new unix seconds would exceed i64::MAX");
|
.expect("new unix seconds would exceed i64::MAX");
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
if new_subsec_millis >= 1000 {
|
if new_subsec_nanos >= 1_000_000_000 {
|
||||||
new_subsec_millis -= 1000;
|
new_subsec_nanos -= 1_000_000_000;
|
||||||
increment_seconds(1);
|
increment_seconds(1);
|
||||||
}
|
}
|
||||||
increment_seconds(
|
increment_seconds(
|
||||||
@@ -406,7 +440,7 @@ fn get_new_stamp_after_addition(
|
|||||||
.try_into()
|
.try_into()
|
||||||
.expect("duration seconds exceeds u32::MAX"),
|
.expect("duration seconds exceeds u32::MAX"),
|
||||||
);
|
);
|
||||||
UnixTimestamp::const_new(new_unix_seconds, new_subsec_millis)
|
UnixTime::new(new_unix_seconds, new_subsec_nanos)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Please note that this operation will panic on the following conditions:
|
/// Please note that this operation will panic on the following conditions:
|
||||||
@@ -414,7 +448,7 @@ fn get_new_stamp_after_addition(
|
|||||||
/// - Unix seconds after subtraction for stamps before the unix epoch exceeds [i64::MIN].
|
/// - Unix seconds after subtraction for stamps before the unix epoch exceeds [i64::MIN].
|
||||||
/// - Unix seconds after addition exceeds [i64::MAX].
|
/// - Unix seconds after addition exceeds [i64::MAX].
|
||||||
/// - Seconds from duration to add exceeds [u32::MAX].
|
/// - Seconds from duration to add exceeds [u32::MAX].
|
||||||
impl AddAssign<Duration> for UnixTimestamp {
|
impl AddAssign<Duration> for UnixTime {
|
||||||
fn add_assign(&mut self, duration: Duration) {
|
fn add_assign(&mut self, duration: Duration) {
|
||||||
*self = get_new_stamp_after_addition(self, duration);
|
*self = get_new_stamp_after_addition(self, duration);
|
||||||
}
|
}
|
||||||
@@ -425,7 +459,7 @@ impl AddAssign<Duration> for UnixTimestamp {
|
|||||||
/// - Unix seconds after subtraction for stamps before the unix epoch exceeds [i64::MIN].
|
/// - Unix seconds after subtraction for stamps before the unix epoch exceeds [i64::MIN].
|
||||||
/// - Unix seconds after addition exceeds [i64::MAX].
|
/// - Unix seconds after addition exceeds [i64::MAX].
|
||||||
/// - Unix seconds exceeds [u32::MAX].
|
/// - Unix seconds exceeds [u32::MAX].
|
||||||
impl Add<Duration> for UnixTimestamp {
|
impl Add<Duration> for UnixTime {
|
||||||
type Output = Self;
|
type Output = Self;
|
||||||
|
|
||||||
fn add(self, duration: Duration) -> Self::Output {
|
fn add(self, duration: Duration) -> Self::Output {
|
||||||
@@ -433,8 +467,8 @@ impl Add<Duration> for UnixTimestamp {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Add<Duration> for &UnixTimestamp {
|
impl Add<Duration> for &UnixTime {
|
||||||
type Output = UnixTimestamp;
|
type Output = UnixTime;
|
||||||
|
|
||||||
fn add(self, duration: Duration) -> Self::Output {
|
fn add(self, duration: Duration) -> Self::Output {
|
||||||
get_new_stamp_after_addition(self, duration)
|
get_new_stamp_after_addition(self, duration)
|
||||||
@@ -445,10 +479,15 @@ impl Add<Duration> for &UnixTimestamp {
|
|||||||
mod tests {
|
mod tests {
|
||||||
use alloc::string::ToString;
|
use alloc::string::ToString;
|
||||||
use chrono::{Datelike, Timelike};
|
use chrono::{Datelike, Timelike};
|
||||||
use std::format;
|
use std::{format, println};
|
||||||
|
|
||||||
use super::{cuc::CucError, *};
|
use super::{cuc::CucError, *};
|
||||||
|
|
||||||
|
#[allow(dead_code)]
|
||||||
|
const UNIX_STAMP_CONST: UnixTime = UnixTime::new(5, 999_999_999);
|
||||||
|
#[allow(dead_code)]
|
||||||
|
const UNIX_STAMP_CONST_2: UnixTime = UnixTime::new_subsec_millis(5, 999);
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_days_conversion() {
|
fn test_days_conversion() {
|
||||||
assert_eq!(unix_to_ccsds_days(DAYS_CCSDS_TO_UNIX.into()), 0);
|
assert_eq!(unix_to_ccsds_days(DAYS_CCSDS_TO_UNIX.into()), 0);
|
||||||
@@ -456,6 +495,7 @@ mod tests {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
|
#[cfg_attr(miri, ignore)]
|
||||||
fn test_get_current_time() {
|
fn test_get_current_time() {
|
||||||
let sec_floats = seconds_since_epoch();
|
let sec_floats = seconds_since_epoch();
|
||||||
assert!(sec_floats > 0.0);
|
assert!(sec_floats > 0.0);
|
||||||
@@ -470,6 +510,7 @@ mod tests {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
|
#[cfg_attr(miri, ignore)]
|
||||||
fn test_ccsds_epoch() {
|
fn test_ccsds_epoch() {
|
||||||
let now = SystemTime::now()
|
let now = SystemTime::now()
|
||||||
.duration_since(SystemTime::UNIX_EPOCH)
|
.duration_since(SystemTime::UNIX_EPOCH)
|
||||||
@@ -484,28 +525,29 @@ mod tests {
|
|||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn basic_unix_stamp_test() {
|
fn basic_unix_stamp_test() {
|
||||||
let stamp = UnixTimestamp::new_only_seconds(-200);
|
let stamp = UnixTime::new_only_secs(-200);
|
||||||
assert_eq!(stamp.unix_seconds, -200);
|
assert_eq!(stamp.secs, -200);
|
||||||
assert_eq!(stamp.subsecond_millis(), 0);
|
assert_eq!(stamp.subsec_millis(), 0);
|
||||||
let stamp = UnixTimestamp::new_only_seconds(250);
|
let stamp = UnixTime::new_only_secs(250);
|
||||||
assert_eq!(stamp.unix_seconds, 250);
|
assert_eq!(stamp.secs, 250);
|
||||||
assert_eq!(stamp.subsecond_millis(), 0);
|
assert_eq!(stamp.subsec_millis(), 0);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn basic_float_unix_stamp_test() {
|
fn basic_float_unix_stamp_test() {
|
||||||
let stamp = UnixTimestamp::new(500, 600).unwrap();
|
let stamp = UnixTime::new_subsec_millis_checked(500, 600).unwrap();
|
||||||
assert_eq!(stamp.unix_seconds, 500);
|
assert_eq!(stamp.secs, 500);
|
||||||
let subsec_millis = stamp.subsecond_millis();
|
let subsec_millis = stamp.subsec_millis();
|
||||||
assert_eq!(subsec_millis, 600);
|
assert_eq!(subsec_millis, 600);
|
||||||
assert!((500.6 - stamp.unix_seconds_f64()).abs() < 0.0001);
|
println!("{:?}", (500.6 - stamp.unix_secs_f64()).to_string());
|
||||||
|
assert!((500.6 - stamp.unix_secs_f64()).abs() < 0.0001);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_ord_larger() {
|
fn test_ord_larger() {
|
||||||
let stamp0 = UnixTimestamp::new_only_seconds(5);
|
let stamp0 = UnixTime::new_only_secs(5);
|
||||||
let stamp1 = UnixTimestamp::new(5, 500).unwrap();
|
let stamp1 = UnixTime::new_subsec_millis_checked(5, 500).unwrap();
|
||||||
let stamp2 = UnixTimestamp::new_only_seconds(6);
|
let stamp2 = UnixTime::new_only_secs(6);
|
||||||
assert!(stamp1 > stamp0);
|
assert!(stamp1 > stamp0);
|
||||||
assert!(stamp2 > stamp0);
|
assert!(stamp2 > stamp0);
|
||||||
assert!(stamp2 > stamp1);
|
assert!(stamp2 > stamp1);
|
||||||
@@ -513,9 +555,9 @@ mod tests {
|
|||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_ord_smaller() {
|
fn test_ord_smaller() {
|
||||||
let stamp0 = UnixTimestamp::new_only_seconds(5);
|
let stamp0 = UnixTime::new_only_secs(5);
|
||||||
let stamp1 = UnixTimestamp::new(5, 500).unwrap();
|
let stamp1 = UnixTime::new_subsec_millis_checked(5, 500).unwrap();
|
||||||
let stamp2 = UnixTimestamp::new_only_seconds(6);
|
let stamp2 = UnixTime::new_only_secs(6);
|
||||||
assert!(stamp0 < stamp1);
|
assert!(stamp0 < stamp1);
|
||||||
assert!(stamp0 < stamp2);
|
assert!(stamp0 < stamp2);
|
||||||
assert!(stamp1 < stamp2);
|
assert!(stamp1 < stamp2);
|
||||||
@@ -523,9 +565,9 @@ mod tests {
|
|||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_ord_larger_neg_numbers() {
|
fn test_ord_larger_neg_numbers() {
|
||||||
let stamp0 = UnixTimestamp::new_only_seconds(-5);
|
let stamp0 = UnixTime::new_only_secs(-5);
|
||||||
let stamp1 = UnixTimestamp::new(-5, 500).unwrap();
|
let stamp1 = UnixTime::new_subsec_millis_checked(-5, 500).unwrap();
|
||||||
let stamp2 = UnixTimestamp::new_only_seconds(-6);
|
let stamp2 = UnixTime::new_only_secs(-6);
|
||||||
assert!(stamp0 > stamp1);
|
assert!(stamp0 > stamp1);
|
||||||
assert!(stamp0 > stamp2);
|
assert!(stamp0 > stamp2);
|
||||||
assert!(stamp1 > stamp2);
|
assert!(stamp1 > stamp2);
|
||||||
@@ -535,9 +577,9 @@ mod tests {
|
|||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_ord_smaller_neg_numbers() {
|
fn test_ord_smaller_neg_numbers() {
|
||||||
let stamp0 = UnixTimestamp::new_only_seconds(-5);
|
let stamp0 = UnixTime::new_only_secs(-5);
|
||||||
let stamp1 = UnixTimestamp::new(-5, 500).unwrap();
|
let stamp1 = UnixTime::new_subsec_millis_checked(-5, 500).unwrap();
|
||||||
let stamp2 = UnixTimestamp::new_only_seconds(-6);
|
let stamp2 = UnixTime::new_only_secs(-6);
|
||||||
assert!(stamp2 < stamp1);
|
assert!(stamp2 < stamp1);
|
||||||
assert!(stamp2 < stamp0);
|
assert!(stamp2 < stamp0);
|
||||||
assert!(stamp1 < stamp0);
|
assert!(stamp1 < stamp0);
|
||||||
@@ -548,8 +590,8 @@ mod tests {
|
|||||||
#[allow(clippy::nonminimal_bool)]
|
#[allow(clippy::nonminimal_bool)]
|
||||||
#[test]
|
#[test]
|
||||||
fn test_eq() {
|
fn test_eq() {
|
||||||
let stamp0 = UnixTimestamp::new(5, 0).unwrap();
|
let stamp0 = UnixTime::new(5, 0);
|
||||||
let stamp1 = UnixTimestamp::new_only_seconds(5);
|
let stamp1 = UnixTime::new_only_secs(5);
|
||||||
assert_eq!(stamp0, stamp1);
|
assert_eq!(stamp0, stamp1);
|
||||||
assert!(stamp0 <= stamp1);
|
assert!(stamp0 <= stamp1);
|
||||||
assert!(stamp0 >= stamp1);
|
assert!(stamp0 >= stamp1);
|
||||||
@@ -559,27 +601,27 @@ mod tests {
|
|||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_addition() {
|
fn test_addition() {
|
||||||
let mut stamp0 = UnixTimestamp::new_only_seconds(1);
|
let mut stamp0 = UnixTime::new_only_secs(1);
|
||||||
stamp0 += Duration::from_secs(5);
|
stamp0 += Duration::from_secs(5);
|
||||||
assert_eq!(stamp0.unix_seconds, 6);
|
assert_eq!(stamp0.as_secs(), 6);
|
||||||
assert_eq!(stamp0.subsecond_millis(), 0);
|
assert_eq!(stamp0.subsec_millis(), 0);
|
||||||
let stamp1 = stamp0 + Duration::from_millis(500);
|
let stamp1 = stamp0 + Duration::from_millis(500);
|
||||||
assert_eq!(stamp1.unix_seconds, 6);
|
assert_eq!(stamp1.secs, 6);
|
||||||
assert_eq!(stamp1.subsecond_millis(), 500);
|
assert_eq!(stamp1.subsec_millis(), 500);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_addition_on_ref() {
|
fn test_addition_on_ref() {
|
||||||
let stamp0 = &UnixTimestamp::new(20, 500).unwrap();
|
let stamp0 = &UnixTime::new_subsec_millis_checked(20, 500).unwrap();
|
||||||
let stamp1 = stamp0 + Duration::from_millis(2500);
|
let stamp1 = stamp0 + Duration::from_millis(2500);
|
||||||
assert_eq!(stamp1.unix_seconds, 23);
|
assert_eq!(stamp1.secs, 23);
|
||||||
assert_eq!(stamp1.subsecond_millis(), 0);
|
assert_eq!(stamp1.subsec_millis(), 0);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_as_dt() {
|
fn test_as_dt() {
|
||||||
let stamp = UnixTimestamp::new_only_seconds(0);
|
let stamp = UnixTime::new_only_secs(0);
|
||||||
let dt = stamp.as_date_time().unwrap();
|
let dt = stamp.chrono_date_time().unwrap();
|
||||||
assert_eq!(dt.year(), 1970);
|
assert_eq!(dt.year(), 1970);
|
||||||
assert_eq!(dt.month(), 1);
|
assert_eq!(dt.month(), 1);
|
||||||
assert_eq!(dt.day(), 1);
|
assert_eq!(dt.day(), 1);
|
||||||
@@ -589,62 +631,85 @@ mod tests {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
|
#[cfg_attr(miri, ignore)]
|
||||||
fn test_from_now() {
|
fn test_from_now() {
|
||||||
let stamp_now = UnixTimestamp::from_now().unwrap();
|
let stamp_now = UnixTime::now().unwrap();
|
||||||
let dt_now = stamp_now.as_date_time().unwrap();
|
let dt_now = stamp_now.chrono_date_time().unwrap();
|
||||||
assert!(dt_now.year() >= 2020);
|
assert!(dt_now.year() >= 2020);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_stamp_diff_positive_0() {
|
fn test_stamp_diff_positive_0() {
|
||||||
let stamp_later = UnixTimestamp::new(2, 0).unwrap();
|
let stamp_later = UnixTime::new(2, 0);
|
||||||
let StampDiff {
|
let StampDiff {
|
||||||
positive_duration,
|
positive_duration,
|
||||||
duration_absolute,
|
duration_absolute,
|
||||||
} = stamp_later - UnixTimestamp::new(1, 0).unwrap();
|
} = (stamp_later - UnixTime::new(1, 0)).expect("stamp diff error");
|
||||||
assert!(positive_duration);
|
assert!(positive_duration);
|
||||||
assert_eq!(duration_absolute, Duration::from_secs(1));
|
assert_eq!(duration_absolute, Duration::from_secs(1));
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_stamp_diff_positive_1() {
|
fn test_stamp_diff_positive_1() {
|
||||||
let stamp_later = UnixTimestamp::new(3, 800).unwrap();
|
let stamp_later = UnixTime::new(3, 800 * 1_000_000);
|
||||||
let stamp_earlier = UnixTimestamp::new(1, 900).unwrap();
|
let stamp_earlier = UnixTime::new_subsec_millis_checked(1, 900).unwrap();
|
||||||
let StampDiff {
|
let StampDiff {
|
||||||
positive_duration,
|
positive_duration,
|
||||||
duration_absolute,
|
duration_absolute,
|
||||||
} = stamp_later - stamp_earlier;
|
} = (stamp_later - stamp_earlier).expect("stamp diff error");
|
||||||
assert!(positive_duration);
|
assert!(positive_duration);
|
||||||
assert_eq!(duration_absolute, Duration::from_millis(1900));
|
assert_eq!(duration_absolute, Duration::from_millis(1900));
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_stamp_diff_negative() {
|
fn test_stamp_diff_negative() {
|
||||||
let stamp_later = UnixTimestamp::new(3, 800).unwrap();
|
let stamp_later = UnixTime::new_subsec_millis_checked(3, 800).unwrap();
|
||||||
let stamp_earlier = UnixTimestamp::new(1, 900).unwrap();
|
let stamp_earlier = UnixTime::new_subsec_millis_checked(1, 900).unwrap();
|
||||||
let StampDiff {
|
let StampDiff {
|
||||||
positive_duration,
|
positive_duration,
|
||||||
duration_absolute,
|
duration_absolute,
|
||||||
} = stamp_earlier - stamp_later;
|
} = (stamp_earlier - stamp_later).expect("stamp diff error");
|
||||||
assert!(!positive_duration);
|
assert!(!positive_duration);
|
||||||
assert_eq!(duration_absolute, Duration::from_millis(1900));
|
assert_eq!(duration_absolute, Duration::from_millis(1900));
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_addition_spillover() {
|
fn test_addition_spillover() {
|
||||||
let mut stamp0 = UnixTimestamp::new(1, 900).unwrap();
|
let mut stamp0 = UnixTime::new_subsec_millis_checked(1, 900).unwrap();
|
||||||
stamp0 += Duration::from_millis(100);
|
stamp0 += Duration::from_millis(100);
|
||||||
assert_eq!(stamp0.unix_seconds, 2);
|
assert_eq!(stamp0.secs, 2);
|
||||||
assert_eq!(stamp0.subsecond_millis(), 0);
|
assert_eq!(stamp0.subsec_millis(), 0);
|
||||||
stamp0 += Duration::from_millis(1100);
|
stamp0 += Duration::from_millis(1100);
|
||||||
assert_eq!(stamp0.unix_seconds, 3);
|
assert_eq!(stamp0.secs, 3);
|
||||||
assert_eq!(stamp0.subsecond_millis(), 100);
|
assert_eq!(stamp0.subsec_millis(), 100);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_cuc_error_printout() {
|
fn test_cuc_error_printout() {
|
||||||
let cuc_error = CucError::InvalidCounterWidth(12);
|
let cuc_error = CucError::InvalidCounterWidth(12);
|
||||||
let stamp_error = TimestampError::from(cuc_error);
|
let stamp_error = TimestampError::from(cuc_error);
|
||||||
assert_eq!(stamp_error.to_string(), format!("cuc error: {cuc_error}"));
|
assert_eq!(stamp_error.to_string(), format!("CUC error: {cuc_error}"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
#[cfg(feature = "timelib")]
|
||||||
|
fn test_unix_stamp_as_timelib_datetime() {
|
||||||
|
let stamp_epoch = UnixTime::EPOCH;
|
||||||
|
let timelib_dt = stamp_epoch.timelib_date_time().unwrap();
|
||||||
|
assert_eq!(timelib_dt.year(), 1970);
|
||||||
|
assert_eq!(timelib_dt.month(), time::Month::January);
|
||||||
|
assert_eq!(timelib_dt.day(), 1);
|
||||||
|
assert_eq!(timelib_dt.hour(), 0);
|
||||||
|
assert_eq!(timelib_dt.minute(), 0);
|
||||||
|
assert_eq!(timelib_dt.second(), 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
#[cfg(feature = "timelib")]
|
||||||
|
fn test_unix_stamp_from_timelib_datetime() {
|
||||||
|
let timelib_dt = time::OffsetDateTime::UNIX_EPOCH;
|
||||||
|
let unix_time = UnixTime::from(timelib_dt);
|
||||||
|
let timelib_converted_back = unix_time.timelib_date_time().unwrap();
|
||||||
|
assert_eq!(timelib_dt, timelib_converted_back);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
948
src/uslp/mod.rs
Normal file
948
src/uslp/mod.rs
Normal file
@@ -0,0 +1,948 @@
|
|||||||
|
/// # Support of the CCSDS Unified Space Data Link Protocol (USLP)
|
||||||
|
use crate::{crc::CRC_CCITT_FALSE, ByteConversionError};
|
||||||
|
|
||||||
|
/// 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, PartialEq, Eq, num_enum::TryFromPrimitive, num_enum::IntoPrimitive)]
|
||||||
|
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||||
|
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
|
||||||
|
#[bitbybit::bitenum(u1, exhaustive = true)]
|
||||||
|
#[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, PartialEq, Eq, num_enum::TryFromPrimitive, num_enum::IntoPrimitive)]
|
||||||
|
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||||
|
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
|
||||||
|
#[bitbybit::bitenum(u1, exhaustive = true)]
|
||||||
|
#[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, thiserror::Error)]
|
||||||
|
pub enum UslpError {
|
||||||
|
#[error("byte conversion error: {0}")]
|
||||||
|
ByteConversion(#[from] ByteConversionError),
|
||||||
|
#[error("header is truncated, which is not supported")]
|
||||||
|
HeaderIsTruncated,
|
||||||
|
#[error("invalid protocol id: {0}")]
|
||||||
|
InvalidProtocolId(u8),
|
||||||
|
#[error("invalid construction rule: {0}")]
|
||||||
|
InvalidConstructionRule(u8),
|
||||||
|
#[error("invalid version number: {0}")]
|
||||||
|
InvalidVersionNumber(u8),
|
||||||
|
#[error("invalid virtual channel ID: {0}")]
|
||||||
|
InvalidVcId(u8),
|
||||||
|
#[error("invalid MAP ID: {0}")]
|
||||||
|
InvalidMapId(u8),
|
||||||
|
#[error("checksum failure")]
|
||||||
|
ChecksumFailure(u16),
|
||||||
|
}
|
||||||
|
|
||||||
|
#[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]
|
||||||
|
pub fn vc_frame_count(&self) -> u64 {
|
||||||
|
self.vc_frame_count
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
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, PartialEq, Eq, num_enum::TryFromPrimitive, num_enum::IntoPrimitive)]
|
||||||
|
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||||
|
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
|
||||||
|
#[bitbybit::bitenum(u5, exhaustive = false)]
|
||||||
|
#[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, PartialEq, Eq, num_enum::TryFromPrimitive, num_enum::IntoPrimitive)]
|
||||||
|
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||||
|
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
|
||||||
|
#[bitbybit::bitenum(u3, exhaustive = true)]
|
||||||
|
#[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,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
|
||||||
|
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 {
|
||||||
|
#[inline]
|
||||||
|
pub const fn len_header(&self) -> usize {
|
||||||
|
if self.construction_rule.applicable_to_fixed_len_tfdz() {
|
||||||
|
3
|
||||||
|
} else {
|
||||||
|
1
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
pub const fn construction_rule(&self) -> ConstructionRule {
|
||||||
|
self.construction_rule
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
pub const fn uslp_protocol_id(&self) -> UslpProtocolId {
|
||||||
|
self.uslp_protocol_id
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
pub const 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.
|
||||||
|
#[derive(Debug)]
|
||||||
|
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;
|
||||||
|
if has_fecf {
|
||||||
|
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,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
pub fn len_frame(&self) -> usize {
|
||||||
|
self.primary_header.len_frame()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
pub fn primary_header(&self) -> &PrimaryHeader {
|
||||||
|
&self.primary_header
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
pub fn data_field_header(&self) -> &TransferFrameDataFieldHeader {
|
||||||
|
&self.data_field_header
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
pub fn data(&self) -> &'buf [u8] {
|
||||||
|
self.data
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
pub fn operational_control_field(&self) -> &Option<u32> {
|
||||||
|
&self.operational_control_field
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
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()), 0x2344);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[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);
|
||||||
|
assert_eq!(primary_header.vc_frame_count_len(), 0);
|
||||||
|
assert_eq!(primary_header.vc_frame_count(), 0);
|
||||||
|
// 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);
|
||||||
|
assert_eq!(primary_header.vc_frame_count_len(), 4);
|
||||||
|
assert_eq!(primary_header.vc_frame_count(), 0x12345678);
|
||||||
|
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_vcf_count_len_two() {
|
||||||
|
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.set_vc_frame_count(2, 5).unwrap();
|
||||||
|
assert_eq!(primary_header.vc_frame_count_len(), 2);
|
||||||
|
assert_eq!(primary_header.vc_frame_count(), 5);
|
||||||
|
assert_eq!(primary_header.write_to_be_bytes(&mut buf).unwrap(), 9);
|
||||||
|
assert_eq!(buf[6] & 0b111, 2);
|
||||||
|
assert_eq!(u16::from_be_bytes(buf[7..9].try_into().unwrap()), 5);
|
||||||
|
|
||||||
|
let primary_header = PrimaryHeader::from_bytes(&buf).unwrap();
|
||||||
|
assert_eq!(primary_header.vc_frame_count_len(), 2);
|
||||||
|
assert_eq!(primary_header.vc_frame_count(), 5);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_vcf_count_len_one() {
|
||||||
|
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.set_vc_frame_count(1, 255).unwrap();
|
||||||
|
assert_eq!(primary_header.vc_frame_count_len(), 1);
|
||||||
|
assert_eq!(primary_header.vc_frame_count(), 255);
|
||||||
|
assert_eq!(primary_header.write_to_be_bytes(&mut buf).unwrap(), 8);
|
||||||
|
assert_eq!(buf[6] & 0b111, 1);
|
||||||
|
assert_eq!(buf[7], 255);
|
||||||
|
|
||||||
|
let primary_header = PrimaryHeader::from_bytes(&buf).unwrap();
|
||||||
|
assert_eq!(primary_header.vc_frame_count_len(), 1);
|
||||||
|
assert_eq!(primary_header.vc_frame_count(), 255);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[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());
|
||||||
|
// Now parse the frame.
|
||||||
|
let frame = TransferFrameReader::from_bytes(&buf, true).unwrap();
|
||||||
|
assert_eq!(*frame.primary_header(), primary_header);
|
||||||
|
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);
|
||||||
|
assert!(frame.operational_control_field().is_none());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_frame_parser_invalid_checksum() {
|
||||||
|
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();
|
||||||
|
// Now parse the frame without having calculated the checksum.
|
||||||
|
match TransferFrameReader::from_bytes(&buf, true) {
|
||||||
|
Ok(_) => panic!("transfer frame read call did not fail"),
|
||||||
|
Err(e) => {
|
||||||
|
assert_eq!(e, UslpError::ChecksumFailure(0));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_frame_parser_buf_too_small() {
|
||||||
|
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();
|
||||||
|
// Now parse the frame.
|
||||||
|
let error = TransferFrameReader::from_bytes(&buf[0..7], true).unwrap_err();
|
||||||
|
assert_eq!(
|
||||||
|
error,
|
||||||
|
ByteConversionError::FromSliceTooSmall {
|
||||||
|
expected: primary_header.len_frame(),
|
||||||
|
found: 7
|
||||||
|
}
|
||||||
|
.into()
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_from_bytes_too_small_0() {
|
||||||
|
let buf: [u8; 3] = [0; 3];
|
||||||
|
assert_eq!(
|
||||||
|
PrimaryHeader::from_bytes(&buf).unwrap_err(),
|
||||||
|
ByteConversionError::FromSliceTooSmall {
|
||||||
|
found: 3,
|
||||||
|
expected: 4
|
||||||
|
}
|
||||||
|
.into()
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_from_bytes_too_small_1() {
|
||||||
|
let buf: [u8; 6] = [0; 6];
|
||||||
|
assert_eq!(
|
||||||
|
PrimaryHeader::from_bytes(&buf).unwrap_err(),
|
||||||
|
ByteConversionError::FromSliceTooSmall {
|
||||||
|
found: 6,
|
||||||
|
expected: 7
|
||||||
|
}
|
||||||
|
.into()
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_from_bytes_truncated_not_supported() {
|
||||||
|
let mut buf: [u8; 7] = [0; 7];
|
||||||
|
let primary_header =
|
||||||
|
PrimaryHeader::new(0x01, SourceOrDestField::Dest, 0b110101, 0b1010, 0).unwrap();
|
||||||
|
primary_header.write_to_be_bytes(&mut buf).unwrap();
|
||||||
|
// Set truncated header flag manually.
|
||||||
|
buf[3] |= 0b1;
|
||||||
|
assert_eq!(
|
||||||
|
PrimaryHeader::from_bytes(&buf).unwrap_err(),
|
||||||
|
UslpError::HeaderIsTruncated
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_from_bytes_too_small_2() {
|
||||||
|
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.set_vc_frame_count(4, 0x12345678).unwrap();
|
||||||
|
primary_header.write_to_be_bytes(&mut buf).unwrap();
|
||||||
|
|
||||||
|
assert_eq!(
|
||||||
|
PrimaryHeader::from_bytes(&buf[0..8]).unwrap_err(),
|
||||||
|
UslpError::ByteConversion(ByteConversionError::FromSliceTooSmall {
|
||||||
|
found: 8,
|
||||||
|
expected: 11
|
||||||
|
})
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_invalid_version_number() {
|
||||||
|
let mut buf: [u8; 7] = [0; 7];
|
||||||
|
let primary_header =
|
||||||
|
PrimaryHeader::new(0x01, SourceOrDestField::Dest, 0b110101, 0b1010, 0).unwrap();
|
||||||
|
primary_header.write_to_be_bytes(&mut buf).unwrap();
|
||||||
|
buf[0] &= 0b00001111;
|
||||||
|
assert_eq!(
|
||||||
|
PrimaryHeader::from_bytes(&buf).unwrap_err(),
|
||||||
|
UslpError::InvalidVersionNumber(0)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_primary_header_buf_too_small() {
|
||||||
|
let primary_header = PrimaryHeader::new(
|
||||||
|
0b10100101_11000011,
|
||||||
|
SourceOrDestField::Dest,
|
||||||
|
0b110101,
|
||||||
|
0b1010,
|
||||||
|
0x2345,
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
if let Err(ByteConversionError::ToSliceTooSmall { found, expected }) =
|
||||||
|
primary_header.write_to_be_bytes(&mut [0; 4])
|
||||||
|
{
|
||||||
|
assert_eq!(found, 4);
|
||||||
|
assert_eq!(expected, 7);
|
||||||
|
} else {
|
||||||
|
panic!("writing primary header did not fail or failed with wrong error");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_applicability_contr_rules() {
|
||||||
|
assert!(ConstructionRule::PacketSpanningMultipleFrames.applicable_to_fixed_len_tfdz());
|
||||||
|
assert!(ConstructionRule::StartOfMapaSduOrVcaSdu.applicable_to_fixed_len_tfdz());
|
||||||
|
assert!(ConstructionRule::ContinuingPortionOfMapaSdu.applicable_to_fixed_len_tfdz());
|
||||||
|
assert!(!ConstructionRule::OctetStream.applicable_to_fixed_len_tfdz());
|
||||||
|
assert!(!ConstructionRule::StartingSegment.applicable_to_fixed_len_tfdz());
|
||||||
|
assert!(!ConstructionRule::ContinuingSegment.applicable_to_fixed_len_tfdz());
|
||||||
|
assert!(!ConstructionRule::LastSegment.applicable_to_fixed_len_tfdz());
|
||||||
|
assert!(!ConstructionRule::NoSegmentation.applicable_to_fixed_len_tfdz());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_header_len_correctness() {
|
||||||
|
let mut tfdh = TransferFrameDataFieldHeader {
|
||||||
|
construction_rule: ConstructionRule::PacketSpanningMultipleFrames,
|
||||||
|
uslp_protocol_id: UslpProtocolId::UserDefinedOctetStream,
|
||||||
|
fhp_or_lvo: Some(0),
|
||||||
|
};
|
||||||
|
assert_eq!(tfdh.len_header(), 3);
|
||||||
|
tfdh = TransferFrameDataFieldHeader {
|
||||||
|
construction_rule: ConstructionRule::StartOfMapaSduOrVcaSdu,
|
||||||
|
uslp_protocol_id: UslpProtocolId::UserDefinedOctetStream,
|
||||||
|
fhp_or_lvo: Some(0),
|
||||||
|
};
|
||||||
|
assert_eq!(tfdh.len_header(), 3);
|
||||||
|
tfdh = TransferFrameDataFieldHeader {
|
||||||
|
construction_rule: ConstructionRule::ContinuingPortionOfMapaSdu,
|
||||||
|
uslp_protocol_id: UslpProtocolId::UserDefinedOctetStream,
|
||||||
|
fhp_or_lvo: Some(0),
|
||||||
|
};
|
||||||
|
assert_eq!(tfdh.len_header(), 3);
|
||||||
|
tfdh = TransferFrameDataFieldHeader {
|
||||||
|
construction_rule: ConstructionRule::OctetStream,
|
||||||
|
uslp_protocol_id: UslpProtocolId::UserDefinedOctetStream,
|
||||||
|
fhp_or_lvo: None,
|
||||||
|
};
|
||||||
|
assert_eq!(tfdh.len_header(), 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_frame_data_field_header_from_bytes_too_small() {
|
||||||
|
let buf: [u8; 0] = [];
|
||||||
|
assert_eq!(
|
||||||
|
TransferFrameDataFieldHeader::from_bytes(&buf).unwrap_err(),
|
||||||
|
ByteConversionError::FromSliceTooSmall {
|
||||||
|
found: 0,
|
||||||
|
expected: 1
|
||||||
|
}
|
||||||
|
.into()
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
73
src/util.rs
73
src/util.rs
@@ -1,9 +1,7 @@
|
|||||||
use crate::ByteConversionError;
|
use crate::ByteConversionError;
|
||||||
use core::fmt::{Debug, Display, Formatter};
|
use core::fmt::Debug;
|
||||||
#[cfg(feature = "serde")]
|
#[cfg(feature = "serde")]
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
#[cfg(feature = "std")]
|
|
||||||
use std::error::Error;
|
|
||||||
|
|
||||||
pub trait ToBeBytes {
|
pub trait ToBeBytes {
|
||||||
type ByteArray: AsRef<[u8]>;
|
type ByteArray: AsRef<[u8]>;
|
||||||
@@ -15,10 +13,12 @@ pub trait ToBeBytes {
|
|||||||
impl ToBeBytes for () {
|
impl ToBeBytes for () {
|
||||||
type ByteArray = [u8; 0];
|
type ByteArray = [u8; 0];
|
||||||
|
|
||||||
|
#[inline]
|
||||||
fn written_len(&self) -> usize {
|
fn written_len(&self) -> usize {
|
||||||
0
|
0
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
fn to_be_bytes(&self) -> Self::ByteArray {
|
fn to_be_bytes(&self) -> Self::ByteArray {
|
||||||
[]
|
[]
|
||||||
}
|
}
|
||||||
@@ -27,9 +27,12 @@ impl ToBeBytes for () {
|
|||||||
impl ToBeBytes for u8 {
|
impl ToBeBytes for u8 {
|
||||||
type ByteArray = [u8; 1];
|
type ByteArray = [u8; 1];
|
||||||
|
|
||||||
|
#[inline]
|
||||||
fn written_len(&self) -> usize {
|
fn written_len(&self) -> usize {
|
||||||
1
|
1
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
fn to_be_bytes(&self) -> Self::ByteArray {
|
fn to_be_bytes(&self) -> Self::ByteArray {
|
||||||
u8::to_be_bytes(*self)
|
u8::to_be_bytes(*self)
|
||||||
}
|
}
|
||||||
@@ -38,9 +41,12 @@ impl ToBeBytes for u8 {
|
|||||||
impl ToBeBytes for u16 {
|
impl ToBeBytes for u16 {
|
||||||
type ByteArray = [u8; 2];
|
type ByteArray = [u8; 2];
|
||||||
|
|
||||||
|
#[inline]
|
||||||
fn written_len(&self) -> usize {
|
fn written_len(&self) -> usize {
|
||||||
2
|
2
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
fn to_be_bytes(&self) -> Self::ByteArray {
|
fn to_be_bytes(&self) -> Self::ByteArray {
|
||||||
u16::to_be_bytes(*self)
|
u16::to_be_bytes(*self)
|
||||||
}
|
}
|
||||||
@@ -49,9 +55,12 @@ impl ToBeBytes for u16 {
|
|||||||
impl ToBeBytes for u32 {
|
impl ToBeBytes for u32 {
|
||||||
type ByteArray = [u8; 4];
|
type ByteArray = [u8; 4];
|
||||||
|
|
||||||
|
#[inline]
|
||||||
fn written_len(&self) -> usize {
|
fn written_len(&self) -> usize {
|
||||||
4
|
4
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
fn to_be_bytes(&self) -> Self::ByteArray {
|
fn to_be_bytes(&self) -> Self::ByteArray {
|
||||||
u32::to_be_bytes(*self)
|
u32::to_be_bytes(*self)
|
||||||
}
|
}
|
||||||
@@ -60,9 +69,12 @@ impl ToBeBytes for u32 {
|
|||||||
impl ToBeBytes for u64 {
|
impl ToBeBytes for u64 {
|
||||||
type ByteArray = [u8; 8];
|
type ByteArray = [u8; 8];
|
||||||
|
|
||||||
|
#[inline]
|
||||||
fn written_len(&self) -> usize {
|
fn written_len(&self) -> usize {
|
||||||
8
|
8
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
fn to_be_bytes(&self) -> Self::ByteArray {
|
fn to_be_bytes(&self) -> Self::ByteArray {
|
||||||
u64::to_be_bytes(*self)
|
u64::to_be_bytes(*self)
|
||||||
}
|
}
|
||||||
@@ -77,7 +89,6 @@ pub trait UnsignedEnum {
|
|||||||
fn value(&self) -> u64;
|
fn value(&self) -> u64;
|
||||||
|
|
||||||
#[cfg(feature = "alloc")]
|
#[cfg(feature = "alloc")]
|
||||||
#[cfg_attr(doc_cfg, doc(cfg(feature = "alloc")))]
|
|
||||||
fn to_vec(&self) -> alloc::vec::Vec<u8> {
|
fn to_vec(&self) -> alloc::vec::Vec<u8> {
|
||||||
let mut buf = alloc::vec![0; self.size()];
|
let mut buf = alloc::vec![0; self.size()];
|
||||||
self.write_to_be_bytes(&mut buf).unwrap();
|
self.write_to_be_bytes(&mut buf).unwrap();
|
||||||
@@ -87,65 +98,45 @@ pub trait UnsignedEnum {
|
|||||||
|
|
||||||
pub trait UnsignedEnumExt: UnsignedEnum + Debug + Copy + Clone + PartialEq + Eq {}
|
pub trait UnsignedEnumExt: UnsignedEnum + Debug + Copy + Clone + PartialEq + Eq {}
|
||||||
|
|
||||||
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
|
#[derive(Debug, Copy, Clone, PartialEq, Eq, thiserror::Error)]
|
||||||
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
||||||
|
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
|
||||||
pub enum UnsignedByteFieldError {
|
pub enum UnsignedByteFieldError {
|
||||||
/// Value is too large for specified width of byte field.
|
/// Value is too large for specified width of byte field.
|
||||||
ValueTooLargeForWidth {
|
#[error("value {value} too large for width {width}")]
|
||||||
width: usize,
|
ValueTooLargeForWidth { width: usize, value: u64 },
|
||||||
value: u64,
|
|
||||||
},
|
|
||||||
/// Only 1, 2, 4 and 8 are allow width values. Optionally contains the expected width if
|
/// Only 1, 2, 4 and 8 are allow width values. Optionally contains the expected width if
|
||||||
/// applicable, for example for conversions.
|
/// applicable, for example for conversions.
|
||||||
|
#[error("invalid width {found}, expected {expected:?}")]
|
||||||
InvalidWidth {
|
InvalidWidth {
|
||||||
found: usize,
|
found: usize,
|
||||||
expected: Option<usize>,
|
expected: Option<usize>,
|
||||||
},
|
},
|
||||||
ByteConversionError(ByteConversionError),
|
#[error("byte conversion error: {0}")]
|
||||||
|
ByteConversionError(#[from] ByteConversionError),
|
||||||
}
|
}
|
||||||
|
|
||||||
impl From<ByteConversionError> for UnsignedByteFieldError {
|
|
||||||
fn from(value: ByteConversionError) -> Self {
|
|
||||||
Self::ByteConversionError(value)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Display for UnsignedByteFieldError {
|
|
||||||
fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
|
|
||||||
match self {
|
|
||||||
Self::ByteConversionError(e) => {
|
|
||||||
write!(f, "low level byte conversion error: {e}")
|
|
||||||
}
|
|
||||||
Self::InvalidWidth { found, .. } => {
|
|
||||||
write!(f, "invalid width {found}, only 1, 2, 4 and 8 are allowed.")
|
|
||||||
}
|
|
||||||
Self::ValueTooLargeForWidth { width, value } => {
|
|
||||||
write!(f, "value {value} too large for width {width}")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(feature = "std")]
|
|
||||||
impl Error for UnsignedByteFieldError {}
|
|
||||||
|
|
||||||
/// Type erased variant.
|
/// Type erased variant.
|
||||||
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
|
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
|
||||||
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
||||||
|
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
|
||||||
pub struct UnsignedByteField {
|
pub struct UnsignedByteField {
|
||||||
width: usize,
|
width: usize,
|
||||||
value: u64,
|
value: u64,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl UnsignedByteField {
|
impl UnsignedByteField {
|
||||||
|
#[inline]
|
||||||
pub const fn new(width: usize, value: u64) -> Self {
|
pub const fn new(width: usize, value: u64) -> Self {
|
||||||
Self { width, value }
|
Self { width, value }
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
pub const fn value_const(&self) -> u64 {
|
pub const fn value_const(&self) -> u64 {
|
||||||
self.value
|
self.value
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
pub fn new_from_be_bytes(width: usize, buf: &[u8]) -> Result<Self, UnsignedByteFieldError> {
|
pub fn new_from_be_bytes(width: usize, buf: &[u8]) -> Result<Self, UnsignedByteFieldError> {
|
||||||
if width > buf.len() {
|
if width > buf.len() {
|
||||||
return Err(ByteConversionError::FromSliceTooSmall {
|
return Err(ByteConversionError::FromSliceTooSmall {
|
||||||
@@ -178,10 +169,12 @@ impl UnsignedByteField {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl UnsignedEnum for UnsignedByteField {
|
impl UnsignedEnum for UnsignedByteField {
|
||||||
|
#[inline]
|
||||||
fn size(&self) -> usize {
|
fn size(&self) -> usize {
|
||||||
self.width
|
self.width
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
fn value(&self) -> u64 {
|
fn value(&self) -> u64 {
|
||||||
self.value_const()
|
self.value_const()
|
||||||
}
|
}
|
||||||
@@ -221,6 +214,7 @@ impl UnsignedEnum for UnsignedByteField {
|
|||||||
|
|
||||||
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
|
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
|
||||||
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
||||||
|
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
|
||||||
pub struct GenericUnsignedByteField<TYPE: Copy + Into<u64>> {
|
pub struct GenericUnsignedByteField<TYPE: Copy + Into<u64>> {
|
||||||
value: TYPE,
|
value: TYPE,
|
||||||
}
|
}
|
||||||
@@ -236,6 +230,7 @@ impl<TYPE: Copy + Into<u64>> GenericUnsignedByteField<TYPE> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl<TYPE: Copy + ToBeBytes + Into<u64>> UnsignedEnum for GenericUnsignedByteField<TYPE> {
|
impl<TYPE: Copy + ToBeBytes + Into<u64>> UnsignedEnum for GenericUnsignedByteField<TYPE> {
|
||||||
|
#[inline]
|
||||||
fn size(&self) -> usize {
|
fn size(&self) -> usize {
|
||||||
self.value.written_len()
|
self.value.written_len()
|
||||||
}
|
}
|
||||||
@@ -251,6 +246,7 @@ impl<TYPE: Copy + ToBeBytes + Into<u64>> UnsignedEnum for GenericUnsignedByteFie
|
|||||||
Ok(self.value.written_len())
|
Ok(self.value.written_len())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
fn value(&self) -> u64 {
|
fn value(&self) -> u64 {
|
||||||
self.value_typed().into()
|
self.value_typed().into()
|
||||||
}
|
}
|
||||||
@@ -276,6 +272,7 @@ impl From<UnsignedByteFieldU8> for UnsignedByteField {
|
|||||||
impl TryFrom<UnsignedByteField> for UnsignedByteFieldU8 {
|
impl TryFrom<UnsignedByteField> for UnsignedByteFieldU8 {
|
||||||
type Error = UnsignedByteFieldError;
|
type Error = UnsignedByteFieldError;
|
||||||
|
|
||||||
|
#[inline]
|
||||||
fn try_from(value: UnsignedByteField) -> Result<Self, Self::Error> {
|
fn try_from(value: UnsignedByteField) -> Result<Self, Self::Error> {
|
||||||
if value.width != 1 {
|
if value.width != 1 {
|
||||||
return Err(UnsignedByteFieldError::InvalidWidth {
|
return Err(UnsignedByteFieldError::InvalidWidth {
|
||||||
@@ -288,6 +285,7 @@ impl TryFrom<UnsignedByteField> for UnsignedByteFieldU8 {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl From<UnsignedByteFieldU16> for UnsignedByteField {
|
impl From<UnsignedByteFieldU16> for UnsignedByteField {
|
||||||
|
#[inline]
|
||||||
fn from(value: UnsignedByteFieldU16) -> Self {
|
fn from(value: UnsignedByteFieldU16) -> Self {
|
||||||
Self::new(2, value.value as u64)
|
Self::new(2, value.value as u64)
|
||||||
}
|
}
|
||||||
@@ -296,6 +294,7 @@ impl From<UnsignedByteFieldU16> for UnsignedByteField {
|
|||||||
impl TryFrom<UnsignedByteField> for UnsignedByteFieldU16 {
|
impl TryFrom<UnsignedByteField> for UnsignedByteFieldU16 {
|
||||||
type Error = UnsignedByteFieldError;
|
type Error = UnsignedByteFieldError;
|
||||||
|
|
||||||
|
#[inline]
|
||||||
fn try_from(value: UnsignedByteField) -> Result<Self, Self::Error> {
|
fn try_from(value: UnsignedByteField) -> Result<Self, Self::Error> {
|
||||||
if value.width != 2 {
|
if value.width != 2 {
|
||||||
return Err(UnsignedByteFieldError::InvalidWidth {
|
return Err(UnsignedByteFieldError::InvalidWidth {
|
||||||
@@ -308,6 +307,7 @@ impl TryFrom<UnsignedByteField> for UnsignedByteFieldU16 {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl From<UnsignedByteFieldU32> for UnsignedByteField {
|
impl From<UnsignedByteFieldU32> for UnsignedByteField {
|
||||||
|
#[inline]
|
||||||
fn from(value: UnsignedByteFieldU32) -> Self {
|
fn from(value: UnsignedByteFieldU32) -> Self {
|
||||||
Self::new(4, value.value as u64)
|
Self::new(4, value.value as u64)
|
||||||
}
|
}
|
||||||
@@ -316,6 +316,7 @@ impl From<UnsignedByteFieldU32> for UnsignedByteField {
|
|||||||
impl TryFrom<UnsignedByteField> for UnsignedByteFieldU32 {
|
impl TryFrom<UnsignedByteField> for UnsignedByteFieldU32 {
|
||||||
type Error = UnsignedByteFieldError;
|
type Error = UnsignedByteFieldError;
|
||||||
|
|
||||||
|
#[inline]
|
||||||
fn try_from(value: UnsignedByteField) -> Result<Self, Self::Error> {
|
fn try_from(value: UnsignedByteField) -> Result<Self, Self::Error> {
|
||||||
if value.width != 4 {
|
if value.width != 4 {
|
||||||
return Err(UnsignedByteFieldError::InvalidWidth {
|
return Err(UnsignedByteFieldError::InvalidWidth {
|
||||||
@@ -328,6 +329,7 @@ impl TryFrom<UnsignedByteField> for UnsignedByteFieldU32 {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl From<UnsignedByteFieldU64> for UnsignedByteField {
|
impl From<UnsignedByteFieldU64> for UnsignedByteField {
|
||||||
|
#[inline]
|
||||||
fn from(value: UnsignedByteFieldU64) -> Self {
|
fn from(value: UnsignedByteFieldU64) -> Self {
|
||||||
Self::new(8, value.value)
|
Self::new(8, value.value)
|
||||||
}
|
}
|
||||||
@@ -336,6 +338,7 @@ impl From<UnsignedByteFieldU64> for UnsignedByteField {
|
|||||||
impl TryFrom<UnsignedByteField> for UnsignedByteFieldU64 {
|
impl TryFrom<UnsignedByteField> for UnsignedByteFieldU64 {
|
||||||
type Error = UnsignedByteFieldError;
|
type Error = UnsignedByteFieldError;
|
||||||
|
|
||||||
|
#[inline]
|
||||||
fn try_from(value: UnsignedByteField) -> Result<Self, Self::Error> {
|
fn try_from(value: UnsignedByteField) -> Result<Self, Self::Error> {
|
||||||
if value.width != 8 {
|
if value.width != 8 {
|
||||||
return Err(UnsignedByteFieldError::InvalidWidth {
|
return Err(UnsignedByteFieldError::InvalidWidth {
|
||||||
|
Reference in New Issue
Block a user