1use crate::error::{Error, Result};
42use alloc::vec::Vec;
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))]
72#[non_exhaustive]
73pub enum FontInfo<'a> {
74 StyleWeight {
76 style: u8,
78 weight: u8,
80 },
81 FileUri {
83 format: u8,
85 uri: &'a [u8],
87 },
88 FontSize {
90 size: u16,
92 info: &'a [u8],
94 },
95 LengthDelimited {
97 font_info_type: u8,
99 info: &'a [u8],
101 },
102}
103
104#[derive(Debug, Clone, PartialEq, Eq)]
106#[cfg_attr(feature = "serde", derive(serde::Serialize))]
107#[cfg_attr(feature = "yoke", derive(yoke::Yokeable))]
108pub struct DownloadableFontInfoSection<'a> {
109 pub font_id_extension: u16,
112 pub font_id: u8,
114 pub version_number: u8,
116 pub current_next_indicator: bool,
118 pub section_number: u8,
120 pub last_section_number: u8,
122 pub font_info: Vec<FontInfo<'a>>,
124}
125
126impl<'a> Parse<'a> for DownloadableFontInfoSection<'a> {
127 type Error = crate::error::Error;
128 fn parse(bytes: &'a [u8]) -> Result<Self> {
129 let min_len = HEADER_LEN + CRC_LEN;
130 if bytes.len() < min_len {
131 return Err(Error::BufferTooShort {
132 need: min_len,
133 have: bytes.len(),
134 what: "DownloadableFontInfoSection",
135 });
136 }
137 if bytes[0] != TABLE_ID {
138 return Err(Error::UnexpectedTableId {
139 table_id: bytes[0],
140 what: "DownloadableFontInfoSection",
141 expected: &[TABLE_ID],
142 });
143 }
144 let section_length = (((bytes[1] & 0x0F) as usize) << 8) | bytes[2] as usize;
145 let total = super::check_section_length(
146 bytes.len(),
147 SECTION_LENGTH_PREFIX,
148 section_length,
149 HEADER_LEN + CRC_LEN,
150 )?;
151
152 let id_word = u16::from_be_bytes([bytes[3], bytes[4]]);
154 let font_id_extension = id_word >> 7;
155 let font_id = (id_word & 0x7F) as u8;
156 let version_number = (bytes[5] >> 1) & 0x1F;
157 let current_next_indicator = bytes[5] & 0x01 != 0;
158 let section_number = bytes[6];
159 let last_section_number = bytes[7];
160
161 let loop_end = total - CRC_LEN;
162 let mut font_info = Vec::new();
163 let mut pos = HEADER_LEN;
164 while pos < loop_end {
165 let font_info_type = bytes[pos];
166 pos += 1;
167 match font_info_type {
168 FONT_INFO_TYPE_STYLE_WEIGHT => {
169 if pos + 1 > loop_end {
170 return Err(Error::SectionLengthOverflow {
171 declared: 1,
172 available: loop_end - pos,
173 });
174 }
175 let b = bytes[pos];
176 pos += 1;
177 font_info.push(FontInfo::StyleWeight {
178 style: b >> 5,
179 weight: (b >> 1) & 0x0F,
180 });
181 }
182 FONT_INFO_TYPE_FILE_URI => {
183 if pos + 2 > loop_end {
184 return Err(Error::SectionLengthOverflow {
185 declared: 2,
186 available: loop_end - pos,
187 });
188 }
189 let format = bytes[pos] & 0x0F;
190 let uri_length = bytes[pos + 1] as usize;
191 let uri_start = pos + 2;
192 let uri_end = uri_start + uri_length;
193 if uri_end > loop_end {
194 return Err(Error::SectionLengthOverflow {
195 declared: uri_length,
196 available: loop_end - uri_start,
197 });
198 }
199 font_info.push(FontInfo::FileUri {
200 format,
201 uri: &bytes[uri_start..uri_end],
202 });
203 pos = uri_end;
204 }
205 FONT_INFO_TYPE_FONT_SIZE => {
206 if pos + 3 > loop_end {
208 return Err(Error::SectionLengthOverflow {
209 declared: 3,
210 available: loop_end - pos,
211 });
212 }
213 let size = u16::from_be_bytes([bytes[pos], bytes[pos + 1]]);
214 let info_length = bytes[pos + 2] as usize;
215 let info_start = pos + 3;
216 let info_end = info_start + info_length;
217 if info_end > loop_end {
218 return Err(Error::SectionLengthOverflow {
219 declared: info_length,
220 available: loop_end - info_start,
221 });
222 }
223 font_info.push(FontInfo::FontSize {
224 size,
225 info: &bytes[info_start..info_end],
226 });
227 pos = info_end;
228 }
229 _ => {
230 if pos + 1 > loop_end {
232 return Err(Error::SectionLengthOverflow {
233 declared: 1,
234 available: loop_end - pos,
235 });
236 }
237 let info_length = bytes[pos] as usize;
238 let info_start = pos + 1;
239 let info_end = info_start + info_length;
240 if info_end > loop_end {
241 return Err(Error::SectionLengthOverflow {
242 declared: info_length,
243 available: loop_end - info_start,
244 });
245 }
246 font_info.push(FontInfo::LengthDelimited {
247 font_info_type,
248 info: &bytes[info_start..info_end],
249 });
250 pos = info_end;
251 }
252 }
253 }
254
255 Ok(DownloadableFontInfoSection {
256 font_id_extension,
257 font_id,
258 version_number,
259 current_next_indicator,
260 section_number,
261 last_section_number,
262 font_info,
263 })
264 }
265}
266
267impl Serialize for DownloadableFontInfoSection<'_> {
268 type Error = crate::error::Error;
269 fn serialized_len(&self) -> usize {
270 let loop_bytes: usize = self
271 .font_info
272 .iter()
273 .map(|f| match f {
274 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(), })
279 .sum();
280 HEADER_LEN + loop_bytes + CRC_LEN
281 }
282 fn serialize_into(&self, buf: &mut [u8]) -> Result<usize> {
283 let len = self.serialized_len();
284 if buf.len() < len {
285 return Err(Error::OutputBufferTooSmall {
286 need: len,
287 have: buf.len(),
288 });
289 }
290 let section_length = (len - SECTION_LENGTH_PREFIX) as u16;
291 buf[0] = TABLE_ID;
292 buf[1] = super::SECTION_B1_FLAGS_DVB | ((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}
361impl<'a> crate::traits::TableDef<'a> for DownloadableFontInfoSection<'a> {
362 const TABLE_ID_RANGES: &'static [(u8, u8)] = &[(TABLE_ID, TABLE_ID)];
363 const NAME: &'static str = "DOWNLOADABLE_FONT_INFO";
364}
365
366#[cfg(test)]
367mod tests {
368 use super::*;
369
370 fn build_section(font_id: u8, version: u8, loop_body: &[u8]) -> Vec<u8> {
372 let section_length =
373 (HEADER_LEN - SECTION_LENGTH_PREFIX + loop_body.len() + CRC_LEN) as u16;
374 let id_word = (font_id as u16) & 0x7F;
376 let mut v = vec![
377 TABLE_ID,
378 super::super::SECTION_B1_FLAGS_DVB | ((section_length >> 8) as u8 & 0x0F),
379 (section_length & 0xFF) as u8,
380 (id_word >> 8) as u8,
381 (id_word & 0xFF) as u8,
382 0xC0 | (version << 1) | 0x01,
383 0x00,
384 0x00,
385 ];
386 v.extend_from_slice(loop_body);
387 v.extend_from_slice(&[0, 0, 0, 0]);
388 v
389 }
390
391 fn mixed_loop() -> Vec<u8> {
393 let uri = b"https://f.example/Droid.otf";
394 let family = b"Droid Sans";
395 let mut b = vec![
396 FONT_INFO_TYPE_STYLE_WEIGHT, (2u8 << 5) | (2u8 << 1), FONT_INFO_TYPE_FILE_URI, 0x01, uri.len() as u8, ];
402 b.extend_from_slice(uri);
403 b.push(FONT_INFO_TYPE_FONT_SIZE);
405 b.extend_from_slice(&24u16.to_be_bytes());
406 b.push(2);
407 b.extend_from_slice(b"px");
408 b.push(0x03);
410 b.push(family.len() as u8);
411 b.extend_from_slice(family);
412 b
413 }
414
415 #[test]
416 fn parse_header_fields() {
417 let bytes = build_section(0x42, 9, &[]);
418 let sec = DownloadableFontInfoSection::parse(&bytes).unwrap();
419 assert_eq!(sec.font_id, 0x42);
420 assert_eq!(sec.font_id_extension, 0);
421 assert_eq!(sec.version_number, 9);
422 assert!(sec.current_next_indicator);
423 assert!(sec.font_info.is_empty());
424 }
425
426 #[test]
427 fn parse_all_variants() {
428 let bytes = build_section(1, 0, &mixed_loop());
429 let sec = DownloadableFontInfoSection::parse(&bytes).unwrap();
430 assert_eq!(sec.font_info.len(), 4);
431 assert_eq!(
432 sec.font_info[0],
433 FontInfo::StyleWeight {
434 style: 2,
435 weight: 2
436 }
437 );
438 match &sec.font_info[1] {
439 FontInfo::FileUri { format, uri } => {
440 assert_eq!(*format, 1);
441 assert_eq!(*uri, b"https://f.example/Droid.otf");
442 }
443 other => panic!("expected FileUri, got {other:?}"),
444 }
445 match &sec.font_info[2] {
446 FontInfo::FontSize { size, info } => {
447 assert_eq!(*size, 24);
448 assert_eq!(*info, b"px");
449 }
450 other => panic!("expected FontSize, got {other:?}"),
451 }
452 match &sec.font_info[3] {
453 FontInfo::LengthDelimited {
454 font_info_type,
455 info,
456 } => {
457 assert_eq!(*font_info_type, 0x03);
458 assert_eq!(*info, b"Droid Sans");
459 }
460 other => panic!("expected LengthDelimited, got {other:?}"),
461 }
462 }
463
464 #[test]
465 fn reserved_type_round_trips_as_length_delimited() {
466 let mut body = vec![0x77u8, 0x03];
468 body.extend_from_slice(&[0xAA, 0xBB, 0xCC]);
469 let bytes = build_section(1, 0, &body);
470 let sec = DownloadableFontInfoSection::parse(&bytes).unwrap();
471 assert_eq!(
472 sec.font_info[0],
473 FontInfo::LengthDelimited {
474 font_info_type: 0x77,
475 info: &[0xAA, 0xBB, 0xCC]
476 }
477 );
478 }
479
480 #[test]
481 fn parse_rejects_wrong_tag() {
482 let mut bytes = build_section(1, 0, &mixed_loop());
483 bytes[0] = 0x4C; assert!(matches!(
485 DownloadableFontInfoSection::parse(&bytes).unwrap_err(),
486 Error::UnexpectedTableId { table_id: 0x4C, .. }
487 ));
488 }
489
490 #[test]
491 fn rejects_short_buffer() {
492 assert!(matches!(
493 DownloadableFontInfoSection::parse(&[0x7C, 0xB0]).unwrap_err(),
494 Error::BufferTooShort {
495 what: "DownloadableFontInfoSection",
496 ..
497 }
498 ));
499 }
500
501 #[test]
502 fn uri_length_overflow_rejected() {
503 let body = vec![FONT_INFO_TYPE_FILE_URI, 0x01, 0x20];
505 let bytes = build_section(1, 0, &body);
506 assert!(matches!(
507 DownloadableFontInfoSection::parse(&bytes).unwrap_err(),
508 Error::SectionLengthOverflow { .. }
509 ));
510 }
511
512 #[test]
513 fn round_trip_all_variants() {
514 let bytes = build_section(0x33, 4, &mixed_loop());
515 let sec = DownloadableFontInfoSection::parse(&bytes).unwrap();
516 let mut buf = vec![0u8; sec.serialized_len()];
517 sec.serialize_into(&mut buf).unwrap();
518 let re = DownloadableFontInfoSection::parse(&buf).unwrap();
519 assert_eq!(sec, re);
520 }
521
522 #[test]
523 fn table_trait_constants() {
524 assert_eq!(TABLE_ID, 0x7C);
525 assert_eq!(PID, 0x0000);
526 }
527
528 #[test]
529 #[cfg(feature = "serde")]
530 fn serde_json_round_trip() {
531 let bytes = build_section(1, 0, &mixed_loop());
532 let sec = DownloadableFontInfoSection::parse(&bytes).unwrap();
533 let j = serde_json::to_string(&sec).unwrap();
534 let reparsed = DownloadableFontInfoSection::parse(&bytes).unwrap();
540 assert_eq!(serde_json::to_string(&reparsed).unwrap(), j);
541 assert!(j.contains("\"font_id\":1"));
542 }
543
544 #[test]
545 fn parse_rejects_zero_section_length() {
546 let mut buf = vec![0u8; 64];
547 buf[0] = TABLE_ID;
548 buf[1] = 0xF0;
549 buf[2] = 0x00;
550 for b in &mut buf[3..] {
551 *b = 0xFF;
552 }
553 assert!(matches!(
554 DownloadableFontInfoSection::parse(&buf).unwrap_err(),
555 Error::SectionLengthOverflow { .. }
556 ));
557 }
558}