protoflow_blocks/blocks/core/
const.rs1use crate::{
4 prelude::{vec, String},
5 StdioConfig, StdioError, StdioSystem, System,
6};
7use protoflow_core::{Block, BlockResult, BlockRuntime, Message, OutputPort};
8use protoflow_derive::Block;
9use simple_mermaid::mermaid;
10
11#[doc = mermaid!("../../../doc/core/const.mmd")]
26#[doc = mermaid!("../../../doc/core/const.seq.mmd" framed)]
29#[derive(Block, Clone)]
54pub struct Const<T: Message = String> {
55 #[output]
57 pub output: OutputPort<T>,
58
59 #[parameter]
61 pub value: T,
62}
63
64impl<T: Message + Default> Const<T> {
65 pub fn new(output: OutputPort<T>) -> Self {
66 Self::with_params(output, T::default())
67 }
68}
69
70impl<T: Message> Const<T> {
71 pub fn with_params(output: OutputPort<T>, value: T) -> Self {
72 Self { output, value }
73 }
74}
75
76impl<T: Message + 'static> Const<T> {
77 pub fn with_system(system: &System, value: T) -> Self {
78 use crate::SystemBuilding;
79 Self::with_params(system.output(), value)
80 }
81}
82
83impl<T: Message> Block for Const<T> {
84 fn execute(&mut self, runtime: &dyn BlockRuntime) -> BlockResult {
85 runtime.wait_for(&self.output)?;
86
87 self.output.send(&self.value)?;
88
89 Ok(())
90 }
91}
92
93#[cfg(feature = "std")]
94impl<T: Message> StdioSystem for Const<T> {
95 fn build_system(config: StdioConfig) -> Result<System, StdioError> {
96 use crate::{CoreBlocks, IoBlocks, SystemBuilding};
97
98 config.allow_only(vec!["value"])?;
99 let value = config.get_string("value")?;
100
101 Ok(System::build(|s| {
102 let const_value = s.const_string(value); let line_encoder = s.encode_with(config.encoding);
104 let stdout = config.write_stdout(s);
105 s.connect(&const_value.output, &line_encoder.input);
106 s.connect(&line_encoder.output, &stdout.input);
107 }))
108 }
109}
110
111#[cfg(test)]
112mod tests {
113 use super::Const;
114 use crate::{System, SystemBuilding};
115
116 #[test]
117 fn instantiate_block() {
118 let _ = System::build(|s| {
120 let _ = s.block(Const::<i32>::with_params(s.output(), 0x00BAB10C));
121 });
122 }
123}