use anyhow::Ok;
use uuid::Uuid;
use crate::{
base::{
block::{Block, BlockDesc, BlockProps, BlockState},
input::{InputProps, input_reader::InputReader},
output::Output,
},
blocks::utils::convert_units,
};
use libhaystack::val::{Number, Value, kind::HaystackKind};
use crate::{blocks::InputImpl, blocks::OutputImpl};
#[block]
#[derive(BlockProps, Debug)]
#[dis = "Minimum"]
#[category = "math"]
pub struct Min {
#[input(kind = "Number")]
pub a: InputImpl,
#[input(kind = "Number")]
pub b: InputImpl,
#[output(kind = "Number")]
pub out: OutputImpl,
}
impl Block for Min {
async fn execute(&mut self) {
self.read_inputs_until_ready().await;
if let (Some(Value::Number(a)), Some(Value::Number(b))) =
(self.a.get_value(), self.b.get_value())
{
let _ = convert_units(&[a.to_owned(), b.to_owned()])
.and_then(|parts| {
if let [a, b] = &parts[..] {
let val = Number {
value: a.value.min(b.value),
unit: a.unit,
};
self.out.set(val.into());
}
Ok(())
})
.or_else(|_| {
self.set_state(BlockState::fault("Min: unit conversion failed"));
Ok(())
});
}
}
}
#[cfg(test)]
mod test {
use assert_matches::assert_matches;
use libhaystack::val::{Number, Value};
use crate::{
base::block::Block, base::block::test_utils::write_block_inputs, blocks::math::Min,
};
#[tokio::test]
async fn test_min_block() {
let mut block = Min::new();
write_block_inputs([(&mut block.a, 8), (&mut block.b, 42)]).await;
block.execute().await;
assert_matches!(
block.out.value,
Value::Number(Number { value, .. }) if value == 8.0
);
}
}