compmd 0.12.0

The CompMD processor: parses, validates and expands CompMD (Component Markdown) documents. In development.
Documentation
//! The strings extension's `format` (spec ยง8.2), locale-free: `"%.1f %s".format([7.5, "mi"])` is `"7.5 mi"`. Its
//! verbs are `%s`, `%d`, `%f` and `%.Nf`, each with a width, padded with spaces before it or, after a `0`, with
//! zeros for `%d` and `%f`; and `%%`.

use super::Functions;
use super::library::{INT_HINT, text};
use super::value::Value;
use std::iter::Peekable;
use std::str::Chars;

/// The decimals `%f` writes without a precision.
const DECIMALS: usize = 6;

/// The template written with the values, one for each verb.
pub(crate) fn format(_: &dyn Functions, args: &[Value]) -> Result<Value, String> {
    let mut out = String::new();
    for (piece, value) in pieces(args)? {
        match piece {
            Piece::Text(text) => out.push_str(&text),
            Piece::Verb(verb) => out.push_str(&verb.written(value.unwrap_or(&Value::Null))?),
        }
    }
    Ok(Value::string(&out))
}

/// The characters `format` writes, at least, worked out without writing them; 0 for a template it refuses.
pub(crate) fn format_size(args: &[Value]) -> usize {
    pieces(args).map_or(0, |pieces| {
        pieces
            .iter()
            .map(|(piece, value)| match piece {
                Piece::Text(text) => text.chars().count(),
                Piece::Verb(verb) => verb.size(value.unwrap_or(&Value::Null)),
            })
            .sum()
    })
}

/// A part of a template: text, `%%` included, or a verb.
enum Piece {
    Text(String),
    Verb(Verb),
}

/// A verb of a template, `%05.1f`: its letter, its width and whether it is padded with zeros, and its precision.
struct Verb {
    letter: char,
    width: usize,
    zeros: bool,
    precision: Option<usize>,
}

/// The pieces of the template `args[0]`, each verb with its value from the list `args[1]`.
fn pieces(args: &[Value]) -> Result<Vec<(Piece, Option<&Value>)>, String> {
    let values: &[Value] = match args.get(1) {
        Some(Value::List(values)) => values,
        _ => &[],
    };
    let mut pieces = Vec::new();
    let mut given = values.iter();
    let mut text_so_far = String::new();
    let mut chars = text(args, 0).chars().peekable();
    while let Some(c) = chars.next() {
        if c != '%' {
            text_so_far.push(c);
        } else if chars.next_if_eq(&'%').is_some() {
            text_so_far.push('%');
        } else {
            let verb = Verb::read(&mut chars)?;
            let value = given.next().ok_or_else(|| {
                format!(
                    "format() takes a value for each verb, and was given {}",
                    values.len()
                )
            })?;
            pieces.push((Piece::Text(std::mem::take(&mut text_so_far)), None));
            pieces.push((Piece::Verb(verb), Some(value)));
        }
    }
    if given.next().is_some() {
        let verbs = pieces.len() / 2;
        return Err(format!(
            "format() takes a value for each verb: {verbs} verbs, {} values",
            values.len()
        ));
    }
    pieces.push((Piece::Text(text_so_far), None));
    Ok(pieces)
}

impl Verb {
    /// Reads the verb after a `%`.
    fn read(chars: &mut Peekable<Chars>) -> Result<Self, String> {
        let zeros = chars.next_if_eq(&'0').is_some();
        let width = number(chars).unwrap_or(0);
        let precision = chars.next_if_eq(&'.').map(|_| number(chars).unwrap_or(0));
        let letter = chars
            .next()
            .ok_or("format()'s template ends in a verb without its letter")?;
        let verb = Self {
            letter,
            width,
            zeros,
            precision,
        };
        match letter {
            's' | 'd' | 'f' => {}
            other => {
                return Err(format!(
                    "format() has the verbs %s, %d, %f and %%, not %{other}"
                ));
            }
        }
        if zeros && letter == 's' {
            return Err("format()'s %s is padded with spaces, not zeros".to_string());
        }
        if precision.is_some() && letter != 'f' {
            return Err(format!("format()'s %{letter} takes no precision"));
        }
        Ok(verb)
    }

    /// `value` written by the verb.
    fn written(&self, value: &Value) -> Result<String, String> {
        let text = match (self.letter, value) {
            ('d', Value::Int(n)) => n.to_string(),
            ('f', Value::Int(_) | Value::Double(_)) => {
                fixed(number_of(value), self.precision.unwrap_or(DECIMALS))
            }
            ('s', value) => value
                .written()
                .map_err(|reason| format!("format()'s %s: {reason}"))?
                .unwrap_or_default(),
            ('d', Value::Double(_)) => {
                return Err(format!("format()'s %d takes an int, not double{INT_HINT}"));
            }
            (letter, value) => {
                return Err(format!(
                    "format()'s %{letter} takes a number, not {}",
                    value.kind()
                ));
            }
        };
        Ok(padded(text, self.width, self.zeros))
    }

    /// The characters it writes for `value`, at least as many as `written` gives, without writing them: a wide
    /// verb's are its width.
    #[allow(
        clippy::cast_possible_truncation,
        clippy::cast_sign_loss,
        reason = "the whole part's digits are few, and the number is rounded and made positive first"
    )]
    fn size(&self, value: &Value) -> usize {
        let written = match (self.letter, value) {
            ('f', Value::Int(_) | Value::Double(_)) => {
                let n = number_of(value);
                let decimals = self.precision.unwrap_or(DECIMALS);
                let whole = n.abs().round();
                let digits = if whole < 1.0 {
                    1
                } else {
                    whole.log10().floor() as usize + 1
                };
                usize::from(n.is_sign_negative()) + digits + usize::from(decimals > 0) + decimals
            }
            (_, value) => value
                .written()
                .ok()
                .flatten()
                .map_or(0, |text| text.chars().count()),
        };
        written.max(self.width)
    }
}

/// `n` with `decimals` decimals, rounded half to even on its exact value. A `double`'s exact value has fewer than
/// [`EXACT_DECIMALS`] decimals, so those after are zeros.
fn fixed(n: f64, decimals: usize) -> String {
    let exact = decimals.min(EXACT_DECIMALS);
    let mut text = format!("{n:.exact$}");
    text.extend(std::iter::repeat_n('0', decimals - exact));
    text
}

/// More decimals than any `double`'s exact value has (1074 at most).
const EXACT_DECIMALS: usize = 1100;

/// `text` padded before to `width` characters: with zeros after its sign when `zeros` is, with spaces otherwise.
fn padded(text: String, width: usize, zeros: bool) -> String {
    let fill = width.saturating_sub(text.chars().count());
    if fill == 0 {
        return text;
    }
    let (sign, digits) = match text.strip_prefix('-') {
        Some(digits) if zeros => ("-", digits),
        _ => ("", text.as_str()),
    };
    let pad = if zeros { '0' } else { ' ' };
    let mut out = String::with_capacity(text.len() + fill);
    out.push_str(sign);
    out.extend(std::iter::repeat_n(pad, fill));
    out.push_str(digits);
    out
}

#[allow(
    clippy::cast_precision_loss,
    reason = "an int is written as the nearest double, as CEL converts it"
)]
fn number_of(value: &Value) -> f64 {
    match value {
        Value::Int(n) => *n as f64,
        Value::Double(n) => *n,
        _ => 0.0,
    }
}

/// The digits next in `chars`, as a number; `None` when there are none. Too many to count are as many as can be.
fn number(chars: &mut Peekable<Chars>) -> Option<usize> {
    let mut found = None;
    while let Some(digit) = chars.next_if(char::is_ascii_digit) {
        let digit = digit.to_digit(10).map_or(0, |d| d as usize);
        found = Some(
            found
                .unwrap_or(0_usize)
                .saturating_mul(10)
                .saturating_add(digit),
        );
    }
    found
}

#[cfg(test)]
mod tests;