Skip to main content

ccxt_common/
precise.rs

1// Native Rust – Precise decimal arithmetic.
2//
3// Mirrors CCXT's Precise.ts exactly.  All arithmetic operates on string
4// representations to avoid floating-point rounding issues, and all inputs
5// / outputs are Strings (just like the TypeScript version).
6
7use num_bigint::BigInt;
8use num_traits::{Signed, Zero};
9
10/// Strict decimal syntax for `string_div` / `string_to_precision`: optional
11/// leading sign, digits with one optional `.`, `_` separators after a digit,
12/// and an optional `e`/`E` exponent of at most 28. Returns `(integer, decimals)`.
13fn decimal_parse(s: &str) -> Option<(BigInt, i32)> {
14    fn mantissa_ok(t: &str) -> bool {
15        let body = t.strip_prefix(['+', '-']).unwrap_or(t);
16        let (mut digit, mut point) = (false, false);
17        for c in body.bytes() {
18            match c {
19                b'0'..=b'9' => digit = true,
20                b'.' if !point => point = true,
21                b'_' if digit => {}
22                _ => return false,
23            }
24        }
25        digit
26    }
27    if mantissa_ok(s) {
28        return precise_parse_big(&s.replace('_', ""));
29    }
30    let epos = s.find(['e', 'E'])?;
31    let (base, exp) = (&s[..epos], &s[epos + 1..]);
32    if !mantissa_ok(base) {
33        return None;
34    }
35    let (negative_exp, digits) = match exp.strip_prefix('-') {
36        Some(rest) => (true, rest),
37        None => (false, exp),
38    };
39    let e: u32 = digits.parse().ok()?;
40    if e > 28 {
41        return None;
42    }
43    let (integer, decimals) = precise_parse_big(&base.replace('_', ""))?;
44    Some((integer, if negative_exp { decimals + e as i32 } else { decimals - e as i32 }))
45}
46
47/// `(|a| * 10^shift) / |b|` as a numerator/denominator pair, `shift` may be negative.
48fn scaled_ratio(a: &BigInt, b: &BigInt, shift: i32) -> (BigInt, BigInt) {
49    if shift >= 0 {
50        (a.abs() * big_pow10(shift), b.abs())
51    } else {
52        (a.abs(), b.abs() * big_pow10(-shift))
53    }
54}
55
56/// `num / den` rounded half to even (both non-negative).
57fn div_half_even(num: &BigInt, den: &BigInt) -> BigInt {
58    let (q, r) = (num / den, num % den);
59    let twice: BigInt = r * 2u8;
60    if twice > *den || (twice == *den && !(&q % 2u8).is_zero()) { q + 1u8 } else { q }
61}
62
63/// Fixed-point rendering of `integer / 10^decimals` with exactly `decimals` places.
64fn fixed_to_string(negative: bool, integer: &BigInt, decimals: u32) -> String {
65    let k = decimals as usize;
66    let digits = format!("{:0>width$}", integer.to_string(), width = k + 1);
67    let (whole, frac) = digits.split_at(digits.len() - k);
68    let sign = if negative { "-" } else { "" };
69    if k == 0 { format!("{sign}{whole}") } else { format!("{sign}{whole}.{frac}") }
70}
71
72// ── public API ────────────────────────────────────────────────────────────────
73
74/// 10^n as a `BigInt`, for aligning two operands to a common scale.
75fn big_pow10(n: i32) -> num_bigint::BigInt {
76    num_bigint::BigInt::from(10u8).pow(n.max(0) as u32)
77}
78
79/// Align two `(integer, decimals)` pairs onto the larger scale, mirroring the
80/// scaling TS `add`/`sub`/`compare` do inline.
81fn big_align(
82    (ai, ad): (num_bigint::BigInt, i32),
83    (bi, bd): (num_bigint::BigInt, i32),
84) -> (num_bigint::BigInt, num_bigint::BigInt, i32) {
85    if ad == bd {
86        return (ai, bi, ad);
87    }
88    if ad > bd {
89        let scaled = bi * big_pow10(ad - bd);
90        (ai, scaled, ad)
91    } else {
92        let scaled = ai * big_pow10(bd - ad);
93        (scaled, bi, bd)
94    }
95}
96
97pub fn string_add(a: &str, b: &str) -> Option<String> {
98    // Arbitrary precision, like CCXT's BigInt-backed `Precise`.
99    let (ai, bi, dec) = big_align(precise_parse_big(a)?, precise_parse_big(b)?);
100    Some(bigint_to_precise_string(&(ai + bi), dec))
101}
102
103pub fn string_sub(a: &str, b: &str) -> Option<String> {
104    let (ai, bi, dec) = big_align(precise_parse_big(a)?, precise_parse_big(b)?);
105    Some(bigint_to_precise_string(&(ai - bi), dec))
106}
107
108pub fn string_mul(a: &str, b: &str) -> Option<String> {
109    string_mul_big(a, b)
110}
111
112/// Arbitrary-precision `a * b`: product integer is `a_int * b_int`, with the
113/// decimal counts summed.
114fn string_mul_big(a: &str, b: &str) -> Option<String> {
115    let (a_int, a_dec) = precise_parse_big(a)?;
116    let (b_int, b_dec) = precise_parse_big(b)?;
117    Some(bigint_to_precise_string(&(a_int * b_int), a_dec + b_dec))
118}
119
120/// `a / b` rounded half to even at the largest scale (at most 28) whose
121/// integer stays below 2^96, then trailing zeros trimmed.
122pub fn string_div(a: &str, b: &str) -> Option<String> {
123    let (ai, ad) = decimal_parse(a)?;
124    let (bi, bd) = decimal_parse(b)?;
125    if bi.is_zero() { return None; }
126    let limit = BigInt::from(1u8) << 96usize;
127    let mut scale = 28;
128    while scale > 0 {
129        let (num, den) = scaled_ratio(&ai, &bi, bd - ad + scale);
130        if num / den < limit { break; }
131        scale -= 1;
132    }
133    let (num, den) = scaled_ratio(&ai, &bi, bd - ad + scale);
134    let mut q = div_half_even(&num, &den);
135    if q >= limit && scale > 0 {
136        scale -= 1;
137        let (num, den) = scaled_ratio(&ai, &bi, bd - ad + scale);
138        q = div_half_even(&num, &den);
139    }
140    let negative = ai.is_negative() != bi.is_negative();
141    Some(bigint_to_precise_string(&if negative { -q } else { q }, scale))
142}
143
144pub fn string_mod(a: &str, b: &str) -> Option<String> {
145    // Mirrors TS `mod()`: rationalize both sides onto a common scale, then
146    // take the remainder of the scaled integers.
147    let (ai, ad) = precise_parse_big(a)?;
148    let (bi, bd) = precise_parse_big(b)?;
149    if bi.is_zero() { return None; }
150    let rat_num = (-ad + bd).max(0);
151    let rat_den = (-bd + ad).max(0);
152    let numerator = ai * big_pow10(rat_num);
153    let denominator = bi * big_pow10(rat_den);
154    Some(bigint_to_precise_string(&(numerator % denominator), rat_den + bd))
155}
156
157pub fn string_eq(a: &str, b: &str) -> Option<bool> {
158    // Mirrors TS `equals()`: reduce both and compare (integer, decimals).
159    let (ia, da) = precise_parse(a)?;
160    let (ib, db) = precise_parse(b)?;
161    let (ia, da) = precise_reduce(ia, da);
162    let (ib, db) = precise_reduce(ib, db);
163    Some(ia == ib && da == db)
164}
165
166/// TS `compare()` — align onto the larger scale, compare the integers.
167fn big_compare(a: &str, b: &str) -> Option<std::cmp::Ordering> {
168    let (ai, bi, _) = big_align(precise_parse_big(a)?, precise_parse_big(b)?);
169    Some(ai.cmp(&bi))
170}
171
172pub fn string_gt(a: &str, b: &str) -> Option<bool> {
173    Some(big_compare(a, b)?.is_gt())
174}
175
176pub fn string_ge(a: &str, b: &str) -> Option<bool> {
177    Some(big_compare(a, b)?.is_ge())
178}
179
180pub fn string_lt(a: &str, b: &str) -> Option<bool> {
181    Some(big_compare(a, b)?.is_lt())
182}
183
184pub fn string_le(a: &str, b: &str) -> Option<bool> {
185    Some(big_compare(a, b)?.is_le())
186}
187
188pub fn string_abs(a: &str) -> Option<String> {
189    let (i, d) = precise_parse_big(a)?;
190    Some(bigint_to_precise_string(&i.abs(), d))
191}
192
193pub fn string_neg(a: &str) -> Option<String> {
194    let (i, d) = precise_parse_big(a)?;
195    Some(bigint_to_precise_string(&(-i), d))
196}
197
198/// Round to `decimals` decimal places using the specified rounding mode.
199/// mode 0 = truncate (keeps a `-` on a negative input truncated to zero),
200/// 3 = ceiling, 4 = floor, any other = round half to even.
201pub fn string_to_precision(a: &str, decimals: u32, mode: u8) -> Option<String> {
202    let (integer, d) = decimal_parse(a)?;
203    let (num, den) = scaled_ratio(&integer, &BigInt::from(1u8), decimals as i32 - d);
204    let num = if integer.is_negative() { -num } else { num };
205    let (q, r) = (&num / &den, &num % &den);
206    let (negative, magnitude) = match mode {
207        0 => (integer.is_negative(), q.abs()),
208        3 => { let v = if r.is_positive() { q + 1u8 } else { q }; (v.is_negative(), v.abs()) }
209        4 => { let v = if r.is_negative() { q - 1u8 } else { q }; (v.is_negative(), v.abs()) }
210        _ => { let v = div_half_even(&num.abs(), &den); (integer.is_negative() && !v.is_zero(), v) }
211    };
212    Some(fixed_to_string(negative, &magnitude, decimals))
213}
214
215// ── precision-aware division ────────────────────────────────────────────────
216//
217// The TS `Precise.stringDiv (a, b, precision)` *truncates* the result to
218// exactly `precision` decimal places; `string_div_prec` ports it with an
219// `i128` fast path and a BigInt fallback.
220
221/// Parses a decimal string into `(integer, decimals)` exactly like the
222/// TS `Precise` constructor (handles scientific `e` notation).
223fn precise_parse(s: &str) -> Option<(i128, i32)> {
224    let mut num = s.to_lowercase();
225    let mut modifier: i32 = 0;
226    if let Some(epos) = num.find('e') {
227        let exp = num[epos + 1..].to_string();
228        modifier = exp.parse().ok()?;
229        num = num[..epos].to_string();
230    }
231    let decimals: i32 = match num.find('.') {
232        Some(di) => (num.len() - di - 1) as i32,
233        None => 0,
234    };
235    let integer: i128 = num.replace('.', "").parse().ok()?;
236    Some((integer, decimals - modifier))
237}
238
239/// Port of `Precise.reduce()` — strips trailing zeros from the integer.
240fn precise_reduce(integer: i128, decimals: i32) -> (i128, i32) {
241    let string = integer.to_string();
242    let start = string.len() as i32 - 1;
243    if start == 0 {
244        return if string == "0" { (integer, 0) } else { (integer, decimals) };
245    }
246    let bytes = string.as_bytes();
247    let mut i = start;
248    while i >= 0 && bytes[i as usize] == b'0' {
249        i -= 1;
250    }
251    let difference = start - i;
252    if difference == 0 {
253        return (integer, decimals);
254    }
255    let new_int: i128 = string[..(i + 1) as usize].parse().unwrap_or(integer);
256    (new_int, decimals - difference)
257}
258
259/// Port of `Precise.toString()`.
260fn precise_to_string(integer: i128, decimals: i32) -> String {
261    let (integer, decimals) = precise_reduce(integer, decimals);
262    let sign = if integer < 0 { "-" } else { "" };
263    let abs_str = integer.unsigned_abs().to_string();
264    let pad_len = if decimals > 0 { decimals as usize } else { 0 };
265    let padded = if abs_str.len() < pad_len {
266        "0".repeat(pad_len - abs_str.len()) + &abs_str
267    } else {
268        abs_str
269    };
270    let arr: Vec<char> = padded.chars().collect();
271    let index = arr.len() as i32 - decimals;
272    let item: String = if index == 0 {
273        "0.".to_string()
274    } else if decimals < 0 {
275        "0".repeat((-decimals) as usize)
276    } else if decimals == 0 {
277        String::new()
278    } else {
279        ".".to_string()
280    };
281    let idx = index.max(0) as usize;
282    let mut result = String::new();
283    for (k, c) in arr.iter().enumerate() {
284        if k == idx {
285            result.push_str(&item);
286        }
287        result.push(*c);
288    }
289    if idx >= arr.len() {
290        result.push_str(&item);
291    }
292    format!("{sign}{result}")
293}
294
295/// Normalises a decimal string by stripping trailing fractional
296/// zeros (mirrors `Precise.reduce()` + `toString()`). Falls back to
297/// the input on overflow / parse failure.
298pub fn reduce_string(s: &str) -> String {
299    match precise_parse(s) {
300        Some((integer, decimals)) => precise_to_string(integer, decimals),
301        None => s.to_string(),
302    }
303}
304
305/// Port of `Precise.stringDiv (a, b, precision)` — truncating
306/// big-integer division to exactly `precision` decimal places.
307pub fn string_div_prec(a: &str, b: &str, precision: i64) -> Option<String> {
308    // Fast path: i128. Any overflow (operand too large to parse, or the
309    // `a_int * 10^distance` intermediate exceeding i128) falls back to the
310    // arbitrary-precision BigInt path so the result matches TS exactly —
311    // NOT to `string_div` (which would silently change the precision).
312    let (a_int, a_dec) = match precise_parse(a) {
313        Some(v) => v,
314        None => return string_div_prec_big(a, b, precision),
315    };
316    let (b_int, b_dec) = match precise_parse(b) {
317        Some(v) => v,
318        None => return string_div_prec_big(a, b, precision),
319    };
320    if b_int == 0 {
321        return None;
322    }
323    let precision = precision as i32;
324    let distance = precision - a_dec + b_dec;
325    let numerator: i128 = if distance == 0 {
326        a_int
327    } else if distance < 0 {
328        match 10i128.checked_pow((-distance) as u32) {
329            Some(exp) => a_int / exp,
330            None => return string_div_prec_big(a, b, precision as i64),
331        }
332    } else {
333        match 10i128.checked_pow(distance as u32).and_then(|e| a_int.checked_mul(e)) {
334            Some(v) => v,
335            None => return string_div_prec_big(a, b, precision as i64),
336        }
337    };
338    Some(precise_to_string(numerator / b_int, precision))
339}
340
341/// BigInt sibling of [`precise_parse`] — no i128 range limit. Splits a
342/// decimal (with optional `e` exponent) into `(integer, decimals)`.
343fn precise_parse_big(s: &str) -> Option<(num_bigint::BigInt, i32)> {
344    let mut num = s.to_lowercase();
345    let mut modifier: i32 = 0;
346    if let Some(epos) = num.find('e') {
347        modifier = num[epos + 1..].parse().ok()?;
348        num = num[..epos].to_string();
349    }
350    let decimals: i32 = match num.find('.') {
351        Some(di) => (num.len() - di - 1) as i32,
352        None => 0,
353    };
354    let integer: num_bigint::BigInt = num.replace('.', "").parse().ok()?;
355    Some((integer, decimals - modifier))
356}
357
358/// Arbitrary-precision port of `Precise.stringDiv (a, b, precision)`.
359/// Mirrors the TS BigInt algorithm exactly; used when the i128 fast path
360/// in [`string_div_prec`] would overflow.
361pub fn string_div_prec_big(a: &str, b: &str, precision: i64) -> Option<String> {
362    let (a_int, a_dec) = precise_parse_big(a)?;
363    let (b_int, b_dec) = precise_parse_big(b)?;
364    if b_int.is_zero() {
365        return None;
366    }
367    let precision = precision as i32;
368    let distance = precision - a_dec + b_dec;
369    // 10^n as a BigInt via its literal digit string ("1" followed by n
370    // zeros) — avoids depending on a particular `pow` API surface.
371    let pow10 = |n: i32| -> BigInt { format!("1{}", "0".repeat(n as usize)).parse().unwrap() };
372    let numerator: BigInt = if distance == 0 {
373        a_int
374    } else if distance < 0 {
375        a_int / pow10(-distance)
376    } else {
377        a_int * pow10(distance)
378    };
379    // BigInt division truncates toward zero, matching TS `BigInt` `/`.
380    let result = numerator / b_int;
381    // The quotient (a value scaled to `precision` decimals) is almost
382    // always small; reuse the i128 formatter when it fits, else format
383    // the BigInt digits directly.
384    match i128::try_from(result.clone()) {
385        Ok(small) => Some(precise_to_string(small, precision)),
386        Err(_) => Some(bigint_to_precise_string(&result, precision)),
387    }
388}
389
390/// Format `(integer, decimals)` where `integer` is a BigInt — the
391/// arbitrary-precision analogue of [`precise_to_string`]. Reduces trailing
392/// zeros (adjusting `decimals`) then positions the decimal point.
393fn bigint_to_precise_string(integer: &num_bigint::BigInt, decimals: i32) -> String {
394    use num_bigint::Sign;
395    let sign = if integer.sign() == Sign::Minus { "-" } else { "" };
396    let mut abs: String = integer.magnitude().to_string();
397    let mut decimals = decimals;
398    // reduce(): strip trailing zeros from the digit string.
399    let bytes = abs.as_bytes();
400    let start = abs.len() as i32 - 1;
401    if start == 0 && abs == "0" {
402        // TS `reduceDigits()` zeroes the scale for a bare "0": `0 * 1e-6` is "0".
403        decimals = 0;
404    }
405    if start > 0 {
406        let mut i = start;
407        while i >= 0 && bytes[i as usize] == b'0' {
408            i -= 1;
409        }
410        let difference = start - i;
411        if difference > 0 {
412            abs.truncate((i + 1) as usize);
413            decimals -= difference;
414        }
415    }
416    let pad_len = if decimals > 0 { decimals as usize } else { 0 };
417    let padded = if abs.len() < pad_len {
418        "0".repeat(pad_len - abs.len()) + &abs
419    } else {
420        abs
421    };
422    let arr: Vec<char> = padded.chars().collect();
423    let index = arr.len() as i32 - decimals;
424    let item: String = if index == 0 {
425        "0.".to_string()
426    } else if decimals < 0 {
427        "0".repeat((-decimals) as usize)
428    } else if decimals == 0 {
429        String::new()
430    } else {
431        ".".to_string()
432    };
433    let idx = index.max(0) as usize;
434    let mut result = String::new();
435    for (k, c) in arr.iter().enumerate() {
436        if k == idx {
437            result.push_str(&item);
438        }
439        result.push(*c);
440    }
441    if idx >= arr.len() {
442        result.push_str(&item);
443    }
444    format!("{sign}{result}")
445}
446
447/// A struct wrapper matching CCXT Precise class usage (e.g. `Precise::string_add`).
448pub struct Precise;
449
450impl Precise {
451    /// TS-style `new Precise(s)` — parses `s` into an `integer` (the
452    /// digit string) + `decimals` (count of digits to the right of the
453    /// decimal point). Returns a `Value::Map` carrying those two
454    /// fields plus a `__precise` marker that `stringify_param` /
455    /// `Value::reduce` recognise — that's what makes
456    /// `precise.decimals = subtract(...)` followed by `precise.reduce()`
457    /// (as transpiled phemex's `toEn` does) work end-to-end.
458    pub fn new(v: crate::Value) -> crate::Value {
459        let s = crate::runtime::stringify_param(&v);
460        let mut sign = "";
461        let mut body: &str = s.trim_start_matches('+');
462        if let Some(stripped) = body.strip_prefix('-') {
463            sign = "-";
464            body = stripped;
465        }
466        let (integer, decimals): (String, i64) = match body.find('.') {
467            None => (format!("{sign}{body}"), 0),
468            Some(dot) => {
469                let before = &body[..dot];
470                let after  = &body[dot + 1..];
471                (format!("{sign}{before}{after}"), after.len() as i64)
472            }
473        };
474        let mut m = indexmap::IndexMap::new();
475        m.insert("integer".to_string(),  crate::Value::Str(integer.into()));
476        m.insert("decimals".to_string(), crate::Value::Int(decimals));
477        m.insert("__precise".to_string(), crate::Value::Bool(true));
478        crate::Value::Map(m)
479    }
480}
481
482impl Precise {
483    pub fn string_add(a: &str, b: &str) -> Option<String> { string_add(a, b) }
484    pub fn string_sub(a: &str, b: &str) -> Option<String> { string_sub(a, b) }
485    pub fn string_mul(a: &str, b: &str) -> Option<String> { string_mul(a, b) }
486    pub fn string_div(a: &str, b: &str) -> Option<String> { string_div(a, b) }
487    pub fn string_mod(a: &str, b: &str) -> Option<String> { string_mod(a, b) }
488    pub fn string_eq(a: &str, b: &str)  -> Option<bool>   { string_eq(a, b) }
489    pub fn string_gt(a: &str, b: &str)  -> Option<bool>   { string_gt(a, b) }
490    pub fn string_ge(a: &str, b: &str)  -> Option<bool>   { string_ge(a, b) }
491    pub fn string_lt(a: &str, b: &str)  -> Option<bool>   { string_lt(a, b) }
492    pub fn string_le(a: &str, b: &str)  -> Option<bool>   { string_le(a, b) }
493    pub fn string_abs(a: &str)          -> Option<String>  { string_abs(a) }
494    pub fn string_neg(a: &str)          -> Option<String>  { string_neg(a) }
495    pub fn string_to_precision(a: &str, decimals: u32, mode: u8) -> Option<String> {
496        string_to_precision(a, decimals, mode)
497    }
498}
499
500// ── Value-accepting versions (used by transpiled code) ───────────────────────
501//
502// The transpiler emits `Precise::stringDiv(a, b)` with Value arguments. These
503// camelCase methods stringify their args and dispatch to the typed versions
504// above. They return `Value` so the rest of the transpiled code can chain.
505
506#[allow(non_snake_case)]
507impl Precise {
508    fn vstr(v: &crate::Value) -> String { crate::runtime::stringify_param(v) }
509    fn vopt(s: Option<String>) -> crate::Value { match s { Some(s) => crate::Value::Str(s.into()), None => crate::Value::Null } }
510    fn vbool(b: Option<bool>)  -> crate::Value { match b { Some(b) => crate::Value::Bool(b), None => crate::Value::Null } }
511
512    /// Mirrors TS `Precise.stringAdd`: when one operand is `undefined` /
513    /// `null` it returns the OTHER side (treating the missing value as the
514    /// arithmetic identity). Bitget's `parsePosition` relies on this when
515    /// `keepMarginRate` is missing (UTA response uses `mmr` instead), so
516    /// `Precise.stringAdd(undefined, feeToClose)` should yield `feeToClose`.
517    pub fn stringAdd(a: &crate::Value, b: &crate::Value) -> crate::Value {
518        // Mirrors TS `Precise.stringAdd`: either operand undefined → undefined.
519        if matches!(a, crate::Value::Null) || matches!(b, crate::Value::Null) {
520            return crate::Value::Null;
521        }
522        Self::vopt(string_add(&Self::vstr(a), &Self::vstr(b)))
523    }
524    /// Mirrors TS `Precise.stringSub`: either operand undefined → undefined.
525    pub fn stringSub(a: &crate::Value, b: &crate::Value) -> crate::Value {
526        if matches!(a, crate::Value::Null) || matches!(b, crate::Value::Null) {
527            return crate::Value::Null;
528        }
529        Self::vopt(string_sub(&Self::vstr(a), &Self::vstr(b)))
530    }
531    /// Mirrors TS `Precise.stringMul`: any undefined operand → undefined
532    /// (matches the typescript `x * undefined === NaN → undefined` chain).
533    pub fn stringMul(a: &crate::Value, b: &crate::Value) -> crate::Value {
534        if matches!(a, crate::Value::Null) || matches!(b, crate::Value::Null) {
535            return crate::Value::Null;
536        }
537        Self::vopt(string_mul(&Self::vstr(a), &Self::vstr(b)))
538    }
539    pub fn stringDiv(a: &crate::Value, b: &crate::Value) -> crate::Value {
540        // TS `Precise.stringDiv` defaults to precision 18 (truncating).
541        Self::vopt(string_div_prec(&Self::vstr(a), &Self::vstr(b), 18))
542    }
543    /// `Precise.stringDiv (a, b, precision)` — truncating division to a
544    /// given number of decimal places.
545    pub fn stringDivPrec(a: &crate::Value, b: &crate::Value, precision: &crate::Value) -> crate::Value {
546        let prec: i64 = match precision {
547            crate::Value::Int(n)   => *n,
548            crate::Value::Float(f) => *f as i64,
549            crate::Value::Str(s)   => s.parse().unwrap_or(18),
550            _ => 18,
551        };
552        Self::vopt(string_div_prec(&Self::vstr(a), &Self::vstr(b), prec))
553    }
554    pub fn stringMod(a: &crate::Value, b: &crate::Value) -> crate::Value { Self::vopt(string_mod(&Self::vstr(a), &Self::vstr(b))) }
555    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))) }
556    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))) }
557    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))) }
558    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))) }
559    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))) }
560    /// TS treats the comparison operators as `false` when either operand
561    /// is undefined (they short-circuit before constructing a `Precise`).
562    fn any_null(a: &crate::Value, b: &crate::Value) -> bool { matches!(a, crate::Value::Null) || matches!(b, crate::Value::Null) }
563    pub fn stringAbs(a: &crate::Value)                   -> crate::Value { Self::vopt(string_abs(&Self::vstr(a))) }
564    pub fn stringNeg(a: &crate::Value)                   -> crate::Value { Self::vopt(string_neg(&Self::vstr(a))) }
565    pub fn stringMin(a: &crate::Value, b: &crate::Value) -> crate::Value {
566        // Mirrors TS `Precise.stringMin`: either operand undefined → undefined.
567        if matches!(a, crate::Value::Null) || matches!(b, crate::Value::Null) {
568            return crate::Value::Null;
569        }
570        let (sa, sb) = (Self::vstr(a), Self::vstr(b));
571        let pick = if let Some(true) = string_le(&sa, &sb) { sa } else { sb };
572        crate::Value::Str(reduce_string(&pick).into())
573    }
574    pub fn stringMax(a: &crate::Value, b: &crate::Value) -> crate::Value {
575        // Mirrors TS `Precise.stringMax`: either operand undefined → undefined.
576        if matches!(a, crate::Value::Null) || matches!(b, crate::Value::Null) {
577            return crate::Value::Null;
578        }
579        let (sa, sb) = (Self::vstr(a), Self::vstr(b));
580        let pick = if let Some(true) = string_ge(&sa, &sb) { sa } else { sb };
581        crate::Value::Str(reduce_string(&pick).into())
582    }
583    pub fn stringEquals(a: &crate::Value, b: &crate::Value) -> crate::Value { Self::stringEq(a, b) }
584    /// Mirrors TS `Precise.stringOr`: bitwise OR of the underlying
585    /// integer representations at a common decimal scale.
586    /// `stringOr("5", "3") == "7"`, `stringOr("5.5", "3") == "6.3"` etc.
587    /// Either undefined operand → undefined (matches TS).
588    pub fn stringOr(a: &crate::Value, b: &crate::Value) -> crate::Value {
589        if matches!(a, crate::Value::Null) || matches!(b, crate::Value::Null) {
590            return crate::Value::Null;
591        }
592        let (sa, sb) = (Self::vstr(a), Self::vstr(b));
593        // Split each into (sign, integer-string, decimal-count). Mirrors
594        // the constructor in TS Precise — chop at `.`, count fractional
595        // digits, drop the `.` so the integer parses as a single number.
596        fn split(s: &str) -> Option<(i64, i64, u32)> {
597            let (sign, body) = if let Some(rest) = s.strip_prefix('-') { (-1i64, rest) } else { (1i64, s) };
598            let (int_part, frac_part) = match body.find('.') {
599                Some(i) => (&body[..i], &body[i + 1..]),
600                None    => (body, ""),
601            };
602            let joined = format!("{int_part}{frac_part}");
603            let n: i64 = joined.parse().ok()?;
604            Some((sign, n, frac_part.len() as u32))
605        }
606        let (sga, ia, da) = match split(&sa) { Some(t) => t, None => return crate::Value::Null };
607        let (sgb, ib, db) = match split(&sb) { Some(t) => t, None => return crate::Value::Null };
608        // Shift the smaller-decimal side up to match.
609        let dmax = da.max(db);
610        let ia_s = sga * ia * 10i64.pow(dmax - da);
611        let ib_s = sgb * ib * 10i64.pow(dmax - db);
612        let or = ia_s | ib_s;
613        let s = if dmax == 0 {
614            or.to_string()
615        } else {
616            // Re-insert the decimal point dmax positions from the right.
617            let abs = or.unsigned_abs();
618            let digits = abs.to_string();
619            let pad = if digits.len() <= dmax as usize { dmax as usize - digits.len() + 1 } else { 0 };
620            let padded = format!("{}{}", "0".repeat(pad), digits);
621            let cut = padded.len() - dmax as usize;
622            let (lhs, rhs) = padded.split_at(cut);
623            let mut out = format!("{lhs}.{rhs}");
624            if or < 0 { out = format!("-{out}"); }
625            out
626        };
627        crate::Value::Str(reduce_string(&s).into())
628    }
629}
630
631#[cfg(test)]
632mod decimal_path_tests {
633    use super::*;
634
635    #[test]
636    fn string_div_pins_outputs() {
637        let cases: &[(&str, &str, &str)] = &[
638            ("10", "4", "2.5"),
639            ("1", "3", "0.3333333333333333333333333333"),
640            ("2", "3", "0.6666666666666666666666666667"),
641            ("-2", "3", "-0.6666666666666666666666666667"),
642            ("2", "-3", "-0.6666666666666666666666666667"),
643            ("-2", "-3", "0.6666666666666666666666666667"),
644            ("10", "3", "3.3333333333333333333333333333"),
645            ("100", "3", "33.333333333333333333333333333"),
646            ("1", "7", "0.1428571428571428571428571429"),
647            ("22", "7", "3.1428571428571428571428571429"),
648            ("5", "2", "2.5"),
649            ("1", "8", "0.125"),
650            ("0", "5", "0"),
651            ("-0", "5", "0"),
652            ("0", "-5", "0"),
653            ("1.50", "0.5", "3"),
654            ("1.5e3", "2", "750"),
655            ("1E-5", "3", "0.0000033333333333333333333333"),
656            ("123456789012345678", "7", "17636684144620811.142857142857"),
657            ("0.123456789012345678", "3", "0.041152263004115226"),
658            ("0.1234567890123456789012345678", "2", "0.0617283945061728394506172839"),
659            ("0.1234567890123456789012345678", "3", "0.0411522630041152263004115226"),
660            ("-0.1234567890123456789012345678", "7", "-0.0176366841446208112716049383"),
661            ("79228162514264337593543950335", "1", "79228162514264337593543950335"),
662            ("79228162514264337593543950335", "3", "26409387504754779197847983445"),
663            ("-79228162514264337593543950335", "7", "-11318308930609191084791992905"),
664            ("1", "3000000", "0.0000003333333333333333333333"),
665            ("1", "0.0003", "3333.3333333333333333333333333"),
666            ("0.0000000000000000000000000001", "3", "0"),
667            ("0.0000000000000000000000000002", "3", "0.0000000000000000000000000001"),
668            ("0.0000000000000000000000000005", "10", "0"),
669            ("0.0000000000000000000000000015", "10", "0.0000000000000000000000000002"),
670            ("-0.0000000000000000000000000015", "10", "-0.0000000000000000000000000002"),
671            ("0.1", "0.3", "0.3333333333333333333333333333"),
672            ("100.000", "8.00", "12.5"),
673            ("+6", "4", "1.5"),
674            (".5", "2", "0.25"),
675            ("5.", "2", "2.5"),
676            ("1_000", "4", "250"),
677        ];
678        for (a, b, want) in cases {
679            assert_eq!(string_div(a, b).as_deref(), Some(*want), "string_div({a:?}, {b:?})");
680        }
681        for (a, b) in [("1", "0"), ("1", "0.000"), ("0", "0"), ("abc", "1"), ("1", ""), ("", "1"), ("1.2.3", "1"), ("-", "1"), ("1e", "1"), (" 1", "1")] {
682            assert_eq!(string_div(a, b), None, "string_div({a:?}, {b:?})");
683        }
684    }
685
686    #[test]
687    fn string_to_precision_pins_outputs() {
688        let cases: &[(&str, u32, u8, &str)] = &[
689            ("1.23456", 2, 0, "1.23"),
690            ("1.23456", 2, 1, "1.23"),
691            ("1.23456", 2, 2, "1.23"),
692            ("1.23456", 2, 3, "1.24"),
693            ("1.23456", 2, 4, "1.23"),
694            ("1.235", 2, 0, "1.23"),
695            ("1.235", 2, 1, "1.24"),
696            ("1.235", 2, 2, "1.24"),
697            ("1.235", 2, 3, "1.24"),
698            ("1.235", 2, 4, "1.23"),
699            ("1.225", 2, 0, "1.22"),
700            ("1.225", 2, 1, "1.22"),
701            ("1.225", 2, 2, "1.22"),
702            ("1.225", 2, 3, "1.23"),
703            ("1.225", 2, 4, "1.22"),
704            ("1.245", 2, 0, "1.24"),
705            ("1.245", 2, 1, "1.24"),
706            ("1.245", 2, 2, "1.24"),
707            ("1.245", 2, 3, "1.25"),
708            ("1.245", 2, 4, "1.24"),
709            ("-1.235", 2, 0, "-1.23"),
710            ("-1.235", 2, 1, "-1.24"),
711            ("-1.235", 2, 2, "-1.24"),
712            ("-1.235", 2, 3, "-1.23"),
713            ("-1.235", 2, 4, "-1.24"),
714            ("-1.225", 2, 0, "-1.22"),
715            ("-1.225", 2, 1, "-1.22"),
716            ("-1.225", 2, 2, "-1.22"),
717            ("-1.225", 2, 3, "-1.22"),
718            ("-1.225", 2, 4, "-1.23"),
719            ("1.231", 2, 0, "1.23"),
720            ("1.231", 2, 1, "1.23"),
721            ("1.231", 2, 2, "1.23"),
722            ("1.231", 2, 3, "1.24"),
723            ("1.231", 2, 4, "1.23"),
724            ("-1.231", 2, 0, "-1.23"),
725            ("-1.231", 2, 1, "-1.23"),
726            ("-1.231", 2, 2, "-1.23"),
727            ("-1.231", 2, 3, "-1.23"),
728            ("-1.231", 2, 4, "-1.24"),
729            ("1.239", 2, 0, "1.23"),
730            ("1.239", 2, 1, "1.24"),
731            ("1.239", 2, 2, "1.24"),
732            ("1.239", 2, 3, "1.24"),
733            ("1.239", 2, 4, "1.23"),
734            ("-1.239", 2, 0, "-1.23"),
735            ("-1.239", 2, 1, "-1.24"),
736            ("-1.239", 2, 2, "-1.24"),
737            ("-1.239", 2, 3, "-1.23"),
738            ("-1.239", 2, 4, "-1.24"),
739            ("0", 2, 0, "0.00"),
740            ("0", 2, 1, "0.00"),
741            ("0", 2, 2, "0.00"),
742            ("0", 2, 3, "0.00"),
743            ("0", 2, 4, "0.00"),
744            ("-0", 2, 0, "0.00"),
745            ("-0", 2, 1, "0.00"),
746            ("-0", 2, 2, "0.00"),
747            ("-0", 2, 3, "0.00"),
748            ("-0", 2, 4, "0.00"),
749            ("-0.001", 2, 0, "-0.00"),
750            ("-0.001", 2, 1, "0.00"),
751            ("-0.001", 2, 2, "0.00"),
752            ("-0.001", 2, 3, "0.00"),
753            ("-0.001", 2, 4, "-0.01"),
754            ("0.001", 2, 0, "0.00"),
755            ("0.001", 2, 1, "0.00"),
756            ("0.001", 2, 2, "0.00"),
757            ("0.001", 2, 3, "0.01"),
758            ("0.001", 2, 4, "0.00"),
759            ("5", 0, 0, "5"),
760            ("5", 0, 1, "5"),
761            ("5", 0, 2, "5"),
762            ("5", 0, 3, "5"),
763            ("5", 0, 4, "5"),
764            ("-5", 0, 0, "-5"),
765            ("-5", 0, 1, "-5"),
766            ("-5", 0, 2, "-5"),
767            ("-5", 0, 3, "-5"),
768            ("-5", 0, 4, "-5"),
769            ("1.5", 0, 0, "1"),
770            ("1.5", 0, 1, "2"),
771            ("1.5", 0, 2, "2"),
772            ("1.5", 0, 3, "2"),
773            ("1.5", 0, 4, "1"),
774            ("2.5", 0, 0, "2"),
775            ("2.5", 0, 1, "2"),
776            ("2.5", 0, 2, "2"),
777            ("2.5", 0, 3, "3"),
778            ("2.5", 0, 4, "2"),
779            ("-2.5", 0, 0, "-2"),
780            ("-2.5", 0, 1, "-2"),
781            ("-2.5", 0, 2, "-2"),
782            ("-2.5", 0, 3, "-2"),
783            ("-2.5", 0, 4, "-3"),
784            ("0.5", 0, 0, "0"),
785            ("0.5", 0, 1, "0"),
786            ("0.5", 0, 2, "0"),
787            ("0.5", 0, 3, "1"),
788            ("0.5", 0, 4, "0"),
789            ("-0.5", 0, 0, "-0"),
790            ("-0.5", 0, 1, "0"),
791            ("-0.5", 0, 2, "0"),
792            ("-0.5", 0, 3, "0"),
793            ("-0.5", 0, 4, "-1"),
794            ("1.2", 5, 0, "1.20000"),
795            ("1.2", 5, 1, "1.20000"),
796            ("1.2", 5, 2, "1.20000"),
797            ("1.2", 5, 3, "1.20000"),
798            ("1.2", 5, 4, "1.20000"),
799            ("1.5e3", 2, 0, "1500.00"),
800            ("1.5e3", 2, 1, "1500.00"),
801            ("1.5e3", 2, 2, "1500.00"),
802            ("1.5e3", 2, 3, "1500.00"),
803            ("1.5e3", 2, 4, "1500.00"),
804            ("123456789.123456789", 4, 0, "123456789.1234"),
805            ("123456789.123456789", 4, 1, "123456789.1235"),
806            ("123456789.123456789", 4, 2, "123456789.1235"),
807            ("123456789.123456789", 4, 3, "123456789.1235"),
808            ("123456789.123456789", 4, 4, "123456789.1234"),
809            ("0.123456789012345678", 10, 0, "0.1234567890"),
810            ("0.123456789012345678", 10, 1, "0.1234567890"),
811            ("0.123456789012345678", 10, 2, "0.1234567890"),
812            ("0.123456789012345678", 10, 3, "0.1234567891"),
813            ("0.123456789012345678", 10, 4, "0.1234567890"),
814            ("0.1234567890123456789012345678", 1, 0, "0.1"),
815            ("0.1234567890123456789012345678", 1, 1, "0.1"),
816            ("0.1234567890123456789012345678", 1, 2, "0.1"),
817            ("0.1234567890123456789012345678", 1, 3, "0.2"),
818            ("0.1234567890123456789012345678", 1, 4, "0.1"),
819            ("1.123456785", 8, 0, "1.12345678"),
820            ("1.123456785", 8, 1, "1.12345678"),
821            ("1.123456785", 8, 2, "1.12345678"),
822            ("1.123456785", 8, 3, "1.12345679"),
823            ("1.123456785", 8, 4, "1.12345678"),
824            ("-1.123456775", 8, 0, "-1.12345677"),
825            ("-1.123456775", 8, 1, "-1.12345678"),
826            ("-1.123456775", 8, 2, "-1.12345678"),
827            ("-1.123456775", 8, 3, "-1.12345677"),
828            ("-1.123456775", 8, 4, "-1.12345678"),
829            ("9.999", 2, 0, "9.99"),
830            ("9.999", 2, 1, "10.00"),
831            ("9.999", 2, 2, "10.00"),
832            ("9.999", 2, 3, "10.00"),
833            ("9.999", 2, 4, "9.99"),
834            ("-9.999", 2, 0, "-9.99"),
835            ("-9.999", 2, 1, "-10.00"),
836            ("-9.999", 2, 2, "-10.00"),
837            ("-9.999", 2, 3, "-9.99"),
838            ("-9.999", 2, 4, "-10.00"),
839            ("79228162514264337593543950335", 0, 0, "79228162514264337593543950335"),
840            ("79228162514264337593543950335", 0, 1, "79228162514264337593543950335"),
841            ("79228162514264337593543950335", 0, 2, "79228162514264337593543950335"),
842            ("79228162514264337593543950335", 0, 3, "79228162514264337593543950335"),
843            ("79228162514264337593543950335", 0, 4, "79228162514264337593543950335"),
844            ("100", 3, 0, "100.000"),
845            ("100", 3, 1, "100.000"),
846            ("100", 3, 2, "100.000"),
847            ("100", 3, 3, "100.000"),
848            ("100", 3, 4, "100.000"),
849            ("0.000", 2, 0, "0.00"),
850            ("0.000", 2, 1, "0.00"),
851            ("0.000", 2, 2, "0.00"),
852            ("0.000", 2, 3, "0.00"),
853            ("0.000", 2, 4, "0.00"),
854            ("-0.000", 1, 0, "0.0"),
855            ("-0.000", 1, 1, "0.0"),
856            ("-0.000", 1, 2, "0.0"),
857            ("-0.000", 1, 3, "0.0"),
858            ("-0.000", 1, 4, "0.0"),
859            ("1_0.5", 0, 0, "10"),
860            ("1_0.5", 0, 1, "10"),
861            ("1_0.5", 0, 2, "10"),
862            ("1_0.5", 0, 3, "11"),
863            ("1_0.5", 0, 4, "10"),
864            ("0.1234567890123456789012345678", 27, 0, "0.123456789012345678901234567"),
865            ("0.1234567890123456789012345678", 27, 2, "0.123456789012345678901234568"),
866            ("-0.1234567890123456789012345678", 27, 0, "-0.123456789012345678901234567"),
867            ("-0.1234567890123456789012345678", 27, 2, "-0.123456789012345678901234568"),
868            ("-0.1234567890123456789012345678", 18, 0, "-0.123456789012345678"),
869            ("-0.1234567890123456789012345678", 18, 2, "-0.123456789012345679"),
870        ];
871        for (a, k, m, want) in cases {
872            assert_eq!(string_to_precision(a, *k, *m).as_deref(), Some(*want), "string_to_precision({a:?}, {k}, {m})");
873        }
874        for a in ["abc", "", "1.2.3", "-", "1e"] {
875            for m in [0u8, 2, 3, 4] {
876                assert_eq!(string_to_precision(a, 2, m), None, "string_to_precision({a:?}, 2, {m})");
877            }
878        }
879    }
880}