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_integer::Integer;
use num_traits::{Signed, ToPrimitive, Zero};
use std::collections::HashMap;
const NEGWORD: &str = "ऋण ";
const POINTWORD: &str = "दशांश";
const ZERO_WORD: &str = "शून्य";
const ONES: [&str; 10] = [
"", "एक", "दोन", "तीन", "चार", "पाच", "सहा", "सात", "आठ", "नऊ",
];
const TENS: [&str; 10] = [
"", "दहा", "वीस", "तीस", "चाळीस", "पन्नास", "साठ", "सत्तर", "ऐंशी", "नव्वद",
];
const TEENS: [&str; 10] = [
"दहा", "अकरा", "बारा", "तेरा", "चौदा", "पंधरा", "सोळा", "सतरा", "अठरा", "एकोणीस",
];
const NINETY_NINE: &str = "नव्याण्णव";
const HUNDRED_SUFFIX: &str = "शे";
const ORDINAL_SUFFIX: &str = "वा";
const ORDINAL_SPECIALS: [(u64, &str); 10] = [
(1, "पहिला"),
(2, "दुसरा"),
(3, "तिसरा"),
(4, "चौथा"),
(5, "पाचवा"),
(6, "सहावा"),
(7, "सातवा"),
(8, "आठवा"),
(9, "नववा"),
(10, "दहावा"),
];
const YEAR_PREFIX: &str = "सन ";
const YEAR_BC_PREFIX: &str = "इसवीसन पूर्व ";
const SEPARATOR_DEFAULT: &str = " आणि ";
const SEPARATOR_UNSET: &str = ",";
const CURRENCY_FALLBACK: &str = "INR";
fn bi(n: u64) -> BigInt {
BigInt::from(n)
}
fn small(n: &BigInt) -> usize {
n.to_usize()
.expect("caller guarantees this value is range-checked below 1000")
}
fn scale(number: &BigInt, divisor: u64, word: &str) -> String {
let (div, rem) = number.div_mod_floor(&bi(divisor));
let mut result = format!("{} {}", int_to_word(&div), word);
if !rem.is_zero() {
result.push(' ');
result.push_str(&int_to_word(&rem));
}
result
}
fn int_to_word(number: &BigInt) -> String {
if number.is_zero() {
return ZERO_WORD.to_string();
}
if number.is_negative() {
return format!("{}{}", NEGWORD, int_to_word(&number.abs()));
}
if number < &bi(10) {
return ONES[small(number)].to_string();
}
if number < &bi(20) {
return TEENS[small(number) - 10].to_string();
}
if number < &bi(100) {
let n = small(number);
let tens_digit = n / 10;
let ones_digit = n % 10;
let mut result = TENS[tens_digit].to_string();
if ones_digit != 0 {
if tens_digit == 2 {
result = if n == 21 {
format!("एक{}", TENS[2])
} else {
format!("{}{}", ONES[ones_digit], TENS[2])
};
} else if tens_digit == 9 && ones_digit == 9 {
result = NINETY_NINE.to_string();
} else {
result.push(' ');
result.push_str(ONES[ones_digit]);
}
}
return result;
}
if number < &bi(1000) {
let (div, rem) = number.div_mod_floor(&bi(100));
let mut result = format!("{}{}", ONES[small(&div)], HUNDRED_SUFFIX);
if !rem.is_zero() {
result.push(' ');
result.push_str(&int_to_word(&rem));
}
return result;
}
if number < &bi(100_000) {
return scale(number, 1_000, "हजार");
}
if number < &bi(10_000_000) {
return scale(number, 100_000, "लाख");
}
if number < &bi(1_000_000_000) {
return scale(number, 10_000_000, "कोटी");
}
if number < &bi(100_000_000_000) {
return scale(number, 1_000_000_000, "अब्ज");
}
scale(number, 100_000_000_000, "खर्व")
}
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);
};
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)
}
pub struct LangMr {
currency_forms: HashMap<&'static str, CurrencyForms>,
}
impl LangMr {
pub fn new() -> Self {
let mut currency_forms = HashMap::new();
currency_forms.insert(
"INR",
CurrencyForms::new(&["रुपया", "रुपये"], &["पैसा", "पैसे"]),
);
currency_forms.insert(
"USD",
CurrencyForms::new(&["डॉलर", "डॉलर"], &["सेंट", "सेंट्स"]),
);
currency_forms.insert(
"EUR",
CurrencyForms::new(&["युरो", "युरो"], &["सेंट", "सेंट्स"]),
);
currency_forms.insert(
"GBP",
CurrencyForms::new(&["पाउंड", "पाउंड"], &["पेन्स", "पेन्स"]),
);
LangMr { currency_forms }
}
}
impl Default for LangMr {
fn default() -> Self {
Self::new()
}
}
impl Lang for LangMr {
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> {
if let Some(i) = value.as_whole_int() {
for (k, word) in ORDINAL_SPECIALS {
if i == bi(k) {
return Ok(word.to_string());
}
}
}
Ok(format!(
"{}{}",
self.to_cardinal_float(value, None)?,
ORDINAL_SUFFIX
))
}
fn ordinal_num_float_entry(&self, value: &FloatValue, repr_str: &str) -> Result<String> {
if let Some(i) = value.as_whole_int() {
if i == bi(1) {
return Ok("१ला".to_string());
}
if i == bi(2) {
return Ok("२रा".to_string());
}
if i == bi(3) {
return Ok("३रा".to_string());
}
if i == bi(4) {
return Ok("४था".to_string());
}
}
Ok(format!("{}{}", repr_str, ORDINAL_SUFFIX))
}
fn year_float_entry(&self, value: &FloatValue) -> Result<String> {
let below_zero = match value {
FloatValue::Float { value, .. } => *value < 0.0,
FloatValue::Decimal { value, .. } => value.is_negative(),
};
if below_zero {
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!(
"{}{}",
YEAR_BC_PREFIX,
self.to_cardinal_float(&abs, None)?
))
} else {
Ok(format!(
"{}{}",
YEAR_PREFIX,
self.to_cardinal_float(value, None)?
))
}
}
fn str_to_number(&self, s: &str) -> Result<ParsedNumber> {
let parsed = python_decimal_parse(s)?;
Ok(parsed)
}
fn inf_result(&self, negative: bool, to: &str) -> Result<String> {
match to {
"ordinal_num" => Ok(format!(
"{}Infinity{}",
if negative { "-" } else { "" },
ORDINAL_SUFFIX
)),
_ => Err(N2WError::Value(
"invalid literal for int() with base 10: 'Infinity'".to_string(),
)),
}
}
fn nan_result(&self, to: &str) -> Result<String> {
match to {
"ordinal_num" => Ok(format!("NaN{}", ORDINAL_SUFFIX)),
"year" => Err(N2WError::Custom {
module: "decimal",
class: "InvalidOperation",
msg: "[<class 'decimal.InvalidOperation'>]".to_string(),
}),
_ => Err(N2WError::Value(
"invalid literal for int() with base 10: 'NaN'".to_string(),
)),
}
}
fn default_currency(&self) -> &str {
"INR"
}
fn default_separator(&self) -> &str {
" आणि "
}
fn negword(&self) -> &str {
NEGWORD
}
fn pointword(&self) -> &str {
"दशांश"
}
fn to_cardinal(&self, value: &BigInt) -> Result<String> {
let (ret, n) = if value.is_negative() {
(NEGWORD, value.abs())
} else {
("", value.clone())
};
Ok(format!("{}{}", ret, int_to_word(&n)).trim().to_string())
}
fn to_ordinal(&self, value: &BigInt) -> Result<String> {
for (k, word) in ORDINAL_SPECIALS {
if value == &bi(k) {
return Ok(word.to_string());
}
}
Ok(format!("{}{}", self.to_cardinal(value)?, ORDINAL_SUFFIX))
}
fn to_ordinal_num(&self, value: &BigInt) -> Result<String> {
if value == &bi(1) {
return Ok("१ला".to_string());
}
if value == &bi(2) {
return Ok("२रा".to_string());
}
if value == &bi(3) {
return Ok("३रा".to_string());
}
if value == &bi(4) {
return Ok("४था".to_string());
}
Ok(format!("{}{}", value, ORDINAL_SUFFIX))
}
fn to_year(&self, value: &BigInt) -> Result<String> {
if value.is_negative() {
Ok(format!(
"{}{}",
YEAR_BC_PREFIX,
self.to_cardinal(&value.abs())?
))
} else {
Ok(format!("{}{}", YEAR_PREFIX, self.to_cardinal(value)?))
}
}
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),
};
Ok(cardinal_from_str(&n)?.trim().to_string())
}
fn lang_name(&self) -> &str {
"Num2Word_MR"
}
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 separator = if separator == SEPARATOR_UNSET {
SEPARATOR_DEFAULT
} else {
separator
};
let _ = adjective;
let is_negative = val.is_negative();
let s = match val {
CurrencyValue::Int(v) => {
if is_negative {
v.abs().to_string()
} else {
v.to_string()
}
}
CurrencyValue::Decimal { value: d, .. } => {
if is_negative {
d.abs().to_string()
} else {
d.to_string()
}
}
};
let parts: Vec<&str> = s.split('.').collect();
let left = if parts[0].is_empty() {
BigInt::zero()
} else {
parts[0]
.parse::<BigInt>()
.map_err(|e| N2WError::Value(e.to_string()))?
};
let right = if parts.len() > 1 && !parts[1].is_empty() {
let mut frac: String = parts[1].chars().take(2).collect();
while frac.chars().count() < 2 {
frac.push('0');
}
frac.parse::<BigInt>()
.map_err(|e| N2WError::Value(e.to_string()))?
} else {
BigInt::zero()
};
let forms = match self.currency_forms.get(currency) {
Some(f) => f,
None => self
.currency_forms
.get(CURRENCY_FALLBACK)
.expect("INR is inserted by LangMr::new"),
};
let cr1 = &forms.unit;
let cr2 = &forms.subunit;
let one = bi(1);
let left_str = int_to_word(&left);
let mut result = format!(
"{} {}",
left_str,
if left != one { &cr1[1] } else { &cr1[0] }
);
if cents && !right.is_zero() {
let cents_str = int_to_word(&right);
result.push_str(separator);
result.push_str(¢s_str);
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())
}
}