use super::descriptor_body;
use crate::error::{Error, Result};
use alloc::vec::Vec;
use broadcast_common::len::need_out;
use broadcast_common::{Parse, Serialize};
pub const TAG: u8 = 0x75;
const HEADER_LEN: usize = 2;
const ENTRY_LEN: usize = 3;
const RUNNING_STATUS_MAX: u8 = 0x07;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
#[non_exhaustive]
pub enum TvaRunningStatus {
Reserved,
NotYetRunning,
StartsShortly,
Paused,
Running,
Cancelled,
Completed,
Unallocated(u8),
}
impl TvaRunningStatus {
#[must_use]
pub fn from_u8(v: u8) -> Self {
match v {
0 => Self::Reserved,
1 => Self::NotYetRunning,
2 => Self::StartsShortly,
3 => Self::Paused,
4 => Self::Running,
5 => Self::Cancelled,
6 => Self::Completed,
v => Self::Unallocated(v),
}
}
#[must_use]
pub const fn to_u8(self) -> u8 {
match self {
Self::Reserved => 0,
Self::NotYetRunning => 1,
Self::StartsShortly => 2,
Self::Paused => 3,
Self::Running => 4,
Self::Cancelled => 5,
Self::Completed => 6,
Self::Unallocated(v) => v,
}
}
#[must_use]
pub fn name(self) -> &'static str {
match self {
Self::Reserved => "reserved",
Self::NotYetRunning => "not yet running",
Self::StartsShortly => "starts shortly",
Self::Paused => "paused",
Self::Running => "running",
Self::Cancelled => "cancelled",
Self::Completed => "completed",
Self::Unallocated(_) => "unallocated",
}
}
}
broadcast_common::impl_spec_display!(TvaRunningStatus, Unallocated);
pub const RESERVED_DEFAULT: u8 = 0b1_1111;
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
#[non_exhaustive]
pub struct TvaIdEntry {
pub reserved: u8,
pub tva_id: u16,
pub running_status: TvaRunningStatus,
}
impl TvaIdEntry {
#[must_use]
pub const fn new(tva_id: u16, running_status: TvaRunningStatus) -> Self {
Self {
reserved: RESERVED_DEFAULT,
tva_id,
running_status,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Default)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
#[non_exhaustive]
pub struct TvaIdDescriptor {
pub entries: Vec<TvaIdEntry>,
}
impl TvaIdDescriptor {
#[must_use]
pub const fn new(entries: Vec<TvaIdEntry>) -> Self {
Self { entries }
}
}
impl<'a> Parse<'a> for TvaIdDescriptor {
type Error = crate::error::Error;
fn parse(bytes: &'a [u8]) -> Result<Self> {
let body = descriptor_body(
bytes,
TAG,
"TvaIdDescriptor",
"unexpected tag for TVA_id_descriptor",
)?;
if body.len() % ENTRY_LEN != 0 {
return Err(Error::InvalidDescriptor {
tag: TAG,
reason: "TVA_id_descriptor length must be a multiple of 3",
});
}
let mut entries = Vec::with_capacity(body.len() / ENTRY_LEN);
for chunk in body.chunks_exact(ENTRY_LEN) {
let tva_id = crate::wire::be_u16(chunk, 0, "tva_id")?;
let running_status = TvaRunningStatus::from_u8(chunk[2] & RUNNING_STATUS_MAX);
entries.push(TvaIdEntry {
reserved: chunk[2] >> 3,
tva_id,
running_status,
});
}
Ok(Self { entries })
}
}
impl Serialize for TvaIdDescriptor {
type Error = crate::error::Error;
fn serialized_len(&self) -> usize {
HEADER_LEN + self.entries.len() * ENTRY_LEN
}
fn serialize_into(&self, buf: &mut [u8]) -> Result<usize> {
for e in &self.entries {
if e.running_status.to_u8() > RUNNING_STATUS_MAX {
return Err(Error::InvalidDescriptor {
tag: TAG,
reason: "running_status exceeds 3 bits",
});
}
}
if self.entries.len() * ENTRY_LEN > u8::MAX as usize {
return Err(Error::InvalidDescriptor {
tag: TAG,
reason: "TVA_id_descriptor body exceeds 255 bytes",
});
}
let len = self.serialized_len();
need_out(buf, len)?;
crate::descriptors::write_descriptor_header(buf, TAG, self.entries.len() * ENTRY_LEN)?;
let mut pos = HEADER_LEN;
for e in &self.entries {
buf[pos..pos + 2].copy_from_slice(&e.tva_id.to_be_bytes());
buf[pos + 2] = (broadcast_common::len::fit_mask(e.reserved, 0x1F, "reserved")? << 3)
| broadcast_common::len::fit_mask(
e.running_status.to_u8(),
RUNNING_STATUS_MAX,
"running_status",
)?;
pos += ENTRY_LEN;
}
Ok(len)
}
}
impl crate::traits::DescriptorDef<'_> for TvaIdDescriptor {
const TAG: u8 = TAG;
const NAME: &'static str = "TVA_ID";
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn parse_single_entry() {
let bytes = [TAG, 3, 0x12, 0x34, 0xFC];
let d = TvaIdDescriptor::parse(&bytes).unwrap();
assert_eq!(d.entries.len(), 1);
assert_eq!(d.entries[0].tva_id, 0x1234);
assert_eq!(d.entries[0].running_status, TvaRunningStatus::Running);
}
#[test]
fn parse_multiple_entries() {
let bytes = [TAG, 6, 0x00, 0x01, 0x01, 0xAB, 0xCD, 0x06];
let d = TvaIdDescriptor::parse(&bytes).unwrap();
assert_eq!(d.entries.len(), 2);
assert_eq!(d.entries[0].tva_id, 0x0001);
assert_eq!(d.entries[0].running_status, TvaRunningStatus::NotYetRunning);
assert_eq!(d.entries[1].tva_id, 0xABCD);
assert_eq!(d.entries[1].running_status, TvaRunningStatus::Completed);
}
#[test]
fn parse_captures_reserved_bits() {
let bytes = [TAG, 3, 0x00, 0x00, 0xFF];
let d = TvaIdDescriptor::parse(&bytes).unwrap();
assert_eq!(
d.entries[0].running_status,
TvaRunningStatus::Unallocated(0x07)
);
assert_eq!(d.entries[0].reserved, 0x1F);
}
#[test]
fn reserved_preserved_for_every_value() {
for r in 0u8..=0x1F {
let bytes = [TAG, 3, 0x12, 0x34, (r << 3) | 0x04];
let d = TvaIdDescriptor::parse(&bytes).unwrap();
assert_eq!(d.entries[0].reserved, r);
let mut buf = vec![0u8; d.serialized_len()];
d.serialize_into(&mut buf).unwrap();
assert_eq!(buf, bytes);
}
}
#[test]
fn default_reserved_is_ones() {
let d = TvaIdDescriptor::new(vec![TvaIdEntry::new(0x1234, TvaRunningStatus::Running)]);
let mut buf = vec![0u8; d.serialized_len()];
d.serialize_into(&mut buf).unwrap();
assert_eq!(buf, [TAG, 3, 0x12, 0x34, 0xFC]);
}
#[test]
fn parse_rejects_wrong_tag() {
assert!(matches!(
TvaIdDescriptor::parse(&[0x74, 0]).unwrap_err(),
Error::InvalidDescriptor { tag: 0x74, .. }
));
}
#[test]
fn parse_rejects_length_not_multiple_of_3() {
let bytes = [TAG, 2, 0, 0];
assert!(matches!(
TvaIdDescriptor::parse(&bytes).unwrap_err(),
Error::InvalidDescriptor { .. }
));
}
#[test]
fn empty_descriptor_valid() {
let bytes = [TAG, 0];
let d = TvaIdDescriptor::parse(&bytes).unwrap();
assert!(d.entries.is_empty());
}
#[test]
fn serialize_round_trip() {
let d = TvaIdDescriptor::new(vec![
TvaIdEntry::new(0x1000, TvaRunningStatus::StartsShortly),
TvaIdEntry::new(0xFFFF, TvaRunningStatus::Reserved),
]);
let mut buf = vec![0u8; d.serialized_len()];
d.serialize_into(&mut buf).unwrap();
assert_eq!(TvaIdDescriptor::parse(&buf).unwrap(), d);
}
#[test]
fn serialize_rejects_running_status_over_range() {
let d = TvaIdDescriptor::new(vec![TvaIdEntry::new(
0,
TvaRunningStatus::Unallocated(0x08),
)]);
let mut buf = vec![0u8; d.serialized_len()];
assert!(matches!(
d.serialize_into(&mut buf).unwrap_err(),
Error::InvalidDescriptor { .. }
));
}
#[test]
fn tva_running_status_full_range_round_trip() {
for b in 0..=0xFF_u8 {
let rs = TvaRunningStatus::from_u8(b);
assert_eq!(rs.to_u8(), b, "round-trip failed for byte 0x{b:02X}");
}
}
#[test]
fn tva_running_status_name_for_known() {
assert_eq!(TvaRunningStatus::NotYetRunning.name(), "not yet running");
assert_eq!(TvaRunningStatus::Running.name(), "running");
assert_eq!(TvaRunningStatus::Completed.name(), "completed");
assert_eq!(TvaRunningStatus::Unallocated(0x07).name(), "unallocated");
}
}