protoflow_blocks/blocks/core/
drop.rs

1// This is free and unencumbered software released into the public domain.
2
3use crate::{StdioConfig, StdioError, StdioSystem, System};
4use protoflow_core::{types::Any, Block, BlockResult, BlockRuntime, InputPort, Message};
5use protoflow_derive::Block;
6use simple_mermaid::mermaid;
7
8/// A block that simply discards all messages it receives.
9///
10/// # Block Diagram
11#[doc = mermaid!("../../../doc/core/drop.mmd")]
12///
13/// # Sequence Diagram
14#[doc = mermaid!("../../../doc/core/drop.seq.mmd" framed)]
15///
16/// # Examples
17///
18/// ## Using the block in a system
19///
20/// ```rust
21/// # use protoflow_blocks::*;
22/// # fn main() {
23/// System::build(|s| {
24///     let stdin = s.read_stdin();
25///     let dropper = s.drop();
26///     s.connect(&stdin.output, &dropper.input);
27/// });
28/// # }
29/// ```
30///
31/// ## Running the block via the CLI
32///
33/// ```console
34/// $ protoflow execute Drop
35/// ```
36///
37#[derive(Block, Clone)]
38pub struct Drop<T: Message = Any> {
39    /// The input message stream.
40    #[input]
41    pub input: InputPort<T>,
42}
43
44impl<T: Message> Drop<T> {
45    pub fn new(input: InputPort<T>) -> Self {
46        Self { input }
47    }
48}
49
50impl<T: Message + 'static> Drop<T> {
51    pub fn with_system(system: &System) -> Self {
52        use crate::SystemBuilding;
53        Self::new(system.input())
54    }
55}
56
57impl<T: Message> Block for Drop<T> {
58    fn execute(&mut self, _runtime: &dyn BlockRuntime) -> BlockResult {
59        while let Some(message) = self.input.recv()? {
60            drop(message);
61        }
62
63        Ok(())
64    }
65}
66
67#[cfg(feature = "std")]
68impl<T: Message> StdioSystem for Drop<T> {
69    fn build_system(config: StdioConfig) -> Result<System, StdioError> {
70        use crate::{CoreBlocks, SystemBuilding};
71
72        config.reject_any()?;
73
74        Ok(System::build(|s| {
75            let stdin = config.read_stdin(s);
76            let dropper = s.drop();
77            s.connect(&stdin.output, &dropper.input);
78        }))
79    }
80}
81
82#[cfg(test)]
83mod tests {
84    use super::Drop;
85    use crate::{System, SystemBuilding};
86
87    #[test]
88    fn instantiate_block() {
89        // Check that the block is constructible:
90        let _ = System::build(|s| {
91            let _ = s.block(Drop::<i32>::new(s.input()));
92        });
93    }
94}