Skip to main content

dvb_si/tables/
tdt.rs

1//! Time and Date Table — ETSI EN 300 468 §5.2.5.
2//!
3//! Short-form section on PID 0x0014 with table_id 0x70. Body is exactly
4//! 5 bytes of UTC time (16-bit MJD + 24-bit BCD HHMMSS). No CRC.
5
6use crate::error::{Error, Result};
7use dvb_common::{Parse, Serialize};
8
9/// table_id for Time and Date Table.
10pub const TABLE_ID: u8 = 0x70;
11/// Well-known PID on which TDT is carried.
12pub const PID: u16 = 0x0014;
13
14const HEADER_LEN: usize = 3;
15const UTC_TIME_LEN: usize = 5;
16
17/// Time and Date Table.
18#[derive(Debug, Clone, Copy, PartialEq, Eq)]
19#[cfg_attr(feature = "serde", derive(serde::Serialize))]
20pub struct TdtSection {
21    /// Raw 5-byte UTC time (16-bit MJD + 24-bit BCD HHMMSS) per
22    /// EN 300 468 Annex C.
23    pub utc_time_raw: [u8; 5],
24}
25
26#[cfg(feature = "chrono")]
27impl TdtSection {
28    /// Decode the UTC time to a chrono DateTime when the `chrono` feature is on.
29    ///
30    /// MJD→calendar conversion per ETSI EN 300 468 Annex C.
31    #[must_use]
32    pub fn utc_time(&self) -> Option<chrono::DateTime<chrono::Utc>> {
33        dvb_common::time::decode_mjd_bcd_utc(self.utc_time_raw)
34    }
35
36    /// Set the UTC time, encoding it into the 40-bit `utc_time` field.
37    ///
38    /// # Errors
39    /// [`ValueOutOfRange`](crate::Error::ValueOutOfRange) if the date is
40    /// outside the representable 16-bit MJD range.
41    pub fn set_utc_time(&mut self, utc_time: chrono::DateTime<chrono::Utc>) -> Result<()> {
42        self.utc_time_raw =
43            dvb_common::time::encode_mjd_bcd_utc(utc_time).ok_or(Error::ValueOutOfRange {
44                field: "TdtSection::utc_time",
45                reason: "date not representable in 16-bit MJD",
46            })?;
47        Ok(())
48    }
49}
50
51impl<'a> Parse<'a> for TdtSection {
52    type Error = crate::error::Error;
53    fn parse(bytes: &'a [u8]) -> Result<Self> {
54        let min_len = HEADER_LEN + UTC_TIME_LEN;
55        if bytes.len() < min_len {
56            return Err(Error::BufferTooShort {
57                need: min_len,
58                have: bytes.len(),
59                what: "TdtSection",
60            });
61        }
62        if bytes[0] != TABLE_ID {
63            return Err(Error::UnexpectedTableId {
64                table_id: bytes[0],
65                what: "TdtSection",
66                expected: &[TABLE_ID],
67            });
68        }
69        let section_length = ((bytes[1] & 0x0F) as u16) << 8 | bytes[2] as u16;
70        if section_length as usize != UTC_TIME_LEN {
71            return Err(Error::SectionLengthOverflow {
72                declared: section_length as usize,
73                available: UTC_TIME_LEN,
74            });
75        }
76        let utc_time_raw = [bytes[3], bytes[4], bytes[5], bytes[6], bytes[7]];
77        Ok(TdtSection { utc_time_raw })
78    }
79}
80
81impl Serialize for TdtSection {
82    type Error = crate::error::Error;
83    fn serialized_len(&self) -> usize {
84        HEADER_LEN + UTC_TIME_LEN
85    }
86    fn serialize_into(&self, buf: &mut [u8]) -> Result<usize> {
87        let len = self.serialized_len();
88        if buf.len() < len {
89            return Err(Error::OutputBufferTooSmall {
90                need: len,
91                have: buf.len(),
92            });
93        }
94        buf[0] = TABLE_ID;
95        buf[1] = 0x70 | ((UTC_TIME_LEN as u16 >> 8) as u8 & 0x0F);
96        buf[2] = UTC_TIME_LEN as u8;
97        buf[3..8].copy_from_slice(&self.utc_time_raw);
98        Ok(len)
99    }
100}
101impl<'a> crate::traits::TableDef<'a> for TdtSection {
102    const TABLE_ID_RANGES: &'static [(u8, u8)] = &[(TABLE_ID, TABLE_ID)];
103    const NAME: &'static str = "TIME_AND_DATE";
104}
105
106#[cfg(test)]
107mod tests {
108    use super::*;
109
110    #[test]
111    fn parse_extracts_utc_time_raw() {
112        let bytes = [TABLE_ID, 0x70, 0x05, 0xE4, 0x09, 0x12, 0x34, 0x56];
113        let tdt = TdtSection::parse(&bytes).unwrap();
114        assert_eq!(tdt.utc_time_raw, [0xE4, 0x09, 0x12, 0x34, 0x56]);
115    }
116
117    #[test]
118    fn parse_rejects_wrong_tag() {
119        let bytes = [0x71, 0x70, 0x05, 0, 0, 0, 0, 0];
120        assert!(matches!(
121            TdtSection::parse(&bytes).unwrap_err(),
122            Error::UnexpectedTableId { table_id: 0x71, .. }
123        ));
124    }
125
126    #[test]
127    fn parse_rejects_wrong_section_length() {
128        let bytes = [TABLE_ID, 0x70, 0x04, 0, 0, 0, 0, 0];
129        assert!(matches!(
130            TdtSection::parse(&bytes).unwrap_err(),
131            Error::SectionLengthOverflow { .. }
132        ));
133    }
134
135    #[test]
136    fn serialize_round_trip() {
137        let tdt = TdtSection {
138            utc_time_raw: [0xE4, 0x09, 0x12, 0x34, 0x56],
139        };
140        let mut buf = vec![0u8; tdt.serialized_len()];
141        tdt.serialize_into(&mut buf).unwrap();
142        let re = TdtSection::parse(&buf).unwrap();
143        assert_eq!(tdt, re);
144    }
145
146    #[cfg(feature = "chrono")]
147    #[test]
148    fn utc_time_decodes_to_chrono() {
149        let tdt = TdtSection {
150            utc_time_raw: [0xEA, 0x19, 0x12, 0x34, 0x56],
151        };
152        let dt = tdt.utc_time();
153        assert!(dt.is_some());
154    }
155}