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
use std::cmp::PartialOrd;
use signalo_traits::Filter;
use signalo_traits::{
Config as ConfigTrait, ConfigClone, ConfigRef, FromGuts, Guts, IntoGuts, Reset, WithConfig,
};
#[cfg(feature = "derive_reset_mut")]
use signalo_traits::ResetMut;
#[derive(Clone, Debug)]
pub struct Config<T, U> {
pub threshold: T,
pub outputs: [U; 2],
}
#[derive(Clone, Debug)]
pub struct Threshold<T, U> {
config: Config<T, U>,
}
impl<T, U> ConfigTrait for Threshold<T, U> {
type Config = Config<T, U>;
}
impl<T, U> WithConfig for Threshold<T, U> {
type Output = Self;
fn with_config(config: Self::Config) -> Self::Output {
Self { config }
}
}
impl<T, U> ConfigRef for Threshold<T, U> {
fn config_ref(&self) -> &Self::Config {
&self.config
}
}
impl<T, U> ConfigClone for Threshold<T, U>
where
Config<T, U>: Clone,
{
fn config(&self) -> Self::Config {
self.config.clone()
}
}
impl<T, U> Guts for Threshold<T, U> {
type Guts = Config<T, U>;
}
impl<T, U> FromGuts for Threshold<T, U> {
fn from_guts(guts: Self::Guts) -> Self {
let config = guts;
Self { config }
}
}
impl<T, U> IntoGuts for Threshold<T, U> {
fn into_guts(self) -> Self::Guts {
self.config
}
}
impl<T, U> Reset for Threshold<T, U> {
fn reset(self) -> Self {
self
}
}
#[cfg(feature = "derive_reset_mut")]
impl<T, U> ResetMut for Threshold<T, U> where Self: Reset {}
impl<T, U> Filter<T> for Threshold<T, U>
where
T: PartialOrd<T>,
U: Clone,
{
type Output = U;
fn filter(&mut self, input: T) -> Self::Output {
let index = (input >= self.config.threshold) as usize;
self.config.outputs[index].clone()
}
}
#[cfg(test)]
mod tests {
use super::*;
use classify::Classification;
#[test]
fn test() {
let filter = Threshold::with_config(Config {
threshold: 10,
outputs: u8::classes(),
});
let input = vec![
0, 1, 7, 2, 5, 8, 16, 3, 19, 6, 14, 9, 9, 17, 17, 4, 12, 20, 20, 7,
];
let output: Vec<_> = input
.iter()
.scan(filter, |filter, &input| Some(filter.filter(input)))
.collect();
assert_eq!(
output,
vec![0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 1, 0, 0, 1, 1, 0, 1, 1, 1, 0]
);
}
}