Skip to main content

dvb_t2mi/payload/
individual_addressing.rs

1//! T2-MI payload type 0x21: Individual addressing — §5.2.8.
2//!
3//! Carries per-transmitter addressing data: tx_identifier + function loop
4//! with entries like ACE-PAPR (0x10), MISO group (0x11), Frequency (0x17), etc.
5
6use std::fmt;
7
8use num_enum::TryFromPrimitive;
9
10use dvb_common::{Parse, Serialize};
11
12/// Function tags per §5.2.8.2 Table 5.
13#[derive(Debug, Clone, Copy, PartialEq, Eq, TryFromPrimitive)]
14#[cfg_attr(feature = "serde", derive(serde::Serialize))]
15#[repr(u8)]
16pub enum AddressingFunctionTag {
17    /// Transmitter time offset.
18    TimeOffset = 0x00,
19    /// Transmitter frequency offset.
20    FrequencyOffset = 0x01,
21    /// Transmitter power.
22    Power = 0x02,
23    /// Private data.
24    PrivateData = 0x03,
25    /// Cell ID.
26    CellId = 0x04,
27    /// Enable.
28    Enable = 0x05,
29    /// Bandwidth (not applicable for T2).
30    Bandwidth = 0x06,
31    /// ACE-PAPR reduction (T2-specific).
32    AcePapr = 0x10,
33    /// MISO group (T2-specific).
34    MisoGroup = 0x11,
35    /// TR-PAPR reduction (T2-specific).
36    TrPapr = 0x12,
37    /// L1-ACE-PAPR (T2-specific).
38    L1AcePapr = 0x13,
39    /// TX-SIG FEF sequence number (T2-specific).
40    TxSigFefSeqNum = 0x15,
41    /// TX-SIG auxiliary stream TX ID (T2-specific).
42    TxSigAuxStreamTxId = 0x16,
43    /// Frequency (T2-specific).
44    Frequency = 0x17,
45}
46
47impl From<AddressingFunctionTag> for u8 {
48    fn from(tag: AddressingFunctionTag) -> Self {
49        tag as u8
50    }
51}
52
53impl fmt::Display for AddressingFunctionTag {
54    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
55        match self {
56            AddressingFunctionTag::TimeOffset => write!(f, "TimeOffset"),
57            AddressingFunctionTag::FrequencyOffset => write!(f, "FrequencyOffset"),
58            AddressingFunctionTag::Power => write!(f, "Power"),
59            AddressingFunctionTag::PrivateData => write!(f, "PrivateData"),
60            AddressingFunctionTag::CellId => write!(f, "CellId"),
61            AddressingFunctionTag::Enable => write!(f, "Enable"),
62            AddressingFunctionTag::Bandwidth => write!(f, "Bandwidth"),
63            AddressingFunctionTag::AcePapr => write!(f, "AcePapr"),
64            AddressingFunctionTag::MisoGroup => write!(f, "MisoGroup"),
65            AddressingFunctionTag::TrPapr => write!(f, "TrPapr"),
66            AddressingFunctionTag::L1AcePapr => write!(f, "L1AcePapr"),
67            AddressingFunctionTag::TxSigFefSeqNum => write!(f, "TxSigFefSeqNum"),
68            AddressingFunctionTag::TxSigAuxStreamTxId => write!(f, "TxSigAuxStreamTxId"),
69            AddressingFunctionTag::Frequency => write!(f, "Frequency"),
70        }
71    }
72}
73
74/// A single function entry within individual addressing.
75#[derive(Debug, Clone, PartialEq, Eq)]
76#[cfg_attr(feature = "serde", derive(serde::Serialize))]
77pub struct FunctionEntry<'a> {
78    /// Function tag identifying the entry type.
79    pub tag: AddressingFunctionTag,
80    /// Raw function body (including tag + length bytes).
81    pub raw: &'a [u8],
82}
83
84/// Individual addressing payload (type 0x21) per ETSI TS 102 773 §5.2.8.1, Fig 11.
85///
86/// Top-level layout:
87/// - byte 0: rfu (8 bits) — reserved, ignored on parse, preserved for round-trip
88/// - byte 1: individual_addressing_length (8 bits) — length of the data loop in bytes
89/// - bytes 2..: individual_addressing_data — a loop of per-transmitter entries, each
90///   `tx_identifier(16) · function_loop_length(8) · function()…`. The tx_identifier
91///   lives INSIDE each entry, not at the top level; the loop is kept raw here.
92#[derive(Debug, Clone, PartialEq, Eq)]
93#[cfg_attr(feature = "serde", derive(serde::Serialize))]
94pub struct IndividualAddressingPayload<'a> {
95    /// Reserved-for-future-use byte (byte 0); preserved verbatim for round-trip.
96    pub rfu: u8,
97    /// Raw individual_addressing_data loop. Length is the 8-bit
98    /// `individual_addressing_length` field, derived from this slice on serialize.
99    pub individual_addressing_data: &'a [u8],
100}
101
102const HEADER_LEN: usize = 2;
103
104impl<'a> Parse<'a> for IndividualAddressingPayload<'a> {
105    type Error = crate::error::Error;
106
107    fn parse(bytes: &'a [u8]) -> Result<Self, crate::error::Error> {
108        if bytes.len() < HEADER_LEN {
109            return Err(crate::Error::BufferTooShort {
110                need: HEADER_LEN,
111                have: bytes.len(),
112                what: "IndividualAddressingPayload header",
113            });
114        }
115
116        let rfu = bytes[0];
117        let individual_addressing_length = bytes[1] as usize;
118        // The data loop must hold exactly the declared number of bytes (§5.2.8.1).
119        let need = HEADER_LEN + individual_addressing_length;
120        if bytes.len() < need {
121            return Err(crate::Error::BufferTooShort {
122                need,
123                have: bytes.len(),
124                what: "IndividualAddressingPayload data",
125            });
126        }
127
128        Ok(IndividualAddressingPayload {
129            rfu,
130            individual_addressing_data: &bytes[HEADER_LEN..need],
131        })
132    }
133}
134
135impl<'a> crate::traits::PayloadDef<'a> for IndividualAddressingPayload<'a> {
136    const PACKET_TYPE: u8 = 0x21;
137    const NAME: &'static str = "INDIVIDUAL_ADDRESSING";
138}
139
140impl Serialize for IndividualAddressingPayload<'_> {
141    type Error = crate::error::Error;
142
143    fn serialized_len(&self) -> usize {
144        HEADER_LEN + self.individual_addressing_data.len()
145    }
146
147    fn serialize_into(&self, buf: &mut [u8]) -> Result<usize, crate::error::Error> {
148        if buf.len() < self.serialized_len() {
149            return Err(crate::Error::OutputBufferTooSmall {
150                need: self.serialized_len(),
151                have: buf.len(),
152            });
153        }
154
155        // individual_addressing_length is an 8-bit field — the data loop cannot
156        // exceed 255 bytes.
157        if self.individual_addressing_data.len() > u8::MAX as usize {
158            return Err(crate::Error::ReservedBitsViolation {
159                field: "individual_addressing_length",
160                reason: "individual_addressing_data exceeds 255 bytes (8-bit length field)",
161            });
162        }
163
164        buf[0] = self.rfu;
165        buf[1] = self.individual_addressing_data.len() as u8;
166
167        if !self.individual_addressing_data.is_empty() {
168            buf[HEADER_LEN..HEADER_LEN + self.individual_addressing_data.len()]
169                .copy_from_slice(self.individual_addressing_data);
170        }
171
172        Ok(self.serialized_len())
173    }
174}
175
176impl fmt::Display for IndividualAddressingPayload<'_> {
177    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
178        write!(
179            f,
180            "IndividualAddressing {{ rfu: 0x{:02X}, addr_data_len: {} }}",
181            self.rfu,
182            self.individual_addressing_data.len()
183        )
184    }
185}
186
187#[cfg(test)]
188mod tests {
189    use super::*;
190
191    #[test]
192    fn addressing_function_tag_try_from_valid() {
193        assert_eq!(
194            AddressingFunctionTag::try_from(0x10),
195            Ok(AddressingFunctionTag::AcePapr)
196        );
197        assert_eq!(
198            AddressingFunctionTag::try_from(0x17),
199            Ok(AddressingFunctionTag::Frequency)
200        );
201    }
202
203    #[test]
204    fn addressing_function_tag_try_from_rejects_unknown() {
205        assert!(AddressingFunctionTag::try_from(0x14).is_err());
206        assert!(AddressingFunctionTag::try_from(0xFF).is_err());
207    }
208
209    #[test]
210    fn exhaustive_byte_sweep() {
211        let mut matched = 0u16;
212        for byte in 0u8..=0xFF {
213            if let Ok(v) = AddressingFunctionTag::try_from(byte) {
214                assert_eq!(v as u8, byte, "round-trip failed for {byte:#04x}");
215                matched += 1;
216            }
217        }
218        assert_eq!(matched, 14, "expected 14 matched variants");
219    }
220
221    #[test]
222    fn address_function_tag_display() {
223        assert_eq!(AddressingFunctionTag::AcePapr.to_string(), "AcePapr");
224    }
225
226    #[test]
227    fn parse_extracts_rfu_and_addressing_data() {
228        // rfu=0x00, length=4, then a 4-byte data loop. The data loop here is one
229        // transmitter entry: tx_identifier=0x0005, function_loop_length=0x04, ...
230        // — but parse keeps the whole loop raw.
231        let buf = [0x00u8, 0x04, 0x00, 0x05, 0x04, 0x10];
232        let result = IndividualAddressingPayload::parse(&buf).unwrap();
233        assert_eq!(result.rfu, 0x00);
234        assert_eq!(result.individual_addressing_data, &[0x00, 0x05, 0x04, 0x10]);
235    }
236
237    #[test]
238    fn parse_preserves_rfu_byte() {
239        let buf = [0xFFu8, 0x00];
240        let result = IndividualAddressingPayload::parse(&buf).unwrap();
241        assert_eq!(result.rfu, 0xFF);
242        assert!(result.individual_addressing_data.is_empty());
243    }
244
245    #[test]
246    fn parse_rejects_short_buffer() {
247        assert!(IndividualAddressingPayload::parse(&[0x00]).is_err());
248    }
249
250    #[test]
251    fn parse_rejects_truncated_data() {
252        // declares 4 data bytes but only 2 follow
253        assert!(IndividualAddressingPayload::parse(&[0x00, 0x04, 0xAA, 0xBB]).is_err());
254    }
255
256    #[test]
257    fn serialize_round_trip() {
258        let orig = IndividualAddressingPayload {
259            rfu: 0x00,
260            individual_addressing_data: &[0x00, 0x03, 0x04, 0xDE, 0xAD],
261        };
262        let mut buf = vec![0u8; orig.serialized_len()];
263        orig.serialize_into(&mut buf).unwrap();
264        // length field is derived from the data slice
265        assert_eq!(buf[1], 5);
266        let parsed = IndividualAddressingPayload::parse(&buf).unwrap();
267        assert_eq!(orig, parsed);
268    }
269
270    #[test]
271    fn serialize_empty_data() {
272        let orig = IndividualAddressingPayload {
273            rfu: 0x00,
274            individual_addressing_data: &[],
275        };
276        let mut buf = vec![0u8; orig.serialized_len()];
277        orig.serialize_into(&mut buf).unwrap();
278        assert_eq!(buf, [0x00, 0x00]);
279    }
280}