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
//! Peak envelope detection over a signal.
//!
//! The primary type of interest in this module is the [**Peak**](./struct.Peak) type, generic
//! over any [**Rectifier**](./trait.Rectifier).

use std::marker::PhantomData;


/// A rectifier that produces only the positive samples from a signal.
#[derive(Copy, Clone, Debug, PartialEq)]
pub enum PositiveHalfWave {}
/// A rectifier that produces only the negative samples from a signal.
#[derive(Copy, Clone, Debug, PartialEq)]
pub enum NegativeHalfWave {}
/// A rectifier that produces the absolute amplitude from samples from a signal.
#[derive(Copy, Clone, Debug, PartialEq)]
pub enum FullWave {}


/// Types that can rectify some incoming signal.
pub trait Rectifier {
    /// Rectify a single sample of some incoming signal.
    fn rectify(sample: f32) -> f32;
}

impl Rectifier for PositiveHalfWave {
    #[inline]
    fn rectify(sample: f32) -> f32 {
        if sample < 0.0 { 0.0 } else { sample }
    }
}

impl Rectifier for NegativeHalfWave {
    #[inline]
    fn rectify(sample: f32) -> f32 {
        if sample > 0.0 { 0.0 } else { sample }
    }
}

impl Rectifier for FullWave {
    #[inline]
    fn rectify(sample: f32) -> f32 {
        sample.abs()
    }
}


/// A peak rectifier, generic over **FullWave**, **PositiveHalfWave** and **NegativeHalfWave**
/// rectification.
///
/// It produces a peak-following envelope when rectify is called over a signal of samples.
#[derive(Copy, Clone, Debug, PartialEq)]
pub struct Peak<R=FullWave> {
    rectifier: PhantomData<R>,
}

impl Peak<FullWave> {
    /// A full-wave peak rectifier.
    pub fn full_wave() -> Peak<FullWave> {
        Peak {
            rectifier: PhantomData,
        }
    }
}

impl Peak<PositiveHalfWave> {
    /// A positive half-wave peak rectifier.
    pub fn positive_half_wave() -> Peak<PositiveHalfWave> {
        Peak {
            rectifier: PhantomData,
        }
    }
}

impl Peak<NegativeHalfWave> {
    /// A negative half-wave peak rectifier.
    pub fn negative_half_wave() -> Peak<NegativeHalfWave> {
        Peak {
            rectifier: PhantomData,
        }
    }
}

impl<R> Peak<R> {
    /// Return the rectified sample.
    #[inline]
    pub fn rectify(sample: f32) -> f32 where R: Rectifier {
        R::rectify(sample)
    }
}