Functional Weave
Code in Python

form.validate-input@1.0.0

impl/rust.rs

9,398 bytes · the Rust implementation · view raw

Imports name this capability’s declared dependencies, which fune builds next to it in your project; each one links to its page.

use super::funejson::Value;  ← the fune runtime: the JSON value the test vectors use; fune build keeps it only where a signature takes one
use super::text_pattern_match::matches_pattern;  ← from text.pattern-match ^1.0.0 · built alongside by fune
use super::validation_email::is_email;  ← from validation.email ^1.0.0 · built alongside by fune

// ASCII whitespace only, so all three languages trim the same characters
// (str::trim would also take Unicode spaces).
fn trim_ascii(value: &str) -> &str {
    value.trim_matches(|c: char| matches!(c, ' ' | '\t' | '\n' | '\r' | '\x0c' | '\x0b'))
}

// "Full name" starts a sentence; after "Enter" it is "full name". A label that
// starts with an acronym ("UK phone number") is left as it is.
fn lower_first(label: &str) -> String {
    let bytes = label.as_bytes();
    let upper = |i: usize| i < bytes.len() && bytes[i].is_ascii_uppercase();
    if upper(0) && !upper(1) {
        let mut out = String::with_capacity(label.len());
        out.push(bytes[0].to_ascii_lowercase() as char);
        out.push_str(&label[1..]);
        out
    } else {
        label.to_string()
    }
}

/// A decimal: sign, whole digits without leading zeros, fraction digits
/// without trailing zeros; zero is (false, "", "").
struct Decimal {
    negative: bool,
    whole: String,
    fraction: String,
}

// ASCII digits only: "٣" is not a digit in any of the three languages.
fn is_digits(s: &str) -> bool {
    !s.is_empty() && s.bytes().all(|b| b.is_ascii_digit())
}

// -12, 12.5, .5 and 0.50: ASCII digits, one optional point, an optional
// leading minus. No exponent, no grouping, no plus: what a person types.
fn parse_decimal(text: &str, integer: bool) -> Option<Decimal> {
    let mut s = text;
    let mut negative = false;
    if let Some(rest) = s.strip_prefix('-') {
        negative = true;
        s = rest;
    }
    let (whole, fraction) = match s.find('.') {
        Some(point) => {
            if integer {
                return None;
            }
            let (whole, fraction) = (&s[..point], &s[point + 1..]);
            if !is_digits(fraction) || (!whole.is_empty() && !is_digits(whole)) {
                return None;
            }
            (whole, fraction)
        }
        None => {
            if !is_digits(s) {
                return None;
            }
            (s, "")
        }
    };
    let whole = whole.trim_start_matches('0').to_string();
    let fraction = fraction.trim_end_matches('0').to_string();
    if whole.is_empty() && fraction.is_empty() {
        negative = false; // -0 is 0
    }
    Some(Decimal { negative, whole, fraction })
}

fn compare_magnitude(a: &Decimal, b: &Decimal) -> i32 {
    if a.whole.len() != b.whole.len() {
        return if a.whole.len() < b.whole.len() { -1 } else { 1 };
    }
    if a.whole != b.whole {
        return if a.whole < b.whole { -1 } else { 1 };
    }
    let width = a.fraction.len().max(b.fraction.len());
    let fa = format!("{:0<width$}", a.fraction, width = width);
    let fb = format!("{:0<width$}", b.fraction, width = width);
    if fa != fb {
        return if fa < fb { -1 } else { 1 };
    }
    0
}

fn compare_decimal(a: &Decimal, b: &Decimal) -> i32 {
    if a.negative != b.negative {
        return if a.negative { -1 } else { 1 };
    }
    let m = compare_magnitude(a, b);
    if a.negative {
        -m
    } else {
        m
    }
}

fn bound(name: &str, text: &Option<String>) -> Option<Decimal> {
    let text = text.as_deref()?;
    match parse_decimal(text, false) {
        Some(d) => Some(d),
        None => panic!("rules.{} must be a decimal number, such as \"0\" or \"-2.5\" (got \"{}\")", name, text),
    }
}

fn fail(code: &str, message: String) -> InputCheck {
    InputCheck { valid: false, value: None, code: Some(code.to_string()), message: Some(message) }
}

/// One input checked as a GOV.UK form checks it: empty first, then length,
/// then the format its kind needs, then the pattern, then the range, each
/// failure with the message to show.
///
/// # Panics
/// The rules are the caller's, so a bad one panics whatever was typed: an
/// empty label, an unknown kind, a negative or crossed length, min or max on a
/// text or email input or not a decimal, min above max, or a pattern
/// text.pattern-match refuses.
pub fn validate_input(value: &str, rules: &InputRules) -> InputCheck {
    let label = trim_ascii(&rules.label);
    if label.is_empty() {
        panic!("an input needs a label, such as \"Full name\", to write its error messages");
    }
    let kind = rules.kind.as_str();
    let numeric = kind == "number" || kind == "integer";
    if kind != "text" && kind != "email" && !numeric {
        panic!("unknown input kind \"{}\"", kind);
    }
    if matches!(rules.min_length, Some(n) if n < 0) {
        panic!("rules.minLength must not be negative");
    }
    if matches!(rules.max_length, Some(n) if n < 0) {
        panic!("rules.maxLength must not be negative");
    }
    if let (Some(lo), Some(hi)) = (rules.min_length, rules.max_length) {
        if lo > hi {
            panic!("rules.minLength must not be more than rules.maxLength");
        }
    }
    if !numeric && rules.min.is_some() {
        panic!("rules.min only applies to number and integer inputs");
    }
    if !numeric && rules.max.is_some() {
        panic!("rules.max only applies to number and integer inputs");
    }
    let low_bound = bound("min", &rules.min);
    let high_bound = bound("max", &rules.max);
    if let (Some(lo), Some(hi)) = (&low_bound, &high_bound) {
        if compare_decimal(lo, hi) > 0 {
            panic!("rules.min must not be more than rules.max");
        }
    }
    // A bad pattern fails here, on every call, not only when someone types.
    if let Some(pattern) = &rules.pattern {
        matches_pattern(pattern, "");
    }

    let text = trim_ascii(value);
    if text.is_empty() {
        if rules.required {
            return fail("required", format!("Enter {}", lower_first(label)));
        }
        return InputCheck { valid: true, value: Some(String::new()), code: None, message: None };
    }
    let length = text.chars().count() as i64;
    if let Some(max) = rules.max_length {
        if length > max {
            return fail("too-long", format!("{} must be {} characters or less", label, max));
        }
    }
    if let Some(min) = rules.min_length {
        if length < min {
            return fail("too-short", format!("{} must be {} characters or more", label, min));
        }
    }

    let mut number: Option<Decimal> = None;
    if kind == "email" && !is_email(text) {
        return fail("email", "Enter an email address in the correct format, like name@example.com".to_string());
    }
    if kind == "number" {
        number = parse_decimal(text, false);
        if number.is_none() {
            return fail("number", format!("{} must be a number", label));
        }
    }
    if kind == "integer" {
        number = parse_decimal(text, true);
        if number.is_none() {
            return fail("integer", format!("{} must be a whole number", label));
        }
    }

    if let Some(pattern) = &rules.pattern {
        if !matches_pattern(pattern, text) {
            let message = match &rules.pattern_message {
                Some(m) => m.clone(),
                None => format!("Enter {} in the correct format", lower_first(label)),
            };
            return fail("pattern", message);
        }
    }

    if let Some(n) = &number {
        let low = low_bound.as_ref().is_some_and(|lo| compare_decimal(n, lo) < 0);
        let high = high_bound.as_ref().is_some_and(|hi| compare_decimal(n, hi) > 0);
        if low || high {
            let code = if low { "too-small" } else { "too-large" };
            let min = rules.min.as_deref().unwrap_or("");
            let max = rules.max.as_deref().unwrap_or("");
            if low_bound.is_some() && high_bound.is_some() {
                return fail(code, format!("{} must be between {} and {}", label, min, max));
            }
            if low {
                return fail(code, format!("{} must be {} or more", label, min));
            }
            return fail(code, format!("{} must be {} or less", label, max));
        }
    }
    InputCheck { valid: true, value: Some(text.to_string()), code: None, message: None }
}

pub fn input_check_to_value(check: &InputCheck) -> Value {
    let text = |v: &Option<String>| v.as_deref().map(Value::str).unwrap_or(Value::Null);
    Value::obj(vec![
        ("valid", Value::Bool(check.valid)),
        ("value", text(&check.value)),
        ("code", text(&check.code)),
        ("message", text(&check.message)),
    ])
}

pub fn input_rules_from_value(v: &Value) -> InputRules {
    let text = |key: &str| match v.get(key) {
        Value::Str(s) => Some(s.clone()),
        _ => None,
    };
    let int = |key: &str| match v.get(key) {
        Value::Int(n) => Some(*n),
        Value::Float(f) if f.fract() == 0.0 => Some(*f as i64),
        Value::Float(_) => panic!("rules.{} must be an integer", key),
        _ => None,
    };
    InputRules {
        label: text("label").unwrap_or_default(),
        kind: text("kind").unwrap_or_default(),
        required: v.get("required").as_bool(),
        min_length: int("minLength"),
        max_length: int("maxLength"),
        pattern: text("pattern"),
        pattern_message: text("patternMessage"),
        min: text("min"),
        max: text("max"),
    }
}

pub fn fune_vector(args: &[Value]) -> Value {
    input_check_to_value(&validate_input(args[0].as_str(), &input_rules_from_value(&args[1])))
}