lib_jsl_information/lfsr/linear_feedback_shift_register.rs
1//! Linear feedback shift register (LFSR).
2//!
3//! See the book entry [LFSRs and Gold codes](https://jwkunz.github.io/lib_jsl/book/information/lfsr.html#the-recurrence-and-its-polynomial).
4
5/// A Fibonacci-style linear feedback shift register of up to 64 stages.
6///
7/// The register holds the bits `s_t ... s_{t+n-1}` of a sequence in the low `width` bits of
8/// `state` (bit 0 is the oldest, `s_t`). Each step emits `s_t` and shifts in the new bit
9/// `s_{t+n} = parity(state & taps)`, i.e. `taps` has bit `k` set when `s_{t+k}` participates in
10/// the recurrence. For the characteristic polynomial `x^n + c_{n-1} x^{n-1} + ... + c_0`, the
11/// `taps` mask is exactly the polynomial with its `x^n` term removed (see
12/// [`Lfsr::from_polynomial`]).
13#[derive(Clone, Debug, PartialEq, Eq)]
14pub struct Lfsr {
15 /// Current register contents (low `width` bits).
16 pub state: u64,
17 /// Feedback tap mask.
18 pub taps: u64,
19 /// Number of stages (1..=64).
20 pub width: u32,
21}
22
23impl Lfsr {
24 /// Creates a register. Panics if `width` is 0 or greater than 64.
25 pub fn new(width: u32, taps: u64, seed: u64) -> Self {
26 assert!((1..=64).contains(&width), "LFSR width must be between 1 and 64");
27 let m = Self::mask(width);
28 Lfsr { state: seed & m, taps: taps & m, width }
29 }
30
31 /// Creates a register from a characteristic polynomial given as a bit mask (bit `k` is the
32 /// coefficient of `x^k`; the leading `x^n` bit determines the width). E.g. `x^3 + x + 1` is
33 /// `0b1011`.
34 pub fn from_polynomial(poly: u64, seed: u64) -> Self {
35 assert!(poly > 1, "polynomial must have degree >= 1");
36 let width = 63 - poly.leading_zeros();
37 Self::new(width, poly & !(1u64 << width), seed)
38 }
39
40 fn mask(width: u32) -> u64 {
41 if width == 64 { u64::MAX } else { (1u64 << width) - 1 }
42 }
43
44 /// Advances the register one step and returns the output bit.
45 // ANCHOR: lfsr_step
46 pub fn step(&mut self) -> u8 {
47 let out = (self.state & 1) as u8;
48 let fb = ((self.state & self.taps).count_ones() & 1) as u64;
49 self.state = (self.state >> 1) | (fb << (self.width - 1));
50 out
51 }
52 // ANCHOR_END: lfsr_step
53
54 /// Returns the next `n` output bits.
55 pub fn bits(&mut self, n: usize) -> Vec<u8> {
56 (0..n).map(|_| self.step()).collect()
57 }
58
59 /// Returns the sequence period starting from the current state (the number of steps until the
60 /// state repeats), or `None` if the state never returns to itself within `limit` steps (as
61 /// happens for the all-zero state's trivial period of 1, which is reported as `Some(1)`).
62 pub fn period(&self, limit: u64) -> Option<u64> {
63 let mut copy = self.clone();
64 let start = copy.state;
65 for i in 1..=limit {
66 copy.step();
67 if copy.state == start {
68 return Some(i);
69 }
70 }
71 None
72 }
73}
74
75impl Iterator for Lfsr {
76 type Item = u8;
77 fn next(&mut self) -> Option<u8> {
78 Some(self.step())
79 }
80}
81
82#[cfg(test)]
83mod tests {
84 use super::*;
85
86 #[test]
87 fn x3_plus_x_plus_1_sequence() {
88 // s_{t+3} = s_t + s_{t+1}; seed s0..s2 = 1,0,0 -> 1 0 0 1 0 1 1 | repeat
89 let mut r = Lfsr::from_polynomial(0b1011, 0b001);
90 assert_eq!(r.bits(14), vec![1, 0, 0, 1, 0, 1, 1, 1, 0, 0, 1, 0, 1, 1]);
91 }
92
93 #[test]
94 fn period_and_state_space() {
95 let r = Lfsr::from_polynomial(0b1011, 1);
96 assert_eq!(r.period(100), Some(7));
97 // x^4 + x + 1 is primitive: period 15; x^4 + x^2 + 1 = (x^2+x+1)^2 is not.
98 assert_eq!(Lfsr::from_polynomial(0b10011, 1).period(100), Some(15));
99 assert!(Lfsr::from_polynomial(0b10101, 1).period(100).unwrap() < 15);
100 // All-zero state is a fixed point.
101 assert_eq!(Lfsr::from_polynomial(0b1011, 0).period(10), Some(1));
102 }
103
104 #[test]
105 fn balance_of_m_sequence() {
106 // An m-sequence has 2^(n-1) ones and 2^(n-1) - 1 zeros per period.
107 let ones: u32 = Lfsr::from_polynomial(0b100101, 1).bits(31).iter().map(|&b| b as u32).sum();
108 assert_eq!(ones, 16);
109 }
110
111 #[test]
112 fn iterator_and_width_64() {
113 let r = Lfsr::new(64, (1 << 63) | 1, 1);
114 assert_eq!(r.take(5).count(), 5);
115 }
116}