1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
use {Code, CodeType, b2, b1};

/// Trait for convolutional encoders.
pub trait Encoder {
  fn encode(&self, signal: &Vec<b1>) -> Vec<b1>;
}

/// Encoder implementation for convolutional codes. Matches on code type,
/// computing FIR and IIR codes separately.
///
/// # Examples
///
/// ```
/// use turbo::{Code, CodeType, b2, b1, ONE, ZERO};
/// use turbo::encoders::Encoder;
/// let toy_code = Code {
///   start_state: b2::new([ZERO, ZERO]),
///   polys: vec![b2::new([ZERO, ONE]),
///               b2::new([ONE, ZERO])],
///   code_type: CodeType::FIRCode
/// };
///
/// let toy_signal = vec![ONE, ONE];
/// let encoded_signal = toy_code.encode(&toy_signal);
///
/// assert_eq!(encoded_signal, vec![ZERO, ONE,
///                                 ONE, ONE]);
/// ```
impl Encoder for Code {
  fn encode(&self, signal: &Vec<b1>) -> Vec<b1> {
    match self.code_type {
      CodeType::FIRCode => encode_fir(self, signal),
      CodeType::IIRCode => encode_iir(self, signal)
    }
  }
}

fn encode_fir(code: &Code, signal: &Vec<b1>) -> Vec<b1> {
  signal.iter().scan(code.start_state, |state, sig_bit| {
    // TODO remove this allocation (collect call)
    let adder_outputs: Vec<_> =
      code.polys.iter().map(|code_poly| {
        poly_add(*code_poly, &[state[1], *sig_bit])
      }).collect();
    
    *state = shift_concat(*state, *sig_bit);
    Some(adder_outputs)
  }).flat_map(|x| x).collect()
}

fn encode_iir(code: &Code, signal: &Vec<b1>) -> Vec<b1> {
  signal.iter().scan(code.start_state, |state, sig_bit| {
    // TODO remove this allocation (collect call)
    let adder_outputs: Vec<_> =
      code.polys.iter().map(|code_poly| {
        poly_add(*code_poly, &[state[1], *sig_bit])
      }).collect();
    
    *state = shift_concat(*state, adder_outputs[adder_outputs.len()-1]);
    Some(adder_outputs)
  }).flat_map(|x| x).collect()
}

// XOR addition functions on sections of the signal or output weighted by the
// code polynomial.
fn poly_add(code_vec: b2, sig_arr: &[b1]) -> b1 {
  sig_arr.iter().rev().zip(code_vec.bits().iter())
                      .map(|(&sig, &code)| sig & code)
                      .fold(b1(false), |accum, val| accum ^ val)
}

// Shifts a bit array once, and pushes another value onto it.
fn shift_concat(bin: b2, val: b1) -> b2 {
  let mut shifted_bin = bin << 1;
  shifted_bin[bin.len() - 1] = val;
  shifted_bin
}