Skip to main content

ccxt_base/
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 rust_decimal::Decimal;
8use rust_decimal::prelude::*;
9use std::str::FromStr;
10
11/// Parse a string to a `Decimal`, returning `None` on failure.
12fn parse(s: &str) -> Option<Decimal> {
13    Decimal::from_str(s).ok()
14}
15
16/// Format a `Decimal` back to a string without trailing zeros.
17fn fmt(d: Decimal) -> String {
18    let s = d.to_string();
19    // Remove trailing zeros after decimal point (but keep at least one digit)
20    let out = if s.contains('.') {
21        s.trim_end_matches('0').trim_end_matches('.').to_owned()
22    } else {
23        s
24    };
25    // Normalise negative zero ("-0") → "0".
26    if out.bytes().all(|b| matches!(b, b'-' | b'0' | b'.')) {
27        "0".to_string()
28    } else {
29        out
30    }
31}
32
33// ── public API ────────────────────────────────────────────────────────────────
34
35/// 10^n as a `BigInt`, for aligning two operands to a common scale.
36fn big_pow10(n: i32) -> num_bigint::BigInt {
37    num_bigint::BigInt::from(10u8).pow(n.max(0) as u32)
38}
39
40/// Align two `(integer, decimals)` pairs onto the larger scale, mirroring the
41/// scaling TS `add`/`sub`/`compare` do inline.
42fn 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    // Arbitrary precision, not `Decimal`: `rust_decimal` holds only 28
60    // significant digits, so 30-digit operands failed to parse and the sum
61    // came back as `None`. CCXT's `Precise` is BigInt-backed, so the result
62    // must not depend on rust_decimal's range.
63    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    // Fast path: rust_decimal. Its `*` PANICS on overflow ("Multiplication
74    // overflowed"), so use `checked_mul` and fall back to the arbitrary-
75    // precision BigInt path (like `string_div_prec`) when the 96-bit mantissa
76    // can't hold the product — e.g. nado's parse_position multiplying large
77    // contract sizes by price. CCXT's `Precise` is arbitrary-precision, so the
78    // result must not depend on rust_decimal's range.
79    string_mul_big(a, b)
80}
81
82/// Arbitrary-precision `a * b`: product integer is `a_int * b_int`, with the
83/// decimal counts summed. Used when the i128/decimal fast path overflows.
84fn 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    // Mirrors TS `mod()`: rationalize both sides onto a common scale, then
99    // take the remainder of the scaled integers.
100    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    // NOT via `Decimal`: `rust_decimal` caps at 28 decimal places, so an
112    // extreme scale like `1e-200` (or its 200-digit expansion) fails to parse
113    // outright and equality silently came back false. Mirror TS `equals()`
114    // instead — reduce both and compare (integer, decimals) — which needs no
115    // rescaling and so has no magnitude limit beyond the digit count itself.
116    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
123/// TS `compare()` — align onto the larger scale, compare the integers.
124fn 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
156/// Round to `decimals` decimal places using the specified rounding mode.
157/// mode 0 = TRUNCATE, mode 2 = ROUND (half-up), mode 3 = ROUND_UP, mode 4 = ROUND_DOWN
158pub 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            // ROUND_UP (away from zero)
164            let scale = Decimal::from(10u64.pow(decimals));
165            (d * scale).ceil() / scale
166        }
167        4 => {
168            // ROUND_DOWN (toward zero)
169            let scale = Decimal::from(10u64.pow(decimals));
170            (d * scale).floor() / scale
171        }
172        _ => d.round_dp(decimals), // ROUND half-up
173    };
174    let s = format!("{:.prec$}", rounded, prec = decimals as usize);
175    Some(s)
176}
177
178/// Parses the number of significant digits in a decimal string.
179pub fn precise_from_string(s: &str) -> Option<Decimal> {
180    parse(s)
181}
182
183// ── precision-aware division ────────────────────────────────────────────────
184//
185// `string_div` above uses `rust_decimal` (fixed ~28-digit precision, rounds).
186// The TS `Precise.stringDiv (a, b, precision)` uses arbitrary-precision
187// big-integer math and *truncates* the result to exactly `precision`
188// decimal places. `string_div_prec` ports that algorithm with `i128`
189// (sufficient for the realistic value range; falls back to `string_div`
190// on overflow).
191
192/// Parses a decimal string into `(integer, decimals)` exactly like the
193/// TS `Precise` constructor (handles scientific `e` notation).
194fn 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
210/// Port of `Precise.reduce()` — strips trailing zeros from the integer.
211fn 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
230/// Port of `Precise.toString()`.
231fn 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
266/// Normalises a decimal string by stripping trailing fractional
267/// zeros (mirrors `Precise.reduce()` + `toString()`). Falls back to
268/// the input on overflow / parse failure.
269pub 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
276/// Port of `Precise.stringDiv (a, b, precision)` — truncating
277/// big-integer division to exactly `precision` decimal places.
278pub fn string_div_prec(a: &str, b: &str, precision: i64) -> Option<String> {
279    // Fast path: i128. Any overflow (operand too large to parse, or the
280    // `a_int * 10^distance` intermediate exceeding i128) falls back to the
281    // arbitrary-precision BigInt path so the result matches TS exactly —
282    // NOT to `string_div` (which would silently change the precision).
283    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
312/// BigInt sibling of [`precise_parse`] — no i128 range limit. Splits a
313/// decimal (with optional `e` exponent) into `(integer, decimals)`.
314fn 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
329/// Arbitrary-precision port of `Precise.stringDiv (a, b, precision)`.
330/// Mirrors the TS BigInt algorithm exactly; used when the i128 fast path
331/// in [`string_div_prec`] would overflow.
332pub 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    // 10^n as a BigInt via its literal digit string ("1" followed by n
343    // zeros) — avoids depending on a particular `pow` API surface.
344    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    // BigInt division truncates toward zero, matching TS `BigInt` `/`.
353    let result = numerator / b_int;
354    // The quotient (a value scaled to `precision` decimals) is almost
355    // always small; reuse the i128 formatter when it fits, else format
356    // the BigInt digits directly.
357    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
363/// Format `(integer, decimals)` where `integer` is a BigInt — the
364/// arbitrary-precision analogue of [`precise_to_string`]. Reduces trailing
365/// zeros (adjusting `decimals`) then positions the decimal point.
366fn 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    // reduce(): strip trailing zeros from the digit string.
372    let bytes = abs.as_bytes();
373    let start = abs.len() as i32 - 1;
374    if start == 0 && abs == "0" {
375        // TS `reduceDigits()` zeroes the scale for a bare "0", so `0 * 1e-6`
376        // renders as "0" and not "0.000000". The i128 `precise_reduce` already
377        // did this; the BigInt path did not, and only showed up once the
378        // Decimal fast path stopped masking it.
379        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
423/// A struct wrapper matching CCXT Precise class usage (e.g. `Precise::string_add`).
424pub struct Precise;
425
426impl Precise {
427    /// TS-style `new Precise(s)` — parses `s` into an `integer` (the
428    /// digit string) + `decimals` (count of digits to the right of the
429    /// decimal point). Returns a `Value::Map` carrying those two
430    /// fields plus a `__precise` marker that `stringify_param` /
431    /// `Value::reduce` recognise — that's what makes
432    /// `precise.decimals = subtract(...)` followed by `precise.reduce()`
433    /// (as transpiled phemex's `toEn` does) work end-to-end.
434    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.into()));
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// ── Value-accepting versions (used by transpiled code) ───────────────────────
477//
478// The transpiler emits `Precise::stringDiv(a, b)` with Value arguments. These
479// camelCase methods stringify their args and dispatch to the typed versions
480// above. They return `Value` so the rest of the transpiled code can chain.
481
482#[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.into()), 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    /// Mirrors TS `Precise.stringAdd`: when one operand is `undefined` /
489    /// `null` it returns the OTHER side (treating the missing value as the
490    /// arithmetic identity). Bitget's `parsePosition` relies on this when
491    /// `keepMarginRate` is missing (UTA response uses `mmr` instead), so
492    /// `Precise.stringAdd(undefined, feeToClose)` should yield `feeToClose`.
493    pub fn stringAdd(a: &crate::Value, b: &crate::Value) -> crate::Value {
494        // Mirrors TS `Precise.stringAdd`: either operand undefined → undefined.
495        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    /// Mirrors TS `Precise.stringSub`: either operand undefined → undefined.
501    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    /// Mirrors TS `Precise.stringMul`: any undefined operand → undefined
508    /// (matches the typescript `x * undefined === NaN → undefined` chain).
509    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        // TS `Precise.stringDiv` defaults to precision 18 (truncating).
517        Self::vopt(string_div_prec(&Self::vstr(a), &Self::vstr(b), 18))
518    }
519    /// `Precise.stringDiv (a, b, precision)` — truncating division to a
520    /// given number of decimal places.
521    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    /// TS treats the comparison operators as `false` when either operand
537    /// is undefined (they short-circuit before constructing a `Precise`).
538    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        // Mirrors TS `Precise.stringMin`: either operand undefined → undefined.
543        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).into())
549    }
550    pub fn stringMax(a: &crate::Value, b: &crate::Value) -> crate::Value {
551        // Mirrors TS `Precise.stringMax`: either operand undefined → undefined.
552        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).into())
558    }
559    pub fn stringEquals(a: &crate::Value, b: &crate::Value) -> crate::Value { Self::stringEq(a, b) }
560    /// Mirrors TS `Precise.stringOr`: bitwise OR of the underlying
561    /// integer representations at a common decimal scale.
562    /// `stringOr("5", "3") == "7"`, `stringOr("5.5", "3") == "6.3"` etc.
563    /// Either undefined operand → undefined (matches TS).
564    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        // Split each into (sign, integer-string, decimal-count). Mirrors
570        // the constructor in TS Precise — chop at `.`, count fractional
571        // digits, drop the `.` so the integer parses as a single number.
572        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        // Shift the smaller-decimal side up to match.
585        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            // Re-insert the decimal point dmax positions from the right.
593            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).into())
604    }
605}