impl/rust/parse_money_input.rs
8,210 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::form_money_input_format_money_input::{number_style_for, separators_of}; ← formatMoneyInput, another function of this group · built into the same file, even by a slim install
use super::form_money_input_money_input_format::{money_for_message, money_input_format}; ← moneyInputFormat, another function of this group · built into the same file, even by a slim install
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::money_amount::money_to_value; ← from money.amount ^1.0.0 · built alongside by fune
use super::money_currency_digits::currency_digits; ← from money.currency-digits ^1.0.0 · built alongside by fune
use super::money_currency_digits_data::CURRENCY_DIGITS; ← money.currency-digits’s rule data (^1.0.0) · built alongside by fune
use super::money_format_data::CURRENCIES; ← money.format’s rule data (^1.0.0) · built alongside by fune
use super::money_parse::parse_money; ← from money.parse ^1.0.0 · built alongside by fune
use super::money_parse_data::CURRENCY_SYMBOLS; ← money.parse’s rule data (^1.0.0) · built alongside by fune
const MAX_SAFE: &str = "9007199254740991";
// The spaces money.parse allows between a symbol and the number.
const SPACES: &[char] = &[' ', '\u{a0}', '\u{202f}'];
// ASCII whitespace only, so all three languages trim the same characters.
fn trim_ascii(value: &str) -> &str {
value.trim_matches(|c: char| matches!(c, ' ' | '\t' | '\n' | '\r' | '\x0c' | '\x0b'))
}
fn is_digits(value: &str) -> bool {
!value.is_empty() && value.bytes().all(|b| b.is_ascii_digit())
}
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()
}
}
/// The longest known symbol or ISO code `matches` accepts, compared in characters.
fn longest_symbol(matches: impl Fn(&str) -> bool) -> Option<&'static str> {
let mut best: Option<&'static str> = None;
let candidates = CURRENCY_SYMBOLS.iter().map(|r| r.symbol).chain(CURRENCY_DIGITS.iter().map(|r| r.code));
for symbol in candidates {
let longer = match best {
None => true,
Some(b) => symbol.chars().count() > b.chars().count(),
};
if matches(symbol) && longer {
best = Some(symbol);
}
}
best
}
fn split_number(s: &str, groups: &[char], decimal: char) -> Option<(String, String)> {
let parts: Vec<&str> = s.split(decimal).collect();
if parts.len() > 2 {
return None;
}
let fraction = if parts.len() == 2 { parts[1] } else { "" };
if parts.len() == 2 && !is_digits(fraction) {
return None;
}
let chunks: Vec<&str> = parts[0].split(|c: char| groups.contains(&c)).collect();
if !chunks.iter().all(|c| is_digits(c)) {
return None;
}
if chunks.len() > 1 {
let first = chunks[0];
if first.len() > 3 || first.starts_with('0') {
return None;
}
if !chunks[1..].iter().all(|c| c.len() == 3) {
return None;
}
}
Some((chunks.concat(), fraction.to_string()))
}
fn invalid(message: String) -> MoneyInputCheck {
MoneyInputCheck { valid: false, amount: None, message: Some(message) }
}
/// An amount typed into a money input, read as integer minor units: the shape
/// checked here, with a message for each way it can be wrong, so that
/// money.parse only ever converts text it accepts; then the bounds.
///
/// # Panics
/// Panics on an empty label, an unknown currency or locale, or min above max.
pub fn parse_money_input(text: &str, currency: &str, locale: &str, rules: &MoneyRules) -> MoneyInputCheck {
let label = trim_ascii(&rules.label);
if label.is_empty() {
panic!("a money input needs a label, such as \"Amount\", to write its error messages");
}
let digits = currency_digits(currency);
let style = number_style_for(locale);
if let (Some(lo), Some(hi)) = (rules.min, rules.max) {
if lo > hi {
panic!("rules.min ({}) must not be more than rules.max ({})", lo, hi);
}
}
let seps = separators_of(style);
let mut s: &str = trim_ascii(text);
if s.is_empty() {
if rules.required {
return invalid(format!("Enter {}", lower_first(label)));
}
return MoneyInputCheck { valid: true, amount: None, message: None };
}
let shape = format!("Enter {} in the correct format, like {}", lower_first(label), money_input_format(currency, locale).example);
let mut negative = false;
if let Some(rest) = s.strip_prefix('-') {
negative = true;
s = rest;
}
let mut symbol = longest_symbol(|k| s.starts_with(k));
if let Some(sym) = symbol {
s = &s[sym.len()..];
if let Some(rest) = s.strip_prefix(SPACES) {
s = rest;
}
if !negative {
if let Some(rest) = s.strip_prefix('-') {
negative = true;
s = rest;
}
}
} else {
symbol = longest_symbol(|k| s.ends_with(k));
if let Some(sym) = symbol {
s = &s[..s.len() - sym.len()];
if let Some(rest) = s.strip_suffix(SPACES) {
s = rest;
}
}
}
let own = match symbol {
None => true,
Some(sym) => {
sym == currency
|| CURRENCY_SYMBOLS.iter().any(|r| r.code == currency && r.symbol == sym)
|| CURRENCIES.iter().any(|r| r.code == currency && r.symbol.trim_matches(' ') == sym)
}
};
if !own {
return invalid(shape);
}
let (whole, fraction) = match split_number(s, seps.groups, seps.decimal) {
Some(found) => found,
None => return invalid(shape),
};
if negative && !rules.allow_negative {
return invalid(format!("{} must not be negative", label));
}
if fraction.len() as i64 > digits {
if digits == 0 {
return invalid(format!("{} must be a whole number", label));
}
let unit = if digits == 1 { "place" } else { "places" };
return invalid(format!("{} must not have more than {} decimal {}", label, digits, unit));
}
let mut padded = fraction.clone();
while (padded.len() as i64) < digits {
padded.push('0');
}
let joined = format!("{}{}", whole, padded);
let all = joined.trim_start_matches('0');
if all.len() > MAX_SAFE.len() || (all.len() == MAX_SAFE.len() && all > MAX_SAFE) {
return invalid(format!("{} is too large", label));
}
let canonical = format!(
"{}{}{}",
if negative { "-" } else { "" },
whole,
if fraction.is_empty() { String::new() } else { format!("{}{}", seps.decimal, fraction) }
);
let amount = parse_money(&canonical, currency, style);
match (rules.min, rules.max) {
(Some(lo), Some(hi)) if amount.minor < lo || amount.minor > hi => {
return invalid(format!(
"{} must be between {} and {}",
label,
money_for_message(lo, currency, locale),
money_for_message(hi, currency, locale)
));
}
(Some(lo), None) if amount.minor < lo => {
return invalid(format!("{} must be {} or more", label, money_for_message(lo, currency, locale)));
}
(None, Some(hi)) if amount.minor > hi => {
return invalid(format!("{} must be {} or less", label, money_for_message(hi, currency, locale)));
}
_ => {}
}
MoneyInputCheck { valid: true, amount: Some(amount), message: None }
}
pub fn money_input_check_to_value(check: &MoneyInputCheck) -> Value {
Value::obj(vec![
("valid", Value::Bool(check.valid)),
("amount", check.amount.as_ref().map(money_to_value).unwrap_or(Value::Null)),
("message", check.message.as_deref().map(Value::str).unwrap_or(Value::Null)),
])
}
pub fn fune_vector(args: &[Value]) -> Value {
let r = &args[3];
let int = |key: &str| match r.get(key) {
Value::Int(n) => Some(*n),
Value::Null => None,
other => panic!("rules.{} must be a whole number of minor units, got {:?}", key, other),
};
let rules = MoneyRules {
label: r.get("label").as_str().to_string(),
required: r.get("required").as_bool(),
min: int("min"),
max: int("max"),
allow_negative: r.get("allowNegative").as_bool(),
};
money_input_check_to_value(&parse_money_input(args[0].as_str(), args[1].as_str(), args[2].as_str(), &rules))
}