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
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
use crate::ring::RingIterator;
use crate::Ring;
use core::ops::{Add, Div, Mul, Sub};

/// Contains min and max value in a `Ring`
#[derive(Debug)]
pub struct Range<T> {
    /// Minimum value
    pub min: T,
    /// Maximum value
    pub max: T,
}

impl<T: PartialOrd> Range<T> {
    /// Creates a Range checking min <= max
    pub fn new(min: T, max: T) -> Option<Self> {
        if min <= max {
            Some(Range { min, max })
        } else {
            None
        }
    }
}

/// Trait defining a `range` method to find min and max in one iteration
pub trait FindRange<T> {
    /// calculate min and max with one iteration
    fn range(&self) -> Option<Range<T>>;
}

impl<T: PartialOrd + Copy + Default, const N: usize> FindRange<T> for Ring<T, N> {
    fn range(&self) -> Option<Range<T>> {
        if self.is_empty() {
            return None;
        }
        let mut iter = self.iter();
        let first = iter.next().unwrap(); // safe because len just checked;
        let mut min_max = Range {
            min: first,
            max: first,
        };
        for el in iter {
            if min_max.min.gt(&el) {
                min_max.min = el;
            }
            if min_max.max.lt(&el) {
                min_max.max = el;
            }
        }

        Some(min_max)
    }
}

#[derive(Debug)]
pub struct RescaleIterator<'a, T, const N: usize> {
    current: Range<T>,
    desired: Range<T>,
    ring_iter: RingIterator<'a, T, N>,
}

impl<
        T: Copy
            + Default
            + PartialOrd
            + Sub<Output = T>
            + Add<Output = T>
            + Mul<Output = T>
            + Div<Output = T>
            + Into<f64>,
        const N: usize,
    > Ring<T, N>
{
    /// Returns an iterator over the `Ring` on which values are rescaled according to the `desired`
    /// range
    pub fn rescaled_iter(&self, current: Range<T>, desired: Range<T>) -> RescaleIterator<T, N> {
        RescaleIterator {
            current,
            desired,
            ring_iter: self.iter(),
        }
    }
}

impl<
        T: Copy
            + Default
            + PartialOrd
            + Sub<Output = T>
            + Add<Output = T>
            + Mul<Output = T>
            + Div<Output = T>
            + Into<f64>,
        const N: usize,
    > Iterator for RescaleIterator<'_, T, N>
{
    type Item = f64;
    // TODO would be nice if type returned is `T`

    fn next(&mut self) -> Option<Self::Item> {
        self.ring_iter.next().map(|el| {
            let mut zero_one =
                (el.into() - self.current.min.into()) / (self.current.delta().into());
            if zero_one.is_nan() {
                zero_one = 0.5;
            }
            zero_one * self.desired.delta().into() + self.desired.min.into()
        })
    }
}

impl<T: Sub<Output = T> + Copy> Range<T> {
    /// Returns the range delta
    pub fn delta(&self) -> T {
        self.max - self.min
    }
}

#[cfg(test)]
mod test {
    use super::{FindRange, Range, Ring};
    const RING_SIZE: usize = 128;

    #[test]
    pub fn test_range() {
        let mut circ: Ring<i32, RING_SIZE> = Ring::new();
        assert!(circ.range().is_none());
        circ.append(0);
        assert_eq!(circ.range().unwrap().min, 0);
        assert_eq!(circ.range().unwrap().max, 0);
        circ.append(1);
        assert_eq!(circ.range().unwrap().min, 0);
        assert_eq!(circ.range().unwrap().max, 1);
        circ.append(-1);
        assert_eq!(circ.range().unwrap().min, -1);
        assert_eq!(circ.range().unwrap().max, 1);
        for _ in 0..RING_SIZE {
            circ.append(0);
        }
        assert_eq!(circ.range().unwrap().min, 0);
        assert_eq!(circ.range().unwrap().max, 0);
    }

    #[test]
    pub fn test_rescale() {
        let mut circ: Ring<i16, RING_SIZE> = Ring::new();
        circ.append(100i16);
        circ.append(200);
        circ.append(300);
        let current = circ.range().unwrap();
        let desired = Range { min: 20, max: 30 };
        let mut rescaled = circ.rescaled_iter(current, desired);
        assert_eq!(rescaled.next().map(|el| el as i16), Some(20i16));
        assert_eq!(rescaled.next().map(|el| el as i16), Some(25i16));
        assert_eq!(rescaled.next().map(|el| el as i16), Some(30i16));
        assert_eq!(rescaled.next(), None);
    }
}