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