rustradio/add_const.rs
1//! Add a constant value to every sample.
2use crate::Sample;
3use crate::stream::{ReadStream, WriteStream};
4
5/// Add const value, implemented in terms of Map.
6///
7/// This is basically example code. We have AddConst and add_const doing the
8/// same thing.
9pub fn add_const<T>(
10 src: ReadStream<T>,
11 val: T,
12) -> (crate::convert::Map<T, T, impl Fn(T) -> T>, ReadStream<T>)
13where
14 T: Sample + std::ops::Add<Output = T>,
15{
16 crate::convert::Map::new(src, "add_const", move |x| x + val)
17}
18
19/// AddConst adds a constant value to every sample.
20///
21/// Tags are preserved.
22///
23/// ```
24/// use rustradio::graph::{Graph, GraphRunner};
25/// use rustradio::blocks::{ConstantSource, SignalSourceFloat, AddConst, NullSink};
26///
27/// let mut graph = Graph::new();
28///
29/// // Add a constant value. Could just as well use AddConst instead of Add.
30/// let (src, src_out) = SignalSourceFloat::new(44100.0, 1000.0, 1.0);
31///
32/// // Sum up the streams.
33/// let (sum, sum_out) = AddConst::new(src_out, 1.0);
34///
35/// graph.add(Box::new(src));
36/// graph.add(Box::new(sum));
37///
38/// // Set up dummy sink.
39/// let sink = NullSink::new(sum_out);
40/// # return Ok(());
41/// graph.run()?;
42/// # Ok::<(), anyhow::Error>(())
43/// ```
44#[derive(rustradio_macros::Block)]
45#[rustradio(crate, new, sync)]
46pub struct AddConst<T: Sample + std::ops::Add<Output = T>> {
47 val: T,
48 #[rustradio(in)]
49 src: ReadStream<T>,
50 #[rustradio(out)]
51 dst: WriteStream<T>,
52}
53
54impl<T> AddConst<T>
55where
56 T: Sample + std::ops::Add<Output = T>,
57{
58 fn process_sync(&self, a: T) -> T {
59 a + self.val
60 }
61}