1use crate::error::{Error, Result};
42use crate::traits::Table;
43use dvb_common::{Parse, Serialize};
44
45pub const TABLE_ID: u8 = 0x7C;
47pub const PID: u16 = 0x0000;
50
51pub const FONT_INFO_TYPE_STYLE_WEIGHT: u8 = 0x00;
53pub const FONT_INFO_TYPE_FILE_URI: u8 = 0x01;
55pub const FONT_INFO_TYPE_FONT_SIZE: u8 = 0x02;
57
58const HEADER_LEN: usize = 8;
61const SECTION_LENGTH_PREFIX: usize = 3;
63const CRC_LEN: usize = 4;
65
66#[derive(Debug, Clone, PartialEq, Eq)]
71#[cfg_attr(feature = "serde", derive(serde::Serialize))]
72pub enum FontInfo<'a> {
73 StyleWeight {
75 style: u8,
77 weight: u8,
79 },
80 FileUri {
82 format: u8,
84 uri: &'a [u8],
86 },
87 FontSize {
89 size: u16,
91 info: &'a [u8],
93 },
94 LengthDelimited {
96 font_info_type: u8,
98 info: &'a [u8],
100 },
101}
102
103#[derive(Debug, Clone, PartialEq, Eq)]
105#[cfg_attr(feature = "serde", derive(serde::Serialize))]
106pub struct DownloadableFontInfoSection<'a> {
107 pub font_id_extension: u16,
110 pub font_id: u8,
112 pub version_number: u8,
114 pub current_next_indicator: bool,
116 pub section_number: u8,
118 pub last_section_number: u8,
120 pub font_info: Vec<FontInfo<'a>>,
122}
123
124impl<'a> Parse<'a> for DownloadableFontInfoSection<'a> {
125 type Error = crate::error::Error;
126 fn parse(bytes: &'a [u8]) -> Result<Self> {
127 let min_len = HEADER_LEN + CRC_LEN;
128 if bytes.len() < min_len {
129 return Err(Error::BufferTooShort {
130 need: min_len,
131 have: bytes.len(),
132 what: "DownloadableFontInfoSection",
133 });
134 }
135 if bytes[0] != TABLE_ID {
136 return Err(Error::UnexpectedTableId {
137 table_id: bytes[0],
138 what: "DownloadableFontInfoSection",
139 expected: &[TABLE_ID],
140 });
141 }
142 let section_length = (((bytes[1] & 0x0F) as usize) << 8) | bytes[2] as usize;
143 let total = SECTION_LENGTH_PREFIX + section_length;
144 if bytes.len() < total || total < HEADER_LEN + CRC_LEN {
145 return Err(Error::SectionLengthOverflow {
146 declared: section_length,
147 available: bytes.len().saturating_sub(SECTION_LENGTH_PREFIX),
148 });
149 }
150
151 let id_word = u16::from_be_bytes([bytes[3], bytes[4]]);
153 let font_id_extension = id_word >> 7;
154 let font_id = (id_word & 0x7F) as u8;
155 let version_number = (bytes[5] >> 1) & 0x1F;
156 let current_next_indicator = bytes[5] & 0x01 != 0;
157 let section_number = bytes[6];
158 let last_section_number = bytes[7];
159
160 let loop_end = total - CRC_LEN;
161 let mut font_info = Vec::new();
162 let mut pos = HEADER_LEN;
163 while pos < loop_end {
164 let font_info_type = bytes[pos];
165 pos += 1;
166 match font_info_type {
167 FONT_INFO_TYPE_STYLE_WEIGHT => {
168 if pos + 1 > loop_end {
169 return Err(Error::SectionLengthOverflow {
170 declared: 1,
171 available: loop_end - pos,
172 });
173 }
174 let b = bytes[pos];
175 pos += 1;
176 font_info.push(FontInfo::StyleWeight {
177 style: b >> 5,
178 weight: (b >> 1) & 0x0F,
179 });
180 }
181 FONT_INFO_TYPE_FILE_URI => {
182 if pos + 2 > loop_end {
183 return Err(Error::SectionLengthOverflow {
184 declared: 2,
185 available: loop_end - pos,
186 });
187 }
188 let format = bytes[pos] & 0x0F;
189 let uri_length = bytes[pos + 1] as usize;
190 let uri_start = pos + 2;
191 let uri_end = uri_start + uri_length;
192 if uri_end > loop_end {
193 return Err(Error::SectionLengthOverflow {
194 declared: uri_length,
195 available: loop_end - uri_start,
196 });
197 }
198 font_info.push(FontInfo::FileUri {
199 format,
200 uri: &bytes[uri_start..uri_end],
201 });
202 pos = uri_end;
203 }
204 FONT_INFO_TYPE_FONT_SIZE => {
205 if pos + 3 > loop_end {
207 return Err(Error::SectionLengthOverflow {
208 declared: 3,
209 available: loop_end - pos,
210 });
211 }
212 let size = u16::from_be_bytes([bytes[pos], bytes[pos + 1]]);
213 let info_length = bytes[pos + 2] as usize;
214 let info_start = pos + 3;
215 let info_end = info_start + info_length;
216 if info_end > loop_end {
217 return Err(Error::SectionLengthOverflow {
218 declared: info_length,
219 available: loop_end - info_start,
220 });
221 }
222 font_info.push(FontInfo::FontSize {
223 size,
224 info: &bytes[info_start..info_end],
225 });
226 pos = info_end;
227 }
228 _ => {
229 if pos + 1 > loop_end {
231 return Err(Error::SectionLengthOverflow {
232 declared: 1,
233 available: loop_end - pos,
234 });
235 }
236 let info_length = bytes[pos] as usize;
237 let info_start = pos + 1;
238 let info_end = info_start + info_length;
239 if info_end > loop_end {
240 return Err(Error::SectionLengthOverflow {
241 declared: info_length,
242 available: loop_end - info_start,
243 });
244 }
245 font_info.push(FontInfo::LengthDelimited {
246 font_info_type,
247 info: &bytes[info_start..info_end],
248 });
249 pos = info_end;
250 }
251 }
252 }
253
254 Ok(DownloadableFontInfoSection {
255 font_id_extension,
256 font_id,
257 version_number,
258 current_next_indicator,
259 section_number,
260 last_section_number,
261 font_info,
262 })
263 }
264}
265
266impl Serialize for DownloadableFontInfoSection<'_> {
267 type Error = crate::error::Error;
268 fn serialized_len(&self) -> usize {
269 let loop_bytes: usize = self
270 .font_info
271 .iter()
272 .map(|f| match f {
273 FontInfo::StyleWeight { .. } => 2, FontInfo::FileUri { uri, .. } => 1 + 2 + uri.len(), FontInfo::FontSize { info, .. } => 1 + 2 + 1 + info.len(), FontInfo::LengthDelimited { info, .. } => 1 + 1 + info.len(), })
278 .sum();
279 HEADER_LEN + loop_bytes + CRC_LEN
280 }
281 fn serialize_into(&self, buf: &mut [u8]) -> Result<usize> {
282 let len = self.serialized_len();
283 if buf.len() < len {
284 return Err(Error::OutputBufferTooSmall {
285 need: len,
286 have: buf.len(),
287 });
288 }
289 let section_length = (len - SECTION_LENGTH_PREFIX) as u16;
290 buf[0] = TABLE_ID;
291 buf[1] = 0xB0 | ((section_length >> 8) as u8 & 0x0F);
293 buf[2] = (section_length & 0xFF) as u8;
294 let id_word = ((self.font_id_extension & 0x01FF) << 7) | (self.font_id as u16 & 0x7F);
296 buf[3..5].copy_from_slice(&id_word.to_be_bytes());
297 buf[5] = 0xC0 | ((self.version_number & 0x1F) << 1) | u8::from(self.current_next_indicator);
299 buf[6] = self.section_number;
300 buf[7] = self.last_section_number;
301
302 let guard_u8 = |len: usize| -> Result<()> {
305 if len > u8::MAX as usize {
306 return Err(Error::SectionLengthOverflow {
307 declared: len,
308 available: u8::MAX as usize,
309 });
310 }
311 Ok(())
312 };
313
314 let mut pos = HEADER_LEN;
315 for f in &self.font_info {
316 match f {
317 FontInfo::StyleWeight { style, weight } => {
318 buf[pos] = FONT_INFO_TYPE_STYLE_WEIGHT;
319 buf[pos + 1] = ((style & 0x07) << 5) | ((weight & 0x0F) << 1);
321 pos += 2;
322 }
323 FontInfo::FileUri { format, uri } => {
324 guard_u8(uri.len())?;
325 buf[pos] = FONT_INFO_TYPE_FILE_URI;
326 buf[pos + 1] = format & 0x0F;
328 buf[pos + 2] = uri.len() as u8;
329 let s = pos + 3;
330 buf[s..s + uri.len()].copy_from_slice(uri);
331 pos = s + uri.len();
332 }
333 FontInfo::FontSize { size, info } => {
334 guard_u8(info.len())?;
335 buf[pos] = FONT_INFO_TYPE_FONT_SIZE;
336 buf[pos + 1..pos + 3].copy_from_slice(&size.to_be_bytes());
337 buf[pos + 3] = info.len() as u8;
338 let s = pos + 4;
339 buf[s..s + info.len()].copy_from_slice(info);
340 pos = s + info.len();
341 }
342 FontInfo::LengthDelimited {
343 font_info_type,
344 info,
345 } => {
346 guard_u8(info.len())?;
347 buf[pos] = *font_info_type;
348 buf[pos + 1] = info.len() as u8;
349 let s = pos + 2;
350 buf[s..s + info.len()].copy_from_slice(info);
351 pos = s + info.len();
352 }
353 }
354 }
355
356 let crc = dvb_common::crc32_mpeg2::compute(&buf[..pos]);
357 buf[pos..len].copy_from_slice(&crc.to_be_bytes());
358 Ok(len)
359 }
360}
361
362impl<'a> Table<'a> for DownloadableFontInfoSection<'a> {
363 const TABLE_ID: u8 = TABLE_ID;
364 const PID: u16 = PID;
365}
366
367impl<'a> crate::traits::TableDef<'a> for DownloadableFontInfoSection<'a> {
368 const TABLE_ID_RANGES: &'static [(u8, u8)] = &[(TABLE_ID, TABLE_ID)];
369 const NAME: &'static str = "DOWNLOADABLE_FONT_INFO";
370}
371
372#[cfg(test)]
373mod tests {
374 use super::*;
375
376 fn build_section(font_id: u8, version: u8, loop_body: &[u8]) -> Vec<u8> {
378 let section_length =
379 (HEADER_LEN - SECTION_LENGTH_PREFIX + loop_body.len() + CRC_LEN) as u16;
380 let id_word = (font_id as u16) & 0x7F;
382 let mut v = vec![
383 TABLE_ID,
384 0xB0 | ((section_length >> 8) as u8 & 0x0F),
385 (section_length & 0xFF) as u8,
386 (id_word >> 8) as u8,
387 (id_word & 0xFF) as u8,
388 0xC0 | (version << 1) | 0x01,
389 0x00,
390 0x00,
391 ];
392 v.extend_from_slice(loop_body);
393 v.extend_from_slice(&[0, 0, 0, 0]);
394 v
395 }
396
397 fn mixed_loop() -> Vec<u8> {
399 let uri = b"https://f.example/Droid.otf";
400 let family = b"Droid Sans";
401 let mut b = vec![
402 FONT_INFO_TYPE_STYLE_WEIGHT, (2u8 << 5) | (2u8 << 1), FONT_INFO_TYPE_FILE_URI, 0x01, uri.len() as u8, ];
408 b.extend_from_slice(uri);
409 b.push(FONT_INFO_TYPE_FONT_SIZE);
411 b.extend_from_slice(&24u16.to_be_bytes());
412 b.push(2);
413 b.extend_from_slice(b"px");
414 b.push(0x03);
416 b.push(family.len() as u8);
417 b.extend_from_slice(family);
418 b
419 }
420
421 #[test]
422 fn parse_header_fields() {
423 let bytes = build_section(0x42, 9, &[]);
424 let sec = DownloadableFontInfoSection::parse(&bytes).unwrap();
425 assert_eq!(sec.font_id, 0x42);
426 assert_eq!(sec.font_id_extension, 0);
427 assert_eq!(sec.version_number, 9);
428 assert!(sec.current_next_indicator);
429 assert!(sec.font_info.is_empty());
430 }
431
432 #[test]
433 fn parse_all_variants() {
434 let bytes = build_section(1, 0, &mixed_loop());
435 let sec = DownloadableFontInfoSection::parse(&bytes).unwrap();
436 assert_eq!(sec.font_info.len(), 4);
437 assert_eq!(
438 sec.font_info[0],
439 FontInfo::StyleWeight {
440 style: 2,
441 weight: 2
442 }
443 );
444 match &sec.font_info[1] {
445 FontInfo::FileUri { format, uri } => {
446 assert_eq!(*format, 1);
447 assert_eq!(*uri, b"https://f.example/Droid.otf");
448 }
449 other => panic!("expected FileUri, got {other:?}"),
450 }
451 match &sec.font_info[2] {
452 FontInfo::FontSize { size, info } => {
453 assert_eq!(*size, 24);
454 assert_eq!(*info, b"px");
455 }
456 other => panic!("expected FontSize, got {other:?}"),
457 }
458 match &sec.font_info[3] {
459 FontInfo::LengthDelimited {
460 font_info_type,
461 info,
462 } => {
463 assert_eq!(*font_info_type, 0x03);
464 assert_eq!(*info, b"Droid Sans");
465 }
466 other => panic!("expected LengthDelimited, got {other:?}"),
467 }
468 }
469
470 #[test]
471 fn reserved_type_round_trips_as_length_delimited() {
472 let mut body = vec![0x77u8, 0x03];
474 body.extend_from_slice(&[0xAA, 0xBB, 0xCC]);
475 let bytes = build_section(1, 0, &body);
476 let sec = DownloadableFontInfoSection::parse(&bytes).unwrap();
477 assert_eq!(
478 sec.font_info[0],
479 FontInfo::LengthDelimited {
480 font_info_type: 0x77,
481 info: &[0xAA, 0xBB, 0xCC]
482 }
483 );
484 }
485
486 #[test]
487 fn parse_rejects_wrong_tag() {
488 let mut bytes = build_section(1, 0, &mixed_loop());
489 bytes[0] = 0x4C; assert!(matches!(
491 DownloadableFontInfoSection::parse(&bytes).unwrap_err(),
492 Error::UnexpectedTableId { table_id: 0x4C, .. }
493 ));
494 }
495
496 #[test]
497 fn rejects_short_buffer() {
498 assert!(matches!(
499 DownloadableFontInfoSection::parse(&[0x7C, 0xB0]).unwrap_err(),
500 Error::BufferTooShort {
501 what: "DownloadableFontInfoSection",
502 ..
503 }
504 ));
505 }
506
507 #[test]
508 fn uri_length_overflow_rejected() {
509 let body = vec![FONT_INFO_TYPE_FILE_URI, 0x01, 0x20];
511 let bytes = build_section(1, 0, &body);
512 assert!(matches!(
513 DownloadableFontInfoSection::parse(&bytes).unwrap_err(),
514 Error::SectionLengthOverflow { .. }
515 ));
516 }
517
518 #[test]
519 fn round_trip_all_variants() {
520 let bytes = build_section(0x33, 4, &mixed_loop());
521 let sec = DownloadableFontInfoSection::parse(&bytes).unwrap();
522 let mut buf = vec![0u8; sec.serialized_len()];
523 sec.serialize_into(&mut buf).unwrap();
524 let re = DownloadableFontInfoSection::parse(&buf).unwrap();
525 assert_eq!(sec, re);
526 }
527
528 #[test]
529 fn table_trait_constants() {
530 assert_eq!(<DownloadableFontInfoSection as Table>::TABLE_ID, 0x7C);
531 assert_eq!(<DownloadableFontInfoSection as Table>::PID, 0x0000);
532 }
533
534 #[test]
535 #[cfg(feature = "serde")]
536 fn serde_json_round_trip() {
537 let bytes = build_section(1, 0, &mixed_loop());
538 let sec = DownloadableFontInfoSection::parse(&bytes).unwrap();
539 let j = serde_json::to_string(&sec).unwrap();
540 let reparsed = DownloadableFontInfoSection::parse(&bytes).unwrap();
546 assert_eq!(serde_json::to_string(&reparsed).unwrap(), j);
547 assert!(j.contains("\"font_id\":1"));
548 }
549}