///|
pub const DECIMAL_MAX_EXP : Int32 = 100_000

///|
pub const DECIMAL_MIN_EXP : Int32 = -100_000

///|
pub const DECIMAL_DIV_PRECISION : Int32 = 24

///|
pub const DECIMAL_MAX_SCALE_OP : Int32 = 4096

///|
/// Arbitrary-precision base-10 floating-point number representing
/// `coeff * 10^exp`, aligned with CUE's decimal arithmetic (`apd.Decimal`).
///
/// Invariants maintained by all constructors and operations:
/// - Zero is uniquely represented as `{ coeff: 0, exp: 0 }`.
/// - For non-zero values, `coeff` has no trailing base-10 zeros.
/// - Adjusted exponent `exp + digit_len(|coeff|) - 1` lies in
///   `[DECIMAL_MIN_EXP, DECIMAL_MAX_EXP]`.
#derive(Debug)
pub struct Decimal {
  coeff : BigInt
  exp : Int32
}

///|
pub impl Eq for Decimal with fn equal(self, other) {
  self.coeff == other.coeff && self.exp == other.exp
}

///|
/// Returns the normalized integer coefficient of `self`.
pub fn Decimal::coeff(self : Decimal) -> BigInt {
  self.coeff
}

///|
/// Returns the normalized base-10 exponent of `self`.
pub fn Decimal::exp(self : Decimal) -> Int32 {
  self.exp
}

///|
/// Returns the canonical zero `Decimal` (`0.0`).
pub fn Decimal::zero() -> Decimal {
  { coeff: BigInt::from_int(0), exp: 0, }
}

///|
pub fn Decimal::is_zero(self : Decimal) -> Bool {
  self.coeff.is_zero()
}

///|
pub fn Decimal::is_negative(self : Decimal) -> Bool {
  self.coeff < BigInt::from_int(0)
}

///|
pub fn Decimal::is_positive(self : Decimal) -> Bool {
  self.coeff > BigInt::from_int(0)
}

///|
pub fn Decimal::is_exact_int(self : Decimal) -> Bool {
  self.exp >= 0
}

///|
fn dec_pow10(exp : Int32) -> BigInt {
  if exp <= 0 {
    return BigInt::from_int(1)
  }
  let mut result = BigInt::from_int(1)
  let mut base = BigInt::from_int(10)
  let mut e = exp
  while e > 0 {
    if (e & 1) == 1 {
      result = result * base
    }
    e = e >> 1
    if e > 0 {
      base = base * base
    }
  }
  result
}

///|
fn dec_abs_digits(n : BigInt) -> (Bool, String) {
  let zero = BigInt::from_int(0)
  if n == zero {
    return (false, "0")
  }
  let neg = n < zero
  let s = (if neg { -n } else { n }).to_string()
  (neg, s)
}

///|
fn normalize_decimal_i64(
  coeff : BigInt,
  exp64 : Int64,
) -> Result[Decimal, String] {
  if coeff.is_zero() {
    return Ok(Decimal::zero())
  }
  let s = (if coeff < BigInt::from_int(0) { -coeff } else { coeff }).to_string()
  let len = s.length()
  let mut end = len
  while end > 0 && s.code_unit_at(end - 1) == '0' {
    end -= 1
  }
  let tz = len - end
  let norm_coeff = if tz > 0 { coeff / dec_pow10(tz) } else { coeff }
  let norm_exp64 = exp64 + tz.to_int64()
  let sig_len = end.to_int64()
  let adj_exp64 = norm_exp64 + sig_len - 1L
  if adj_exp64 > DECIMAL_MAX_EXP.to_int64() ||
    norm_exp64 > DECIMAL_MAX_EXP.to_int64() {
    return Err("decimal exponent overflow")
  }
  if adj_exp64 < DECIMAL_MIN_EXP.to_int64() ||
    norm_exp64 < DECIMAL_MIN_EXP.to_int64() {
    return Err("decimal exponent underflow")
  }
  Ok({ coeff: norm_coeff, exp: norm_exp64.to_int(), })
}

///|
/// Constructs a normalized `Decimal` from an arbitrary coefficient and base-10 exponent.
pub fn Decimal::from_parts(
  coeff : BigInt,
  exp : Int32,
) -> Result[Decimal, String] {
  normalize_decimal_i64(coeff, exp.to_int64())
}

///|
/// Converts an exact `BigInt` to a normalized `Decimal`.
pub fn Decimal::from_bigint(n : BigInt) -> Result[Decimal, String] {
  normalize_decimal_i64(n, 0L)
}

///|
/// Returns the additive inverse `-self`.
pub fn Decimal::neg(self : Decimal) -> Decimal {
  if self.coeff.is_zero() {
    self
  } else {
    { coeff: -self.coeff, exp: self.exp, }
  }
}

///|
/// Returns the absolute value `|self|`.
pub fn Decimal::abs(self : Decimal) -> Decimal {
  if self.is_negative() {
    self.neg()
  } else {
    self
  }
}

///|
fn dec_cmp_unsigned_strs(a_digits : String, b_digits : String) -> Int32 {
  let la = a_digits.length()
  let lb = b_digits.length()
  let max_len = if la > lb { la } else { lb }
  for i in 0.. cb {
      return 1
    }
  }
  0
}

///|
/// Exact numerical comparison between two `Decimal`s in O(len(a)+len(b)) without
/// allocating `pow10` even for huge exponent differences.
pub fn Decimal::compare(self : Decimal, other : Decimal) -> Int32 {
  let sa = if self.coeff.is_zero() {
    0
  } else if self.coeff < BigInt::from_int(0) {
    -1
  } else {
    1
  }
  let sb = if other.coeff.is_zero() {
    0
  } else if other.coeff < BigInt::from_int(0) {
    -1
  } else {
    1
  }
  if sa != sb {
    return if sa < sb { -1 } else { 1 }
  }
  if sa == 0 {
    return 0
  }
  let (_, da) = dec_abs_digits(self.coeff)
  let (_, db) = dec_abs_digits(other.coeff)
  let mag_a = self.exp.to_int64() + da.length().to_int64() - 1L
  let mag_b = other.exp.to_int64() + db.length().to_int64() - 1L
  let abs_cmp = if mag_a < mag_b {
    -1
  } else if mag_a > mag_b {
    1
  } else {
    dec_cmp_unsigned_strs(da, db)
  }
  if sa < 0 {
    -abs_cmp
  } else {
    abs_cmp
  }
}

///|
/// Exact comparison between a `Decimal` and an arbitrary `BigInt` without
/// precision loss or `pow10` allocation.
pub fn Decimal::compare_bigint(self : Decimal, n : BigInt) -> Int32 {
  let sa = if self.coeff.is_zero() {
    0
  } else if self.coeff < BigInt::from_int(0) {
    -1
  } else {
    1
  }
  let zero = BigInt::from_int(0)
  let sb = if n == zero { 0 } else if n < zero { -1 } else { 1 }
  if sa != sb {
    return if sa < sb { -1 } else { 1 }
  }
  if sa == 0 {
    return 0
  }
  let (_, da) = dec_abs_digits(self.coeff)
  let (_, db_raw) = dec_abs_digits(n)
  let mag_a = self.exp.to_int64() + da.length().to_int64() - 1L
  let mag_b = db_raw.length().to_int64() - 1L
  let abs_cmp = if mag_a < mag_b {
    -1
  } else if mag_a > mag_b {
    1
  } else {
    let db_trim = trim_trailing_zeros(db_raw)
    dec_cmp_unsigned_strs(da, db_trim)
  }
  if sa < 0 {
    -abs_cmp
  } else {
    abs_cmp
  }
}

///|
/// Parses a validated decimal string (with optional leading `+`/`-`) using CUE's
/// decimal rules (`_`, `.5`, `1.`, `1.e5`, `2.5e-3`).
pub fn Decimal::parse(raw : String) -> Result[Decimal, String] {
  if raw.is_empty() {
    return Err("invalid float literal: empty input")
  }
  let chars = raw.to_array()
  if chars[0] == '-' {
    let sb = StringBuilder()
    for i in 1.. Ok(d.neg())
      Err(_) => Err("invalid float literal '\{raw}'")
    }
  } else if chars[0] == '+' {
    let sb = StringBuilder()
    for i in 1.. Ok(d)
      Err(_) => Err("invalid float literal '\{raw}'")
    }
  } else {
    parse_decimal_literal(raw)
  }
}

///|
/// Parses an unsigned CUE floating-point literal into an exact normalized
/// arbitrary-precision `Decimal`.
///
/// Supports `_` separators, trailing dot (`0.`, `1.`, `1.e5`), leading dot
/// (`.5`, `.5e-3`), and exponents (`1e5`, `2.5e-3`), rejecting malformed
/// literals, `NaN`, `Infinity`, leading `-`, and exponent overflow/underflow.
pub fn parse_decimal_literal(raw : String) -> Result[Decimal, String] {
  if raw.is_empty() {
    return Err("invalid float literal: empty input")
  }
  let chars = raw.to_array()
  let int_buf = StringBuilder()
  let frac_buf = StringBuilder()
  let mut idx = 0
  let mut int_count = 0
  let mut frac_count = 0
  if chars[0] != '.' {
    let (after_int, ic, ibad) = scan_validated_digits(
      chars, 0, is_dec_digit, int_buf,
    )
    if ic == 0 || ibad {
      return Err("invalid float literal '\{raw}'")
    }
    int_count = ic
    idx = after_int
  }
  if idx < chars.length() && chars[idx] == '.' {
    idx += 1
    let (after_frac, fc, fbad) = scan_validated_digits(
      chars, idx, is_dec_digit, frac_buf,
    )
    if fbad {
      return Err("invalid float literal '\{raw}'")
    }
    frac_count = fc
    idx = after_frac
  }
  if int_count == 0 && frac_count == 0 {
    return Err("invalid float literal '\{raw}'")
  }
  let mut exp_neg = false
  let mut exp_abs = 0L
  let raw_len = chars.length().to_int64()
  let exp_sat = if raw_len + 200_000L > 1_000_000L {
    raw_len + 200_000L
  } else {
    1_000_000L
  }
  if idx < chars.length() && (chars[idx] == 'e' || chars[idx] == 'E') {
    idx += 1
    if idx < chars.length() {
      if chars[idx] == '+' {
        idx += 1
      } else if chars[idx] == '-' {
        exp_neg = true
        idx += 1
      }
    }
    let exp_buf = StringBuilder()
    let (after_exp, ec, ebad) = scan_validated_digits(
      chars, idx, is_dec_digit, exp_buf,
    )
    if ec == 0 || ebad {
      return Err("invalid float literal '\{raw}'")
    }
    idx = after_exp
    for ch in exp_buf.to_string() {
      if exp_abs < exp_sat {
        exp_abs = exp_abs * 10L + (ch.to_int() - '0'.to_int()).to_int64()
        if exp_abs > exp_sat {
          exp_abs = exp_sat
        }
      }
    }
  }
  if idx != chars.length() {
    return Err("invalid float literal '\{raw}'")
  }
  let combined = int_buf.to_string() + frac_buf.to_string()
  let sig_buf = StringBuilder()
  let mut seen_nonzero = false
  for ch in combined {
    if !seen_nonzero && ch == '0' {
      continue
    }
    seen_nonzero = true
    sig_buf.write_char(ch)
  }
  if !seen_nonzero {
    return Ok(Decimal::zero())
  }
  let raw_sig = sig_buf.to_string()
  let trimmed = trim_trailing_zeros(raw_sig)
  if trimmed.length() > DECIMAL_MAX_SCALE_OP {
    return Err(
      "invalid float literal '\{raw}': significant digits (\{trimmed.length()}) exceed limit (\{DECIMAL_MAX_SCALE_OP})",
    )
  }
  let trimmed_zeros = raw_sig.length() - trimmed.length()
  let signed_exp = if exp_neg { -exp_abs } else { exp_abs }
  let norm_exp64 = signed_exp - frac_count.to_int64() + trimmed_zeros.to_int64()
  let adj_exp64 = norm_exp64 + trimmed.length().to_int64() - 1L
  if adj_exp64 > DECIMAL_MAX_EXP.to_int64() ||
    norm_exp64 > DECIMAL_MAX_EXP.to_int64() {
    return Err("invalid float literal '\{raw}': float overflow")
  }
  if adj_exp64 < DECIMAL_MIN_EXP.to_int64() ||
    norm_exp64 < DECIMAL_MIN_EXP.to_int64() {
    return Err("invalid float literal '\{raw}': float underflow")
  }
  let coeff = @string.parse_bigint(trimmed, radix=10) catch {
    _ => return Err("invalid float literal '\{raw}'")
  }
  Ok({ coeff, exp: norm_exp64.to_int(), })
}

///|
/// Converts a finite IEEE-754 `Double` into an exact normalized `Decimal`,
/// rejecting `NaN` and `±Inf` and normalizing `-0.0` to `Decimal::zero()`.
pub fn Decimal::from_double(d : Double) -> Result[Decimal, String] {
  if d.is_nan() {
    return Err("invalid float: NaN is not a valid CUE number")
  }
  if d.is_inf() {
    return Err("invalid float: infinity is not a valid CUE number")
  }
  if d == 0.0 {
    return Ok(Decimal::zero())
  }
  Decimal::parse(d.to_string())
}

///|
/// Converts a `Decimal` to the nearest IEEE-754 `Double` (used for floating-point
/// transcendental math built-ins such as `math.Sin` and `math.Sqrt`).
pub fn Decimal::to_double(self : Decimal) -> Result[Double, String] {
  if self.coeff.is_zero() {
    return Ok(0.0)
  }
  let (neg, digits) = dec_abs_digits(self.coeff)
  match decimal_to_finite_double(digits, self.exp) {
    Ok(d) => {
      let signed = if neg { -d } else { d }
      Ok(if signed == 0.0 { 0.0 } else { signed })
    }
    Err(msg) => Err(msg)
  }
}

///|
fn check_scale_diff(
  diff : Int64,
  max_digits : Int32,
  op : String,
) -> Result[Int32, String] {
  let limit = if max_digits > 0 { max_digits } else { DECIMAL_MAX_SCALE_OP }
  if diff > limit.to_int64() {
    Err("\{op}: decimal scale difference (\{diff}) exceeds limit (\{limit})")
  } else {
    Ok(diff.to_int())
  }
}

///|
/// Exact base-10 addition `self + other`.
pub fn Decimal::add(
  self : Decimal,
  other : Decimal,
  max_digits~ : Int32 = DECIMAL_MAX_SCALE_OP,
) -> Result[Decimal, String] {
  if self.is_zero() {
    return Ok(other)
  }
  if other.is_zero() {
    return Ok(self)
  }
  let limit = if max_digits > 0 { max_digits } else { DECIMAL_MAX_SCALE_OP }
  let (min_exp, c_sum) = if self.exp == other.exp {
    (self.exp, self.coeff + other.coeff)
  } else if self.exp > other.exp {
    let diff64 = self.exp.to_int64() - other.exp.to_int64()
    let diff = match check_scale_diff(diff64, limit, "decimal add") {
      Ok(d) => d
      Err(msg) => return Err(msg)
    }
    (other.exp, self.coeff * dec_pow10(diff) + other.coeff)
  } else {
    let diff64 = other.exp.to_int64() - self.exp.to_int64()
    let diff = match check_scale_diff(diff64, limit, "decimal add") {
      Ok(d) => d
      Err(msg) => return Err(msg)
    }
    (self.exp, self.coeff + other.coeff * dec_pow10(diff))
  }
  let (_, sum_digits) = dec_abs_digits(c_sum)
  if sum_digits.length() > limit {
    return Err(
      "decimal add: result digit count (\{sum_digits.length()}) exceeds limit (\{limit})",
    )
  }
  normalize_decimal_i64(c_sum, min_exp.to_int64())
}

///|
/// Exact base-10 subtraction `self - other`.
pub fn Decimal::sub(
  self : Decimal,
  other : Decimal,
  max_digits~ : Int32 = DECIMAL_MAX_SCALE_OP,
) -> Result[Decimal, String] {
  self.add(other.neg(), max_digits~)
}

///|
/// Exact base-10 multiplication `self * other`.
pub fn Decimal::mul(
  self : Decimal,
  other : Decimal,
  max_digits~ : Int32 = DECIMAL_MAX_SCALE_OP,
) -> Result[Decimal, String] {
  if self.is_zero() || other.is_zero() {
    return Ok(Decimal::zero())
  }
  let limit = if max_digits > 0 { max_digits } else { DECIMAL_MAX_SCALE_OP }
  let (_, da) = dec_abs_digits(self.coeff)
  let (_, db) = dec_abs_digits(other.coeff)
  if da.length() + db.length() > limit + 1 {
    return Err("decimal mul: operand digit count exceeds limit (\{limit})")
  }
  let prod = self.coeff * other.coeff
  normalize_decimal_i64(prod, self.exp.to_int64() + other.exp.to_int64())
}

///|
/// Base-10 division `self / other` rounded half-to-even to `precision` significant
/// digits (default `DECIMAL_DIV_PRECISION = 24`, aligned with Go CUE's `apd`).
pub fn Decimal::div(
  self : Decimal,
  other : Decimal,
  precision~ : Int32 = DECIMAL_DIV_PRECISION,
) -> Result[Decimal, String] {
  if other.is_zero() {
    return Err("division by zero")
  }
  if self.is_zero() {
    return Ok(Decimal::zero())
  }
  let prec = if precision > 0 { precision } else { DECIMAL_DIV_PRECISION }
  let neg = self.is_negative() != other.is_negative()
  let zero = BigInt::from_int(0)
  let abs_a = if self.coeff < zero { -self.coeff } else { self.coeff }
  let abs_b = if other.coeff < zero { -other.coeff } else { other.coeff }
  let len_a = abs_a.to_string().length()
  let len_b = abs_b.to_string().length()
  if len_a > DECIMAL_MAX_SCALE_OP || len_b > DECIMAL_MAX_SCALE_OP {
    return Err(
      "decimal div: operand digit count exceeds limit (\{DECIMAL_MAX_SCALE_OP})",
    )
  }
  // Target shift k so that floor((abs_a * 10^k) / abs_b) has >= prec digits.
  if prec > DECIMAL_MAX_SCALE_OP {
    return Err(
      "decimal div: precision (\{prec}) exceeds limit (\{DECIMAL_MAX_SCALE_OP})",
    )
  }
  let mut k = prec + (len_b - len_a) + 1
  if k < 0 {
    k = 0
  }
  if k > DECIMAL_MAX_SCALE_OP {
    return Err(
      "decimal div: scale shift (\{k}) exceeds limit (\{DECIMAL_MAX_SCALE_OP})",
    )
  }
  let num = abs_a * dec_pow10(k)
  let mut q = num / abs_b
  let mut rem = num % abs_b
  let one = BigInt::from_int(1)
  // Exact rounding at exact `prec` significant digits without double rounding.
  let mut final_exp64 = self.exp.to_int64() -
    other.exp.to_int64() -
    k.to_int64()
  let q_len = q.to_string().length()
  if q_len > prec {
    let extra = q_len - prec
    if extra > DECIMAL_MAX_SCALE_OP {
      return Err(
        "decimal div: extra rounding scale (\{extra}) exceeds limit (\{DECIMAL_MAX_SCALE_OP})",
      )
    }
    let div_extra = dec_pow10(extra)
    // Combine remainder from exact quotient `(abs_a * 10^k) = q_full * abs_b + rem`:
    // Exact division by `abs_b * div_extra` avoids double rounding!
    let eff_den = abs_b * div_extra
    let q_exact = num / eff_den
    rem = num % eff_den
    q = q_exact
    let twice_rem = rem << 1
    if twice_rem > eff_den || (twice_rem == eff_den && !(q & one).is_zero()) {
      q = q + one
    }
    final_exp64 = self.exp.to_int64() -
      other.exp.to_int64() -
      k.to_int64() +
      extra.to_int64()
  } else {
    let twice_rem = rem << 1
    if twice_rem > abs_b || (twice_rem == abs_b && !(q & one).is_zero()) {
      q = q + one
    }
  }
  let signed_q = if neg { -q } else { q }
  normalize_decimal_i64(signed_q, final_exp64)
}

///|
/// Computes `(trunc_quot, is_exact, is_neg, abs_rem, scale_den)` for integer
/// conversion/rounding of a `Decimal`.
fn decimal_split_int(
  d : Decimal,
  max_digits : Int32,
  op : String,
) -> Result[(BigInt, Bool, Bool, BigInt, BigInt), String] {
  let zero = BigInt::from_int(0)
  let one = BigInt::from_int(1)
  if d.is_zero() {
    return Ok((zero, true, false, zero, one))
  }
  let limit = if max_digits > 0 { max_digits } else { DECIMAL_MAX_SCALE_OP }
  if d.exp >= 0 {
    let (_, digits) = dec_abs_digits(d.coeff)
    if digits.length().to_int64() + d.exp.to_int64() > limit.to_int64() {
      return Err("\{op}: integer magnitude exceeds digit limit (\{limit})")
    }
    let val = d.coeff * dec_pow10(d.exp)
    return Ok((val, true, val < zero, zero, one))
  }
  let frac_digits = -d.exp
  let neg = d.coeff < zero
  let abs_coeff = if neg { -d.coeff } else { d.coeff }
  let (_, digits) = dec_abs_digits(d.coeff)
  if frac_digits >= digits.length() {
    // 0 < |d| < 1 strictly (since normalized non-zero d has no trailing zeros)
    // Wait: represent fractional remainder relative to 1 if |d| < 1:
    // Actually only need check_scale if we need exact half comparison (round).
    if frac_digits > limit {
      // For floor/ceil/trunc, 0 < |d| < 1 still doesn't need pow10!
      // Only return exact remainder when within limit; for |d| < 0.5 clearly non-half!
      return Ok((zero, false, neg, zero, one))
    }
    let den = dec_pow10(frac_digits)
    return Ok((zero, false, neg, abs_coeff, den))
  }
  let int_len = digits.length() - frac_digits
  if int_len > limit {
    return Err("\{op}: integer magnitude exceeds digit limit (\{limit})")
  }
  if frac_digits > limit {
    return Err("\{op}: decimal fraction scale exceeds limit (\{limit})")
  }
  let den = dec_pow10(frac_digits)
  let q_abs = abs_coeff / den
  let rem_abs = abs_coeff % den
  let exact = rem_abs.is_zero()
  let q_signed = if neg { -q_abs } else { q_abs }
  Ok((q_signed, exact, neg, rem_abs, den))
}

///|
/// Exact mathematical truncation toward zero as a `BigInt`.
pub fn Decimal::trunc(
  self : Decimal,
  max_digits~ : Int32 = DECIMAL_MAX_SCALE_OP,
) -> Result[BigInt, String] {
  match decimal_split_int(self, max_digits, "decimal trunc") {
    Ok((q, _, _, _, _)) => Ok(q)
    Err(msg) => Err(msg)
  }
}

///|
/// Exact mathematical floor `floor(self)` as a `BigInt`.
pub fn Decimal::floor(
  self : Decimal,
  max_digits~ : Int32 = DECIMAL_MAX_SCALE_OP,
) -> Result[BigInt, String] {
  match decimal_split_int(self, max_digits, "decimal floor") {
    Ok((q, exact, neg, _, _)) =>
      if exact || !neg {
        Ok(q)
      } else {
        Ok(q - BigInt::from_int(1))
      }
    Err(msg) => Err(msg)
  }
}

///|
/// Exact mathematical ceiling `ceil(self)` as a `BigInt`.
pub fn Decimal::ceil(
  self : Decimal,
  max_digits~ : Int32 = DECIMAL_MAX_SCALE_OP,
) -> Result[BigInt, String] {
  match decimal_split_int(self, max_digits, "decimal ceil") {
    Ok((q, exact, neg, _, _)) =>
      if exact || neg {
        Ok(q)
      } else {
        Ok(q + BigInt::from_int(1))
      }
    Err(msg) => Err(msg)
  }
}

///|
/// Exact rounding half-away-from-zero (matching CUE `math.Round` / Go `math.Round`).
pub fn Decimal::round(
  self : Decimal,
  max_digits~ : Int32 = DECIMAL_MAX_SCALE_OP,
) -> Result[BigInt, String] {
  match decimal_split_int(self, max_digits, "decimal round") {
    Ok((q, exact, neg, rem_abs, den)) => {
      if exact {
        return Ok(q)
      }
      // If `0 < |self| < 1` with `frac_digits > limit`, `rem_abs` was 0 with
      // `den == 1`; inspect top fractional digit directly: |self| >= 0.5 iff
      // `-exp == sig_len && first_digit >= '5'`.
      let ge_half = if rem_abs.is_zero() {
        let (_, digits) = dec_abs_digits(self.coeff)
        -self.exp == digits.length() && digits.code_unit_at(0) >= '5'
      } else {
        rem_abs << 1 >= den
      }
      if !ge_half {
        Ok(q)
      } else if neg {
        Ok(q - BigInt::from_int(1))
      } else {
        Ok(q + BigInt::from_int(1))
      }
    }
    Err(msg) => Err(msg)
  }
}

///|
/// Formats a `Decimal` into canonical lossless CUE (and RFC 8259 JSON) float syntax.
/// Always includes either a decimal point `.` or scientific exponent `e`/`E` so
/// float values remain syntactically distinct from `Int`.
pub fn Decimal::format_cue(self : Decimal) -> String {
  if self.coeff.is_zero() {
    return "0.0"
  }
  let (neg, digits) = dec_abs_digits(self.coeff)
  let len = digits.length()
  let adj_exp = self.exp + len - 1
  let sb = StringBuilder()
  if neg {
    sb.write_char('-')
  }
  if self.exp >= 0 {
    if self.exp <= 15 && adj_exp <= 20 {
      sb.write_string(digits)
      for _ in 0.. 1 {
        sb.write_char('.')
        for i in 1..= -6 && adj_exp <= 20 {
    if frac_digits >= len {
      sb.write_string("0.")
      for _ in 0..<(frac_digits - len) {
        sb.write_char('0')
      }
      sb.write_string(digits)
    } else {
      let split_at = len - frac_digits
      for i in 0.. 1 {
      sb.write_char('.')
      for i in 1..= 0 {
      sb.write_char('+')
    }
    sb.write_string(adj_exp.to_string())
  }
  sb.to_string()
}

///|
/// Formats a `Decimal` into valid RFC 8259 JSON numeric syntax.
pub fn Decimal::format_json(self : Decimal) -> String {
  self.format_cue()
}