1use rust_decimal::Decimal;
8use rust_decimal::prelude::*;
9use std::str::FromStr;
10
11fn parse(s: &str) -> Option<Decimal> {
13 Decimal::from_str(s).ok()
14}
15
16fn fmt(d: Decimal) -> String {
18 let s = d.to_string();
19 let out = if s.contains('.') {
21 s.trim_end_matches('0').trim_end_matches('.').to_owned()
22 } else {
23 s
24 };
25 if out.bytes().all(|b| matches!(b, b'-' | b'0' | b'.')) {
27 "0".to_string()
28 } else {
29 out
30 }
31}
32
33fn big_pow10(n: i32) -> num_bigint::BigInt {
37 num_bigint::BigInt::from(10u8).pow(n.max(0) as u32)
38}
39
40fn big_align(
43 (ai, ad): (num_bigint::BigInt, i32),
44 (bi, bd): (num_bigint::BigInt, i32),
45) -> (num_bigint::BigInt, num_bigint::BigInt, i32) {
46 if ad == bd {
47 return (ai, bi, ad);
48 }
49 if ad > bd {
50 let scaled = bi * big_pow10(ad - bd);
51 (ai, scaled, ad)
52 } else {
53 let scaled = ai * big_pow10(bd - ad);
54 (scaled, bi, bd)
55 }
56}
57
58pub fn string_add(a: &str, b: &str) -> Option<String> {
59 let (ai, bi, dec) = big_align(precise_parse_big(a)?, precise_parse_big(b)?);
64 Some(bigint_to_precise_string(&(ai + bi), dec))
65}
66
67pub fn string_sub(a: &str, b: &str) -> Option<String> {
68 let (ai, bi, dec) = big_align(precise_parse_big(a)?, precise_parse_big(b)?);
69 Some(bigint_to_precise_string(&(ai - bi), dec))
70}
71
72pub fn string_mul(a: &str, b: &str) -> Option<String> {
73 string_mul_big(a, b)
80}
81
82fn string_mul_big(a: &str, b: &str) -> Option<String> {
85 let (a_int, a_dec) = precise_parse_big(a)?;
86 let (b_int, b_dec) = precise_parse_big(b)?;
87 Some(bigint_to_precise_string(&(a_int * b_int), a_dec + b_dec))
88}
89
90pub fn string_div(a: &str, b: &str) -> Option<String> {
91 let divisor = parse(b)?;
92 if divisor.is_zero() { return None; }
93 Some(fmt(parse(a)? / divisor))
94}
95
96pub fn string_mod(a: &str, b: &str) -> Option<String> {
97 use num_traits::Zero;
98 let (ai, ad) = precise_parse_big(a)?;
101 let (bi, bd) = precise_parse_big(b)?;
102 if bi.is_zero() { return None; }
103 let rat_num = (-ad + bd).max(0);
104 let rat_den = (-bd + ad).max(0);
105 let numerator = ai * big_pow10(rat_num);
106 let denominator = bi * big_pow10(rat_den);
107 Some(bigint_to_precise_string(&(numerator % denominator), rat_den + bd))
108}
109
110pub fn string_eq(a: &str, b: &str) -> Option<bool> {
111 let (ia, da) = precise_parse(a)?;
117 let (ib, db) = precise_parse(b)?;
118 let (ia, da) = precise_reduce(ia, da);
119 let (ib, db) = precise_reduce(ib, db);
120 Some(ia == ib && da == db)
121}
122
123fn big_compare(a: &str, b: &str) -> Option<std::cmp::Ordering> {
125 let (ai, bi, _) = big_align(precise_parse_big(a)?, precise_parse_big(b)?);
126 Some(ai.cmp(&bi))
127}
128
129pub fn string_gt(a: &str, b: &str) -> Option<bool> {
130 Some(big_compare(a, b)?.is_gt())
131}
132
133pub fn string_ge(a: &str, b: &str) -> Option<bool> {
134 Some(big_compare(a, b)?.is_ge())
135}
136
137pub fn string_lt(a: &str, b: &str) -> Option<bool> {
138 Some(big_compare(a, b)?.is_lt())
139}
140
141pub fn string_le(a: &str, b: &str) -> Option<bool> {
142 Some(big_compare(a, b)?.is_le())
143}
144
145pub fn string_abs(a: &str) -> Option<String> {
146 use num_traits::Signed;
147 let (i, d) = precise_parse_big(a)?;
148 Some(bigint_to_precise_string(&i.abs(), d))
149}
150
151pub fn string_neg(a: &str) -> Option<String> {
152 let (i, d) = precise_parse_big(a)?;
153 Some(bigint_to_precise_string(&(-i), d))
154}
155
156pub fn string_to_precision(a: &str, decimals: u32, mode: u8) -> Option<String> {
159 let d = parse(a)?;
160 let rounded = match mode {
161 0 => d.trunc_with_scale(decimals),
162 3 => {
163 let scale = Decimal::from(10u64.pow(decimals));
165 (d * scale).ceil() / scale
166 }
167 4 => {
168 let scale = Decimal::from(10u64.pow(decimals));
170 (d * scale).floor() / scale
171 }
172 _ => d.round_dp(decimals), };
174 let s = format!("{:.prec$}", rounded, prec = decimals as usize);
175 Some(s)
176}
177
178pub fn precise_from_string(s: &str) -> Option<Decimal> {
180 parse(s)
181}
182
183fn precise_parse(s: &str) -> Option<(i128, i32)> {
195 let mut num = s.to_lowercase();
196 let mut modifier: i32 = 0;
197 if let Some(epos) = num.find('e') {
198 let exp = num[epos + 1..].to_string();
199 modifier = exp.parse().ok()?;
200 num = num[..epos].to_string();
201 }
202 let decimals: i32 = match num.find('.') {
203 Some(di) => (num.len() - di - 1) as i32,
204 None => 0,
205 };
206 let integer: i128 = num.replace('.', "").parse().ok()?;
207 Some((integer, decimals - modifier))
208}
209
210fn precise_reduce(integer: i128, decimals: i32) -> (i128, i32) {
212 let string = integer.to_string();
213 let start = string.len() as i32 - 1;
214 if start == 0 {
215 return if string == "0" { (integer, 0) } else { (integer, decimals) };
216 }
217 let bytes = string.as_bytes();
218 let mut i = start;
219 while i >= 0 && bytes[i as usize] == b'0' {
220 i -= 1;
221 }
222 let difference = start - i;
223 if difference == 0 {
224 return (integer, decimals);
225 }
226 let new_int: i128 = string[..(i + 1) as usize].parse().unwrap_or(integer);
227 (new_int, decimals - difference)
228}
229
230fn precise_to_string(integer: i128, decimals: i32) -> String {
232 let (integer, decimals) = precise_reduce(integer, decimals);
233 let sign = if integer < 0 { "-" } else { "" };
234 let abs_str = integer.unsigned_abs().to_string();
235 let pad_len = if decimals > 0 { decimals as usize } else { 0 };
236 let padded = if abs_str.len() < pad_len {
237 "0".repeat(pad_len - abs_str.len()) + &abs_str
238 } else {
239 abs_str
240 };
241 let arr: Vec<char> = padded.chars().collect();
242 let index = arr.len() as i32 - decimals;
243 let item: String = if index == 0 {
244 "0.".to_string()
245 } else if decimals < 0 {
246 "0".repeat((-decimals) as usize)
247 } else if decimals == 0 {
248 String::new()
249 } else {
250 ".".to_string()
251 };
252 let idx = index.max(0) as usize;
253 let mut result = String::new();
254 for (k, c) in arr.iter().enumerate() {
255 if k == idx {
256 result.push_str(&item);
257 }
258 result.push(*c);
259 }
260 if idx >= arr.len() {
261 result.push_str(&item);
262 }
263 format!("{sign}{result}")
264}
265
266pub fn reduce_string(s: &str) -> String {
270 match precise_parse(s) {
271 Some((integer, decimals)) => precise_to_string(integer, decimals),
272 None => s.to_string(),
273 }
274}
275
276pub fn string_div_prec(a: &str, b: &str, precision: i64) -> Option<String> {
279 let (a_int, a_dec) = match precise_parse(a) {
284 Some(v) => v,
285 None => return string_div_prec_big(a, b, precision),
286 };
287 let (b_int, b_dec) = match precise_parse(b) {
288 Some(v) => v,
289 None => return string_div_prec_big(a, b, precision),
290 };
291 if b_int == 0 {
292 return None;
293 }
294 let precision = precision as i32;
295 let distance = precision - a_dec + b_dec;
296 let numerator: i128 = if distance == 0 {
297 a_int
298 } else if distance < 0 {
299 match 10i128.checked_pow((-distance) as u32) {
300 Some(exp) => a_int / exp,
301 None => return string_div_prec_big(a, b, precision as i64),
302 }
303 } else {
304 match 10i128.checked_pow(distance as u32).and_then(|e| a_int.checked_mul(e)) {
305 Some(v) => v,
306 None => return string_div_prec_big(a, b, precision as i64),
307 }
308 };
309 Some(precise_to_string(numerator / b_int, precision))
310}
311
312fn precise_parse_big(s: &str) -> Option<(num_bigint::BigInt, i32)> {
315 let mut num = s.to_lowercase();
316 let mut modifier: i32 = 0;
317 if let Some(epos) = num.find('e') {
318 modifier = num[epos + 1..].parse().ok()?;
319 num = num[..epos].to_string();
320 }
321 let decimals: i32 = match num.find('.') {
322 Some(di) => (num.len() - di - 1) as i32,
323 None => 0,
324 };
325 let integer: num_bigint::BigInt = num.replace('.', "").parse().ok()?;
326 Some((integer, decimals - modifier))
327}
328
329pub fn string_div_prec_big(a: &str, b: &str, precision: i64) -> Option<String> {
333 use num_bigint::BigInt;
334 use num_traits::Zero;
335 let (a_int, a_dec) = precise_parse_big(a)?;
336 let (b_int, b_dec) = precise_parse_big(b)?;
337 if b_int.is_zero() {
338 return None;
339 }
340 let precision = precision as i32;
341 let distance = precision - a_dec + b_dec;
342 let pow10 = |n: i32| -> BigInt { format!("1{}", "0".repeat(n as usize)).parse().unwrap() };
345 let numerator: BigInt = if distance == 0 {
346 a_int
347 } else if distance < 0 {
348 a_int / pow10(-distance)
349 } else {
350 a_int * pow10(distance)
351 };
352 let result = numerator / b_int;
354 match i128::try_from(result.clone()) {
358 Ok(small) => Some(precise_to_string(small, precision)),
359 Err(_) => Some(bigint_to_precise_string(&result, precision)),
360 }
361}
362
363fn bigint_to_precise_string(integer: &num_bigint::BigInt, decimals: i32) -> String {
367 use num_bigint::Sign;
368 let sign = if integer.sign() == Sign::Minus { "-" } else { "" };
369 let mut abs: String = integer.magnitude().to_string();
370 let mut decimals = decimals;
371 let bytes = abs.as_bytes();
373 let start = abs.len() as i32 - 1;
374 if start == 0 && abs == "0" {
375 decimals = 0;
380 }
381 if start > 0 {
382 let mut i = start;
383 while i >= 0 && bytes[i as usize] == b'0' {
384 i -= 1;
385 }
386 let difference = start - i;
387 if difference > 0 {
388 abs.truncate((i + 1) as usize);
389 decimals -= difference;
390 }
391 }
392 let pad_len = if decimals > 0 { decimals as usize } else { 0 };
393 let padded = if abs.len() < pad_len {
394 "0".repeat(pad_len - abs.len()) + &abs
395 } else {
396 abs
397 };
398 let arr: Vec<char> = padded.chars().collect();
399 let index = arr.len() as i32 - decimals;
400 let item: String = if index == 0 {
401 "0.".to_string()
402 } else if decimals < 0 {
403 "0".repeat((-decimals) as usize)
404 } else if decimals == 0 {
405 String::new()
406 } else {
407 ".".to_string()
408 };
409 let idx = index.max(0) as usize;
410 let mut result = String::new();
411 for (k, c) in arr.iter().enumerate() {
412 if k == idx {
413 result.push_str(&item);
414 }
415 result.push(*c);
416 }
417 if idx >= arr.len() {
418 result.push_str(&item);
419 }
420 format!("{sign}{result}")
421}
422
423pub struct Precise;
425
426impl Precise {
427 pub fn new(v: crate::Value) -> crate::Value {
435 let s = crate::runtime::stringify_param(&v);
436 let mut sign = "";
437 let mut body: &str = s.trim_start_matches('+');
438 if let Some(stripped) = body.strip_prefix('-') {
439 sign = "-";
440 body = stripped;
441 }
442 let (integer, decimals): (String, i64) = match body.find('.') {
443 None => (format!("{sign}{body}"), 0),
444 Some(dot) => {
445 let before = &body[..dot];
446 let after = &body[dot + 1..];
447 (format!("{sign}{before}{after}"), after.len() as i64)
448 }
449 };
450 let mut m = indexmap::IndexMap::new();
451 m.insert("integer".to_string(), crate::Value::Str(integer));
452 m.insert("decimals".to_string(), crate::Value::Int(decimals));
453 m.insert("__precise".to_string(), crate::Value::Bool(true));
454 crate::Value::Map(m)
455 }
456}
457
458impl Precise {
459 pub fn string_add(a: &str, b: &str) -> Option<String> { string_add(a, b) }
460 pub fn string_sub(a: &str, b: &str) -> Option<String> { string_sub(a, b) }
461 pub fn string_mul(a: &str, b: &str) -> Option<String> { string_mul(a, b) }
462 pub fn string_div(a: &str, b: &str) -> Option<String> { string_div(a, b) }
463 pub fn string_mod(a: &str, b: &str) -> Option<String> { string_mod(a, b) }
464 pub fn string_eq(a: &str, b: &str) -> Option<bool> { string_eq(a, b) }
465 pub fn string_gt(a: &str, b: &str) -> Option<bool> { string_gt(a, b) }
466 pub fn string_ge(a: &str, b: &str) -> Option<bool> { string_ge(a, b) }
467 pub fn string_lt(a: &str, b: &str) -> Option<bool> { string_lt(a, b) }
468 pub fn string_le(a: &str, b: &str) -> Option<bool> { string_le(a, b) }
469 pub fn string_abs(a: &str) -> Option<String> { string_abs(a) }
470 pub fn string_neg(a: &str) -> Option<String> { string_neg(a) }
471 pub fn string_to_precision(a: &str, decimals: u32, mode: u8) -> Option<String> {
472 string_to_precision(a, decimals, mode)
473 }
474}
475
476#[allow(non_snake_case)]
483impl Precise {
484 fn vstr(v: &crate::Value) -> String { crate::runtime::stringify_param(v) }
485 fn vopt(s: Option<String>) -> crate::Value { match s { Some(s) => crate::Value::Str(s), None => crate::Value::Null } }
486 fn vbool(b: Option<bool>) -> crate::Value { match b { Some(b) => crate::Value::Bool(b), None => crate::Value::Null } }
487
488 pub fn stringAdd(a: &crate::Value, b: &crate::Value) -> crate::Value {
494 if matches!(a, crate::Value::Null) || matches!(b, crate::Value::Null) {
496 return crate::Value::Null;
497 }
498 Self::vopt(string_add(&Self::vstr(a), &Self::vstr(b)))
499 }
500 pub fn stringSub(a: &crate::Value, b: &crate::Value) -> crate::Value {
502 if matches!(a, crate::Value::Null) || matches!(b, crate::Value::Null) {
503 return crate::Value::Null;
504 }
505 Self::vopt(string_sub(&Self::vstr(a), &Self::vstr(b)))
506 }
507 pub fn stringMul(a: &crate::Value, b: &crate::Value) -> crate::Value {
510 if matches!(a, crate::Value::Null) || matches!(b, crate::Value::Null) {
511 return crate::Value::Null;
512 }
513 Self::vopt(string_mul(&Self::vstr(a), &Self::vstr(b)))
514 }
515 pub fn stringDiv(a: &crate::Value, b: &crate::Value) -> crate::Value {
516 Self::vopt(string_div_prec(&Self::vstr(a), &Self::vstr(b), 18))
518 }
519 pub fn stringDivPrec(a: &crate::Value, b: &crate::Value, precision: &crate::Value) -> crate::Value {
522 let prec: i64 = match precision {
523 crate::Value::Int(n) => *n,
524 crate::Value::Float(f) => *f as i64,
525 crate::Value::Str(s) => s.parse().unwrap_or(18),
526 _ => 18,
527 };
528 Self::vopt(string_div_prec(&Self::vstr(a), &Self::vstr(b), prec))
529 }
530 pub fn stringMod(a: &crate::Value, b: &crate::Value) -> crate::Value { Self::vopt(string_mod(&Self::vstr(a), &Self::vstr(b))) }
531 pub fn stringEq(a: &crate::Value, b: &crate::Value) -> crate::Value { if Self::any_null(a, b) { return crate::Value::Bool(false); } Self::vbool(string_eq(&Self::vstr(a), &Self::vstr(b))) }
532 pub fn stringGt(a: &crate::Value, b: &crate::Value) -> crate::Value { if Self::any_null(a, b) { return crate::Value::Bool(false); } Self::vbool(string_gt(&Self::vstr(a), &Self::vstr(b))) }
533 pub fn stringGe(a: &crate::Value, b: &crate::Value) -> crate::Value { if Self::any_null(a, b) { return crate::Value::Bool(false); } Self::vbool(string_ge(&Self::vstr(a), &Self::vstr(b))) }
534 pub fn stringLt(a: &crate::Value, b: &crate::Value) -> crate::Value { if Self::any_null(a, b) { return crate::Value::Bool(false); } Self::vbool(string_lt(&Self::vstr(a), &Self::vstr(b))) }
535 pub fn stringLe(a: &crate::Value, b: &crate::Value) -> crate::Value { if Self::any_null(a, b) { return crate::Value::Bool(false); } Self::vbool(string_le(&Self::vstr(a), &Self::vstr(b))) }
536 fn any_null(a: &crate::Value, b: &crate::Value) -> bool { matches!(a, crate::Value::Null) || matches!(b, crate::Value::Null) }
539 pub fn stringAbs(a: &crate::Value) -> crate::Value { Self::vopt(string_abs(&Self::vstr(a))) }
540 pub fn stringNeg(a: &crate::Value) -> crate::Value { Self::vopt(string_neg(&Self::vstr(a))) }
541 pub fn stringMin(a: &crate::Value, b: &crate::Value) -> crate::Value {
542 if matches!(a, crate::Value::Null) || matches!(b, crate::Value::Null) {
544 return crate::Value::Null;
545 }
546 let (sa, sb) = (Self::vstr(a), Self::vstr(b));
547 let pick = if let Some(true) = string_le(&sa, &sb) { sa } else { sb };
548 crate::Value::Str(reduce_string(&pick))
549 }
550 pub fn stringMax(a: &crate::Value, b: &crate::Value) -> crate::Value {
551 if matches!(a, crate::Value::Null) || matches!(b, crate::Value::Null) {
553 return crate::Value::Null;
554 }
555 let (sa, sb) = (Self::vstr(a), Self::vstr(b));
556 let pick = if let Some(true) = string_ge(&sa, &sb) { sa } else { sb };
557 crate::Value::Str(reduce_string(&pick))
558 }
559 pub fn stringEquals(a: &crate::Value, b: &crate::Value) -> crate::Value { Self::stringEq(a, b) }
560 pub fn stringOr(a: &crate::Value, b: &crate::Value) -> crate::Value {
565 if matches!(a, crate::Value::Null) || matches!(b, crate::Value::Null) {
566 return crate::Value::Null;
567 }
568 let (sa, sb) = (Self::vstr(a), Self::vstr(b));
569 fn split(s: &str) -> Option<(i64, i64, u32)> {
573 let (sign, body) = if let Some(rest) = s.strip_prefix('-') { (-1i64, rest) } else { (1i64, s) };
574 let (int_part, frac_part) = match body.find('.') {
575 Some(i) => (&body[..i], &body[i + 1..]),
576 None => (body, ""),
577 };
578 let joined = format!("{int_part}{frac_part}");
579 let n: i64 = joined.parse().ok()?;
580 Some((sign, n, frac_part.len() as u32))
581 }
582 let (sga, ia, da) = match split(&sa) { Some(t) => t, None => return crate::Value::Null };
583 let (sgb, ib, db) = match split(&sb) { Some(t) => t, None => return crate::Value::Null };
584 let dmax = da.max(db);
586 let ia_s = sga * ia * 10i64.pow(dmax - da);
587 let ib_s = sgb * ib * 10i64.pow(dmax - db);
588 let or = ia_s | ib_s;
589 let s = if dmax == 0 {
590 or.to_string()
591 } else {
592 let abs = or.unsigned_abs();
594 let digits = abs.to_string();
595 let pad = if digits.len() <= dmax as usize { dmax as usize - digits.len() + 1 } else { 0 };
596 let padded = format!("{}{}", "0".repeat(pad), digits);
597 let cut = padded.len() - dmax as usize;
598 let (lhs, rhs) = padded.split_at(cut);
599 let mut out = format!("{lhs}.{rhs}");
600 if or < 0 { out = format!("-{out}"); }
601 out
602 };
603 crate::Value::Str(reduce_string(&s))
604 }
605}