dvb_si/descriptors/
std.rs1use super::descriptor_body;
6use crate::error::{Error, Result};
7use dvb_common::{Parse, Serialize};
8
9pub const TAG: u8 = 0x11;
11const HEADER_LEN: usize = 2;
12const BODY_LEN: u8 = 1;
13
14#[derive(Debug, Clone, PartialEq, Eq)]
16#[cfg_attr(feature = "serde", derive(serde::Serialize))]
17#[cfg_attr(feature = "yoke", derive(yoke::Yokeable))]
18pub struct StdDescriptor {
19 pub leak_valid_flag: bool,
21}
22
23impl<'a> Parse<'a> for StdDescriptor {
24 type Error = crate::error::Error;
25
26 fn parse(bytes: &'a [u8]) -> Result<Self> {
27 let body = descriptor_body(
28 bytes,
29 TAG,
30 "StdDescriptor",
31 "unexpected tag for STD_descriptor",
32 )?;
33 if body.len() != BODY_LEN as usize {
34 return Err(Error::InvalidDescriptor {
35 tag: TAG,
36 reason: "STD_descriptor length must equal 1",
37 });
38 }
39 let leak_valid_flag = (body[0] & 0x01) != 0;
40 Ok(Self { leak_valid_flag })
41 }
42}
43
44impl Serialize for StdDescriptor {
45 type Error = crate::error::Error;
46
47 fn serialized_len(&self) -> usize {
48 HEADER_LEN + (BODY_LEN as usize)
49 }
50
51 fn serialize_into(&self, buf: &mut [u8]) -> Result<usize> {
52 let len = self.serialized_len();
53 if buf.len() < len {
54 return Err(Error::OutputBufferTooSmall {
55 need: len,
56 have: buf.len(),
57 });
58 }
59 buf[0] = TAG;
60 buf[1] = BODY_LEN;
61 buf[HEADER_LEN] = self.leak_valid_flag as u8;
62 Ok(len)
63 }
64}
65impl<'a> crate::traits::DescriptorDef<'a> for StdDescriptor {
66 const TAG: u8 = TAG;
67 const NAME: &'static str = "STD";
68}
69
70#[cfg(test)]
71mod tests {
72 use super::*;
73
74 #[test]
75 fn parse_leak_valid() {
76 let bytes = [TAG, 1, 0b0000_0001];
77 let d = StdDescriptor::parse(&bytes).unwrap();
78 assert!(d.leak_valid_flag);
79 }
80
81 #[test]
82 fn parse_leak_not_valid() {
83 let bytes = [TAG, 1, 0b0000_0000];
84 let d = StdDescriptor::parse(&bytes).unwrap();
85 assert!(!d.leak_valid_flag);
86 }
87
88 #[test]
89 fn serialize_round_trip() {
90 let d = StdDescriptor {
91 leak_valid_flag: true,
92 };
93 let mut buf = vec![0u8; d.serialized_len()];
94 d.serialize_into(&mut buf).unwrap();
95 let reparsed = StdDescriptor::parse(&buf).unwrap();
96 assert_eq!(d, reparsed);
97 }
98
99 #[test]
100 fn parse_rejects_wrong_tag() {
101 let err = StdDescriptor::parse(&[0x12, 1, 0]).unwrap_err();
102 assert!(matches!(err, Error::InvalidDescriptor { tag: 0x12, .. }));
103 }
104
105 #[test]
106 fn parse_rejects_wrong_length() {
107 let err = StdDescriptor::parse(&[TAG, 0]).unwrap_err();
108 assert!(matches!(err, Error::InvalidDescriptor { tag: TAG, .. }));
109 }
110
111 #[test]
112 fn serialize_rejects_small_buffer() {
113 let d = StdDescriptor {
114 leak_valid_flag: false,
115 };
116 let mut tiny = vec![0u8; 2];
117 let err = d.serialize_into(&mut tiny).unwrap_err();
118 assert!(matches!(err, Error::OutputBufferTooSmall { .. }));
119 }
120}