use crate::base::{Lang, N2WError, Result};
use crate::currency::{CurrencyForms, CurrencyValue};
use crate::floatpath::FloatValue;
use bigdecimal::BigDecimal;
use num_bigint::BigInt;
use num_integer::Integer;
use num_traits::{One, Signed, ToPrimitive, Zero};
use std::collections::HashMap;
const NEGWORD: &str = "ਮਾਇਨਸ ";
const POINTWORD: &str = "ਦਸ਼ਮਲਵ";
const ZERO: &str = "ਸਿਫਰ";
const HUNDRED: &str = "ਸੌ";
const THOUSAND: &str = "ਹਜ਼ਾਰ";
const LAKH: &str = "ਲੱਖ";
const CRORE: &str = "ਕਰੋੜ";
const ONES: [&str; 10] = ["", "ਇੱਕ", "ਦੋ", "ਤਿੰਨ", "ਚਾਰ", "ਪੰਜ", "ਛੇ", "ਸੱਤ", "ਅੱਠ", "ਨੌ"];
const TENS: [&str; 10] = [
"",
"ਦਸ",
"ਵੀਹ",
"ਤੀਹ",
"ਚਾਲੀ",
"ਪੰਜਾਹ",
"ਸੱਠ",
"ਸੱਤਰ",
"ਅੱਸੀ",
"ਨੱਬੇ",
];
const TEENS: [&str; 10] = [
"ਦਸ",
"ਗਿਆਰਾਂ",
"ਬਾਰਾਂ",
"ਤੇਰਾਂ",
"ਚੌਦਾਂ",
"ਪੰਦਰਾਂ",
"ਸੋਲਾਂ",
"ਸਤਾਰਾਂ",
"ਅਠਾਰਾਂ",
"ਉੱਨੀ",
];
const ORDINAL_SUFFIX: &str = "ਵਾਂ";
const ORDINAL_SPECIALS: [&str; 6] = [
"", "ਪਹਿਲਾ", "ਦੂਜਾ", "ਤੀਜਾ", "ਚੌਥਾ", "ਪੰਜਵਾਂ", ];
fn to_usize(n: &BigInt) -> usize {
n.to_usize().expect("caller proved this value is < 1000")
}
fn int_to_word(n: &BigInt) -> String {
if n.is_zero() {
return ZERO.to_string();
}
if n.is_negative() {
return format!("{}{}", NEGWORD, int_to_word(&n.abs()));
}
if n < &BigInt::from(10) {
return ONES[to_usize(n)].to_string();
}
if n < &BigInt::from(20) {
return TEENS[to_usize(n) - 10].to_string();
}
if n < &BigInt::from(100) {
let v = to_usize(n);
let mut result = TENS[v / 10].to_string();
if v % 10 != 0 {
result.push(' ');
result.push_str(ONES[v % 10]);
}
return result;
}
if n < &BigInt::from(1000) {
let v = to_usize(n);
let mut result = format!("{} {}", ONES[v / 100], HUNDRED);
let remainder = v % 100;
if remainder != 0 {
result.push(' ');
result.push_str(&int_to_word(&BigInt::from(remainder)));
}
return result;
}
for (limit, divisor, word) in [
(100_000u64, 1_000u64, THOUSAND),
(10_000_000u64, 100_000u64, LAKH),
(1_000_000_000u64, 10_000_000u64, CRORE),
] {
if n < &BigInt::from(limit) {
let (quotient, remainder) = n.div_mod_floor(&BigInt::from(divisor));
let mut result = format!("{} {}", int_to_word("ient), word);
if !remainder.is_zero() {
result.push(' ');
result.push_str(&int_to_word(&remainder));
}
return result;
}
}
n.to_string()
}
fn shortest_digits(a: f64) -> (String, i32) {
let sci = format!("{:e}", a);
let (mant, exp) = sci
.split_once('e')
.expect("{:e} on a finite f64 always emits an exponent");
let mut digits: Vec<u8> = mant.bytes().filter(|c| *c != b'.').collect();
let mut decpt: i32 = exp.parse::<i32>().expect("{:e} exponent is an integer") + 1;
let bits = a.to_bits();
let biased = ((bits >> 52) & 0x7ff) as i32;
let frac = bits & ((1u64 << 52) - 1);
let (mut m, mut e) = if biased == 0 {
(frac, -1074i32) } else {
(frac | (1u64 << 52), biased - 1075)
};
if m == 0 {
return (String::from_utf8(digits).expect("ASCII digits"), decpt);
}
let z = m.trailing_zeros() as i32;
m >>= z;
e += z;
let q = digits.len() as i32 - decpt;
let mut tie = e + q + 1 == 0;
if tie && q < 0 {
let r = -q as u32;
tie = r <= 22 && m % 5u64.pow(r) == 0;
}
if !tie {
return (String::from_utf8(digits).expect("ASCII digits"), decpt);
}
let last = digits[digits.len() - 1] - b'0';
if last % 2 == 1 {
if m % 4 == 1 {
*digits.last_mut().expect("non-empty") -= 1;
} else {
let mut i = digits.len();
loop {
if i == 0 {
digits.insert(0, b'1');
decpt += 1;
break;
}
i -= 1;
if digits[i] == b'9' {
digits[i] = b'0';
} else {
digits[i] += 1;
break;
}
}
}
while digits.len() > 1 && *digits.last().expect("non-empty") == b'0' {
digits.pop();
}
}
(String::from_utf8(digits).expect("ASCII digits"), decpt)
}
fn py_float_repr(value: f64) -> String {
if value.is_nan() {
return "nan".to_string();
}
if value.is_infinite() {
return if value > 0.0 { "inf" } else { "-inf" }.to_string();
}
let sign = if value.is_sign_negative() { "-" } else { "" };
let (digits, decpt) = shortest_digits(value.abs());
let ndigits = digits.len() as i32;
if decpt <= -4 || decpt > 16 {
let exp = decpt - 1;
let mut mant = String::from(&digits[..1]);
if digits.len() > 1 {
mant.push('.');
mant.push_str(&digits[1..]);
}
format!(
"{}{}e{}{:02}",
sign,
mant,
if exp < 0 { '-' } else { '+' },
exp.abs()
)
} else if decpt <= 0 {
format!("{}0.{}{}", sign, "0".repeat(-decpt as usize), digits)
} else if decpt >= ndigits {
format!(
"{}{}{}.0",
sign,
digits,
"0".repeat((decpt - ndigits) as usize)
)
} else {
let d = decpt as usize;
format!("{}{}.{}", sign, &digits[..d], &digits[d..])
}
}
fn py_decimal_str(value: &BigDecimal) -> String {
let (int_val, scale) = value.as_bigint_and_exponent();
let exp = -(scale as i128);
let sign = if int_val.is_negative() { "-" } else { "" };
let int_digits = int_val.abs().to_string(); let len = int_digits.len() as i128;
let leftdigits = exp + len;
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 >= len {
(
format!("{}{}", int_digits, "0".repeat((dotplace - len) as usize)),
String::new(),
)
} else {
let d = dotplace as usize;
(
int_digits[..d].to_string(),
format!(".{}", &int_digits[d..]),
)
};
let expstr = if leftdigits == dotplace {
String::new()
} else {
let d = leftdigits - dotplace;
format!("E{}{}", if d < 0 { '-' } else { '+' }, d.abs())
};
format!("{}{}{}{}", sign, intpart, fracpart, expstr)
}
fn py_int(s: &str) -> Result<BigInt> {
let err = || N2WError::Value(format!("invalid literal for int() with base 10: '{}'", s));
let t = s.trim();
let (negative, body) = match t.strip_prefix('-') {
Some(rest) => (true, rest),
None => (false, t.strip_prefix('+').unwrap_or(t)),
};
if body.is_empty()
|| body.starts_with('_')
|| body.ends_with('_')
|| body.contains("__")
|| !body.chars().all(|c| c.is_ascii_digit() || c == '_')
{
return Err(err());
}
let digits: String = body.chars().filter(|c| *c != '_').collect();
let n: BigInt = digits.parse().map_err(|_| err())?;
Ok(if negative { -n } else { n })
}
fn cardinal_from_str(number: &str) -> Result<String> {
let n = number.trim();
let (n, mut ret) = match n.strip_prefix('-') {
Some(rest) => (rest, NEGWORD.to_string()),
None => (n, String::new()),
};
let Some(dot) = n.find('.') else {
ret.push_str(&int_to_word(&py_int(n)?));
return Ok(ret.trim().to_string());
};
let (left, right) = (&n[..dot], &n[dot + 1..]);
ret.push_str(&int_to_word(&py_int(left)?));
ret.push(' ');
ret.push_str(POINTWORD);
ret.push(' ');
let mut first = true;
for d in right.chars() {
if !first {
ret.push(' ');
}
first = false;
let mut buf = [0u8; 4];
ret.push_str(&int_to_word(&py_int(d.encode_utf8(&mut buf))?));
}
Ok(ret.trim().to_string())
}
fn split_currency_parts(val: &CurrencyValue) -> (BigInt, BigInt) {
let d = match val {
CurrencyValue::Int(v) => return (v.abs(), BigInt::zero()),
CurrencyValue::Decimal { value: d, .. } => d.abs(),
};
let (unscaled, scale) = d.as_bigint_and_exponent();
let digits = unscaled.to_string();
if scale <= 0 {
let mut int_digits = digits;
int_digits.push_str(&"0".repeat((-scale) as usize));
return (parse_digits(&int_digits), BigInt::zero());
}
let scale = scale as usize;
let padded = if digits.len() <= scale {
format!("{}{}", "0".repeat(scale - digits.len() + 1), digits)
} else {
digits
};
let split_at = padded.len() - scale;
let (int_part, frac_part) = padded.split_at(split_at);
let mut cents: String = frac_part.chars().take(2).collect();
while cents.len() < 2 {
cents.push('0');
}
(parse_digits(int_part), parse_digits(¢s))
}
fn parse_digits(s: &str) -> BigInt {
s.parse::<BigInt>()
.expect("digit string built from a BigInt's own decimal form")
}
pub struct LangPa {
forms: HashMap<&'static str, CurrencyForms>,
}
impl Default for LangPa {
fn default() -> Self {
Self::new()
}
}
impl LangPa {
pub fn new() -> Self {
let mut forms = HashMap::new();
forms.insert("INR", CurrencyForms::new(&["ਰੁਪਈਆ", "ਰੁਪਏ"], &["ਪੈਸਾ", "ਪੈਸੇ"]));
forms.insert(
"USD",
CurrencyForms::new(&["dollar", "dollars"], &["cent", "cents"]),
);
forms.insert(
"EUR",
CurrencyForms::new(&["euro", "euros"], &["cent", "cents"]),
);
LangPa { forms }
}
fn forms_or_inr(&self, currency: &str) -> &CurrencyForms {
self.forms
.get(currency)
.or_else(|| self.forms.get("INR"))
.expect("INR is always present in the table")
}
}
impl Lang for LangPa {
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 default_currency(&self) -> &str {
"INR"
}
fn default_separator(&self) -> &str {
" "
}
fn negword(&self) -> &str {
NEGWORD
}
fn pointword(&self) -> &str {
"ਦਸ਼ਮਲਵ"
}
fn to_cardinal_float(
&self,
value: &FloatValue,
precision_override: Option<u32>,
) -> Result<String> {
let _ = precision_override;
let n = match value {
FloatValue::Float { value, .. } => py_float_repr(*value),
FloatValue::Decimal { value, .. } => py_decimal_str(value),
};
cardinal_from_str(&n)
}
fn to_cardinal(&self, value: &BigInt) -> Result<String> {
let ret = if value.is_negative() { NEGWORD } else { "" };
Ok(format!("{}{}", ret, int_to_word(&value.abs()))
.trim()
.to_string())
}
fn to_ordinal(&self, value: &BigInt) -> Result<String> {
if value.is_positive() {
if let Some(i) = value.to_usize() {
if i <= 5 {
return Ok(ORDINAL_SPECIALS[i].to_string());
}
}
}
Ok(format!("{}{}", self.to_cardinal(value)?, ORDINAL_SUFFIX))
}
fn to_ordinal_num(&self, value: &BigInt) -> Result<String> {
Ok(format!("{}.", value))
}
fn to_year(&self, value: &BigInt) -> Result<String> {
if value.is_negative() {
Ok(format!("BC {}", self.to_cardinal(&value.abs())?))
} else {
self.to_cardinal(value)
}
}
fn ordinal_float_entry(&self, value: &FloatValue) -> Result<String> {
if let Some(i) = value.as_whole_int() {
if i.is_positive() && i <= BigInt::from(5) {
return self.to_ordinal(&i);
}
}
Ok(format!(
"{}{}",
self.cardinal_float_entry(value, None)?,
ORDINAL_SUFFIX
))
}
fn ordinal_num_float_entry(&self, _value: &FloatValue, repr_str: &str) -> Result<String> {
Ok(format!("{}.", repr_str))
}
fn year_float_entry(&self, value: &FloatValue) -> Result<String> {
let negative = match value {
FloatValue::Float { value, .. } => *value < 0.0,
FloatValue::Decimal { value, .. } => value.is_negative(),
};
if negative {
let abs = match value {
FloatValue::Float { value, precision } => FloatValue::Float {
value: value.abs(),
precision: *precision,
},
FloatValue::Decimal { value, precision } => FloatValue::Decimal {
value: value.abs(),
precision: *precision,
},
};
Ok(format!("BC {}", self.cardinal_float_entry(&abs, None)?))
} else {
self.cardinal_float_entry(value, None)
}
}
fn str_to_number(&self, s: &str) -> Result<crate::strnum::ParsedNumber> {
match crate::strnum::python_decimal_parse(s)? {
crate::strnum::ParsedNumber::Inf { .. } => Err(N2WError::Value(
"invalid literal for int() with base 10: 'Infinity'".into(),
)),
other => Ok(other),
}
}
fn lang_name(&self) -> &str {
"Num2Word_PA"
}
fn currency_forms(&self, code: &str) -> Option<&CurrencyForms> {
self.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 (left, right) = split_currency_parts(val);
let forms = self.forms_or_inr(currency);
let unit = if left.is_one() {
&forms.unit[0]
} else {
&forms.unit[1]
};
let mut result = format!("{} {}", int_to_word(&left), unit);
if cents && !right.is_zero() {
let subunit = if right.is_one() {
&forms.subunit[0]
} else {
&forms.subunit[1]
};
result.push_str(separator);
result.push_str(&int_to_word(&right));
result.push(' ');
result.push_str(subunit);
}
if is_negative {
result = format!("{}{}", NEGWORD, result);
}
Ok(result.trim().to_string())
}
}
#[cfg(test)]
mod float_tests {
use super::*;
use std::str::FromStr;
fn flt(v: f64) -> String {
let precision = py_float_repr(v)
.split_once('.')
.map(|(_, f)| f.len() as u32)
.unwrap_or(0);
LangPa::new()
.to_cardinal_float(
&FloatValue::Float {
value: v,
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;
LangPa::new()
.to_cardinal_float(&FloatValue::Decimal { value, precision }, None)
.unwrap()
}
#[test]
fn corpus_float_rows() {
assert_eq!(flt(0.0), "ਸਿਫਰ ਦਸ਼ਮਲਵ ਸਿਫਰ");
assert_eq!(flt(0.5), "ਸਿਫਰ ਦਸ਼ਮਲਵ ਪੰਜ");
assert_eq!(flt(1.0), "ਇੱਕ ਦਸ਼ਮਲਵ ਸਿਫਰ");
assert_eq!(flt(1.5), "ਇੱਕ ਦਸ਼ਮਲਵ ਪੰਜ");
assert_eq!(flt(2.25), "ਦੋ ਦਸ਼ਮਲਵ ਦੋ ਪੰਜ");
assert_eq!(flt(3.14), "ਤਿੰਨ ਦਸ਼ਮਲਵ ਇੱਕ ਚਾਰ");
assert_eq!(flt(0.01), "ਸਿਫਰ ਦਸ਼ਮਲਵ ਸਿਫਰ ਇੱਕ");
assert_eq!(flt(0.1), "ਸਿਫਰ ਦਸ਼ਮਲਵ ਇੱਕ");
assert_eq!(flt(0.99), "ਸਿਫਰ ਦਸ਼ਮਲਵ ਨੌ ਨੌ");
assert_eq!(flt(1.01), "ਇੱਕ ਦਸ਼ਮਲਵ ਸਿਫਰ ਇੱਕ");
assert_eq!(flt(12.34), "ਬਾਰਾਂ ਦਸ਼ਮਲਵ ਤਿੰਨ ਚਾਰ");
assert_eq!(flt(99.99), "ਨੱਬੇ ਨੌ ਦਸ਼ਮਲਵ ਨੌ ਨੌ");
assert_eq!(flt(100.5), "ਇੱਕ ਸੌ ਦਸ਼ਮਲਵ ਪੰਜ");
assert_eq!(flt(1234.56), "ਇੱਕ ਹਜ਼ਾਰ ਦੋ ਸੌ ਤੀਹ ਚਾਰ ਦਸ਼ਮਲਵ ਪੰਜ ਛੇ");
assert_eq!(flt(-0.5), "ਮਾਇਨਸ ਸਿਫਰ ਦਸ਼ਮਲਵ ਪੰਜ");
assert_eq!(flt(-1.5), "ਮਾਇਨਸ ਇੱਕ ਦਸ਼ਮਲਵ ਪੰਜ");
assert_eq!(flt(-12.34), "ਮਾਇਨਸ ਬਾਰਾਂ ਦਸ਼ਮਲਵ ਤਿੰਨ ਚਾਰ");
assert_eq!(flt(1.005), "ਇੱਕ ਦਸ਼ਮਲਵ ਸਿਫਰ ਸਿਫਰ ਪੰਜ");
assert_eq!(flt(2.675), "ਦੋ ਦਸ਼ਮਲਵ ਛੇ ਸੱਤ ਪੰਜ");
}
#[test]
fn corpus_decimal_rows() {
assert_eq!(dec("0.01"), "ਸਿਫਰ ਦਸ਼ਮਲਵ ਸਿਫਰ ਇੱਕ");
assert_eq!(dec("1.10"), "ਇੱਕ ਦਸ਼ਮਲਵ ਇੱਕ ਸਿਫਰ");
assert_eq!(dec("12.345"), "ਬਾਰਾਂ ਦਸ਼ਮਲਵ ਤਿੰਨ ਚਾਰ ਪੰਜ");
assert_eq!(dec("98746251323029.99"), "98746251323029 ਦਸ਼ਮਲਵ ਨੌ ਨੌ");
assert_eq!(dec("0.001"), "ਸਿਫਰ ਦਸ਼ਮਲਵ ਸਿਫਰ ਸਿਫਰ ਇੱਕ");
}
#[test]
fn negative_zero_keeps_negword() {
assert_eq!(flt(-0.0), "ਮਾਇਨਸ ਸਿਫਰ ਦਸ਼ਮਲਵ ਸਿਫਰ");
}
#[test]
fn repr_tie_to_even() {
assert_eq!(flt(-78198386800398.125), "ਮਾਇਨਸ 78198386800398 ਦਸ਼ਮਲਵ ਇੱਕ ਦੋ");
}
#[test]
fn exponent_notation_raises_value_error() {
let cases = [
(1e16, "1e+16"),
(1e-05, "1e-05"),
(1.5e16, "e"),
(1.5e-05, "e"),
];
for (v, lit) in cases {
let precision = py_float_repr(v)
.split_once('.')
.map(|(_, f)| f.len() as u32)
.unwrap_or(0);
match LangPa::new().to_cardinal_float(
&FloatValue::Float {
value: v,
precision,
},
None,
) {
Err(N2WError::Value(m)) => assert_eq!(
m,
format!("invalid literal for int() with base 10: '{}'", lit),
"value {:?}",
v
),
other => panic!("expected ValueError for {:?}, got {:?}", v, other),
}
}
}
#[test]
fn precision_override_ignored() {
assert_eq!(
flt(1.23456),
LangPa::new()
.to_cardinal_float(
&FloatValue::Float {
value: 1.23456,
precision: 5,
},
Some(1),
)
.unwrap()
);
}
}