1macro_rules! declare_descriptors {
57 (
58 $lt:lifetime;
59 $( $variant:ident = $tag:literal => $($path:ident)::+ $(<$plt:lifetime>)? ),+ $(,)?
60 $( ; @no_dispatch $( $nd_variant:ident => $($nd_path:ident)::+ $(<$nd_plt:lifetime>)? ),+ $(,)? )?
61 ) => {
62 #[derive(Debug)]
69 #[cfg_attr(feature = "serde", derive(serde::Serialize))]
70 #[cfg_attr(feature = "serde", serde(rename_all = "camelCase"))]
71 #[cfg_attr(feature = "yoke", derive(yoke::Yokeable))]
76 #[non_exhaustive]
77 pub enum AnyDescriptor<$lt> {
78 $(
79 #[allow(missing_docs)]
80 $variant($($path)::+ $(<$plt>)?),
81 )+
82 $($(
83 #[allow(missing_docs)]
84 $nd_variant($($nd_path)::+ $(<$nd_plt>)?),
85 )+)?
86 Other {
90 tag: u8,
92 #[cfg_attr(
96 feature = "serde",
97 serde(serialize_with = "crate::descriptors::registry::serialize_erased")
98 )]
99 value: Box<dyn crate::descriptors::registry::DescriptorObject>,
100 },
101 Unknown {
104 tag: u8,
106 body: &$lt [u8],
108 },
109 }
110
111 $(
112 impl<$lt> From<$($path)::+ $(<$plt>)?> for AnyDescriptor<$lt> {
113 fn from(d: $($path)::+ $(<$plt>)?) -> Self {
114 Self::$variant(d)
115 }
116 }
117 )+
118 $($(
119 impl<$lt> From<$($nd_path)::+ $(<$nd_plt>)?> for AnyDescriptor<$lt> {
120 fn from(d: $($nd_path)::+ $(<$nd_plt>)?) -> Self {
121 Self::$nd_variant(d)
122 }
123 }
124 )+)?
125
126 impl<$lt> AnyDescriptor<$lt> {
127 pub const DISPATCHED_TAGS: &'static [u8] = &[$($tag),+];
130
131 #[must_use]
137 pub fn name(&self) -> &'static str {
138 match self {
139 $(
140 Self::$variant(_) =>
141 <$($path)::+ as crate::traits::DescriptorDef>::NAME,
142 )+
143 $($(
144 Self::$nd_variant(_) =>
145 <$($nd_path)::+ as crate::traits::DescriptorDef>::NAME,
146 )+)?
147 Self::Other { .. } => "CUSTOM",
148 Self::Unknown { .. } => "UNKNOWN",
149 }
150 }
151
152 pub(crate) fn dispatch(tag: u8, full: &$lt [u8]) -> Option<crate::Result<Self>> {
158 use dvb_common::Parse;
159 match tag {
160 $(
161 $tag => Some(<$($path)::+>::parse(full).map(Self::$variant)),
162 )+
163 _ => None,
164 }
165 }
166 }
167
168 #[cfg(test)]
169 mod macro_drift {
170 #[test]
171 fn tag_literals_match_descriptor_def() {
172 use crate::traits::DescriptorDef;
173 $(
174 assert_eq!(
175 $tag,
176 <$($path)::+ as DescriptorDef>::TAG,
177 concat!("tag literal drift for ", stringify!($variant)),
178 );
179 assert!(
180 !<$($path)::+ as DescriptorDef>::NAME.is_empty(),
181 concat!("empty NAME for ", stringify!($variant)),
182 );
183 )+
184 $($(
185 assert!(
186 !<$($nd_path)::+ as DescriptorDef>::NAME.is_empty(),
187 concat!("empty NAME for ", stringify!($nd_variant)),
188 );
189 )+)?
190 }
191 }
192 };
193}
194
195declare_descriptors! {'a;
196 Registration = 0x05 => crate::descriptors::registration::RegistrationDescriptor<'a>,
198 DataStreamAlignment = 0x06 => crate::descriptors::data_stream_alignment::DataStreamAlignmentDescriptor,
199 Ca = 0x09 => crate::descriptors::ca::CaDescriptor<'a>,
200 Iso639Language = 0x0A => crate::descriptors::iso_639_language::Iso639LanguageDescriptor,
201 PrivateDataIndicator = 0x0F => crate::descriptors::private_data_indicator::PrivateDataIndicatorDescriptor,
202 NetworkName = 0x40 => crate::descriptors::network_name::NetworkNameDescriptor<'a>,
204 ServiceList = 0x41 => crate::descriptors::service_list::ServiceListDescriptor,
205 Stuffing = 0x42 => crate::descriptors::stuffing::StuffingDescriptor<'a>,
206 SatelliteDeliverySystem = 0x43 => crate::descriptors::satellite_delivery_system::SatelliteDeliverySystemDescriptor,
207 CableDeliverySystem = 0x44 => crate::descriptors::cable_delivery_system::CableDeliverySystemDescriptor,
208 VbiData = 0x45 => crate::descriptors::vbi_data::VbiDataDescriptor<'a>,
209 VbiTeletext = 0x46 => crate::descriptors::vbi_teletext::VbiTeletextDescriptor,
210 BouquetName = 0x47 => crate::descriptors::bouquet_name::BouquetNameDescriptor<'a>,
211 Service = 0x48 => crate::descriptors::service::ServiceDescriptor<'a>,
212 CountryAvailability = 0x49 => crate::descriptors::country_availability::CountryAvailabilityDescriptor,
213 Linkage = 0x4A => crate::descriptors::linkage::LinkageDescriptor<'a>,
214 NvodReference = 0x4B => crate::descriptors::nvod_reference::NvodReferenceDescriptor,
215 TimeShiftedService = 0x4C => crate::descriptors::time_shifted_service::TimeShiftedServiceDescriptor,
216 ShortEvent = 0x4D => crate::descriptors::short_event::ShortEventDescriptor<'a>,
217 ExtendedEvent = 0x4E => crate::descriptors::extended_event::ExtendedEventDescriptor<'a>,
218 TimeShiftedEvent = 0x4F => crate::descriptors::time_shifted_event::TimeShiftedEventDescriptor,
219 Component = 0x50 => crate::descriptors::component::ComponentDescriptor<'a>,
220 Mosaic = 0x51 => crate::descriptors::mosaic::MosaicDescriptor,
221 StreamIdentifier = 0x52 => crate::descriptors::stream_identifier::StreamIdentifierDescriptor,
222 CaIdentifier = 0x53 => crate::descriptors::ca_identifier::CaIdentifierDescriptor,
223 Content = 0x54 => crate::descriptors::content::ContentDescriptor,
224 ParentalRating = 0x55 => crate::descriptors::parental_rating::ParentalRatingDescriptor,
225 Teletext = 0x56 => crate::descriptors::teletext::TeletextDescriptor,
226 Telephone = 0x57 => crate::descriptors::telephone::TelephoneDescriptor<'a>,
227 LocalTimeOffset = 0x58 => crate::descriptors::local_time_offset::LocalTimeOffsetDescriptor,
228 Subtitling = 0x59 => crate::descriptors::subtitling::SubtitlingDescriptor,
229 TerrestrialDeliverySystem = 0x5A => crate::descriptors::terrestrial_delivery_system::TerrestrialDeliverySystemDescriptor,
230 MultilingualNetworkName = 0x5B => crate::descriptors::multilingual_network_name::MultilingualNetworkNameDescriptor<'a>,
231 MultilingualBouquetName = 0x5C => crate::descriptors::multilingual_bouquet_name::MultilingualBouquetNameDescriptor<'a>,
232 MultilingualServiceName = 0x5D => crate::descriptors::multilingual_service_name::MultilingualServiceNameDescriptor<'a>,
233 MultilingualComponent = 0x5E => crate::descriptors::multilingual_component::MultilingualComponentDescriptor<'a>,
234 PrivateDataSpecifier = 0x5F => crate::descriptors::private_data_specifier::PrivateDataSpecifierDescriptor,
235 ServiceMove = 0x60 => crate::descriptors::service_move::ServiceMoveDescriptor,
236 ShortSmoothingBuffer = 0x61 => crate::descriptors::short_smoothing_buffer::ShortSmoothingBufferDescriptor<'a>,
237 FrequencyList = 0x62 => crate::descriptors::frequency_list::FrequencyListDescriptor,
238 PartialTransportStream = 0x63 => crate::descriptors::partial_transport_stream::PartialTransportStreamDescriptor,
239 DataBroadcast = 0x64 => crate::descriptors::data_broadcast::DataBroadcastDescriptor<'a>,
240 Scrambling = 0x65 => crate::descriptors::scrambling::ScramblingDescriptor,
241 DataBroadcastId = 0x66 => crate::descriptors::data_broadcast_id::DataBroadcastIdDescriptor<'a>,
242 TransportStream = 0x67 => crate::descriptors::transport_stream::TransportStreamDescriptor<'a>,
243 Dsng = 0x68 => crate::descriptors::dsng::DsngDescriptor<'a>,
244 Pdc = 0x69 => crate::descriptors::pdc::PdcDescriptor,
245 Ac3 = 0x6A => crate::descriptors::ac3::Ac3Descriptor<'a>,
246 AncillaryData = 0x6B => crate::descriptors::ancillary_data::AncillaryDataDescriptor,
247 CellList = 0x6C => crate::descriptors::cell_list::CellListDescriptor,
248 CellFrequencyLink = 0x6D => crate::descriptors::cell_frequency_link::CellFrequencyLinkDescriptor,
249 AnnouncementSupport = 0x6E => crate::descriptors::announcement_support::AnnouncementSupportDescriptor,
250 ApplicationSignalling = 0x6F => crate::descriptors::application_signalling::ApplicationSignallingDescriptor,
251 AdaptationFieldData = 0x70 => crate::descriptors::adaptation_field_data::AdaptationFieldDataDescriptor,
252 ServiceIdentifier = 0x71 => crate::descriptors::service_identifier::ServiceIdentifierDescriptor<'a>,
253 ServiceAvailability = 0x72 => crate::descriptors::service_availability::ServiceAvailabilityDescriptor,
254 DefaultAuthority = 0x73 => crate::descriptors::default_authority::DefaultAuthorityDescriptor<'a>,
255 RelatedContent = 0x74 => crate::descriptors::related_content::RelatedContentDescriptor,
256 TvaId = 0x75 => crate::descriptors::tva_id::TvaIdDescriptor,
257 ContentIdentifier = 0x76 => crate::descriptors::content_identifier::ContentIdentifierDescriptor<'a>,
258 TimeSliceFecIdentifier = 0x77 => crate::descriptors::time_slice_fec_identifier::TimeSliceFecIdentifierDescriptor<'a>,
259 EcmRepetitionRate = 0x78 => crate::descriptors::ecm_repetition_rate::EcmRepetitionRateDescriptor<'a>,
260 S2SatelliteDeliverySystem = 0x79 => crate::descriptors::s2_satellite_delivery_system::S2SatelliteDeliverySystemDescriptor,
261 EnhancedAc3 = 0x7A => crate::descriptors::enhanced_ac3::EnhancedAc3Descriptor<'a>,
262 Dts = 0x7B => crate::descriptors::dts::DtsDescriptor<'a>,
263 Aac = 0x7C => crate::descriptors::aac::AacDescriptor<'a>,
264 XaitLocation = 0x7D => crate::descriptors::xait_location::XaitLocationDescriptor,
265 FtaContentManagement = 0x7E => crate::descriptors::fta_content_management::FtaContentManagementDescriptor,
266 Extension = 0x7F => crate::descriptors::extension::ExtensionDescriptor<'a>;
267 @no_dispatch
271 LogicalChannel => crate::descriptors::logical_channel::LogicalChannelDescriptor,
272}
273
274#[must_use]
281pub fn parse_loop(bytes: &[u8]) -> DescriptorIter<'_> {
282 DescriptorIter {
283 bytes,
284 pos: 0,
285 fused: false,
286 }
287}
288
289#[derive(Debug, Clone)]
291pub struct DescriptorIter<'a> {
292 bytes: &'a [u8],
293 pos: usize,
294 fused: bool,
295}
296
297impl<'a> Iterator for DescriptorIter<'a> {
298 type Item = crate::Result<AnyDescriptor<'a>>;
299
300 fn next(&mut self) -> Option<Self::Item> {
301 if self.fused || self.pos >= self.bytes.len() {
302 return None;
303 }
304 let rem = &self.bytes[self.pos..];
305 if rem.len() < 2 {
306 self.fused = true;
307 return Some(Err(crate::Error::BufferTooShort {
308 need: 2,
309 have: rem.len(),
310 what: "descriptor header in loop",
311 }));
312 }
313 let tag = rem[0];
314 let len = rem[1] as usize;
315 let total = 2 + len;
316 if rem.len() < total {
317 self.fused = true;
318 return Some(Err(crate::Error::BufferTooShort {
319 need: total,
320 have: rem.len(),
321 what: "descriptor body in loop",
322 }));
323 }
324 let full = &rem[..total];
325 self.pos += total;
326 Some(match AnyDescriptor::dispatch(tag, full) {
327 Some(res) => res,
330 None => Ok(AnyDescriptor::Unknown {
331 tag,
332 body: &full[2..],
333 }),
334 })
335 }
336}
337
338impl std::iter::FusedIterator for DescriptorIter<'_> {}
339
340#[derive(Clone, Copy, PartialEq, Eq, Hash, Default)]
364#[cfg_attr(feature = "yoke", derive(yoke::Yokeable))]
365pub struct DescriptorLoop<'a>(&'a [u8]);
366
367impl<'a> DescriptorLoop<'a> {
368 #[must_use]
371 pub const fn new(raw: &'a [u8]) -> Self {
372 Self(raw)
373 }
374
375 #[must_use]
378 pub const fn raw(&self) -> &'a [u8] {
379 self.0
380 }
381
382 #[must_use]
386 pub fn iter(&self) -> DescriptorIter<'a> {
387 parse_loop(self.0)
388 }
389}
390
391impl<'a> std::ops::Deref for DescriptorLoop<'a> {
392 type Target = [u8];
396 fn deref(&self) -> &[u8] {
397 self.0
398 }
399}
400
401impl<'a> From<&'a [u8]> for DescriptorLoop<'a> {
402 fn from(raw: &'a [u8]) -> Self {
403 Self(raw)
404 }
405}
406
407impl std::fmt::Debug for DescriptorLoop<'_> {
408 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
410 write!(f, "DescriptorLoop(<{} bytes>)", self.0.len())
411 }
412}
413
414impl<'a> IntoIterator for &DescriptorLoop<'a> {
415 type Item = crate::Result<AnyDescriptor<'a>>;
416 type IntoIter = DescriptorIter<'a>;
417 fn into_iter(self) -> Self::IntoIter {
418 self.iter()
419 }
420}
421
422#[cfg(feature = "serde")]
423impl serde::Serialize for DescriptorLoop<'_> {
424 fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
429 struct Entry<'a>(crate::Result<AnyDescriptor<'a>>);
430 impl serde::Serialize for Entry<'_> {
431 fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
432 match &self.0 {
433 Ok(d) => d.serialize(s),
434 Err(e) => {
435 use serde::ser::SerializeMap;
436 let mut m = s.serialize_map(Some(1))?;
437 m.serialize_entry("parseError", &e.to_string())?;
438 m.end()
439 }
440 }
441 }
442 }
443 s.collect_seq(self.iter().map(Entry))
444 }
445}
446#[cfg(test)]
452mod tests {
453 use super::*;
454
455 #[test]
456 fn unknown_tag_yields_unknown_with_body_sans_header() {
457 let bytes = [0xA7, 0x02, 0xDE, 0xAD];
459 let items: Vec<_> = parse_loop(&bytes).collect();
460 assert_eq!(items.len(), 1);
461 match items[0].as_ref().unwrap() {
462 AnyDescriptor::Unknown { tag, body } => {
463 assert_eq!(*tag, 0xA7);
464 assert_eq!(*body, &[0xDE, 0xAD]);
465 }
466 other => panic!("expected Unknown, got {other:?}"),
467 }
468 }
469
470 #[test]
471 fn empty_loop_yields_nothing() {
472 assert_eq!(parse_loop(&[]).count(), 0);
473 }
474
475 #[test]
476 fn logical_channel_0x83_is_not_dispatched() {
477 let bytes = [0x83, 0x04, 0x00, 0x01, 0xFC, 0x01];
479 let items: Vec<_> = parse_loop(&bytes).collect();
480 assert_eq!(items.len(), 1);
481 assert!(matches!(
482 items[0].as_ref().unwrap(),
483 AnyDescriptor::Unknown { tag: 0x83, .. }
484 ));
485 }
486
487 #[test]
488 fn descriptor_loop_iter_matches_parse_loop() {
489 let raw = [
490 0x4D, 0x07, b'e', b'n', b'g', 0x02, b'H', b'i', 0x00, 0xA7, 0x02, 0xCA, 0xFE, ];
493 let via_loop: Vec<_> = DescriptorLoop::new(&raw)
494 .iter()
495 .map(|r| format!("{r:?}"))
496 .collect();
497 let via_fn: Vec<_> = parse_loop(&raw).map(|r| format!("{r:?}")).collect();
498 assert_eq!(via_loop, via_fn);
499 assert_eq!(DescriptorLoop::new(&raw).raw(), &raw[..]);
501 assert_eq!(DescriptorLoop::new(&raw).len(), raw.len());
502 let count = (&DescriptorLoop::new(&raw)).into_iter().count();
504 assert_eq!(count, 2);
505 }
506
507 #[test]
508 fn descriptor_loop_debug_is_cheap() {
509 let raw = [0x4D, 0x02, 0x01, 0x02];
510 assert_eq!(
511 format!("{:?}", DescriptorLoop::new(&raw)),
512 "DescriptorLoop(<4 bytes>)"
513 );
514 }
515
516 #[cfg(feature = "serde")]
517 #[test]
518 fn descriptor_loop_serializes_typed_unknown_and_parse_error() {
519 let raw = [
523 0x4D, 0x07, b'e', b'n', b'g', 0x02, b'H', b'i', 0x00, 0xA7, 0x02, 0xCA, 0xFE, 0x55, 0x05, 0x00, ];
527 let v = serde_json::to_value(DescriptorLoop::new(&raw)).unwrap();
528 let arr = v.as_array().expect("sequence");
529 assert_eq!(arr.len(), 3);
530 assert!(arr[0].get("shortEvent").is_some(), "got {}", arr[0]);
532 assert_eq!(arr[0]["shortEvent"]["event_name"], "Hi");
533 let unknown = arr[1].get("unknown").expect("unknown variant");
535 assert_eq!(unknown["tag"], 0xA7);
536 assert_eq!(unknown["body"], serde_json::json!([0xCA, 0xFE]));
537 assert!(
539 arr[2].get("parseError").is_some(),
540 "expected parseError, got {}",
541 arr[2]
542 );
543 }
544}