1use alloc::boxed::Box;
50#[cfg(feature = "serde")]
51use alloc::string::ToString;
52
53macro_rules! declare_descriptors {
61 (
62 $lt:lifetime;
63 $( $variant:ident = $tag:literal => $($path:ident)::+ $(<$plt:lifetime>)? ),+ $(,)?
64 $( ; @no_dispatch $( $nd_variant:ident => $($nd_path:ident)::+ $(<$nd_plt:lifetime>)? ),+ $(,)? )?
65 ) => {
66 #[derive(Debug)]
73 #[cfg_attr(feature = "serde", derive(serde::Serialize))]
74 #[cfg_attr(feature = "serde", serde(rename_all = "camelCase"))]
75 #[cfg_attr(feature = "yoke", derive(yoke::Yokeable))]
80 #[non_exhaustive]
81 pub enum AnyDescriptor<$lt> {
82 $(
83 #[allow(missing_docs)]
84 $variant($($path)::+ $(<$plt>)?),
85 )+
86 $($(
87 #[allow(missing_docs)]
88 $nd_variant($($nd_path)::+ $(<$nd_plt>)?),
89 )+)?
90 Other {
94 tag: u8,
96 #[cfg_attr(
100 feature = "serde",
101 serde(serialize_with = "crate::descriptors::registry::serialize_erased")
102 )]
103 value: Box<dyn crate::descriptors::registry::DescriptorObject>,
104 },
105 Unknown {
108 tag: u8,
110 body: &$lt [u8],
112 },
113 }
114
115 $(
116 impl<$lt> From<$($path)::+ $(<$plt>)?> for AnyDescriptor<$lt> {
117 fn from(d: $($path)::+ $(<$plt>)?) -> Self {
118 Self::$variant(d)
119 }
120 }
121 )+
122 $($(
123 impl<$lt> From<$($nd_path)::+ $(<$nd_plt>)?> for AnyDescriptor<$lt> {
124 fn from(d: $($nd_path)::+ $(<$nd_plt>)?) -> Self {
125 Self::$nd_variant(d)
126 }
127 }
128 )+)?
129
130 impl<$lt> AnyDescriptor<$lt> {
131 pub const DISPATCHED_TAGS: &'static [u8] = &[$($tag),+];
134
135 #[must_use]
141 pub fn name(&self) -> &'static str {
142 match self {
143 $(
144 Self::$variant(_) =>
145 <$($path)::+ as crate::traits::DescriptorDef>::NAME,
146 )+
147 $($(
148 Self::$nd_variant(_) =>
149 <$($nd_path)::+ as crate::traits::DescriptorDef>::NAME,
150 )+)?
151 Self::Other { .. } => "CUSTOM",
152 Self::Unknown { .. } => "UNKNOWN",
153 }
154 }
155
156 #[doc(hidden)]
161 pub fn reserialize(&self) -> Option<core::result::Result<alloc::vec::Vec<u8>, alloc::string::String>> {
162 use broadcast_common::Serialize;
163 fn go<S: Serialize>(d: &S) -> core::result::Result<alloc::vec::Vec<u8>, alloc::string::String>
164 where
165 S::Error: core::fmt::Debug,
166 {
167 let mut out = alloc::vec![0u8; d.serialized_len()];
168 d.serialize_into(&mut out).map_err(|e| alloc::format!("{e:?}"))?;
169 Ok(out)
170 }
171 match self {
172 $( Self::$variant(d) => Some(go(d)), )+
173 $($( Self::$nd_variant(d) => Some(go(d)), )+)?
174 Self::Other { .. } => None,
175 Self::Unknown { tag, body } => {
176 Some(
177 broadcast_common::len::fit_u8(body.len(), "descriptor_length")
178 .map(|n| {
179 let mut v = alloc::vec![*tag, n];
180 v.extend_from_slice(body);
181 v
182 })
183 .map_err(|e| alloc::format!("{e:?}")),
184 )
185 }
186 }
187 }
188
189 pub(crate) fn dispatch(tag: u8, full: &$lt [u8]) -> Option<crate::Result<Self>> {
195 use broadcast_common::Parse;
196 match tag {
197 $(
198 $tag => Some(<$($path)::+>::parse(full).map(Self::$variant)),
199 )+
200 _ => None,
201 }
202 }
203 }
204
205 #[cfg(test)]
206 mod macro_drift {
207 #[test]
208 fn tag_literals_match_descriptor_def() {
209 use crate::traits::DescriptorDef;
210 $(
211 assert_eq!(
212 $tag,
213 <$($path)::+ as DescriptorDef>::TAG,
214 concat!("tag literal drift for ", stringify!($variant)),
215 );
216 assert!(
217 !<$($path)::+ as DescriptorDef>::NAME.is_empty(),
218 concat!("empty NAME for ", stringify!($variant)),
219 );
220 )+
221 $($(
222 assert!(
223 !<$($nd_path)::+ as DescriptorDef>::NAME.is_empty(),
224 concat!("empty NAME for ", stringify!($nd_variant)),
225 );
226 )+)?
227 }
228 }
229 };
230}
231
232declare_descriptors! {'a;
233 VideoStream = 0x02 => crate::descriptors::video_stream::VideoStreamDescriptor,
235 AudioStream = 0x03 => crate::descriptors::audio_stream::AudioStreamDescriptor,
236 Hierarchy = 0x04 => crate::descriptors::hierarchy::HierarchyDescriptor,
237 Registration = 0x05 => crate::descriptors::registration::RegistrationDescriptor<'a>,
238 DataStreamAlignment = 0x06 => crate::descriptors::data_stream_alignment::DataStreamAlignmentDescriptor,
239 TargetBackgroundGrid = 0x07 => crate::descriptors::target_background_grid::TargetBackgroundGridDescriptor,
240 VideoWindow = 0x08 => crate::descriptors::video_window::VideoWindowDescriptor,
241 Ca = 0x09 => crate::descriptors::ca::CaDescriptor<'a>,
242 Iso639Language = 0x0A => crate::descriptors::iso_639_language::Iso639LanguageDescriptor,
243 SystemClock = 0x0B => crate::descriptors::system_clock::SystemClockDescriptor,
244 MultiplexBufferUtilization = 0x0C => crate::descriptors::multiplex_buffer_utilization::MultiplexBufferUtilizationDescriptor,
245 Copyright = 0x0D => crate::descriptors::copyright::CopyrightDescriptor<'a>,
246 MaximumBitrate = 0x0E => crate::descriptors::maximum_bitrate::MaximumBitrateDescriptor,
247 PrivateDataIndicator = 0x0F => crate::descriptors::private_data_indicator::PrivateDataIndicatorDescriptor,
248 SmoothingBuffer = 0x10 => crate::descriptors::smoothing_buffer::SmoothingBufferDescriptor,
249 Std = 0x11 => crate::descriptors::std::StdDescriptor,
250 Ibp = 0x12 => crate::descriptors::ibp::IbpDescriptor,
251 CarouselIdentifier = 0x13 => crate::descriptors::carousel_identifier::CarouselIdentifierDescriptor<'a>,
252 AssociationTag = 0x14 => crate::descriptors::association_tag::AssociationTagDescriptor<'a>,
253 DeferredAssociationTags = 0x15 => crate::descriptors::deferred_association_tags::DeferredAssociationTagsDescriptor<'a>,
254 Mpeg4Video = 0x1B => crate::descriptors::mpeg4_video::Mpeg4VideoDescriptor,
255 Mpeg4Audio = 0x1C => crate::descriptors::mpeg4_audio::Mpeg4AudioDescriptor,
256 Iod = 0x1D => crate::descriptors::iod::IodDescriptor<'a>,
257 Sl = 0x1E => crate::descriptors::sl::SlDescriptor,
258 Fmc = 0x1F => crate::descriptors::fmc::FmcDescriptor,
259 ExternalEsId = 0x20 => crate::descriptors::external_es_id::ExternalEsIdDescriptor,
260 Muxcode = 0x21 => crate::descriptors::muxcode::MuxcodeDescriptor<'a>,
261 FmxBufferSize = 0x22 => crate::descriptors::fmx_buffer_size::FmxBufferSizeDescriptor<'a>,
262 MultiplexBuffer = 0x23 => crate::descriptors::multiplex_buffer::MultiplexBufferDescriptor,
263 ContentLabeling = 0x24 => crate::descriptors::content_labeling::ContentLabelingDescriptor<'a>,
264 MetadataPointer = 0x25 => crate::descriptors::metadata_pointer::MetadataPointerDescriptor<'a>,
265 Metadata = 0x26 => crate::descriptors::metadata::MetadataDescriptor<'a>,
266 MetadataStd = 0x27 => crate::descriptors::metadata_std::MetadataStdDescriptor,
267 AvcVideo = 0x28 => crate::descriptors::avc_video::AvcVideoDescriptor,
268 AvcTimingAndHrd = 0x2A => crate::descriptors::avc_timing_and_hrd::AvcTimingAndHrdDescriptor,
269 Mpeg2AacAudio = 0x2B => crate::descriptors::mpeg2_aac_audio::Mpeg2AacAudioDescriptor,
270 FlexMuxTiming = 0x2C => crate::descriptors::flex_mux_timing::FlexMuxTimingDescriptor,
271 Mpeg4Text = 0x2D => crate::descriptors::mpeg4_text::Mpeg4TextDescriptor<'a>,
272 Mpeg4AudioExtension = 0x2E => crate::descriptors::mpeg4_audio_extension::Mpeg4AudioExtensionDescriptor,
273 AuxiliaryVideoStream = 0x2F => crate::descriptors::auxiliary_video_stream::AuxiliaryVideoStreamDescriptor<'a>,
274 SvcExtension = 0x30 => crate::descriptors::svc_extension::SvcExtensionDescriptor,
275 MvcExtension = 0x31 => crate::descriptors::mvc_extension::MvcExtensionDescriptor,
276 J2kVideo = 0x32 => crate::descriptors::j2k_video::J2kVideoDescriptor<'a>,
277 MvcOperationPoint = 0x33 => crate::descriptors::mvc_operation_point::MvcOperationPointDescriptor,
278 Mpeg2StereoscopicVideoFormat = 0x34 => crate::descriptors::stereoscopic::Mpeg2StereoscopicVideoFormatDescriptor,
279 StereoscopicProgramInfo = 0x35 => crate::descriptors::stereoscopic::StereoscopicProgramInfoDescriptor,
280 StereoscopicVideoInfo = 0x36 => crate::descriptors::stereoscopic::StereoscopicVideoInfoDescriptor,
281 TransportProfile = 0x37 => crate::descriptors::transport_profile::TransportProfileDescriptor,
282 HevcVideo = 0x38 => crate::descriptors::hevc_video::HevcVideoDescriptor,
283 VvcVideo = 0x39 => crate::descriptors::vvc_video::VvcVideoDescriptor,
284 EvcVideo = 0x3A => crate::descriptors::evc_video::EvcVideoDescriptor,
285 Mpeg2Extension = 0x3F => crate::descriptors::mpeg2_extension::Mpeg2ExtensionDescriptor,
286 NetworkName = 0x40 => crate::descriptors::network_name::NetworkNameDescriptor<'a>,
288 ServiceList = 0x41 => crate::descriptors::service_list::ServiceListDescriptor,
289 Stuffing = 0x42 => crate::descriptors::stuffing::StuffingDescriptor<'a>,
290 SatelliteDeliverySystem = 0x43 => crate::descriptors::satellite_delivery_system::SatelliteDeliverySystemDescriptor,
291 CableDeliverySystem = 0x44 => crate::descriptors::cable_delivery_system::CableDeliverySystemDescriptor,
292 VbiData = 0x45 => crate::descriptors::vbi_data::VbiDataDescriptor<'a>,
293 VbiTeletext = 0x46 => crate::descriptors::vbi_teletext::VbiTeletextDescriptor,
294 BouquetName = 0x47 => crate::descriptors::bouquet_name::BouquetNameDescriptor<'a>,
295 Service = 0x48 => crate::descriptors::service::ServiceDescriptor<'a>,
296 CountryAvailability = 0x49 => crate::descriptors::country_availability::CountryAvailabilityDescriptor,
297 Linkage = 0x4A => crate::descriptors::linkage::LinkageDescriptor<'a>,
298 NvodReference = 0x4B => crate::descriptors::nvod_reference::NvodReferenceDescriptor,
299 TimeShiftedService = 0x4C => crate::descriptors::time_shifted_service::TimeShiftedServiceDescriptor,
300 ShortEvent = 0x4D => crate::descriptors::short_event::ShortEventDescriptor<'a>,
301 ExtendedEvent = 0x4E => crate::descriptors::extended_event::ExtendedEventDescriptor<'a>,
302 TimeShiftedEvent = 0x4F => crate::descriptors::time_shifted_event::TimeShiftedEventDescriptor,
303 Component = 0x50 => crate::descriptors::component::ComponentDescriptor<'a>,
304 Mosaic = 0x51 => crate::descriptors::mosaic::MosaicDescriptor,
305 StreamIdentifier = 0x52 => crate::descriptors::stream_identifier::StreamIdentifierDescriptor,
306 CaIdentifier = 0x53 => crate::descriptors::ca_identifier::CaIdentifierDescriptor,
307 Content = 0x54 => crate::descriptors::content::ContentDescriptor,
308 ParentalRating = 0x55 => crate::descriptors::parental_rating::ParentalRatingDescriptor,
309 Teletext = 0x56 => crate::descriptors::teletext::TeletextDescriptor,
310 Telephone = 0x57 => crate::descriptors::telephone::TelephoneDescriptor<'a>,
311 LocalTimeOffset = 0x58 => crate::descriptors::local_time_offset::LocalTimeOffsetDescriptor,
312 Subtitling = 0x59 => crate::descriptors::subtitling::SubtitlingDescriptor,
313 TerrestrialDeliverySystem = 0x5A => crate::descriptors::terrestrial_delivery_system::TerrestrialDeliverySystemDescriptor,
314 MultilingualNetworkName = 0x5B => crate::descriptors::multilingual_network_name::MultilingualNetworkNameDescriptor<'a>,
315 MultilingualBouquetName = 0x5C => crate::descriptors::multilingual_bouquet_name::MultilingualBouquetNameDescriptor<'a>,
316 MultilingualServiceName = 0x5D => crate::descriptors::multilingual_service_name::MultilingualServiceNameDescriptor<'a>,
317 MultilingualComponent = 0x5E => crate::descriptors::multilingual_component::MultilingualComponentDescriptor<'a>,
318 PrivateDataSpecifier = 0x5F => crate::descriptors::private_data_specifier::PrivateDataSpecifierDescriptor,
319 ServiceMove = 0x60 => crate::descriptors::service_move::ServiceMoveDescriptor,
320 ShortSmoothingBuffer = 0x61 => crate::descriptors::short_smoothing_buffer::ShortSmoothingBufferDescriptor<'a>,
321 FrequencyList = 0x62 => crate::descriptors::frequency_list::FrequencyListDescriptor,
322 PartialTransportStream = 0x63 => crate::descriptors::partial_transport_stream::PartialTransportStreamDescriptor,
323 DataBroadcast = 0x64 => crate::descriptors::data_broadcast::DataBroadcastDescriptor<'a>,
324 Scrambling = 0x65 => crate::descriptors::scrambling::ScramblingDescriptor,
325 DataBroadcastId = 0x66 => crate::descriptors::data_broadcast_id::DataBroadcastIdDescriptor<'a>,
326 TransportStream = 0x67 => crate::descriptors::transport_stream::TransportStreamDescriptor<'a>,
327 Dsng = 0x68 => crate::descriptors::dsng::DsngDescriptor<'a>,
328 Pdc = 0x69 => crate::descriptors::pdc::PdcDescriptor,
329 Ac3 = 0x6A => crate::descriptors::ac3::Ac3Descriptor<'a>,
330 AncillaryData = 0x6B => crate::descriptors::ancillary_data::AncillaryDataDescriptor,
331 CellList = 0x6C => crate::descriptors::cell_list::CellListDescriptor,
332 CellFrequencyLink = 0x6D => crate::descriptors::cell_frequency_link::CellFrequencyLinkDescriptor,
333 AnnouncementSupport = 0x6E => crate::descriptors::announcement_support::AnnouncementSupportDescriptor,
334 ApplicationSignalling = 0x6F => crate::descriptors::application_signalling::ApplicationSignallingDescriptor,
335 AdaptationFieldData = 0x70 => crate::descriptors::adaptation_field_data::AdaptationFieldDataDescriptor,
336 ServiceIdentifier = 0x71 => crate::descriptors::service_identifier::ServiceIdentifierDescriptor<'a>,
337 ServiceAvailability = 0x72 => crate::descriptors::service_availability::ServiceAvailabilityDescriptor,
338 DefaultAuthority = 0x73 => crate::descriptors::default_authority::DefaultAuthorityDescriptor<'a>,
339 RelatedContent = 0x74 => crate::descriptors::related_content::RelatedContentDescriptor,
340 TvaId = 0x75 => crate::descriptors::tva_id::TvaIdDescriptor,
341 ContentIdentifier = 0x76 => crate::descriptors::content_identifier::ContentIdentifierDescriptor<'a>,
342 TimeSliceFecIdentifier = 0x77 => crate::descriptors::time_slice_fec_identifier::TimeSliceFecIdentifierDescriptor<'a>,
343 EcmRepetitionRate = 0x78 => crate::descriptors::ecm_repetition_rate::EcmRepetitionRateDescriptor<'a>,
344 S2SatelliteDeliverySystem = 0x79 => crate::descriptors::s2_satellite_delivery_system::S2SatelliteDeliverySystemDescriptor,
345 EnhancedAc3 = 0x7A => crate::descriptors::enhanced_ac3::EnhancedAc3Descriptor<'a>,
346 Dts = 0x7B => crate::descriptors::dts::DtsDescriptor<'a>,
347 Aac = 0x7C => crate::descriptors::aac::AacDescriptor<'a>,
348 XaitLocation = 0x7D => crate::descriptors::xait_location::XaitLocationDescriptor,
349 FtaContentManagement = 0x7E => crate::descriptors::fta_content_management::FtaContentManagementDescriptor,
350 Extension = 0x7F => crate::descriptors::extension::ExtensionDescriptor<'a>;
351 @no_dispatch
355 TuwaAvs3Video => crate::descriptors::tuwa_avs3_video::TuwaAvs3VideoDescriptor,
357 Avs2Video => crate::descriptors::avs2_video::Avs2VideoDescriptor,
358 LogicalChannel => crate::descriptors::logical_channel::LogicalChannelDescriptor,
359 NordigLogicalChannelV1 => crate::descriptors::nordig::NordigLogicalChannelV1,
360 ChinaCaptionService => crate::descriptors::china_caption_service::ChinaCaptionServiceDescriptor,
361 NordigLogicalChannelV2 => crate::descriptors::nordig::NordigLogicalChannelV2,
362 Avs3Video => crate::descriptors::avs3_video::Avs3VideoDescriptor,
363 Avs3Audio => crate::descriptors::avs3_audio::Avs3AudioDescriptor,
364 Avs2Audio => crate::descriptors::avs2_audio::Avs2AudioDescriptor,
365}
366
367#[must_use]
374pub fn parse_loop(bytes: &[u8]) -> DescriptorIter<'_> {
375 DescriptorIter {
376 bytes,
377 pos: 0,
378 fused: false,
379 }
380}
381
382pub(crate) fn next_loop_entry<'a>(
390 bytes: &'a [u8],
391 pos: &mut usize,
392 fused: &mut bool,
393) -> Option<crate::Result<(u8, &'a [u8])>> {
394 if *fused || *pos >= bytes.len() {
395 return None;
396 }
397 let rem = &bytes[*pos..];
398 if rem.len() < 2 {
399 *fused = true;
400 return Some(Err(crate::Error::BufferTooShort {
401 need: 2,
402 have: rem.len(),
403 what: "descriptor header in loop",
404 }));
405 }
406 let tag = rem[0];
407 let len = rem[1] as usize;
408 let total = 2 + len;
409 if rem.len() < total {
410 *fused = true;
411 return Some(Err(crate::Error::BufferTooShort {
412 need: total,
413 have: rem.len(),
414 what: "descriptor body in loop",
415 }));
416 }
417 let full = &rem[..total];
418 *pos += total;
419 Some(Ok((tag, full)))
420}
421
422#[derive(Debug, Clone)]
424pub struct DescriptorIter<'a> {
425 bytes: &'a [u8],
426 pos: usize,
427 fused: bool,
428}
429
430impl<'a> Iterator for DescriptorIter<'a> {
431 type Item = crate::Result<AnyDescriptor<'a>>;
432
433 fn next(&mut self) -> Option<Self::Item> {
434 let (tag, full) = match next_loop_entry(self.bytes, &mut self.pos, &mut self.fused)? {
435 Ok(v) => v,
436 Err(e) => return Some(Err(e)),
437 };
438 Some(match AnyDescriptor::dispatch(tag, full) {
439 Some(res) => res,
440 None => Ok(AnyDescriptor::Unknown {
441 tag,
442 body: &full[2..],
443 }),
444 })
445 }
446}
447
448impl core::iter::FusedIterator for DescriptorIter<'_> {}
449
450#[derive(Clone, Copy, PartialEq, Eq, Hash, Default)]
474#[cfg_attr(feature = "yoke", derive(yoke::Yokeable))]
475pub struct DescriptorLoop<'a>(&'a [u8]);
476
477const DESC_HEADER_LEN: usize = 2;
479
480impl<'a> DescriptorLoop<'a> {
481 #[must_use]
484 pub const fn new(raw: &'a [u8]) -> Self {
485 Self(raw)
486 }
487
488 #[must_use]
491 pub const fn raw(&self) -> &'a [u8] {
492 self.0
493 }
494
495 #[must_use]
499 pub fn iter(&self) -> DescriptorIter<'a> {
500 parse_loop(self.0)
501 }
502
503 pub fn raw_tags(&self) -> impl Iterator<Item = (u8, &'a [u8])> {
513 let b = self.0;
514 let mut pos = 0usize;
515 core::iter::from_fn(move || {
516 if pos + DESC_HEADER_LEN > b.len() {
517 return None;
518 }
519 let tag = b[pos];
520 let len = b[pos + 1] as usize;
521 let end = pos + DESC_HEADER_LEN + len;
522 if end > b.len() {
523 return None; }
525 let body = &b[pos + DESC_HEADER_LEN..end];
526 pos = end;
527 Some((tag, body))
528 })
529 }
530
531 #[must_use]
536 pub fn contains_tag(&self, tag: u8) -> bool {
537 let b = self.0;
538 let mut pos = 0usize;
539 while pos < b.len() {
540 if b[pos] == tag {
541 return true;
542 }
543 if pos + 1 >= b.len() {
546 break;
547 }
548 pos += DESC_HEADER_LEN + b[pos + 1] as usize;
549 }
550 false
551 }
552
553 #[must_use]
561 pub fn iter_with<'r>(
562 &self,
563 registry: &'r crate::descriptors::registry::DescriptorRegistry,
564 ) -> crate::descriptors::registry::RegistryIter<'r, 'a> {
565 registry.parse_loop(self.0)
566 }
567
568 #[must_use]
581 pub fn iter_with_extensions<'r>(
582 &self,
583 desc_reg: &'r crate::descriptors::registry::DescriptorRegistry,
584 ext_reg: &'r crate::descriptors::extension::registry::ExtensionRegistry,
585 ) -> crate::descriptors::registry::ExtRegistryIter<'r, 'a> {
586 crate::descriptors::registry::ExtRegistryIter::new(desc_reg, ext_reg, self.0, None)
587 }
588
589 #[must_use]
595 pub fn iter_with_extensions_in_scope<'r>(
596 &self,
597 desc_reg: &'r crate::descriptors::registry::DescriptorRegistry,
598 ext_reg: &'r crate::descriptors::extension::registry::ExtensionRegistry,
599 inherited: Option<u32>,
600 ) -> crate::descriptors::registry::ExtRegistryIter<'r, 'a> {
601 crate::descriptors::registry::ExtRegistryIter::new(desc_reg, ext_reg, self.0, inherited)
602 }
603}
604
605impl core::ops::Deref for DescriptorLoop<'_> {
606 type Target = [u8];
610 fn deref(&self) -> &[u8] {
611 self.0
612 }
613}
614
615impl<'a> From<&'a [u8]> for DescriptorLoop<'a> {
616 fn from(raw: &'a [u8]) -> Self {
617 Self(raw)
618 }
619}
620
621impl core::fmt::Debug for DescriptorLoop<'_> {
622 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
624 write!(f, "DescriptorLoop(<{} bytes>)", self.0.len())
625 }
626}
627
628impl<'a> IntoIterator for &DescriptorLoop<'a> {
629 type Item = crate::Result<AnyDescriptor<'a>>;
630 type IntoIter = DescriptorIter<'a>;
631 fn into_iter(self) -> Self::IntoIter {
632 self.iter()
633 }
634}
635
636#[cfg(feature = "serde")]
637impl serde::Serialize for DescriptorLoop<'_> {
638 fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
643 struct Entry<'a>(crate::Result<AnyDescriptor<'a>>);
644 impl serde::Serialize for Entry<'_> {
645 fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
646 match &self.0 {
647 Ok(d) => d.serialize(s),
648 Err(e) => {
649 use serde::ser::SerializeMap;
650 let mut m = s.serialize_map(Some(1))?;
651 m.serialize_entry("parseError", &e.to_string())?;
652 m.end()
653 }
654 }
655 }
656 }
657 s.collect_seq(self.iter().map(Entry))
658 }
659}
660#[cfg(test)]
666mod tests {
667 use super::*;
668
669 #[test]
670 fn contains_tag_detects_present_tag_regardless_of_body() {
671 assert!(DescriptorLoop::new(&[0x6A, 0x01, 0x80]).contains_tag(0x6A));
673 assert!(DescriptorLoop::new(&[0x6A, 0x00]).contains_tag(0x6A));
675 assert!(DescriptorLoop::new(&[0x6A, 0x01]).contains_tag(0x6A));
677 assert!(DescriptorLoop::new(&[0x09, 0x02, 0x00, 0x00, 0x7A, 0x00]).contains_tag(0x7A));
679 assert!(!DescriptorLoop::new(&[0x09, 0x02, 0x00, 0x00]).contains_tag(0x6A));
681 assert!(!DescriptorLoop::new(&[]).contains_tag(0x6A));
682 }
683
684 #[test]
685 fn raw_tags_walks_tlv_without_typed_parsing() {
686 let loop_ = DescriptorLoop::new(&[0x6A, 0x00, 0x40, 0x02, 0xAA, 0xBB]);
688 let pairs: Vec<_> = loop_.raw_tags().collect();
689 assert_eq!(pairs, vec![(0x6A, &[][..]), (0x40, &[0xAA, 0xBB][..])]);
690 let trunc = DescriptorLoop::new(&[0x40, 0x01, 0xAA, 0x6A, 0x05]);
693 let tags: Vec<u8> = trunc.raw_tags().map(|(t, _)| t).collect();
694 assert_eq!(tags, vec![0x40]); assert!(trunc.contains_tag(0x6A));
697 }
698
699 #[test]
700 fn unknown_tag_yields_unknown_with_body_sans_header() {
701 let bytes = [0xA7, 0x02, 0xDE, 0xAD];
703 let items: Vec<_> = parse_loop(&bytes).collect();
704 assert_eq!(items.len(), 1);
705 match items[0].as_ref().unwrap() {
706 AnyDescriptor::Unknown { tag, body } => {
707 assert_eq!(*tag, 0xA7);
708 assert_eq!(*body, &[0xDE, 0xAD]);
709 }
710 other => panic!("expected Unknown, got {other:?}"),
711 }
712 }
713
714 #[test]
715 fn empty_loop_yields_nothing() {
716 assert_eq!(parse_loop(&[]).count(), 0);
717 }
718
719 #[test]
720 fn logical_channel_0x83_is_not_dispatched() {
721 let bytes = [0x83, 0x04, 0x00, 0x01, 0xFC, 0x01];
723 let items: Vec<_> = parse_loop(&bytes).collect();
724 assert_eq!(items.len(), 1);
725 assert!(matches!(
726 items[0].as_ref().unwrap(),
727 AnyDescriptor::Unknown { tag: 0x83, .. }
728 ));
729 }
730
731 #[test]
732 fn descriptor_loop_iter_matches_parse_loop() {
733 let raw = [
734 0x4D, 0x07, b'e', b'n', b'g', 0x02, b'H', b'i', 0x00, 0xA7, 0x02, 0xCA, 0xFE, ];
737 let via_loop: Vec<_> = DescriptorLoop::new(&raw)
738 .iter()
739 .map(|r| format!("{r:?}"))
740 .collect();
741 let via_fn: Vec<_> = parse_loop(&raw).map(|r| format!("{r:?}")).collect();
742 assert_eq!(via_loop, via_fn);
743 assert_eq!(DescriptorLoop::new(&raw).raw(), &raw[..]);
745 assert_eq!(DescriptorLoop::new(&raw).len(), raw.len());
746 let count = (&DescriptorLoop::new(&raw)).into_iter().count();
748 assert_eq!(count, 2);
749 }
750
751 #[test]
752 fn descriptor_loop_debug_is_cheap() {
753 let raw = [0x4D, 0x02, 0x01, 0x02];
754 assert_eq!(
755 format!("{:?}", DescriptorLoop::new(&raw)),
756 "DescriptorLoop(<4 bytes>)"
757 );
758 }
759
760 #[test]
761 fn iter_with_custom_tag_yields_other() {
762 use crate::descriptors::registry::DescriptorRegistry;
763 use crate::traits::DescriptorDef;
764
765 #[derive(Debug, PartialEq, Eq)]
766 #[cfg_attr(feature = "serde", derive(serde::Serialize))]
767 struct MyTag0xA7 {
768 x: u8,
769 }
770
771 impl<'a> broadcast_common::Parse<'a> for MyTag0xA7 {
772 type Error = crate::error::Error;
773 fn parse(bytes: &'a [u8]) -> crate::Result<Self> {
774 if bytes.len() < 3 {
775 return Err(crate::error::Error::BufferTooShort {
776 need: 3,
777 have: bytes.len(),
778 what: "MyTag0xA7",
779 });
780 }
781 Ok(Self { x: bytes[2] })
782 }
783 }
784
785 impl DescriptorDef<'_> for MyTag0xA7 {
786 const TAG: u8 = 0xA7;
787 const NAME: &'static str = "MY_TAG_0xA7";
788 }
789
790 let mut reg = DescriptorRegistry::new();
791 reg.register::<MyTag0xA7>();
792
793 let raw = [
794 0x4D, 0x07, b'e', b'n', b'g', 0x02, b'H', b'i', 0x00, 0xA7, 0x02, 0xCA, 0xFE,
795 ];
796 let loop_ = DescriptorLoop::new(&raw);
797 let items: Vec<_> = loop_.iter_with(®).collect::<Result<_, _>>().unwrap();
798 assert_eq!(items.len(), 2);
799 assert!(matches!(items[0], AnyDescriptor::ShortEvent(_)));
800 match &items[1] {
801 AnyDescriptor::Other { tag, value } => {
802 assert_eq!(*tag, 0xA7);
803 assert_eq!(value.downcast_ref::<MyTag0xA7>().unwrap().x, 0xCA);
804 }
805 other => panic!("expected Other, got {other:?}"),
806 }
807 }
808
809 #[test]
810 fn iter_with_empty_registry_matches_iter_for_builtin() {
811 let raw = [
812 0x4D, 0x07, b'e', b'n', b'g', 0x02, b'H', b'i', 0x00, 0xA7, 0x02, 0xCA, 0xFE,
813 ];
814 let loop_ = DescriptorLoop::new(&raw);
815 let reg = crate::descriptors::registry::DescriptorRegistry::new();
816 let via_iter: Vec<_> = loop_.iter().collect();
817 let via_iter_with: Vec<_> = loop_.iter_with(®).collect();
818
819 assert_eq!(via_iter.len(), via_iter_with.len());
820 for (a, b) in via_iter.iter().zip(via_iter_with.iter()) {
821 match (a, b) {
822 (Ok(AnyDescriptor::ShortEvent(_)), Ok(AnyDescriptor::ShortEvent(_))) => {}
823 (
824 Ok(AnyDescriptor::Unknown { tag: t1, body: b1 }),
825 Ok(AnyDescriptor::Unknown { tag: t2, body: b2 }),
826 ) => {
827 assert_eq!(t1, t2);
828 assert_eq!(b1, b2);
829 }
830 (Err(_), Err(_)) => {}
831 (l, r) => panic!("mismatch: {l:?} vs {r:?}"),
832 }
833 }
834 }
835
836 #[cfg(feature = "serde")]
837 #[test]
838 fn descriptor_loop_serializes_typed_unknown_and_parse_error() {
839 let raw = [
843 0x4D, 0x07, b'e', b'n', b'g', 0x02, b'H', b'i', 0x00, 0xA7, 0x02, 0xCA, 0xFE, 0x55, 0x05, 0x00, ];
847 let v = serde_json::to_value(DescriptorLoop::new(&raw)).unwrap();
848 let arr = v.as_array().expect("sequence");
849 assert_eq!(arr.len(), 3);
850 assert!(arr[0].get("shortEvent").is_some(), "got {}", arr[0]);
852 assert_eq!(arr[0]["shortEvent"]["event_name"], "Hi");
853 let unknown = arr[1].get("unknown").expect("unknown variant");
855 assert_eq!(unknown["tag"], 0xA7);
856 assert_eq!(unknown["body"], serde_json::json!([0xCA, 0xFE]));
857 assert!(
859 arr[2].get("parseError").is_some(),
860 "expected parseError, got {}",
861 arr[2]
862 );
863 }
864}