Skip to main content

cu_fec/
wire.rs

1//! RFC 8681 FEC Scheme-Specific Information and payload identifiers.
2
3use core::fmt;
4
5use crate::{DensityThreshold, EncodingSymbolId};
6
7/// An error in RFC 8681 wire metadata.
8#[derive(Clone, Copy, Debug, Eq, PartialEq)]
9pub enum WireError {
10    /// A byte slice does not have the required fixed wire length.
11    InvalidLength {
12        /// Required byte count.
13        expected: usize,
14        /// Supplied byte count.
15        actual: usize,
16    },
17    /// A repair window must contain at least one source symbol.
18    EmptyRepairWindow,
19    /// The 12-bit NSS field cannot represent the requested window size.
20    RepairWindowTooLarge,
21}
22
23impl fmt::Display for WireError {
24    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
25        match self {
26            Self::InvalidLength { expected, actual } => {
27                write!(formatter, "expected {expected} bytes, received {actual}")
28            }
29            Self::EmptyRepairWindow => formatter.write_str("repair window must not be empty"),
30            Self::RepairWindowTooLarge => {
31                formatter.write_str("repair window exceeds the 12-bit NSS field")
32            }
33        }
34    }
35}
36
37impl core::error::Error for WireError {}
38
39/// The three-octet RFC 8681 FEC Scheme-Specific Information value.
40#[derive(Clone, Copy, Debug, Eq, PartialEq)]
41pub struct FecSchemeSpecificInfo {
42    symbol_size: u16,
43    window_size_ratio: u8,
44}
45
46impl TryFrom<&[u8]> for FecSchemeSpecificInfo {
47    type Error = WireError;
48
49    fn try_from(bytes: &[u8]) -> Result<Self, Self::Error> {
50        let bytes: [u8; 3] = bytes.try_into().map_err(|_| WireError::InvalidLength {
51            expected: 3,
52            actual: bytes.len(),
53        })?;
54        Ok(Self::from_bytes(bytes))
55    }
56}
57
58impl From<FecSchemeSpecificInfo> for [u8; 3] {
59    fn from(value: FecSchemeSpecificInfo) -> Self {
60        value.to_bytes()
61    }
62}
63
64impl From<[u8; 3]> for FecSchemeSpecificInfo {
65    fn from(bytes: [u8; 3]) -> Self {
66        Self::from_bytes(bytes)
67    }
68}
69
70impl FecSchemeSpecificInfo {
71    /// Creates scheme-specific information from the symbol size and WSR value.
72    pub const fn new(symbol_size: u16, window_size_ratio: u8) -> Self {
73        Self {
74            symbol_size,
75            window_size_ratio,
76        }
77    }
78
79    /// Returns the encoding symbol size in bytes.
80    pub const fn symbol_size(self) -> u16 {
81        self.symbol_size
82    }
83
84    /// Returns the window size ratio, where zero means unspecified.
85    pub const fn window_size_ratio(self) -> u8 {
86        self.window_size_ratio
87    }
88
89    /// Encodes the value in network byte order.
90    pub const fn to_bytes(self) -> [u8; 3] {
91        let size = self.symbol_size.to_be_bytes();
92        [size[0], size[1], self.window_size_ratio]
93    }
94
95    /// Decodes a value in network byte order.
96    pub const fn from_bytes(bytes: [u8; 3]) -> Self {
97        Self::new(u16::from_be_bytes([bytes[0], bytes[1]]), bytes[2])
98    }
99}
100
101/// The four-octet Explicit Source FEC Payload ID from RFC 8681.
102#[derive(Clone, Copy, Debug, Eq, PartialEq)]
103pub struct SourcePayloadId {
104    esi: EncodingSymbolId,
105}
106
107impl SourcePayloadId {
108    /// Creates an identifier for an encoding symbol.
109    pub const fn new(esi: EncodingSymbolId) -> Self {
110        Self { esi }
111    }
112
113    /// Returns the Encoding Symbol ID (ESI).
114    pub const fn esi(self) -> EncodingSymbolId {
115        self.esi
116    }
117
118    /// Encodes the identifier in network byte order.
119    pub const fn to_bytes(self) -> [u8; 4] {
120        self.esi.get().to_be_bytes()
121    }
122
123    /// Decodes an identifier in network byte order.
124    pub const fn from_bytes(bytes: [u8; 4]) -> Self {
125        Self::new(EncodingSymbolId::new(u32::from_be_bytes(bytes)))
126    }
127}
128
129impl TryFrom<&[u8]> for SourcePayloadId {
130    type Error = WireError;
131
132    fn try_from(bytes: &[u8]) -> Result<Self, Self::Error> {
133        let bytes: [u8; 4] = bytes.try_into().map_err(|_| WireError::InvalidLength {
134            expected: 4,
135            actual: bytes.len(),
136        })?;
137        Ok(Self::from_bytes(bytes))
138    }
139}
140
141impl From<SourcePayloadId> for [u8; 4] {
142    fn from(value: SourcePayloadId) -> Self {
143        value.to_bytes()
144    }
145}
146
147impl From<[u8; 4]> for SourcePayloadId {
148    fn from(bytes: [u8; 4]) -> Self {
149        Self::from_bytes(bytes)
150    }
151}
152
153/// The eight-octet Repair FEC Payload ID from RFC 8681.
154#[derive(Clone, Copy, Debug, Eq, PartialEq)]
155pub struct RepairPayloadId {
156    repair_key: u16,
157    density: DensityThreshold,
158    source_symbols: u16,
159    first_source_esi: EncodingSymbolId,
160}
161
162impl RepairPayloadId {
163    /// Creates a repair payload identifier.
164    pub const fn new(
165        repair_key: u16,
166        density: DensityThreshold,
167        source_symbols: u16,
168        first_source_esi: EncodingSymbolId,
169    ) -> Result<Self, WireError> {
170        if source_symbols == 0 {
171            return Err(WireError::EmptyRepairWindow);
172        }
173        if source_symbols > 0x0fff {
174            return Err(WireError::RepairWindowTooLarge);
175        }
176        Ok(Self {
177            repair_key,
178            density,
179            source_symbols,
180            first_source_esi,
181        })
182    }
183
184    /// Returns the coefficient-generator seed.
185    pub const fn repair_key(self) -> u16 {
186        self.repair_key
187    }
188
189    /// Returns the coding-coefficient density threshold.
190    pub const fn density(self) -> DensityThreshold {
191        self.density
192    }
193
194    /// Returns the number of source symbols in the encoding window.
195    pub const fn source_symbols(self) -> u16 {
196        self.source_symbols
197    }
198
199    /// Returns the ESI of the first source symbol in the encoding window.
200    pub const fn first_source_esi(self) -> EncodingSymbolId {
201        self.first_source_esi
202    }
203
204    /// Advances the repair key for another symbol packed in the same packet.
205    pub const fn for_symbol_offset(self, offset: u16) -> Self {
206        Self {
207            repair_key: self.repair_key.wrapping_add(offset),
208            ..self
209        }
210    }
211
212    /// Encodes the identifier in network byte order.
213    pub const fn to_bytes(self) -> [u8; 8] {
214        let key = self.repair_key.to_be_bytes();
215        let density_and_count =
216            (((self.density.get() as u16) << 12) | self.source_symbols).to_be_bytes();
217        let first = self.first_source_esi.get().to_be_bytes();
218        [
219            key[0],
220            key[1],
221            density_and_count[0],
222            density_and_count[1],
223            first[0],
224            first[1],
225            first[2],
226            first[3],
227        ]
228    }
229
230    /// Decodes an identifier in network byte order.
231    pub fn from_bytes(bytes: [u8; 8]) -> Result<Self, WireError> {
232        let repair_key = u16::from_be_bytes([bytes[0], bytes[1]]);
233        let density_and_count = u16::from_be_bytes([bytes[2], bytes[3]]);
234        let density = DensityThreshold::new((density_and_count >> 12) as u8)
235            .expect("a four-bit density is always valid");
236        let source_symbols = density_and_count & 0x0fff;
237        let first_source_esi =
238            EncodingSymbolId::new(u32::from_be_bytes([bytes[4], bytes[5], bytes[6], bytes[7]]));
239        Self::new(repair_key, density, source_symbols, first_source_esi)
240    }
241}
242
243impl TryFrom<&[u8]> for RepairPayloadId {
244    type Error = WireError;
245
246    fn try_from(bytes: &[u8]) -> Result<Self, Self::Error> {
247        let bytes: [u8; 8] = bytes.try_into().map_err(|_| WireError::InvalidLength {
248            expected: 8,
249            actual: bytes.len(),
250        })?;
251        Self::from_bytes(bytes)
252    }
253}
254
255impl TryFrom<[u8; 8]> for RepairPayloadId {
256    type Error = WireError;
257
258    fn try_from(bytes: [u8; 8]) -> Result<Self, Self::Error> {
259        Self::from_bytes(bytes)
260    }
261}
262
263impl From<RepairPayloadId> for [u8; 8] {
264    fn from(value: RepairPayloadId) -> Self {
265        value.to_bytes()
266    }
267}
268
269#[cfg(test)]
270mod tests {
271    use super::*;
272    use crate::Field;
273
274    #[test]
275    fn wire_values_are_big_endian_and_round_trip() {
276        let info = FecSchemeSpecificInfo::new(0x0578, 191);
277        assert_eq!(info.to_bytes(), [0x05, 0x78, 191]);
278        assert_eq!(FecSchemeSpecificInfo::from_bytes(info.to_bytes()), info);
279
280        let source = SourcePayloadId::new(EncodingSymbolId::new(0x1234_5678));
281        assert_eq!(source.to_bytes(), [0x12, 0x34, 0x56, 0x78]);
282        assert_eq!(SourcePayloadId::from_bytes(source.to_bytes()), source);
283
284        let repair = RepairPayloadId::new(
285            0x1234,
286            DensityThreshold::new(10).unwrap(),
287            0x0bcd,
288            EncodingSymbolId::new(0x89ab_cdef),
289        )
290        .unwrap();
291        assert_eq!(
292            repair.to_bytes(),
293            [0x12, 0x34, 0xab, 0xcd, 0x89, 0xab, 0xcd, 0xef]
294        );
295        assert_eq!(RepairPayloadId::from_bytes(repair.to_bytes()), Ok(repair));
296        assert_eq!(repair.for_symbol_offset(u16::MAX).repair_key(), 0x1233);
297        assert_eq!(Field::Gf2.fec_encoding_id(), 9);
298        assert_eq!(Field::Gf256.fec_encoding_id(), 10);
299
300        assert_eq!(
301            FecSchemeSpecificInfo::try_from(info.to_bytes().as_slice()),
302            Ok(info)
303        );
304        assert_eq!(
305            SourcePayloadId::try_from(source.to_bytes().as_slice()),
306            Ok(source)
307        );
308        assert_eq!(
309            RepairPayloadId::try_from(repair.to_bytes().as_slice()),
310            Ok(repair)
311        );
312    }
313
314    #[test]
315    fn rejects_unrepresentable_windows() {
316        assert_eq!(
317            RepairPayloadId::new(0, DensityThreshold::FULL, 0, EncodingSymbolId::new(0)),
318            Err(WireError::EmptyRepairWindow)
319        );
320        assert_eq!(
321            RepairPayloadId::new(0, DensityThreshold::FULL, 4096, EncodingSymbolId::new(0),),
322            Err(WireError::RepairWindowTooLarge)
323        );
324        assert_eq!(
325            RepairPayloadId::from_bytes([0; 8]),
326            Err(WireError::EmptyRepairWindow)
327        );
328        assert_eq!(
329            SourcePayloadId::try_from([0_u8; 3].as_slice()),
330            Err(WireError::InvalidLength {
331                expected: 4,
332                actual: 3,
333            })
334        );
335    }
336}