raptor_code/decoder.rs
1use alloc::vec::Vec;
2
3use crate::encodingsymbols::EncodingSymbol;
4use crate::raptor;
5
6/// A struct that represents a source block decoder that uses Raptor codes.
7pub struct SourceBlockDecoder {
8 raptor: raptor::Raptor,
9}
10
11impl SourceBlockDecoder {
12 /// Create a new decoder
13 ///
14 /// # Arguments
15 ///
16 /// * `nb_source_symbols` - Number of source symbols in the block
17 ///
18 /// # Returns
19 ///
20 /// * A new `SourceBlockDecoder` instance
21 pub fn new(nb_source_symbols: usize) -> Self {
22 SourceBlockDecoder {
23 raptor: raptor::Raptor::new(nb_source_symbols as u32),
24 }
25 }
26
27 /// Push an encoding symbol to the decoder
28 ///
29 /// # Arguments
30 ///
31 /// * `encoding_symbol` - A slice of u8 numbers representing the encoding
32 /// symbol data
33 /// * `esi` - Encoding symbol identifier (ESI)
34 pub fn push_encoding_symbol(&mut self, encoding_symbol: &[u8], esi: u32) {
35 let encoding_symbol = EncodingSymbol::new(encoding_symbol, esi);
36 self.raptor.add_encoding_symbol(&encoding_symbol);
37 }
38
39 /// Return true when the block can be fully decoded
40 pub fn fully_specified(&self) -> bool {
41 self.raptor.fully_specified()
42 }
43
44 /// Decode the source block
45 ///
46 ///
47 /// # Parameters
48 ///
49 /// * `source_block_length`: The size of the source block in bytes.
50 /// * `encoding_symbol_size`: Size of an encoding symbol
51 ///
52 /// # Returns
53 ///
54 /// * `None` if the source block cannot be decoded
55 /// * `Some(Vec<u8>)` if the block is decoded. The vector contains the
56 /// decoded source block data
57 pub fn decode(&mut self, source_block_length: usize) -> Option<Vec<u8>> {
58 self.raptor.decode(source_block_length)
59 }
60}
61
62/// Decodes a source block from a given set of available encoding symbols.
63///
64/// # Parameters
65///
66/// * `encoding_symbols`: A list of available encoding symbols. Missing encoding
67/// symbols should be represented as `None`.
68/// * `nb_source_symbols`: The number of source symbols in the block (k).
69/// * `source_block_length`: The size of the source block in bytes.
70///
71/// # Returns
72///
73/// A vector of bytes representing the decoded source block, or `None` if the
74/// source block cannot be decoded. The function uses the available encoding
75/// symbols to reconstruct the original source block.
76pub fn decode_source_block(
77 encoding_symbols: &[Option<Vec<u8>>],
78 nb_source_symbols: usize,
79 source_block_length: usize,
80) -> Option<Vec<u8>> {
81 let encoding_symbols = EncodingSymbol::from_option_block(encoding_symbols);
82 let mut raptor = raptor::Raptor::new(nb_source_symbols as u32);
83 raptor.add_encoding_symbols(&encoding_symbols);
84 raptor.decode(source_block_length)
85}