use crate::stdlib::common::*;
use bigdecimal::{BigDecimal, RoundingMode, Zero};
use fusevm::Value;
use num_bigint::BigInt;
use std::cell::Cell;
use std::str::FromStr;
thread_local! {
static BC_SCALE: Cell<i64> = const { Cell::new(0) };
}
fn current_scale() -> i64 {
BC_SCALE.with(|c| c.get())
}
fn bc_normalize(s: &str) -> Option<String> {
let (sign, rest) = match s.as_bytes().first() {
Some(b'-') => ("-", &s[1..]),
Some(b'+') => ("", &s[1..]),
_ => ("", s),
};
let (int, frac) = rest.split_once('.').unwrap_or((rest, ""));
if !int.bytes().all(|b| b.is_ascii_digit()) || !frac.bytes().all(|b| b.is_ascii_digit()) {
return None;
}
let int = if int.is_empty() { "0" } else { int };
let frac = if frac.is_empty() { "0" } else { frac };
Some(format!("{sign}{int}.{frac}"))
}
fn bc_operand(
args: &[Value],
idx: usize,
func: &str,
pos: usize,
name: &str,
) -> Result<BigDecimal, String> {
let raw = str_arg(args, idx);
let norm = bc_normalize(&raw).ok_or_else(|| {
throws(
"ValueError",
format!("{func}(): Argument #{pos} (${name}) is not well-formed"),
)
})?;
Ok(BigDecimal::from_str(&norm).unwrap_or_else(|_| BigDecimal::zero()))
}
fn bc_integral(bd: &BigDecimal, func: &str, pos: usize, name: &str) -> Result<BigInt, String> {
if bd.with_scale_round(0, RoundingMode::Down) != *bd {
return Err(throws(
"ValueError",
format!("{func}(): Argument #{pos} (${name}) cannot have a fractional part"),
));
}
Ok(bd_to_bigint(bd))
}
fn scale_arg(args: &[Value], idx: usize) -> i64 {
let s = if args.len() > idx {
int_arg(args, idx)
} else {
current_scale()
};
s.clamp(0, 1 << 20)
}
fn format_scaled(bd: &BigDecimal, scale: i64) -> String {
let scale = scale.max(0);
let truncated = bd.with_scale_round(scale, RoundingMode::Down);
let raw = truncated.to_plain_string();
let neg = raw.starts_with('-');
let mut body = raw.trim_start_matches('-').to_string();
if scale > 0 {
match body.find('.') {
Some(dot) => {
let frac = body.len() - dot - 1;
if frac < scale as usize {
body.push_str(&"0".repeat(scale as usize - frac));
}
}
None => {
body.push('.');
body.push_str(&"0".repeat(scale as usize));
}
}
} else if let Some(dot) = body.find('.') {
body.truncate(dot);
}
let is_zero = body.bytes().all(|b| b == b'0' || b == b'.');
if neg && !is_zero {
format!("-{body}")
} else {
body
}
}
fn bd_to_bigint(bd: &BigDecimal) -> BigInt {
let int_str = bd.with_scale_round(0, RoundingMode::Down).to_plain_string();
BigInt::from_str(&int_str).unwrap_or_else(|_| BigInt::zero())
}
fn bd_pow(base: &BigDecimal, exp: i64) -> BigDecimal {
if exp == 0 {
return BigDecimal::from(1);
}
let mut result = BigDecimal::from(1);
let mut b = base.clone();
let mut e = exp.unsigned_abs();
while e > 0 {
if e & 1 == 1 {
result *= b.clone();
}
e >>= 1;
if e > 0 {
b = b.clone() * b.clone();
}
}
if exp < 0 {
BigDecimal::from(1) / result
} else {
result
}
}
pub fn dispatch(name: &str, args: &[Value]) -> Option<Result<Value, String>> {
let mut unhandled = false;
let out: Result<Value, String> = (|| match name {
"bcadd" => {
let a = bc_operand(args, 0, "bcadd", 1, "num1")?;
let b = bc_operand(args, 1, "bcadd", 2, "num2")?;
let s = scale_arg(args, 2);
Ok(Value::str(format_scaled(&(a + b), s)))
}
"bcsub" => {
let a = bc_operand(args, 0, "bcsub", 1, "num1")?;
let b = bc_operand(args, 1, "bcsub", 2, "num2")?;
let s = scale_arg(args, 2);
Ok(Value::str(format_scaled(&(a - b), s)))
}
"bcmul" => {
let a = bc_operand(args, 0, "bcmul", 1, "num1")?;
let b = bc_operand(args, 1, "bcmul", 2, "num2")?;
let s = scale_arg(args, 2);
Ok(Value::str(format_scaled(&(a * b), s)))
}
"bcdiv" => {
let a = bc_operand(args, 0, "bcdiv", 1, "num1")?;
let b = bc_operand(args, 1, "bcdiv", 2, "num2")?;
let s = scale_arg(args, 2);
if b.is_zero() {
Err(throws("DivisionByZeroError", "Division by zero"))
} else {
Ok(Value::str(format_scaled(&(a / b), s)))
}
}
"bcmod" => {
let a = bc_operand(args, 0, "bcmod", 1, "num1")?;
let b = bc_operand(args, 1, "bcmod", 2, "num2")?;
let s = scale_arg(args, 2);
if b.is_zero() {
Err(throws("DivisionByZeroError", "Modulo by zero"))
} else {
let q = (a.clone() / b.clone()).with_scale_round(0, RoundingMode::Down);
let r = a - b * q;
Ok(Value::str(format_scaled(&r, s)))
}
}
"bcpow" => {
let base = bc_operand(args, 0, "bcpow", 1, "num")?;
let exp = bc_integral(
&bc_operand(args, 1, "bcpow", 2, "exponent")?,
"bcpow",
2,
"exponent",
)?;
let s = scale_arg(args, 2);
let exp_i64 = i64::try_from(&exp).unwrap_or(if exp.sign() == num_bigint::Sign::Minus {
i64::MIN
} else {
i64::MAX
});
if exp_i64 < 0 && base.is_zero() {
Err(throws("DivisionByZeroError", "Negative power of zero"))
} else {
Ok(Value::str(format_scaled(&bd_pow(&base, exp_i64), s)))
}
}
"bcsqrt" => {
let n = bc_operand(args, 0, "bcsqrt", 1, "num")?;
let s = scale_arg(args, 1);
match n.sqrt() {
Some(r) => Ok(Value::str(format_scaled(&r, s))),
None => Err(throws(
"ValueError",
"bcsqrt(): Argument #1 ($num) must be greater than or equal to 0",
)),
}
}
"bccomp" => {
let a = bc_operand(args, 0, "bccomp", 1, "num1")?;
let b = bc_operand(args, 1, "bccomp", 2, "num2")?;
let s = scale_arg(args, 2);
let at = a.with_scale_round(s, RoundingMode::Down);
let bt = b.with_scale_round(s, RoundingMode::Down);
let c = match at.cmp(&bt) {
std::cmp::Ordering::Less => -1,
std::cmp::Ordering::Equal => 0,
std::cmp::Ordering::Greater => 1,
};
Ok(Value::int(c))
}
"bcscale" => {
if args.is_empty() {
Ok(Value::int(current_scale()))
} else {
let prev = current_scale();
let next = int_arg(args, 0).max(0);
BC_SCALE.with(|c| c.set(next));
Ok(Value::int(prev))
}
}
"bcpowmod" => {
let base_bd = bc_operand(args, 0, "bcpowmod", 1, "num")?;
let exp_bd = bc_operand(args, 1, "bcpowmod", 2, "exponent")?;
let mod_bd = bc_operand(args, 2, "bcpowmod", 3, "modulus")?;
let base = bc_integral(&base_bd, "bcpowmod", 1, "num")?;
let exp = bc_integral(&exp_bd, "bcpowmod", 2, "exponent")?;
let s = scale_arg(args, 3);
if exp.sign() == num_bigint::Sign::Minus {
return Err(throws(
"ValueError",
"bcpowmod(): Argument #2 ($exponent) must be greater than or equal to 0",
));
}
let modulus = bc_integral(&mod_bd, "bcpowmod", 3, "modulus")?;
if modulus.is_zero() {
Err(throws("DivisionByZeroError", "Modulo by zero"))
} else {
let r = base.modpow(&exp, &modulus);
Ok(Value::str(format_scaled(&BigDecimal::from(r), s)))
}
}
_ => {
unhandled = true;
Ok(Value::Undef)
}
})();
if unhandled {
None
} else {
Some(out)
}
}