1use crate::error::{Error, Result};
14use crate::traits::Table;
15use dvb_common::{Parse, Serialize};
16
17pub const TABLE_ID: u8 = 0x7F;
19pub const PID: u16 = 0x001F;
21
22const MIN_HEADER_LEN: usize = 3;
23const EXTENSION_HEADER_LEN: usize = 5;
24const DESC_LOOP_LEN_FIELD: usize = 2;
25const CRC_LEN: usize = 4;
26
27#[derive(Debug, Clone, PartialEq, Eq)]
29#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
30pub struct Sit {
31 pub table_id_extension: u16,
34 pub version_number: u8,
36 pub current_next_indicator: bool,
38 pub section_number: u8,
40 pub last_section_number: u8,
42 pub transmission_info_descriptors: Vec<u8>,
44 pub service_loop: Vec<u8>,
46}
47
48impl<'a> Parse<'a> for Sit {
49 type Error = crate::error::Error;
50
51 fn parse(bytes: &'a [u8]) -> Result<Self> {
52 let min_len = MIN_HEADER_LEN + EXTENSION_HEADER_LEN + DESC_LOOP_LEN_FIELD + CRC_LEN;
53 if bytes.len() < min_len {
54 return Err(Error::BufferTooShort {
55 need: min_len,
56 have: bytes.len(),
57 what: "Sit",
58 });
59 }
60 if bytes[0] != TABLE_ID {
61 return Err(Error::UnexpectedTableId {
62 table_id: bytes[0],
63 what: "Sit",
64 expected: &[TABLE_ID],
65 });
66 }
67 let section_length = ((bytes[1] & 0x0F) as usize) << 8 | bytes[2] as usize;
68 let total = MIN_HEADER_LEN + section_length;
69 if bytes.len() < total {
70 return Err(Error::SectionLengthOverflow {
71 declared: section_length,
72 available: bytes.len() - MIN_HEADER_LEN,
73 });
74 }
75
76 let table_id_extension = u16::from_be_bytes([bytes[3], bytes[4]]);
77 let version_number = (bytes[5] >> 1) & 0x1F;
78 let current_next_indicator = (bytes[5] & 0x01) != 0;
79 let section_number = bytes[6];
80 let last_section_number = bytes[7];
81
82 let dl_pos = MIN_HEADER_LEN + EXTENSION_HEADER_LEN;
83 let ti_len = (((bytes[dl_pos] & 0x0F) as usize) << 8) | bytes[dl_pos + 1] as usize;
84 let ti_start = dl_pos + DESC_LOOP_LEN_FIELD;
85 let ti_end = ti_start + ti_len;
86 let crc_start = total - CRC_LEN;
87 if ti_end > crc_start {
88 return Err(Error::SectionLengthOverflow {
89 declared: ti_len,
90 available: crc_start.saturating_sub(ti_start),
91 });
92 }
93
94 Ok(Sit {
95 table_id_extension,
96 version_number,
97 current_next_indicator,
98 section_number,
99 last_section_number,
100 transmission_info_descriptors: bytes[ti_start..ti_end].to_vec(),
101 service_loop: bytes[ti_end..crc_start].to_vec(),
104 })
105 }
106}
107
108impl Serialize for Sit {
109 type Error = crate::error::Error;
110
111 fn serialized_len(&self) -> usize {
112 MIN_HEADER_LEN
113 + EXTENSION_HEADER_LEN
114 + DESC_LOOP_LEN_FIELD
115 + self.transmission_info_descriptors.len()
116 + self.service_loop.len()
117 + CRC_LEN
118 }
119
120 fn serialize_into(&self, buf: &mut [u8]) -> Result<usize> {
121 let len = self.serialized_len();
122 if buf.len() < len {
123 return Err(Error::OutputBufferTooSmall {
124 need: len,
125 have: buf.len(),
126 });
127 }
128 let section_length = (len - MIN_HEADER_LEN) as u16;
129 buf[0] = TABLE_ID;
130 buf[1] = 0xB0 | ((section_length >> 8) as u8 & 0x0F);
131 buf[2] = (section_length & 0xFF) as u8;
132 buf[3..5].copy_from_slice(&self.table_id_extension.to_be_bytes());
133 buf[5] = 0xC0 | ((self.version_number & 0x1F) << 1) | u8::from(self.current_next_indicator);
134 buf[6] = self.section_number;
135 buf[7] = self.last_section_number;
136
137 let dl_pos = MIN_HEADER_LEN + EXTENSION_HEADER_LEN;
138 let ti_len = self.transmission_info_descriptors.len() as u16;
139 buf[dl_pos] = 0xF0 | ((ti_len >> 8) as u8 & 0x0F);
140 buf[dl_pos + 1] = (ti_len & 0xFF) as u8;
141 let ti_start = dl_pos + DESC_LOOP_LEN_FIELD;
142 let ti_end = ti_start + self.transmission_info_descriptors.len();
143 buf[ti_start..ti_end].copy_from_slice(&self.transmission_info_descriptors);
144 let sl_end = ti_end + self.service_loop.len();
145 buf[ti_end..sl_end].copy_from_slice(&self.service_loop);
146
147 let crc_pos = len - CRC_LEN;
148 let crc = dvb_common::crc32_mpeg2::compute(&buf[..crc_pos]);
149 buf[crc_pos..len].copy_from_slice(&crc.to_be_bytes());
150 Ok(len)
151 }
152}
153
154impl<'a> Table<'a> for Sit {
155 const TABLE_ID: u8 = TABLE_ID;
156 const PID: u16 = PID;
157}
158
159impl<'a> crate::traits::TableDef<'a> for Sit {
160 const TABLE_ID_RANGES: &'static [(u8, u8)] = &[(TABLE_ID, TABLE_ID)];
161 const NAME: &'static str = "SELECTION_INFORMATION";
162}
163
164#[cfg(test)]
165mod tests {
166 use super::*;
167
168 fn build_sit(
169 table_id_extension: u16,
170 version: u8,
171 ti_desc: &[u8],
172 service_loop: &[u8],
173 ) -> Vec<u8> {
174 let section_length = (EXTENSION_HEADER_LEN
175 + DESC_LOOP_LEN_FIELD
176 + ti_desc.len()
177 + service_loop.len()
178 + CRC_LEN) as u16;
179 let mut v = vec![
180 TABLE_ID,
181 0xB0 | ((section_length >> 8) as u8 & 0x0F),
182 (section_length & 0xFF) as u8,
183 ];
184 v.extend_from_slice(&table_id_extension.to_be_bytes());
185 v.push(0xC0 | ((version & 0x1F) << 1) | 0x01);
186 v.push(0x00);
187 v.push(0x00);
188 let dl = ti_desc.len() as u16;
189 v.push(0xF0 | ((dl >> 8) as u8 & 0x0F));
190 v.push((dl & 0xFF) as u8);
191 v.extend_from_slice(ti_desc);
192 v.extend_from_slice(service_loop);
193 v.extend_from_slice(&[0, 0, 0, 0]);
194 v
195 }
196
197 #[test]
198 fn parse_rejects_wrong_tag() {
199 let mut bytes = build_sit(0x1234, 5, &[], &[]);
200 bytes[0] = 0x7E;
201 assert!(matches!(
202 Sit::parse(&bytes).unwrap_err(),
203 Error::UnexpectedTableId { table_id: 0x7E, .. }
204 ));
205 }
206
207 #[test]
208 fn parse_rejects_short_buffer() {
209 assert!(matches!(
210 Sit::parse(&[0x7F, 0xB0]).unwrap_err(),
211 Error::BufferTooShort { .. }
212 ));
213 }
214
215 #[test]
216 fn parse_empty() {
217 let sit = Sit::parse(&build_sit(0x1234, 5, &[], &[])).unwrap();
218 assert_eq!(sit.table_id_extension, 0x1234);
219 assert_eq!(sit.version_number, 5);
220 assert!(sit.current_next_indicator);
221 assert!(sit.transmission_info_descriptors.is_empty());
222 assert!(sit.service_loop.is_empty());
223 }
224
225 #[test]
226 fn parse_separates_both_loops() {
227 let ti = [0x4D, 0x02, 0x01, 0x02]; let service = [0x00, 0x01, 0x80 | (4 << 4), 0x00];
230 let sit = Sit::parse(&build_sit(0xABCD, 7, &ti, &service)).unwrap();
231 assert_eq!(sit.transmission_info_descriptors, &ti[..]);
232 assert_eq!(sit.service_loop, &service[..]);
233 }
234
235 #[test]
236 fn serialize_round_trip() {
237 let ti = [0x4D, 0x02, 0x01, 0x02];
238 let service = [0x00, 0x01, 0xC0, 0x00];
239 let sit = Sit::parse(&build_sit(0xCAFE, 3, &ti, &service)).unwrap();
240 let mut buf = vec![0u8; sit.serialized_len()];
241 sit.serialize_into(&mut buf).unwrap();
242 assert_eq!(Sit::parse(&buf).unwrap(), sit);
243 }
244
245 #[test]
246 fn serialize_round_trip_empty() {
247 let sit = Sit::parse(&build_sit(0x0001, 0, &[], &[])).unwrap();
248 let mut buf = vec![0u8; sit.serialized_len()];
249 sit.serialize_into(&mut buf).unwrap();
250 assert_eq!(Sit::parse(&buf).unwrap(), sit);
251 }
252
253 #[test]
254 fn table_trait_constants() {
255 assert_eq!(<Sit as Table>::TABLE_ID, 0x7F);
256 assert_eq!(<Sit as Table>::PID, 0x001F);
257 }
258
259 #[test]
260 fn sit_round_trips_via_json() {
261 let sit = Sit::parse(&build_sit(
262 0xDEAD,
263 9,
264 &[0x4D, 0x00],
265 &[0x00, 0x01, 0xC0, 0x00],
266 ))
267 .unwrap();
268 let j = serde_json::to_string(&sit).unwrap();
269 assert_eq!(serde_json::from_str::<Sit>(&j).unwrap(), sit);
270 }
271}