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 broadcast_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. Private — use [`utc_time_decoded`](Self::utc_time_decoded)
23    /// for decoded access.
24    pub(crate) utc_time_raw: [u8; 5],
25}
26
27impl TdtSection {
28    /// Decode the UTC time to a plain date-time struct (no `chrono` feature
29    /// required).
30    ///
31    /// Returns `None` if the date/time fields are out of range. MJD→calendar
32    /// conversion per ETSI EN 300 468 Annex C.
33    #[must_use]
34    pub fn utc_time_decoded(&self) -> Option<broadcast_common::time::MjdBcdDateTime> {
35        broadcast_common::time::decode_mjd_bcd(self.utc_time_raw)
36    }
37
38    /// Set the UTC time, encoding it from a [`broadcast_common::time::MjdBcdDateTime`].
39    ///
40    /// # Errors
41    /// [`ValueOutOfRange`](crate::Error::ValueOutOfRange) if the date is
42    /// outside the representable 16-bit MJD range.
43    pub fn set_utc_time_decoded(
44        &mut self,
45        dt: broadcast_common::time::MjdBcdDateTime,
46    ) -> Result<()> {
47        self.utc_time_raw =
48            broadcast_common::time::encode_mjd_bcd(dt).ok_or(Error::ValueOutOfRange {
49                field: "TdtSection::utc_time",
50                reason: "date not representable in 16-bit MJD",
51            })?;
52        Ok(())
53    }
54
55    /// Raw 5-byte UTC time field (for round-trip / serialization).
56    #[must_use]
57    pub fn utc_time_raw(&self) -> [u8; 5] {
58        self.utc_time_raw
59    }
60
61    /// Construct a `TdtSection` from raw wire fields.
62    #[must_use]
63    pub fn new(utc_time_raw: [u8; 5]) -> Self {
64        Self { utc_time_raw }
65    }
66}
67
68#[cfg(feature = "chrono")]
69impl TdtSection {
70    /// Decode the UTC time to a chrono DateTime when the `chrono` feature is on.
71    ///
72    /// MJD→calendar conversion per ETSI EN 300 468 Annex C.
73    #[must_use]
74    pub fn utc_time(&self) -> Option<chrono::DateTime<chrono::Utc>> {
75        broadcast_common::time::decode_mjd_bcd_utc(self.utc_time_raw)
76    }
77
78    /// Set the UTC time, encoding it into the 40-bit `utc_time` field.
79    ///
80    /// # Errors
81    /// [`ValueOutOfRange`](crate::Error::ValueOutOfRange) if the date is
82    /// outside the representable 16-bit MJD range.
83    pub fn set_utc_time(&mut self, utc_time: chrono::DateTime<chrono::Utc>) -> Result<()> {
84        self.utc_time_raw =
85            broadcast_common::time::encode_mjd_bcd_utc(utc_time).ok_or(Error::ValueOutOfRange {
86                field: "TdtSection::utc_time",
87                reason: "date not representable in 16-bit MJD",
88            })?;
89        Ok(())
90    }
91}
92
93impl<'a> Parse<'a> for TdtSection {
94    type Error = crate::error::Error;
95    fn parse(bytes: &'a [u8]) -> Result<Self> {
96        let min_len = HEADER_LEN + UTC_TIME_LEN;
97        if bytes.len() < min_len {
98            return Err(Error::BufferTooShort {
99                need: min_len,
100                have: bytes.len(),
101                what: "TdtSection",
102            });
103        }
104        if bytes[0] != TABLE_ID {
105            return Err(Error::UnexpectedTableId {
106                table_id: bytes[0],
107                what: "TdtSection",
108                expected: &[TABLE_ID],
109            });
110        }
111        let section_length = ((bytes[1] & 0x0F) as u16) << 8 | bytes[2] as u16;
112        if section_length as usize != UTC_TIME_LEN {
113            return Err(Error::SectionLengthOverflow {
114                declared: section_length as usize,
115                available: UTC_TIME_LEN,
116            });
117        }
118        let utc_time_raw = [bytes[3], bytes[4], bytes[5], bytes[6], bytes[7]];
119        Ok(TdtSection { utc_time_raw })
120    }
121}
122
123impl Serialize for TdtSection {
124    type Error = crate::error::Error;
125    fn serialized_len(&self) -> usize {
126        HEADER_LEN + UTC_TIME_LEN
127    }
128    fn serialize_into(&self, buf: &mut [u8]) -> Result<usize> {
129        let len = self.serialized_len();
130        if buf.len() < len {
131            return Err(Error::OutputBufferTooSmall {
132                need: len,
133                have: buf.len(),
134            });
135        }
136        buf[0] = TABLE_ID;
137        buf[1] = super::SECTION_B1_FLAGS_SHORT | ((UTC_TIME_LEN as u16 >> 8) as u8 & 0x0F);
138        buf[2] = UTC_TIME_LEN as u8;
139        buf[3..8].copy_from_slice(&self.utc_time_raw);
140        Ok(len)
141    }
142}
143impl<'a> crate::traits::TableDef<'a> for TdtSection {
144    const TABLE_ID_RANGES: &'static [(u8, u8)] = &[(TABLE_ID, TABLE_ID)];
145    const NAME: &'static str = "TIME_AND_DATE";
146}
147
148#[cfg(test)]
149mod tests {
150    use super::*;
151
152    #[test]
153    fn parse_extracts_utc_time_raw() {
154        let bytes = [TABLE_ID, 0x70, 0x05, 0xE4, 0x09, 0x12, 0x34, 0x56];
155        let tdt = TdtSection::parse(&bytes).unwrap();
156        assert_eq!(tdt.utc_time_raw(), [0xE4, 0x09, 0x12, 0x34, 0x56]);
157    }
158
159    #[test]
160    fn parse_rejects_wrong_tag() {
161        let bytes = [0x71, 0x70, 0x05, 0, 0, 0, 0, 0];
162        assert!(matches!(
163            TdtSection::parse(&bytes).unwrap_err(),
164            Error::UnexpectedTableId { table_id: 0x71, .. }
165        ));
166    }
167
168    #[test]
169    fn parse_rejects_wrong_section_length() {
170        let bytes = [TABLE_ID, 0x70, 0x04, 0, 0, 0, 0, 0];
171        assert!(matches!(
172            TdtSection::parse(&bytes).unwrap_err(),
173            Error::SectionLengthOverflow { .. }
174        ));
175    }
176
177    #[test]
178    fn serialize_round_trip() {
179        let tdt = TdtSection {
180            utc_time_raw: [0xE4, 0x09, 0x12, 0x34, 0x56],
181        };
182        let mut buf = vec![0u8; tdt.serialized_len()];
183        tdt.serialize_into(&mut buf).unwrap();
184        let re = TdtSection::parse(&buf).unwrap();
185        assert_eq!(tdt, re);
186    }
187
188    #[cfg(feature = "chrono")]
189    #[test]
190    fn utc_time_decodes_to_chrono() {
191        let tdt = TdtSection {
192            utc_time_raw: [0xEA, 0x19, 0x12, 0x34, 0x56],
193        };
194        let dt = tdt.utc_time();
195        assert!(dt.is_some());
196    }
197
198    #[test]
199    fn utc_time_decodes_without_chrono() {
200        let tdt = TdtSection {
201            utc_time_raw: [0xE4, 0x09, 0x12, 0x34, 0x56],
202        };
203        let dt = tdt.utc_time_decoded().unwrap();
204        assert_eq!(dt.year, 2018);
205        assert_eq!(dt.month, 9);
206        assert_eq!(dt.day, 16);
207        assert_eq!(dt.hour, 12);
208        assert_eq!(dt.minute, 34);
209        assert_eq!(dt.second, 56);
210    }
211}