Skip to content

Commit

Permalink
allow typed blocks in flowgraph api
Browse files Browse the repository at this point in the history
  • Loading branch information
bastibl committed Nov 15, 2024
1 parent 8e643c6 commit 1204ef1
Show file tree
Hide file tree
Showing 18 changed files with 42 additions and 87 deletions.
2 changes: 1 addition & 1 deletion benches/apply.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ pub fn apply(c: &mut Criterion) {

group.bench_function(format!("mock-u32-plus-1-{n_samp}"), |b| {
b.iter(|| {
let block = Apply::new_typed(|x: &u32| x + 1);
let block = Apply::new(|x: &u32| x + 1);

let mut mocker = Mocker::new(block);
mocker.input(0, input.clone());
Expand Down
7 changes: 7 additions & 0 deletions crates/macros/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -165,6 +165,8 @@ pub fn connect(attr: proc_macro::TokenStream) -> proc_macro::TokenStream {
use futuresdr::runtime::Block;
use futuresdr::runtime::Error;
use futuresdr::runtime::Flowgraph;
use futuresdr::runtime::Kernel;
use futuresdr::runtime::TypedBlock;
use std::result::Result;

struct FgOp;
Expand All @@ -181,6 +183,11 @@ pub fn connect(attr: proc_macro::TokenStream) -> proc_macro::TokenStream {
fg.add_block(b)
}
}
impl<T: Kernel + 'static> Add<TypedBlock<T>> for FgOp {
fn add(fg: &mut Flowgraph, b: TypedBlock<T>) -> Result<usize, Error> {
fg.add_block(b)
}
}
});

// Add the blocks to the flowgraph
Expand Down
2 changes: 1 addition & 1 deletion examples/egui/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,5 +10,5 @@ use futuresdr::num_complex::Complex32;
use futuresdr::runtime::Block;

pub fn power_block() -> Block {
Apply::new(|x: &Complex32| x.norm_sqr())
Apply::new(|x: &Complex32| x.norm_sqr()).into()
}
6 changes: 1 addition & 5 deletions examples/m17/src/moving_average.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,11 +19,7 @@ pub struct MovingAverage {
}

impl MovingAverage {
pub fn new(len: usize) -> Block {
Block::from_typed(Self::new_typed(len))
}

pub fn new_typed(len: usize) -> TypedBlock<Self> {
pub fn new(len: usize) -> TypedBlock<Self> {
assert!(len > 0);
TypedBlock::new(
BlockMetaBuilder::new("MovingAverage").build(),
Expand Down
2 changes: 1 addition & 1 deletion examples/mock.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ fn main() {
.take(64)
.collect();

let block = Apply::new_typed(|x: &u32| x + 1);
let block = Apply::new(|x: &u32| x + 1);

let mut mocker = Mocker::new(block);
mocker.input(0, input.clone());
Expand Down
6 changes: 3 additions & 3 deletions examples/spectrum/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,13 +11,13 @@ use futuresdr::num_complex::Complex32;
use futuresdr::runtime::Block;

pub fn lin2db_block() -> Block {
Apply::new(|x: &f32| 10.0 * x.log10())
Apply::new(|x: &f32| 10.0 * x.log10()).into()
}

pub fn power_block() -> Block {
Apply::new(|x: &Complex32| x.norm_sqr())
Apply::new(|x: &Complex32| x.norm_sqr()).into()
}

pub fn lin2power_db() -> Block {
Apply::new(|x: &Complex32| 10.0 * x.norm_sqr().log10())
Apply::new(|x: &Complex32| 10.0 * x.norm_sqr().log10()).into()
}
6 changes: 1 addition & 5 deletions examples/wlan/src/moving_average.rs
Original file line number Diff line number Diff line change
Expand Up @@ -45,11 +45,7 @@ pub struct MovingAverage<T: MovingAverageType + Send + 'static> {
}

impl<T: MovingAverageType + Send + 'static> MovingAverage<T> {
pub fn new(len: usize) -> Block {
Block::from_typed(Self::new_typed(len))
}

pub fn new_typed(len: usize) -> TypedBlock<Self> {
pub fn new(len: usize) -> TypedBlock<Self> {
assert!(len > 0);
TypedBlock::new(
BlockMetaBuilder::new("MovingAverage").build(),
Expand Down
11 changes: 1 addition & 10 deletions src/blocks/apply.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
use crate::anyhow::Result;
use crate::runtime::Block;
use crate::runtime::BlockMeta;
use crate::runtime::BlockMetaBuilder;
use crate::runtime::Kernel;
Expand Down Expand Up @@ -68,15 +67,7 @@ where
///
/// ## Parameter
/// - `f`: Function to apply on each sample
pub fn new(f: F) -> Block {
Block::from_typed(Self::new_typed(f))
}

/// Create typed [`Apply`] block
///
/// ## Parameter
/// - `f`: Function to apply on each sample
pub fn new_typed(f: F) -> TypedBlock<Self> {
pub fn new(f: F) -> TypedBlock<Self> {
TypedBlock::new(
BlockMetaBuilder::new("Apply").build(),
StreamIoBuilder::new()
Expand Down
7 changes: 2 additions & 5 deletions src/blocks/combine.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,13 +24,10 @@ use crate::runtime::WorkIo;
/// # Usage
/// ```
/// use futuresdr::blocks::Combine;
/// use futuresdr::runtime::Flowgraph;
///
/// let mut fg = Flowgraph::new();
///
/// let adder = fg.add_block(Combine::new(|a: &f32, b: &f32| {
/// let adder = Combine::new(|a: &f32, b: &f32| {
/// a + b
/// }))?;
/// });
/// ```
#[allow(clippy::type_complexity)]
pub struct Combine<F, A, B, C>
Expand Down
8 changes: 1 addition & 7 deletions src/blocks/message_copy.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
use crate::runtime::Block;
use crate::runtime::BlockMeta;
use crate::runtime::BlockMetaBuilder;
use crate::runtime::Kernel;
Expand All @@ -14,12 +13,7 @@ pub struct MessageCopy {}

impl MessageCopy {
/// Create MessageCopy block
pub fn new() -> Block {
Self::new_typed().into()
}

/// Create MessageCopy block
pub fn new_typed() -> TypedBlock<Self> {
pub fn new() -> TypedBlock<Self> {
TypedBlock::new(
BlockMetaBuilder::new("MessageCopy").build(),
StreamIoBuilder::new().build(),
Expand Down
20 changes: 2 additions & 18 deletions src/blocks/moving_avg.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
use crate::anyhow::Result;
use crate::runtime::Block;
use crate::runtime::BlockMeta;
use crate::runtime::BlockMetaBuilder;
use crate::runtime::Kernel;
Expand All @@ -25,22 +24,7 @@ pub struct MovingAvg<const WIDTH: usize> {
}

impl<const WIDTH: usize> MovingAvg<WIDTH> {
/// Instantiate moving average as a [`Block`].
///
/// # Arguments
///
/// * `decay_factor`: amount current value should contribute to the rolling average.
/// Must be in `[0.0, 1.0]`.
/// * `history_size`: number of chunks to average over
///
/// Typical parameter values might be `decay_factor=0.1` and `history_size=3`
/// # Panics
/// Function will panic if `decay_factor` is not in `[0.0, 1.0]`
pub fn new(decay_factor: f32, history_size: usize) -> Block {
Block::from_typed(Self::new_typed(decay_factor, history_size))
}

/// Instantiate moving average as a [`TypedBlock`].
/// Instantiate moving average.
///
/// # Arguments
///
Expand All @@ -52,7 +36,7 @@ impl<const WIDTH: usize> MovingAvg<WIDTH> {
///
/// # Panics
/// Function will panic if `decay_factor` is not in `[0.0, 1.0]`
pub fn new_typed(decay_factor: f32, history_size: usize) -> TypedBlock<Self> {
pub fn new(decay_factor: f32, history_size: usize) -> TypedBlock<Self> {
assert!(
(0.0..=1.0).contains(&decay_factor),
"decay_factor must be in [0, 1]"
Expand Down
12 changes: 6 additions & 6 deletions src/blocks/seify/builder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -115,7 +115,7 @@ impl<D: DeviceTrait + Clone> Builder<D> {
match (self.dev.take(), self.builder_type) {
(Some(dev), BuilderType::Source) => {
self.config.apply(&dev, &self.channels, Direction::Rx)?;
Ok(Source::new_typed(dev, self.channels, self.start_time))
Ok(Source::new(dev, self.channels, self.start_time))
}
_ => Err(Error::InvalidParameter),
}
Expand All @@ -125,7 +125,7 @@ impl<D: DeviceTrait + Clone> Builder<D> {
match (self.dev.take(), self.builder_type) {
(Some(dev), BuilderType::Sink) => {
self.config.apply(&dev, &self.channels, Direction::Tx)?;
Ok(Sink::new_typed(dev, self.channels, self.start_time))
Ok(Sink::new(dev, self.channels, self.start_time))
}
_ => Err(Error::InvalidParameter),
}
Expand All @@ -136,23 +136,23 @@ impl<D: DeviceTrait + Clone> Builder<D> {
Some(dev) => match self.builder_type {
BuilderType::Sink => {
self.config.apply(&dev, &self.channels, Direction::Tx)?;
Ok(Sink::new(dev, self.channels, self.start_time))
Ok(Sink::new(dev, self.channels, self.start_time).into())
}
BuilderType::Source => {
self.config.apply(&dev, &self.channels, Direction::Rx)?;
Ok(Source::new(dev, self.channels, self.start_time))
Ok(Source::new(dev, self.channels, self.start_time).into())
}
},
None => {
let dev = Device::from_args(&self.args)?;
match self.builder_type {
BuilderType::Sink => {
self.config.apply(&dev, &self.channels, Direction::Tx)?;
Ok(Sink::new(dev, self.channels, self.start_time))
Ok(Sink::new(dev, self.channels, self.start_time).into())
}
BuilderType::Source => {
self.config.apply(&dev, &self.channels, Direction::Rx)?;
Ok(Source::new(dev, self.channels, self.start_time))
Ok(Source::new(dev, self.channels, self.start_time).into())
}
}
}
Expand Down
7 changes: 1 addition & 6 deletions src/blocks/seify/sink.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@ use crate::anyhow::Result;
use crate::blocks::seify::Builder;
use crate::blocks::seify::Config;
use crate::num_complex::Complex32;
use crate::runtime::Block;
use crate::runtime::BlockMeta;
use crate::runtime::BlockMetaBuilder;
use crate::runtime::ItemTag;
Expand Down Expand Up @@ -50,11 +49,7 @@ pub struct Sink<D: DeviceTrait + Clone> {
}

impl<D: DeviceTrait + Clone> Sink<D> {
pub(super) fn new(dev: Device<D>, channels: Vec<usize>, start_time: Option<i64>) -> Block {
Self::new_typed(dev, channels, start_time).into()
}

pub(super) fn new_typed(
pub(super) fn new(
dev: Device<D>,
channels: Vec<usize>,
start_time: Option<i64>,
Expand Down
7 changes: 1 addition & 6 deletions src/blocks/seify/source.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@ use crate::blocks::seify::builder::BuilderType;
use crate::blocks::seify::Builder;
use crate::blocks::seify::Config;
use crate::num_complex::Complex32;
use crate::runtime::Block;
use crate::runtime::BlockMeta;
use crate::runtime::BlockMetaBuilder;
use crate::runtime::Kernel;
Expand Down Expand Up @@ -47,11 +46,7 @@ pub struct Source<D: DeviceTrait + Clone> {
}

impl<D: DeviceTrait + Clone> Source<D> {
pub(super) fn new(dev: Device<D>, channels: Vec<usize>, start_time: Option<i64>) -> Block {
Self::new_typed(dev, channels, start_time).into()
}

pub(super) fn new_typed(
pub(super) fn new(
dev: Device<D>,
channels: Vec<usize>,
start_time: Option<i64>,
Expand Down
4 changes: 2 additions & 2 deletions src/runtime/flowgraph.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,8 +39,8 @@ impl Flowgraph {
}

/// Add [`Block`] to flowgraph
pub fn add_block(&mut self, block: Block) -> Result<usize, Error> {
self.topology.as_mut().unwrap().add_block(block)
pub fn add_block(&mut self, block: impl Into<Block>) -> Result<usize, Error> {
self.topology.as_mut().unwrap().add_block(block.into())
}

/// Make stream connection
Expand Down
12 changes: 6 additions & 6 deletions src/runtime/topology.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,11 @@
use futures::channel::mpsc::Sender;
use slab::Slab;
use std::any::Any;
use std::any::TypeId;
use std::collections::HashMap;
use std::fmt::Debug;
use std::hash::Hash;
use std::hash::Hasher;

use crate::runtime::buffer::BufferBuilder;
use crate::runtime::buffer::BufferWriter;
Expand All @@ -8,12 +14,6 @@ use crate::runtime::BlockMessage;
use crate::runtime::ConnectCtx;
use crate::runtime::Error;
use crate::runtime::PortId;
use slab::Slab;
use std::any::Any;
use std::any::TypeId;
use std::fmt::Debug;
use std::hash::Hash;
use std::hash::Hasher;

pub trait BufferBuilderKey: Debug + Send + Sync {
fn eq(&self, other: &dyn BufferBuilderKey) -> bool;
Expand Down
6 changes: 3 additions & 3 deletions tests/mocker.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ fn multi_input_mock() {
.take(128)
.collect();

let block = Apply::new_typed(|x: &u32| x + 1);
let block = Apply::new(|x: &u32| x + 1);

let mut mocker = Mocker::new(block);
mocker.input(0, input[..64].to_vec());
Expand All @@ -34,7 +34,7 @@ fn multi_input_mock() {

#[test]
fn tags_through_mock() -> Result<()> {
let mut noop = Apply::<_, f32, f32>::new_typed(|x| *x);
let mut noop = Apply::<_, f32, f32>::new(|x| *x);
noop.sio.set_tag_propagation(Box::new(copy_tag_propagation));

let mut mock = Mocker::new(noop);
Expand Down Expand Up @@ -91,7 +91,7 @@ fn tags_through_mock() -> Result<()> {

#[test]
fn mock_pmts() -> Result<()> {
let copy = MessageCopy::new_typed();
let copy = MessageCopy::new();

let mut mock = Mocker::new(copy);
mock.init();
Expand Down
4 changes: 2 additions & 2 deletions tests/moving_avg.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ use futuresdr::runtime::Mocker;

#[test]
fn moving_avg_correct_output() {
let block = MovingAvg::<3>::new_typed(0.1, 3);
let block = MovingAvg::<3>::new(0.1, 3);
let mut mocker = Mocker::new(block);

mocker.input::<f32>(0, vec![1.0, 2.0, 3.0, 1.0, 2.0, 3.0, 1.0, 2.0, 3.0]);
Expand All @@ -15,7 +15,7 @@ fn moving_avg_correct_output() {

#[test]
fn moving_avg_handles_non_finite_values() {
let block = MovingAvg::<3>::new_typed(0.1, 3);
let block = MovingAvg::<3>::new(0.1, 3);
let mut mocker = Mocker::new(block);
mocker.input::<f32>(
0,
Expand Down

0 comments on commit 1204ef1

Please sign in to comment.