mln-rs-style 0.0.21

Part of mln-rs, a MapLibre map renderer written in Rust. Depend on mln-rs instead.
Documentation
use crate::conversion::Convertible;
use crate::expression::forms::interpolate::parse_stop_label;
use crate::expression::parse::{ParseResult, ParsingContext};
use crate::expression::stops::{Stops, covering_stops};
use crate::expression::type_::Type;
use crate::expression::{EvalResult, EvaluationContext, EvaluationError, Expr, Node, Output};
use crate::feature::Value as FeatureValue;
use crate::range::Range;

/// `["step", input, output, label, output, ...]`.
#[derive(Clone, PartialEq, mln_wire::Wire)]
pub struct Step {
    type_: Type,
    input: Expr,
    stops: Stops,
}

impl Step {
    /// A step over `input`, which is a number.
    #[must_use]
    pub fn new_expr(type_: Type, input: Expr, stops: Stops) -> Expr {
        assert_eq!(input.type_(), Type::Number);
        Expr::new(Node::Step(Box::new(Step { type_, input, stops })))
    }

    pub(crate) fn type_(&self) -> &Type {
        &self.type_
    }

    #[must_use]
    pub(crate) fn input(&self) -> &Expr {
        &self.input
    }

    #[must_use]
    pub fn covering_stops(&self, lower: f64, upper: f64) -> Range<f64> {
        covering_stops(&self.stops, lower, upper)
    }

    pub(crate) fn parse(value: &Convertible<'_>, ctx: &mut ParsingContext) -> ParseResult {
        debug_assert!(value.is_array());

        let length = value.array_length();

        if length - 1 < 4 {
            ctx.error(format!("Expected at least 4 arguments, but found only {}.", length - 1));
            return None;
        }

        // [step, input, firstOutput_value, 2 * (n pairs)...]
        if !(length - 1).is_multiple_of(2) {
            ctx.error("Expected an even number of arguments.".to_owned());
            return None;
        }

        let input = ctx.parse(&value.array_member(1), 1, Some(Type::Number), None)?;

        let mut stops = Stops::new();
        let mut output_type: Option<Type> = None;
        if let Some(expected) = ctx.expected()
            && expected != Type::Value
        {
            output_type = Some(expected);
        }

        let mut previous = f64::NEG_INFINITY;

        // consume the first output value, which doesn't have a corresponding
        // input value, before proceeding into the "stops" loop below.
        let first_output = ctx.parse(&value.array_member(2), 2, output_type.clone(), None)?;
        if output_type.is_none() {
            output_type = Some(first_output.type_());
        }
        stops.emplace(f64::NEG_INFINITY, first_output);

        let mut i = 3;
        while i + 1 < length {
            let Some(label) = parse_stop_label(&value.array_member(i)) else {
                ctx.error_at(
                    r#"Input/output pairs for "step" expressions must be defined using literal numeric values (not computed expressions) for the input values."#
                        .to_owned(),
                    i,
                );
                return None;
            };

            if label <= previous {
                ctx.error_at(
                    r#"Input/output pairs for "step" expressions must be arranged with input values in strictly ascending order."#
                        .to_owned(),
                    i,
                );
                return None;
            }
            previous = label;

            let output = ctx.parse(&value.array_member(i + 1), i + 1, output_type.clone(), None)?;
            if output_type.is_none() {
                output_type = Some(output.type_());
            }

            stops.emplace(label, output);
            i += 2;
        }

        let Some(output_type) = output_type else {
            ctx.error(format!("Expected at least 4 arguments, but found only {}.", length - 1));
            return None;
        };

        Some(Step::new_expr(output_type, input, stops))
    }

    /// The output of the last stop at or below the input.
    pub(crate) fn eval<'e, T: Output<'e>>(&'e self, params: &EvaluationContext<'_>) -> EvalResult<T> {
        let x = self.input.eval_num(params)?;
        if x.is_nan() {
            return Err(EvaluationError::new("Input is not a number."));
        }

        if self.stops.is_empty() {
            return Err(EvaluationError::new("No stops in step curve."));
        }

        let it = self.stops.upper_bound(x);
        T::eval(self.stops.output(it.saturating_sub(1)), params)
    }

    pub(crate) fn each_child<'a>(&'a self, visit: &mut dyn FnMut(&'a Expr)) {
        visit(&self.input);
        self.each_output(visit);
    }

    pub(crate) fn each_output<'a>(&'a self, visit: &mut dyn FnMut(&'a Expr)) {
        self.stops.values().for_each(visit);
    }

    pub(crate) fn serialize(&self) -> FeatureValue {
        let mut serialized = vec![FeatureValue::String("step".to_owned()), self.input.serialize()];
        for (i, (k, v)) in self.stops.iter().enumerate() {
            // The base output's label is -infinity, which isn't written.
            if i > 0 {
                serialized.push(FeatureValue::Double(k));
            }
            serialized.push(v.serialize());
        }
        FeatureValue::Array(serialized)
    }
}