use crate::base::{Lang, N2WError, Result};
use crate::currency::{CurrencyForms, CurrencyValue};
use crate::floatpath::FloatValue;
use crate::strnum::{python_decimal_parse, ParsedNumber};
use bigdecimal::BigDecimal;
use num_bigint::BigInt;
use num_traits::{One, Signed, ToPrimitive, Zero};
use std::collections::HashMap;
const NEGWORD: &str = "minus ";
const POINTWORD: &str = "point";
const ONES: [&str; 10] = [
"",
"benn",
"ñaar",
"ñett",
"ñeent",
"juróom",
"juróom-benn",
"juróom-ñaar",
"juróom-ñett",
"juróom-ñeent",
];
const TENS: [&str; 10] = [
"",
"fukk",
"ñaar-fukk",
"ñett-fukk",
"ñeent-fukk",
"juróom-fukk",
"juróom-benn-fukk",
"juróom-ñaar-fukk",
"juróom-ñett-fukk",
"juróom-ñeent-fukk",
];
const HUNDRED: &str = "téeméer";
const THOUSAND: &str = "junni";
const MILLION: &str = "tamndareet";
const BILLION: u32 = 1_000_000_000;
pub struct LangWo {
currency_forms: HashMap<&'static str, CurrencyForms>,
currency_forms_fallback: CurrencyForms,
}
impl LangWo {
pub fn new() -> Self {
let xof = CurrencyForms::new(&["dërëm", "dërëm"], &["santim", "santim"]);
let mut currency_forms = HashMap::new();
currency_forms.insert("XOF", xof.clone());
currency_forms.insert(
"USD",
CurrencyForms::new(&["dollar", "dollars"], &["cent", "cents"]),
);
currency_forms.insert(
"EUR",
CurrencyForms::new(&["euro", "euros"], &["cent", "cents"]),
);
LangWo {
currency_forms,
currency_forms_fallback: xof,
}
}
}
impl Default for LangWo {
fn default() -> Self {
Self::new()
}
}
fn int_to_word(number: &BigInt) -> String {
if number.is_zero() {
return "zero".to_string();
}
if number.is_negative() {
return format!("{}{}", NEGWORD, int_to_word(&number.abs()));
}
if number >= &BigInt::from(BILLION) {
return number.to_string();
}
int_to_word_small(number.to_u32().expect("checked < 10^9 and >= 0 above"))
}
fn int_to_word_small(number: u32) -> String {
if number < 10 {
ONES[number as usize].to_string()
} else if number < 100 {
let tens_val = (number / 10) as usize;
let ones_val = (number % 10) as usize;
if ones_val == 0 {
TENS[tens_val].to_string()
} else {
format!("{} {}", TENS[tens_val], ONES[ones_val])
}
} else if number < 1_000 {
let hundreds_val = (number / 100) as usize;
let remainder = number % 100;
let mut result = format!("{} {}", ONES[hundreds_val], HUNDRED);
if remainder != 0 {
result.push(' ');
result.push_str(&int_to_word_small(remainder));
}
result
} else if number < 1_000_000 {
let thousands_val = number / 1_000;
let remainder = number % 1_000;
let mut result = format!("{} {}", int_to_word_small(thousands_val), THOUSAND);
if remainder != 0 {
result.push(' ');
result.push_str(&int_to_word_small(remainder));
}
result
} else {
let millions_val = number / 1_000_000;
let remainder = number % 1_000_000;
let mut result = format!("{} {}", int_to_word_small(millions_val), MILLION);
if remainder != 0 {
result.push(' ');
result.push_str(&int_to_word_small(remainder));
}
result
}
}
fn parse_int(s: &str) -> Result<BigInt> {
s.parse::<BigInt>().map_err(|_| {
N2WError::Value(format!(
"invalid literal for int() with base 10: '{}'",
s
))
})
}
fn python_float_repr(v: f64) -> String {
if v.is_nan() {
return "nan".to_string();
}
if v.is_infinite() {
return (if v.is_sign_negative() { "-inf" } else { "inf" }).to_string();
}
let sign = if v.is_sign_negative() { "-" } else { "" };
let a = v.abs();
let s = format!("{:e}", a);
let (mant, exp) = s.split_once('e').expect("LowerExp always emits an 'e'");
let exp: i32 = exp.parse().expect("LowerExp emits an integer exponent");
let mut digits: String = mant.chars().filter(|c| *c != '.').collect();
let mut decpt = exp + 1;
let frac_digits = digits.chars().count() as i32 - decpt;
if frac_digits > 0 && a != 0.0 {
let t = format!("{:.*}", frac_digits as usize, a);
let (ip, fp) = t.split_once('.').expect("frac_digits > 0 forces a point");
let all = format!("{}{}", ip, fp);
let trimmed = all.trim_start_matches('0');
if !trimmed.is_empty() {
let lead = all.chars().count() - trimmed.chars().count();
digits = trimmed.to_string();
decpt = ip.chars().count() as i32 - lead as i32;
}
}
let n = digits.chars().count() as i32;
if decpt <= -4 || decpt > 16 {
let e = decpt - 1;
let mut out = String::from(sign);
let mut it = digits.chars();
out.push(it.next().expect("a finite double has at least one digit"));
if n > 1 {
out.push('.');
out.push_str(it.as_str());
}
out.push('e');
out.push(if e < 0 { '-' } else { '+' });
out.push_str(&format!("{:02}", (e as i64).abs()));
out
} else if decpt <= 0 {
format!("{}0.{}{}", sign, "0".repeat((-decpt) as usize), digits)
} else if decpt >= n {
format!("{}{}{}.0", sign, digits, "0".repeat((decpt - n) as usize))
} else {
let k = decpt as usize;
format!(
"{}{}.{}",
sign,
digits.chars().take(k).collect::<String>(),
digits.chars().skip(k).collect::<String>()
)
}
}
fn python_decimal_str(d: &BigDecimal) -> String {
let (unscaled, scale) = d.as_bigint_and_exponent();
let sign = if unscaled.is_negative() { "-" } else { "" };
let int_digits = unscaled.abs().to_string();
let exp: i64 = -scale;
let ndig = int_digits.chars().count() as i64;
let leftdigits = exp + ndig;
let dotplace = if exp <= 0 && leftdigits > -6 {
leftdigits
} else {
1
};
let (intpart, fracpart) = if dotplace <= 0 {
(
"0".to_string(),
format!(".{}{}", "0".repeat((-dotplace) as usize), int_digits),
)
} else if dotplace >= ndig {
(
format!("{}{}", int_digits, "0".repeat((dotplace - ndig) as usize)),
String::new(),
)
} else {
let k = dotplace as usize;
(
int_digits.chars().take(k).collect::<String>(),
format!(".{}", int_digits.chars().skip(k).collect::<String>()),
)
};
let exp_part = if leftdigits == dotplace {
String::new()
} else {
format!("E{:+}", leftdigits - dotplace)
};
format!("{}{}{}{}", sign, intpart, fracpart, exp_part)
}
fn python_str(v: &FloatValue) -> String {
match v {
FloatValue::Float { value, .. } => python_float_repr(*value),
FloatValue::Decimal { value, .. } => python_decimal_str(value),
}
}
fn cardinal_from_str(n: &str) -> Result<String> {
let n = n.trim();
let (ret_prefix, n): (&str, &str) = match n.strip_prefix('-') {
Some(rest) => (NEGWORD, rest),
None => ("", n),
};
if let Some((left, right)) = n.split_once('.') {
let mut ret = format!(
"{}{} {} ",
ret_prefix,
int_to_word(&parse_int(left)?),
POINTWORD
);
for ch in right.chars() {
let d = ch.to_digit(10).ok_or_else(|| {
N2WError::Value(format!(
"invalid literal for int() with base 10: '{}'",
ch
))
})?;
ret.push_str(&int_to_word(&BigInt::from(d)));
ret.push(' ');
}
Ok(ret.trim().to_string())
} else {
Ok(format!("{}{}", ret_prefix, int_to_word(&parse_int(n)?))
.trim()
.to_string())
}
}
impl Lang for LangWo {
fn cardinal_float_entry(
&self,
value: &crate::floatpath::FloatValue,
precision_override: Option<u32>,
) -> crate::base::Result<String> {
self.to_cardinal_float(value, precision_override)
}
fn ordinal_float_entry(&self, value: &FloatValue) -> Result<String> {
Ok(format!("{}-eel", self.cardinal_float_entry(value, None)?))
}
fn ordinal_num_float_entry(&self, _value: &FloatValue, repr_str: &str) -> Result<String> {
Ok(format!("{}.", repr_str))
}
fn str_to_number(&self, s: &str) -> Result<ParsedNumber> {
match python_decimal_parse(s)? {
ParsedNumber::Inf { .. } => Err(N2WError::Value(
"invalid literal for int() with base 10: 'Infinity'".into(),
)),
other => Ok(other),
}
}
fn default_currency(&self) -> &str {
"XOF"
}
fn default_separator(&self) -> &str {
" "
}
fn negword(&self) -> &str {
NEGWORD
}
fn pointword(&self) -> &str {
"point"
}
fn to_cardinal(&self, value: &BigInt) -> Result<String> {
let n = value.to_string();
let (ret, magnitude_str) = match n.strip_prefix('-') {
Some(rest) => (NEGWORD, rest),
None => ("", n.as_str()),
};
let magnitude: BigInt = magnitude_str
.parse()
.expect("decimal rendering of a BigInt minus its sign is always parseable");
Ok(format!("{}{}", ret, int_to_word(&magnitude))
.trim()
.to_string())
}
fn to_ordinal(&self, value: &BigInt) -> Result<String> {
Ok(format!("{}-eel", self.to_cardinal(value)?))
}
fn to_ordinal_num(&self, value: &BigInt) -> Result<String> {
Ok(format!("{}.", value))
}
fn to_year(&self, value: &BigInt) -> Result<String> {
self.to_cardinal(value)
}
fn to_cardinal_float(
&self,
value: &FloatValue,
_precision_override: Option<u32>,
) -> Result<String> {
cardinal_from_str(&python_str(value))
}
fn lang_name(&self) -> &str {
"Num2Word_WO"
}
fn currency_forms(&self, code: &str) -> Option<&CurrencyForms> {
self.currency_forms.get(code)
}
fn to_currency(
&self,
val: &CurrencyValue,
currency: &str,
cents: bool,
separator: Option<&str>,
_adjective: bool, ) -> Result<String> {
let separator = separator.unwrap_or(self.default_separator());
let is_negative = val.is_negative();
let s = match val {
CurrencyValue::Int(i) => i.abs().to_string(),
CurrencyValue::Decimal { value: d, .. } => d.abs().to_string(),
};
let mut parts = s.split('.');
let p0 = parts.next().unwrap_or("");
let p1 = parts.next();
let left = if p0.is_empty() {
BigInt::zero()
} else {
parse_int(p0)?
};
let right = match p1 {
Some(frac) if !frac.is_empty() => {
let mut padded: String = frac.chars().take(2).collect();
while padded.chars().count() < 2 {
padded.push('0'); }
parse_int(&padded)?
}
_ => BigInt::zero(),
};
let forms = self
.currency_forms
.get(currency)
.unwrap_or(&self.currency_forms_fallback);
let cr1 = &forms.unit;
let cr2 = &forms.subunit;
let one = BigInt::one();
let mut result = format!(
"{} {}",
int_to_word(&left),
if left != one { &cr1[1] } else { &cr1[0] }
);
if cents && !right.is_zero() {
result.push_str(separator);
result.push_str(&int_to_word(&right));
result.push(' ');
result.push_str(if right != one { &cr2[1] } else { &cr2[0] });
}
if is_negative {
result = format!("{}{}", NEGWORD, result);
}
Ok(result.trim().to_string())
}
}
#[cfg(test)]
mod float_tests {
use super::*;
use bigdecimal::BigDecimal;
use std::str::FromStr;
fn f(value: f64) -> String {
let precision = {
let s = python_float_repr(value);
match s.split_once('.') {
Some((_, frac))
if !frac.contains(|ch: char| matches!(ch, 'e' | 'E' | '+' | '-')) =>
{
frac.chars().count() as u32
}
_ => 0,
}
};
LangWo::new()
.to_cardinal_float(&FloatValue::Float { value, precision }, None)
.unwrap()
}
fn dec(s: &str) -> String {
let value = BigDecimal::from_str(s).unwrap();
let precision = (-value.as_bigint_and_exponent().1).unsigned_abs() as u32;
LangWo::new()
.to_cardinal_float(&FloatValue::Decimal { value, precision }, None)
.unwrap()
}
#[test]
fn corpus_float() {
assert_eq!(f(0.0), "zero point zero");
assert_eq!(f(0.5), "zero point juróom");
assert_eq!(f(1.0), "benn point zero");
assert_eq!(f(1.5), "benn point juróom");
assert_eq!(f(2.25), "ñaar point ñaar juróom");
assert_eq!(f(3.14), "ñett point benn ñeent");
assert_eq!(f(0.01), "zero point zero benn");
assert_eq!(f(0.1), "zero point benn");
assert_eq!(f(0.99), "zero point juróom-ñeent juróom-ñeent");
assert_eq!(f(1.01), "benn point zero benn");
assert_eq!(f(12.34), "fukk ñaar point ñett ñeent");
assert_eq!(
f(99.99),
"juróom-ñeent-fukk juróom-ñeent point juróom-ñeent juróom-ñeent"
);
assert_eq!(f(100.5), "benn téeméer point juróom");
assert_eq!(
f(1234.56),
"benn junni ñaar téeméer ñett-fukk ñeent point juróom juróom-benn"
);
assert_eq!(f(-0.5), "minus zero point juróom");
assert_eq!(f(-1.5), "minus benn point juróom");
assert_eq!(f(-12.34), "minus fukk ñaar point ñett ñeent");
assert_eq!(f(1.005), "benn point zero zero juróom");
assert_eq!(f(2.675), "ñaar point juróom-benn juróom-ñaar juróom");
}
#[test]
fn corpus_decimal() {
assert_eq!(dec("0.01"), "zero point zero benn");
assert_eq!(dec("1.10"), "benn point benn zero");
assert_eq!(dec("12.345"), "fukk ñaar point ñett ñeent juróom");
assert_eq!(
dec("98746251323029.99"),
"98746251323029 point juróom-ñeent juróom-ñeent"
);
assert_eq!(dec("0.001"), "zero point zero zero benn");
}
#[test]
fn float_edges() {
assert_eq!(f(-0.0), "minus zero point zero");
assert_eq!(f(670352580196876.25), "670352580196876 point ñaar");
assert_eq!(dec("5"), "juróom");
assert_eq!(dec("-5"), "minus juróom");
}
#[test]
fn exponent_literals_raise_value_error() {
let whole = LangWo::new().to_cardinal_float(
&FloatValue::Float {
value: 1e16,
precision: 16,
},
None,
);
match whole {
Err(N2WError::Value(m)) => {
assert_eq!(m, "invalid literal for int() with base 10: '1e+16'")
}
other => panic!("expected ValueError, got {:?}", other),
}
let dotted = LangWo::new().to_cardinal_float(
&FloatValue::Float {
value: 1.5e16,
precision: 16,
},
None,
);
match dotted {
Err(N2WError::Value(m)) => {
assert_eq!(m, "invalid literal for int() with base 10: 'e'")
}
other => panic!("expected ValueError, got {:?}", other),
}
let d = LangWo::new().to_cardinal_float(
&FloatValue::Decimal {
value: BigDecimal::from_str("1E+16").unwrap(),
precision: 0,
},
None,
);
match d {
Err(N2WError::Value(m)) => {
assert_eq!(m, "invalid literal for int() with base 10: '1E+16'")
}
other => panic!("expected ValueError, got {:?}", other),
}
}
#[test]
fn precision_override_ignored() {
let full = LangWo::new()
.to_cardinal_float(
&FloatValue::Float {
value: 2.675,
precision: 3,
},
Some(1),
)
.unwrap();
assert_eq!(full, "ñaar point juróom-benn juróom-ñaar juróom");
}
}