mln-rs-engine 0.0.21

Part of mln-rs, a MapLibre map renderer written in Rust. Depend on mln-rs instead.
Documentation
use std::marker::PhantomData;

use mln_style::color::Color;

/// The value types a binder keeps statistics for: only `f32` tracks a
/// maximum.
pub trait StatisticValue {
    /// `Some(value)` for `f32`, `None` for the types whose statistics track
    /// nothing.
    fn statistic(&self) -> Option<f32>;
}

impl StatisticValue for f32 {
    fn statistic(&self) -> Option<f32> {
        Some(*self)
    }
}

impl StatisticValue for Color {
    fn statistic(&self) -> Option<f32> {
        None
    }
}

#[derive(Clone, Debug, mln_wire::Wire)]
pub struct PaintPropertyStatistics<T> {
    max: Option<f32>,
    #[wire(skip)]
    _t: PhantomData<T>,
}

impl<T> Default for PaintPropertyStatistics<T> {
    fn default() -> Self {
        PaintPropertyStatistics { max: None, _t: PhantomData }
    }
}

impl<T: StatisticValue> PaintPropertyStatistics<T> {
    /// The largest value added; always `None` for value types other than
    /// `f32`.
    #[must_use]
    pub fn max(&self) -> Option<f32> {
        self.max
    }

    /// Raises the maximum to `value` if it is larger.
    pub(crate) fn add(&mut self, value: &T) {
        if let Some(value) = value.statistic() {
            self.max = Some(match self.max {
                // A NaN value never raises the maximum.
                Some(max) => {
                    if max < value {
                        value
                    } else {
                        max
                    }
                }
                None => value,
            });
        }
    }
}