Skip to main content

waterui_core/state/
computed_f32.rs

1//! Ergonomic conversion traits for f32 computed signals.
2//!
3//! This module provides [`IntoComputedF32`] which allows functions to accept
4//! both raw numeric literals (`0.5`, `1`, `2.0`) and reactive signals that
5//! produce numeric values, converting them uniformly to `Computed<f32>`.
6
7use nami::{Signal, SignalExt};
8use num_traits::ToPrimitive;
9
10/// Converts constants or reactive signals into an `f32` signal.
11pub trait IntoSignalF32 {
12    /// Concrete signal type after conversion.
13    type Signal: Signal<Output = f32>;
14    /// Converts the input into an `f32` signal.
15    fn into_signal_f32(self) -> Self::Signal;
16}
17
18impl<S> IntoSignalF32 for S
19where
20    S: Signal + 'static,
21    S::Output: IntoF32,
22{
23    type Signal = nami::map::Map<S, fn(S::Output) -> f32, f32>;
24    fn into_signal_f32(self) -> Self::Signal {
25        self.map(IntoF32::into_f32)
26    }
27}
28
29/// A trait for types that can be converted to f32.
30///
31/// This is implemented for common numeric types to allow
32/// seamless conversion in signal pipelines.
33pub trait IntoF32: 'static {
34    /// Converts this value into an f32.
35    fn into_f32(self) -> f32;
36}
37
38macro_rules! impl_into_f32 {
39    ($($t:ty),*) => {
40        $(
41            impl IntoF32 for $t {
42                #[inline]
43                fn into_f32(self) -> f32 {
44                    self.to_f32().unwrap_or_else(|| {
45                        panic!("failed to convert `{}` into f32", stringify!($t))
46                    })
47                }
48            }
49        )*
50    };
51}
52
53impl_into_f32!(f32, f64, i8, i16, i32, i64, isize, u8, u16, u32, u64, usize);