1use crate::error::{Error, Result};
17use crate::traits::Table;
18use dvb_common::{Parse, Serialize};
19use num_enum::TryFromPrimitive;
20
21pub const TABLE_ID: u8 = 0x4D;
23pub const PID: u16 = 0x001B;
25
26const HEADER_LEN: usize = 9;
28const SECTION_LENGTH_PREFIX: usize = 3;
30const CRC_LEN: usize = 4;
32
33#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, TryFromPrimitive)]
35#[cfg_attr(feature = "serde", derive(serde::Serialize))]
36#[repr(u8)]
37pub enum SatTableId {
38 PositionV2 = 0,
40 CellFragment = 1,
42 TimeAssociation = 2,
44 BeamhoppingTimePlan = 3,
46 PositionV3 = 4,
48}
49
50#[derive(Debug, Clone, PartialEq, Eq)]
55#[cfg_attr(feature = "serde", derive(serde::Serialize))]
56#[cfg_attr(feature = "yoke", derive(yoke::Yokeable))]
57pub struct Sat<'a> {
58 pub satellite_table_id: u8,
60 pub table_count: u16,
62 pub version_number: u8,
64 pub current_next_indicator: bool,
66 pub section_number: u8,
68 pub last_section_number: u8,
70 pub body: &'a [u8],
72}
73
74impl Sat<'_> {
75 #[must_use]
77 pub fn kind(&self) -> Option<SatTableId> {
78 SatTableId::try_from(self.satellite_table_id).ok()
79 }
80}
81
82impl<'a> Parse<'a> for Sat<'a> {
83 type Error = crate::error::Error;
84 fn parse(bytes: &'a [u8]) -> Result<Self> {
85 let min_len = HEADER_LEN + CRC_LEN;
86 if bytes.len() < min_len {
87 return Err(Error::BufferTooShort {
88 need: min_len,
89 have: bytes.len(),
90 what: "Sat",
91 });
92 }
93 if bytes[0] != TABLE_ID {
94 return Err(Error::UnexpectedTableId {
95 table_id: bytes[0],
96 what: "Sat",
97 expected: &[TABLE_ID],
98 });
99 }
100 let section_length = (((bytes[1] & 0x0F) as usize) << 8) | bytes[2] as usize;
101 let total = SECTION_LENGTH_PREFIX + section_length;
102 if bytes.len() < total || total < HEADER_LEN + CRC_LEN {
103 return Err(Error::SectionLengthOverflow {
104 declared: section_length,
105 available: bytes.len().saturating_sub(SECTION_LENGTH_PREFIX),
106 });
107 }
108 let satellite_table_id = bytes[3] >> 2;
109 let table_count = (((bytes[3] & 0x03) as u16) << 8) | bytes[4] as u16;
110 let version_number = (bytes[5] >> 1) & 0x1F;
111 let current_next_indicator = bytes[5] & 0x01 != 0;
112 let section_number = bytes[6];
113 let last_section_number = bytes[7];
114 let body = &bytes[HEADER_LEN..total - CRC_LEN];
116 Ok(Sat {
117 satellite_table_id,
118 table_count,
119 version_number,
120 current_next_indicator,
121 section_number,
122 last_section_number,
123 body,
124 })
125 }
126}
127
128impl Serialize for Sat<'_> {
129 type Error = crate::error::Error;
130 fn serialized_len(&self) -> usize {
131 HEADER_LEN + self.body.len() + CRC_LEN
132 }
133 fn serialize_into(&self, buf: &mut [u8]) -> Result<usize> {
134 let len = self.serialized_len();
135 if buf.len() < len {
136 return Err(Error::OutputBufferTooSmall {
137 need: len,
138 have: buf.len(),
139 });
140 }
141 let section_length = (len - SECTION_LENGTH_PREFIX) as u16;
142 buf[0] = TABLE_ID;
143 buf[1] = 0xF0 | ((section_length >> 8) as u8 & 0x0F);
145 buf[2] = (section_length & 0xFF) as u8;
146 buf[3] = (self.satellite_table_id << 2) | ((self.table_count >> 8) as u8 & 0x03);
147 buf[4] = (self.table_count & 0xFF) as u8;
148 buf[5] = 0xC0 | ((self.version_number & 0x1F) << 1) | u8::from(self.current_next_indicator);
150 buf[6] = self.section_number;
151 buf[7] = self.last_section_number;
152 buf[8] = 0x00; let body_end = HEADER_LEN + self.body.len();
154 buf[HEADER_LEN..body_end].copy_from_slice(self.body);
155 let crc = dvb_common::crc32_mpeg2::compute(&buf[..body_end]);
156 buf[body_end..len].copy_from_slice(&crc.to_be_bytes());
157 Ok(len)
158 }
159}
160
161impl<'a> Table<'a> for Sat<'a> {
162 const TABLE_ID: u8 = TABLE_ID;
163 const PID: u16 = PID;
164}
165
166impl<'a> crate::traits::TableDef<'a> for Sat<'a> {
167 const TABLE_ID_RANGES: &'static [(u8, u8)] = &[(TABLE_ID, TABLE_ID)];
168 const NAME: &'static str = "SATELLITE_ACCESS";
169}
170
171#[cfg(test)]
172mod tests {
173 use super::*;
174
175 fn build_sat(satellite_table_id: u8, table_count: u16, body: &[u8]) -> Vec<u8> {
177 let section_length = (HEADER_LEN - SECTION_LENGTH_PREFIX + body.len() + CRC_LEN) as u16;
178 let mut v = vec![
179 TABLE_ID,
180 0xF0 | ((section_length >> 8) as u8 & 0x0F),
181 (section_length & 0xFF) as u8,
182 (satellite_table_id << 2) | ((table_count >> 8) as u8 & 0x03),
183 (table_count & 0xFF) as u8,
184 0xC0 | (0x05 << 1) | 0x01, 0x00, 0x00, 0x00, ];
189 v.extend_from_slice(body);
190 v.extend_from_slice(&[0, 0, 0, 0]);
191 v
192 }
193
194 #[test]
195 fn parse_position_v3_discriminant() {
196 let body = [0xAA, 0xBB, 0xCC, 0xDD];
197 let bytes = build_sat(4, 0x1A3, &body);
198 let sat = Sat::parse(&bytes).unwrap();
199 assert_eq!(sat.satellite_table_id, 4);
200 assert_eq!(sat.kind(), Some(SatTableId::PositionV3));
201 assert_eq!(sat.table_count, 0x1A3);
202 assert_eq!(sat.version_number, 5);
203 assert!(sat.current_next_indicator);
204 assert_eq!(sat.body, &body);
205 }
206
207 #[test]
208 fn reserved_discriminant_has_no_kind() {
209 let bytes = build_sat(7, 0, &[]);
210 let sat = Sat::parse(&bytes).unwrap();
211 assert_eq!(sat.satellite_table_id, 7);
212 assert_eq!(sat.kind(), None);
213 }
214
215 #[test]
216 fn parse_rejects_wrong_tag() {
217 let mut bytes = build_sat(0, 0, &[1, 2, 3]);
218 bytes[0] = 0x40;
219 assert!(matches!(
220 Sat::parse(&bytes).unwrap_err(),
221 Error::UnexpectedTableId { table_id: 0x40, .. }
222 ));
223 }
224
225 #[test]
226 fn rejects_short_buffer() {
227 assert!(matches!(
228 Sat::parse(&[0x4D, 0xF0]).unwrap_err(),
229 Error::BufferTooShort { what: "Sat", .. }
230 ));
231 }
232
233 #[test]
234 fn serialize_round_trip() {
235 let body = [0x01, 0x02, 0x03, 0x04, 0x05];
236 let bytes = build_sat(1, 0x2FF, &body);
237 let sat = Sat::parse(&bytes).unwrap();
238 let mut buf = vec![0u8; sat.serialized_len()];
239 sat.serialize_into(&mut buf).unwrap();
240 let re = Sat::parse(&buf).unwrap();
241 assert_eq!(sat, re);
242 assert_eq!(re.kind(), Some(SatTableId::CellFragment));
243 assert_eq!(re.table_count, 0x2FF);
244 }
245}