dvb_t2mi/payload/any.rs
1//! Unified payload dispatch: [`AnyPayload`].
2//!
3//! [`AnyPayload`] is generated from a single declarative list
4//! (`declare_payloads!`) — one line per T2-MI payload type.
5//! The list is the single source of truth: it produces the enum, the
6//! `From<T>` conversions, the `packet_type` → parser dispatcher, and a drift
7//! test that pins each literal to the type's
8//! [`crate::traits::PayloadDef::PACKET_TYPE`].
9//!
10//! # Dispatch contract
11//!
12//! [`AnyPayload::dispatch`] takes the **payload bytes only** (the bytes after
13//! the 6-byte T2-MI header, up to but not including the 4-byte CRC trailer).
14//! Each payload parser expects exactly those bytes — the header and CRC are NOT
15//! passed in. To recover the payload slice from a raw packet buffer use
16//! [`crate::packet::Header::payload_bytes`].
17//!
18//! # Adding a payload
19//!
20//! 1. Create the module with the wire layout and the symmetric
21//! [`dvb_common::Parse`] / [`dvb_common::Serialize`] impls + round-trip
22//! tests (copy an existing module).
23//! 2. `impl PayloadDef` for the type (`PACKET_TYPE` from the spec / the
24//! [`crate::packet::PacketType`] enum value, `NAME` in SCREAMING_SNAKE
25//! without the `_payload` suffix).
26//! 3. Add one line to the `declare_payloads!` invocation below — the enum
27//! variant, dispatcher arm, and drift test are generated from it.
28//! 4. The integration completeness test walks the generated
29//! [`AnyPayload::DISPATCHED_TYPES`] automatically — no test edits needed.
30
31/// Declares [`AnyPayload`] + its dispatcher from one packet-type list.
32///
33/// Each line is `Variant = 0xTYPE => module::Type[<'a>]`.
34macro_rules! declare_payloads {
35 (
36 $lt:lifetime;
37 $( $variant:ident = $ptype:literal => $($path:ident)::+ $(<$plt:lifetime>)? ),+ $(,)?
38 ) => {
39 /// Every crate-implemented T2-MI payload, plus an `Unknown` fallthrough.
40 ///
41 /// serde uses external tagging with camelCase variant keys.
42 /// Variant names map 1:1 to the payload modules; see each module
43 /// for the wire layout.
44 ///
45 /// # Dispatch contract
46 ///
47 /// Use [`AnyPayload::dispatch`] with the payload bytes (post-header,
48 /// pre-CRC). See the module-level documentation for details.
49 #[derive(Debug)]
50 #[cfg_attr(feature = "serde", derive(serde::Serialize))]
51 #[cfg_attr(feature = "serde", serde(rename_all = "camelCase"))]
52 // Covariant in `$lt`: every variant holds only lifetime-parametrised
53 // payload views or `&$lt [u8]` (`Unknown`), so the derive is sound.
54 #[cfg_attr(feature = "yoke", derive(yoke::Yokeable))]
55 #[non_exhaustive]
56 pub enum AnyPayload<$lt> {
57 $(
58 #[allow(missing_docs)]
59 $variant($($path)::+ $(<$plt>)?),
60 )+
61 /// Packet type with no typed implementation; `body` contains the
62 /// raw payload bytes (post-header, pre-CRC).
63 Unknown {
64 /// The raw `packet_type` byte.
65 packet_type: u8,
66 /// The raw payload bytes.
67 body: &$lt [u8],
68 },
69 }
70
71 $(
72 impl<$lt> From<$($path)::+ $(<$plt>)?> for AnyPayload<$lt> {
73 fn from(p: $($path)::+ $(<$plt>)?) -> Self {
74 Self::$variant(p)
75 }
76 }
77 )+
78
79 impl<$lt> AnyPayload<$lt> {
80 /// Every `packet_type` the generated dispatcher routes (excludes
81 /// [`AnyPayload::Unknown`]).
82 pub const DISPATCHED_TYPES: &'static [u8] = &[$($ptype),+];
83
84 /// Diagnostic name of the contained payload — the type's
85 /// [`PayloadDef::NAME`](crate::traits::PayloadDef::NAME)
86 /// (`"BBFRAME"`, `"L1_CURRENT"`, …); `"UNKNOWN"` for
87 /// [`AnyPayload::Unknown`].
88 #[must_use]
89 pub fn name(&self) -> &'static str {
90 match self {
91 $(
92 Self::$variant(_) =>
93 <$($path)::+ as crate::traits::PayloadDef>::NAME,
94 )+
95 Self::Unknown { .. } => "UNKNOWN",
96 }
97 }
98
99 /// Parse one payload by its `packet_type`.
100 ///
101 /// `payload_bytes` must be the **payload-only slice** (bytes after
102 /// the 6-byte T2-MI header, before the 4-byte CRC trailer).
103 ///
104 /// Returns `None` when `packet_type` has no typed implementation
105 /// (the caller turns that into [`AnyPayload::Unknown`]).
106 /// Returns `Some(Err)` on a typed parse failure for a recognised type.
107 ///
108 /// See the [module-level documentation][self] for the dispatch
109 /// contract (payload-only bytes, header and CRC excluded).
110 pub fn dispatch(
111 packet_type: u8,
112 payload_bytes: &$lt [u8],
113 ) -> Option<crate::Result<Self>> {
114 use dvb_common::Parse;
115 match packet_type {
116 $(
117 $ptype => Some(
118 <$($path)::+>::parse(payload_bytes).map(Self::$variant),
119 ),
120 )+
121 _ => None,
122 }
123 }
124 }
125
126 #[cfg(test)]
127 mod macro_drift {
128 #[test]
129 fn packet_type_literals_match_payload_def() {
130 use crate::traits::PayloadDef;
131 $(
132 assert_eq!(
133 $ptype,
134 <$($path)::+ as PayloadDef>::PACKET_TYPE,
135 concat!("PACKET_TYPE literal drift for ", stringify!($variant)),
136 );
137 assert!(
138 !<$($path)::+ as PayloadDef>::NAME.is_empty(),
139 concat!("empty NAME for ", stringify!($variant)),
140 );
141 )+
142 }
143 }
144 };
145}
146
147declare_payloads! {'a;
148 // TS 102 773 Table 1 — all 12 defined packet types in numerical order.
149 Bbframe = 0x00 => crate::payload::bbframe::BbframePayload<'a>,
150 AuxIq = 0x01 => crate::payload::aux_iq::AuxIqPayload<'a>,
151 ArbitraryCells = 0x02 => crate::payload::arbitrary_cells::ArbitraryCellsPayload<'a>,
152 L1Current = 0x10 => crate::payload::l1_current::L1CurrentPayload<'a>,
153 L1Future = 0x11 => crate::payload::l1_future::L1FuturePayload<'a>,
154 P2Bias = 0x12 => crate::payload::p2_bias::P2BiasPayload,
155 Timestamp = 0x20 => crate::payload::timestamp::T2TimestampPayload,
156 IndividualAddressing = 0x21 => crate::payload::individual_addressing::IndividualAddressingPayload<'a>,
157 FefNull = 0x30 => crate::payload::fef_null::FefNullPayload,
158 FefIq = 0x31 => crate::payload::fef_iq::FefIqPayload<'a>,
159 FefComposite = 0x32 => crate::payload::fef_composite::FefCompositePayload,
160 FefSubpart = 0x33 => crate::payload::fef_subpart::FefSubPartPayload<'a>,
161}
162
163#[cfg(test)]
164mod tests {
165 use super::*;
166
167 // ── Completeness ─────────────────────────────────────────────────────────
168
169 /// `AnyPayload::name()` reflects `PayloadDef::NAME`; `UNKNOWN` for unknowns.
170 #[test]
171 fn name_maps_variant_to_payloaddef_name() {
172 let bb = AnyPayload::dispatch(0x00, &[0x00, 0x00, 0x00])
173 .expect("dispatched")
174 .expect("valid bbframe payload");
175 assert_eq!(bb.name(), "BBFRAME");
176 let unknown = AnyPayload::Unknown {
177 packet_type: 0x7F,
178 body: &[],
179 };
180 assert_eq!(unknown.name(), "UNKNOWN");
181 }
182
183 /// Every entry in DISPATCHED_TYPES must dispatch to a non-Unknown variant.
184 #[test]
185 fn every_dispatched_type_routes_non_unknown() {
186 // Minimal valid payload bytes for each packet type (all RFU = 0 — the
187 // parsers reject non-zero reserved bits). See each payload module's
188 // own tests for full boundary coverage.
189
190 // 0x00 BBFrame: frame_idx(1) + plp_id(1) + intl_frame_start+rfu(1) = 3 bytes.
191 let bbframe_bytes: &[u8] = &[0x00, 0x00, 0x00];
192 // 0x01 AuxIq: frame_idx(1) + aux_id(4bits, must be 1..=15)+rfu(4bits)(1) + rfu(1) = 3 bytes.
193 // aux_id=1: byte1 = (1<<4) = 0x10.
194 let aux_iq_bytes: &[u8] = &[0x00, 0x10, 0x00];
195 // 0x02 ArbitraryCells: 8-byte header (rfu bytes 3,4 = 0, byte5 top 2 = 0).
196 let arb_cells_bytes: &[u8] = &[0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00];
197 // 0x10 L1Current: frame_idx(1) + freq_source(2bits)+rfu(6bits)(1) = 2 bytes.
198 let l1_current_bytes: &[u8] = &[0x00, 0x00];
199 // 0x11 L1Future: frame_idx(1) + rfu(1) = 2 bytes.
200 let l1_future_bytes: &[u8] = &[0x00, 0x00];
201 // 0x12 P2Bias: 5 bytes, all rfu = 0.
202 let p2_bias_bytes: &[u8] = &[0x00, 0x00, 0x00, 0x00, 0x00];
203 // 0x20 Timestamp: 11 bytes, rfu top 4 bits of byte0 = 0, bw=0 (1.7 MHz).
204 let timestamp_bytes: &[u8] = &[
205 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
206 ];
207 // 0x21 IndividualAddressing: rfu(1) + length(1, value 0) = 2 bytes.
208 let indiv_addr_bytes: &[u8] = &[0x00, 0x00];
209 // 0x30 FefNull: fef_idx(1) + rfu(1, must be 0) + s1_field+s2_field(1) = 3 bytes.
210 let fef_null_bytes: &[u8] = &[0x00, 0x00, 0x00];
211 // 0x31 FefIq: fef_idx(1) + rfu(1, must be 0) + s1+s2(1) = 3 bytes.
212 let fef_iq_bytes: &[u8] = &[0x00, 0x00, 0x00];
213 // 0x32 FefComposite: 8 bytes. byte1 [7]=rfu1=0, bytes2-5=rfu2=0.
214 let fef_composite_bytes: &[u8] = &[0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00];
215 // 0x33 FefSubpart: 15 bytes.
216 // bytes 3-6 = rfu1 = 0, byte 11 = rfu2 = 0, byte 12 top 2 = 0.
217 // subpart_variety bytes 9-10 = 0x0000 = Null.
218 let fef_subpart_bytes: &[u8] = &[
219 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
220 0x00,
221 ];
222
223 let fixtures: &[(u8, &[u8])] = &[
224 (0x00, bbframe_bytes),
225 (0x01, aux_iq_bytes),
226 (0x02, arb_cells_bytes),
227 (0x10, l1_current_bytes),
228 (0x11, l1_future_bytes),
229 (0x12, p2_bias_bytes),
230 (0x20, timestamp_bytes),
231 (0x21, indiv_addr_bytes),
232 (0x30, fef_null_bytes),
233 (0x31, fef_iq_bytes),
234 (0x32, fef_composite_bytes),
235 (0x33, fef_subpart_bytes),
236 ];
237
238 for &(pt, bytes) in fixtures {
239 let result = AnyPayload::dispatch(pt, bytes);
240 assert!(result.is_some(), "0x{pt:02x} returned None from dispatch");
241 let parsed = result.unwrap();
242 assert!(
243 parsed.is_ok(),
244 "0x{pt:02x} dispatch parse failed: {:?}",
245 parsed.unwrap_err()
246 );
247 assert!(
248 !matches!(parsed.unwrap(), AnyPayload::Unknown { .. }),
249 "0x{pt:02x} was dispatched to Unknown"
250 );
251 }
252 }
253
254 /// DISPATCHED_TYPES has exactly 12 entries (one per TS 102 773 Table 1 type).
255 #[test]
256 fn dispatched_types_count_is_twelve() {
257 assert_eq!(AnyPayload::DISPATCHED_TYPES.len(), 12);
258 }
259
260 /// DISPATCHED_TYPES contains all 12 defined packet_type values.
261 #[test]
262 fn dispatched_types_contains_all_defined_packet_types() {
263 let expected = [
264 0x00u8, 0x01, 0x02, 0x10, 0x11, 0x12, 0x20, 0x21, 0x30, 0x31, 0x32, 0x33,
265 ];
266 for pt in expected {
267 assert!(
268 AnyPayload::DISPATCHED_TYPES.contains(&pt),
269 "0x{pt:02x} missing from DISPATCHED_TYPES"
270 );
271 }
272 }
273
274 // ── Unknown fallthrough ───────────────────────────────────────────────────
275
276 /// An undispatched packet_type returns None from dispatch (caller makes Unknown).
277 #[test]
278 fn undispatched_packet_type_returns_none() {
279 // 0x22..=0x2F are RFU, never defined.
280 assert!(AnyPayload::dispatch(0x22, &[]).is_none());
281 assert!(AnyPayload::dispatch(0xFF, &[]).is_none());
282 }
283
284 // ── From impls ────────────────────────────────────────────────────────────
285
286 #[test]
287 fn from_bbframe_payload_into_any_payload() {
288 use crate::payload::bbframe::BbframePayload;
289 let p = BbframePayload {
290 frame_idx: 1,
291 plp_id: 2,
292 intl_frame_start: false,
293 bbframe: &[],
294 };
295 let any = AnyPayload::from(p);
296 assert!(matches!(any, AnyPayload::Bbframe(_)));
297 }
298
299 #[test]
300 fn from_fef_null_payload_into_any_payload() {
301 use crate::payload::fef_null::{FefNullPayload, S1Field};
302 let p = FefNullPayload {
303 fef_idx: 0,
304 s1_field: S1Field::V0,
305 s2_field: 0,
306 };
307 let any = AnyPayload::from(p);
308 assert!(matches!(any, AnyPayload::FefNull(_)));
309 }
310
311 // ── serde ─────────────────────────────────────────────────────────────────
312
313 #[cfg(feature = "serde")]
314 #[test]
315 fn bbframe_serializes_as_camel_case_external_tag() {
316 use crate::payload::bbframe::BbframePayload;
317 let p = BbframePayload {
318 frame_idx: 0x42,
319 plp_id: 0x05,
320 intl_frame_start: true,
321 bbframe: &[],
322 };
323 let any = AnyPayload::Bbframe(p);
324 let json = serde_json::to_value(&any).unwrap();
325 assert!(
326 json.get("bbframe").is_some(),
327 "expected camelCase 'bbframe' key, got: {json}"
328 );
329 assert_eq!(json["bbframe"]["frame_idx"], 0x42);
330 }
331
332 #[cfg(feature = "serde")]
333 #[test]
334 fn unknown_serializes_with_packet_type_and_body() {
335 let any = AnyPayload::Unknown {
336 packet_type: 0x22,
337 body: &[0xDE, 0xAD],
338 };
339 let json = serde_json::to_value(&any).unwrap();
340 assert!(
341 json.get("unknown").is_some(),
342 "expected 'unknown' key, got: {json}"
343 );
344 assert_eq!(json["unknown"]["packet_type"], 0x22);
345 }
346}