mln-rs-style 0.0.21

Part of mln-rs, a MapLibre map renderer written in Rust. Depend on mln-rs instead.
Documentation
//! `["length", input]`, which [`Expr::eval_num`] evaluates with
//! [`evaluate`].

use crate::conversion::Convertible;
use crate::expression::parse::{ParseResult, ParsingContext};
use crate::expression::type_::{self, Type};
use crate::expression::value::{Value, type_of};
use crate::expression::{EvalResult, EvaluationContext, EvaluationError, Expr, Node};

pub(crate) fn parse(value: &Convertible<'_>, ctx: &mut ParsingContext) -> ParseResult {
    let length = value.array_length();

    if length != 2 {
        ctx.error(format!("Expected one argument, but found {length} instead."));
        return None;
    }

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

    let t = &input.type_();
    if !t.is_array() && *t != Type::String && *t != Type::Value {
        ctx.error(format!("Expected argument of type string or array, but found {} instead.", type_::to_string(t)));
        return None;
    }

    Some(Expr::new(Node::Length(Box::new(input))))
}

/// The length of `input`'s string or array.
pub(crate) fn evaluate(input: &Expr, params: &EvaluationContext<'_>) -> EvalResult<f64> {
    let value = input.evaluate_ref(params)?;
    match &*value {
        Value::String(s) => Ok(s.chars().count() as f64),
        Value::Array(v) => Ok(v.len() as f64),
        _ => Err(EvaluationError::new(format!(
            "Expected value to be of type string or array, but found {} instead.",
            type_::to_string(&type_of(&value))
        ))),
    }
}

/// The byte offset of the char at `char_offset` in `s`, or `s.len()` when
/// `s` has no char there.
#[must_use]
pub(crate) fn char_byte_offset(s: &str, char_offset: usize) -> usize {
    s.char_indices().nth(char_offset).map_or(s.len(), |(i, _)| i)
}