Skip to main content

lib_jsl_dsp/discrete/digital_communications/
addressable_shift_register.rs

1//! Addressable shift register: a fixed-length delay line whose every stage can be read or written
2//! by address, the building block of tapped delay lines, FIR structures and LFSR-like blocks.
3//!
4//! Address 0 is the newest stage and address `capacity - 1` the oldest. Pushing a value shifts every
5//! stage by one (the old contents move to higher addresses) and returns the value that falls off
6//! the end. The implementation is a circular buffer, so a push is `O(1)` regardless of length.
7//!
8//! See the book entry [DSP: synchronisation, communications, radar and controls](https://jwkunz.github.io/lib_jsl/book/comms/index.html#addressable-shift-register).
9
10use crate::discrete::stream_operator::{StreamOperator, StreamOperatorManagement};
11use lib_jsl_core::ErrorsJSL;
12
13/// A shift register of `capacity` stages with random access to every stage.
14#[derive(Clone, Debug, PartialEq)]
15pub struct AddressableShiftRegister<T: Clone> {
16    data: Vec<T>,
17    /// Index in `data` of the newest stage (address 0).
18    head: usize,
19    initial: T,
20}
21
22impl<T: Clone> AddressableShiftRegister<T> {
23    /// A register of `capacity` stages (at least 1), every stage holding `initial`.
24    pub fn new(capacity: usize, initial: T) -> Result<Self, ErrorsJSL> {
25        if capacity == 0 {
26            return Err(ErrorsJSL::InvalidInputRange("A shift register needs at least one stage"));
27        }
28        Ok(AddressableShiftRegister { data: vec![initial.clone(); capacity], head: 0, initial })
29    }
30
31    pub fn capacity(&self) -> usize {
32        self.data.len()
33    }
34
35    fn index(&self, address: usize) -> usize {
36        (self.head + address) % self.data.len()
37    }
38
39    /// Shifts in `value` at address 0 and returns the value shifted out of the last stage.
40    pub fn push(&mut self, value: T) -> T {
41        // The oldest stage is the one just before the head; overwriting it makes it the new head.
42        self.head = (self.head + self.data.len() - 1) % self.data.len();
43        std::mem::replace(&mut self.data[self.head], value)
44    }
45
46    /// The value at `address` (0 = newest), or `None` if out of range.
47    pub fn get(&self, address: usize) -> Option<&T> {
48        if address < self.data.len() { Some(&self.data[self.index(address)]) } else { None }
49    }
50
51    /// Overwrites the value at `address`; fails if the address is out of range.
52    pub fn set(&mut self, address: usize, value: T) -> Result<(), ErrorsJSL> {
53        if address >= self.data.len() {
54            return Err(ErrorsJSL::InvalidInputRange("Shift register address out of range"));
55        }
56        let i = self.index(address);
57        self.data[i] = value;
58        Ok(())
59    }
60
61    /// The values at several addresses (a tapped delay line read). Fails on any bad address.
62    pub fn taps(&self, addresses: &[usize]) -> Result<Vec<T>, ErrorsJSL> {
63        addresses.iter().map(|&a| self.get(a).cloned().ok_or(ErrorsJSL::InvalidInputRange("Shift register address out of range"))).collect()
64    }
65
66    /// Iterates from the newest stage to the oldest.
67    pub fn iter(&self) -> impl Iterator<Item = &T> + '_ {
68        (0..self.data.len()).map(move |a| &self.data[self.index(a)])
69    }
70
71    /// The contents ordered newest first.
72    pub fn to_vec(&self) -> Vec<T> {
73        self.iter().cloned().collect()
74    }
75
76    /// Resets every stage to the initial value.
77    pub fn clear(&mut self) {
78        for v in self.data.iter_mut() {
79            *v = self.initial.clone();
80        }
81        self.head = 0;
82    }
83}
84
85impl<T: Clone> StreamOperatorManagement for AddressableShiftRegister<T> {
86    fn reset(&mut self) -> Result<(), ErrorsJSL> {
87        self.clear();
88        Ok(())
89    }
90
91    fn finalize(&mut self) -> Result<(), ErrorsJSL> {
92        Ok(())
93    }
94}
95
96/// As a stream operator the register is a pure delay: each output is the input from `capacity`
97/// samples earlier (the initial value for the first `capacity` outputs).
98impl<T: Clone> StreamOperator<T, T> for AddressableShiftRegister<T> {
99    fn process(&mut self, data_in: &[T]) -> Result<Option<Vec<T>>, ErrorsJSL> {
100        if data_in.is_empty() {
101            return Ok(None);
102        }
103        Ok(Some(data_in.iter().map(|x| self.push(x.clone())).collect()))
104    }
105
106    fn flush(&mut self) -> Result<Option<Vec<T>>, ErrorsJSL> {
107        Ok(None)
108    }
109}
110
111#[cfg(test)]
112mod tests {
113    use super::*;
114
115    #[test]
116    fn push_shifts_and_returns_the_dropped_value() {
117        let mut r = AddressableShiftRegister::new(3, 0).unwrap();
118        assert_eq!(r.push(1), 0);
119        assert_eq!(r.push(2), 0);
120        assert_eq!(r.push(3), 0);
121        assert_eq!(r.to_vec(), vec![3, 2, 1]);
122        assert_eq!(r.push(4), 1, "the oldest value falls off the end");
123        assert_eq!(r.to_vec(), vec![4, 3, 2]);
124        assert_eq!((r.get(0), r.get(2), r.get(3)), (Some(&4), Some(&2), None));
125    }
126
127    #[test]
128    fn addressing_set_taps_and_wraparound() {
129        let mut r = AddressableShiftRegister::new(5, 0.0).unwrap();
130        for i in 1..=12 {
131            r.push(i as f64);
132        }
133        assert_eq!(r.to_vec(), vec![12.0, 11.0, 10.0, 9.0, 8.0], "correct after many wraps of the circular buffer");
134        r.set(2, -1.0).unwrap();
135        assert_eq!(r.taps(&[0, 2, 4]).unwrap(), vec![12.0, -1.0, 8.0]);
136        assert!(r.set(5, 0.0).is_err());
137        assert!(r.taps(&[1, 9]).is_err());
138        r.push(13.0);
139        assert_eq!(r.to_vec(), vec![13.0, 12.0, 11.0, -1.0, 9.0], "writes shift along with the data");
140    }
141
142    #[test]
143    fn behaves_like_a_delay_line_through_the_stream_interface() {
144        let mut r = AddressableShiftRegister::new(4, 0).unwrap();
145        let y = r.process(&[1, 2, 3, 4, 5, 6]).unwrap().unwrap();
146        assert_eq!(y, vec![0, 0, 0, 0, 1, 2]);
147        StreamOperatorManagement::reset(&mut r).unwrap();
148        assert_eq!(r.to_vec(), vec![0; 4]);
149        assert!(r.process(&[]).unwrap().is_none() && r.flush().unwrap().is_none());
150    }
151
152    #[test]
153    fn single_stage_and_invalid_capacity() {
154        let mut r = AddressableShiftRegister::new(1, 'a').unwrap();
155        assert_eq!(r.push('b'), 'a');
156        assert_eq!(r.push('c'), 'b');
157        assert_eq!(r.to_vec(), vec!['c']);
158        assert!(AddressableShiftRegister::new(0, 0).is_err());
159    }
160}