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