(*--------------------------------------------------------------------------- Copyright (c) 2026 Thomas Gazagnaire. All rights reserved. SPDX-License-Identifier: ISC The conversions below are a port of SQLite's, from sqlite3 3.54.0 src/util.c (powerOfTen, sqlite3Multiply128, sqlite3Multiply160, sqlite3Fp2Convert10, sqlite3Fp10Convert2 and sqlite3FpDecode) and src/printf.c (the etGENERIC layout). SQLite is in the public domain; sqlite3Fp10Convert2 is in turn adapted from Russ Cox's https://github.com/rsc/fpfmt. ---------------------------------------------------------------------------*) type t = { negative : bool; digits : string; point : int } (* SQLite works these conversions in unsigned 64-bit fixed point. Int64 is OCaml's u64: add and mul wrap identically, [shr] is the logical shift, and the comparisons below are spelled unsigned where the difference shows. *) let add = Int64.add let mul = Int64.mul let band = Int64.logand let bor = Int64.logor let shl = Int64.shift_left let shr = Int64.shift_right_logical let low x = band x 0xffffffffL let bit n = shl 1L n (* The number of leading zero bits of [m], 64 for a zero (countLeadingZeros): each step asks whether the top half of what is left is empty. *) let leading_zeros m = if Int64.equal m 0L then 64 else begin let m = ref m and n = ref 0 in let step k = if Int64.equal (shr !m (64 - k)) 0L then begin n := !n + k; m := shl !m k end in step 32; step 16; step 8; step 4; step 2; step 1; !n end (* The 128-bit product of [a] and [b], as its high and low 64-bit halves (sqlite3Multiply128). *) let mul128 a b = let a0 = low a and a1 = shr a 32 in let b0 = low b and b1 = shr b 32 in let a0b0 = mul a0 b0 in let a1b1 = mul a1 b1 in let a0b1 = mul a0 b1 in let a1b0 = mul a1 b0 in let t = add (add (shr a0b0 32) (low a0b1)) (low a1b0) in let lo = bor (low a0b0) (shl t 32) in let hi = add (add a1b1 (shr a0b1 32)) (add (shr a1b0 32) (shr t 32)) in (hi, lo) (* The upper 96 bits of the 160-bit product of the 96-bit [(a lsl 32) + a_lo] and the 64-bit [b] (sqlite3Multiply160): its top 64 bits, and the next 32 as an int. The low 64 bits of the product are dropped. *) let mul160 a a_lo b = let x2 = shr a 32 and x1 = low a and x0 = Int64.of_int a_lo in let y1 = shr b 32 and y0 = low b in let x2y1 = mul x2 y1 in let r4 = shr x2y1 32 in let x2y0 = mul x2 y0 in let x1y1 = mul x1 y1 in let r3 = add (add (low x2y1) (shr x2y0 32)) (shr x1y1 32) in let x1y0 = mul x1 y0 in let x0y1 = mul x0 y1 in let r2 = add (add (low x2y0) (low x1y1)) (add (shr x1y0 32) (shr x0y1 32)) in let x0y0 = mul x0 y0 in let r1 = add (add (low x1y0) (low x0y1)) (shr x0y0 32) in let r2 = add r2 (shr r1 32) in let r3 = add r3 (shr r2 32) in (add (shl r4 32) r3, Int64.to_int (low r2)) (* The three powerOfTen tables of util.c, as tool/mkfptab.c --round derives them from a 256-bit running power of ten. *) (* 1.0e+0 to 1.0e+26, each shifted so its leading one sits at bit 63. *) let base = [| 0x8000000000000000L; 0xa000000000000000L; 0xc800000000000000L; 0xfa00000000000000L; 0x9c40000000000000L; 0xc350000000000000L; 0xf424000000000000L; 0x9896800000000000L; 0xbebc200000000000L; 0xee6b280000000000L; 0x9502f90000000000L; 0xba43b74000000000L; 0xe8d4a51000000000L; 0x9184e72a00000000L; 0xb5e620f480000000L; 0xe35fa931a0000000L; 0x8e1bc9bf04000000L; 0xb1a2bc2ec5000000L; 0xde0b6b3a76400000L; 0x8ac7230489e80000L; 0xad78ebc5ac620000L; 0xd8d726b7177a8000L; 0x878678326eac9000L; 0xa968163f0a57b400L; 0xd3c21bcecceda100L; 0x84595161401484a0L; 0xa56fa5b99019a5c8L; |] (* Every 27th power of ten from 1.0e-351 to 1.0e+324, top 64 bits. Entry 13 holds 1.0e-1 rather than 1.0e+0, which needs no scaling at all. *) let scale = [| 0x8049a4ac0c5811aeL; 0xcf42894a5dce35eaL; 0xa76c582338ed2621L; 0x873e4f75e2224e68L; 0xda7f5bf590966848L; 0xb080392cc4349decL; 0x8e938662882af53eL; 0xe65829b3046b0afaL; 0xba121a4650e4ddebL; 0x964e858c91ba2655L; 0xf2d56790ab41c2a2L; 0xc428d05aa4751e4cL; 0x9e74d1b791e07e48L; 0xccccccccccccccccL; 0xcecb8f27f4200f3aL; 0xa70c3c40a64e6c51L; 0x86f0ac99b4e8dafdL; 0xda01ee641a708de9L; 0xb01ae745b101e9e4L; 0x8e41ade9fbebc27dL; 0xe5d3ef282a242e81L; 0xb9a74a0637ce2ee1L; 0x95f83d0a1fb69cd9L; 0xf24a01a73cf2dccfL; 0xc3b8358109e84f07L; 0x9e19db92b4e31ba9L; |] (* The next 32 bits of each {!scale} entry, rounded to nearest -- except entry 13, the 1.0e-1 special case, which is truncated. *) let scale_lo = [| 0x205b896d; 0x52064cad; 0xaf2af2b8; 0x5a7744a7; 0xaf39a475; 0xbd8d794e; 0x547eb47b; 0x0cb4a5a3; 0x92f34d62; 0x3a6a07f9; 0xfae27299; 0xaa97e14c; 0x775ea265; 0xcccccccc; 0x00000000; 0x999090b6; 0x69a028bb; 0xe80e6f48; 0x5ec05dd0; 0x14588f14; 0x8f1668c9; 0x6d953e2c; 0x4abdaf10; 0xbc633b39; 0x0a862f81; 0x6c07a2c2; |] (* {!scale} entry [g + 13] refined by {!base} entry [n], renormalised so the leading one is back at bit 63. *) let scaled g n = let s = scale.(g + 13) and s_lo = scale_lo.(g + 13) in if n = 0 then (s, s_lo) else let x, lo = mul160 s s_lo base.(n) in if Int64.equal (band x Int64.min_int) 0L then ( bor (shl x 1) (Int64.of_int ((lo lsr 31) land 1)), (lo lsl 1) lor 1 land 0xffffffff ) else (x, lo) (* The most significant 96 bits of [10 ** p] for [p] in [-348 .. 347]: the top 64 as an Int64, the next 32 as an int (powerOfTen). *) let power_of_ten p = if p >= 0 then if p < 27 then (base.(p), 0) else scaled (p / 27) (p mod 27) else if p = -1 then (scale.(13), scale_lo.(13)) else let g = p / 27 and n = p mod 27 in if n <> 0 then scaled (g - 1) (n + 27) else scaled g 0 (* [pwr10to2 p] is floor(log2(10 ** p)) and [pwr2to10 e] is floor(log10(2 ** e)), from the five-digit ratios ln(10)/ln(2) = 108853/32768 and ln(2)/ln(10) = 78913/262144. *) let pwr10to2 p = (p * 108853) asr 15 let pwr2to10 e = (e * 78913) asr 18 (* [convert10 m e n] is [(d, p)] with [m * 2 ** e] approximately [d * 10 ** p] and [d] carrying at least [n] significant digits, for [n] in [1 .. 18] (sqlite3Fp2Convert10). [m] must have its top bit set. At 18 digits [d] is rounded at its last bit; below, it is truncated. This is the approximation the port exists for: only the top 64 bits of [m * powerOfTen p] are kept, so [d] is biased low by up to [2 ** -64] relative to the true value. Its 18th digit therefore falls the other side of a rounding boundary just often enough to show in the 17th digit printed -- which a correctly rounded decode gets right and SQLite does not. *) let convert10 m e n = let p = n - 1 - pwr2to10 (e + 63) in let pow, _ = power_of_ten p in let h, _ = mul128 m pow in if n = 18 then begin let drop = -(e + pwr10to2 p + 2) in assert (drop >= 0 && drop < 63); let h = shr h drop in (shr (add h (band (shl h 1) 2L)) 1, -p) end else (shr h (-(e + pwr10to2 p + 1)), -p) (* The high half of [x * pwr10h] rounded down to a sticky bit. [pwr10h] is an upper bound on the power of ten, so when the product's low [s] bits all vanish the true value could be on either side of the boundary; [pwr10l], the complement of the 32 bits [pwr10h] rounded away, is multiplied out to settle it. *) let refine x pwr10l s hi lo = if not (Int64.equal (band hi (Int64.sub (bit s) 1L)) 0L) then (1L, hi) else let mid1 = Int64.to_int (shr lo 32) in let mid2, _ = mul128 x (shl (Int64.of_int pwr10l) 32) in let mid2 = Int64.to_int (shr mid2 32) in ( (if (mid1 - mid2) land 0xffffffff > 1 then 1L else 0L), if mid1 < mid2 then Int64.sub hi 1L else hi ) (* The double nearest [d * 10 ** p] (sqlite3Fp10Convert2), and zero for a [d] of zero, which SQLite itself reaches only through undefined behaviour. *) let convert2 d p = if p < -348 || Int64.equal d 0L then 0.0 else if p > 347 then Float.infinity else let b = 64 - leading_zeros d in let lp = pwr10to2 p in let e = 53 - b - lp in if e >= 1130 then 0.0 else let e = if e > 1074 then 1074 else e in let s = -(e - (64 - b) + lp + 3) in assert (s >= 0 && s < 64); let pwr10h, pwr10l = power_of_ten p in (* round the power of ten up to an upper bound, keeping the complement of the 32 bits rounded away so a tie can still be settled *) let pwr10h, pwr10l = if pwr10l <> 0 then (add pwr10h 1L, lnot pwr10l land 0xffffffff) else (pwr10h, pwr10l) in let x = shl d (64 - b) in let hi, lo = mul128 x pwr10h in let sticky, hi = refine x pwr10l s hi lo in let u = bor (shr hi s) sticky in let u, e = if Int64.unsigned_compare u (Int64.sub (bit 55) 2L) >= 0 then (bor (shr u 1) (band u 1L), e - 1) else (u, e) in let m = shr (add (add u 1L) (band (shr u 2) 1L)) 2 in if e <= -972 then Float.infinity else if Int64.equal (band m (bit 52)) 0L then Int64.float_of_bits m else Int64.float_of_bits (bor (band m (Int64.lognot (bit 52))) (shl (Int64.of_int (1075 - e)) 52)) (* The decimal digits of [m] read as unsigned. Anything at or above [2 ** 63] is split once so the quotient is back in [Int64]'s signed range. *) let unsigned_digits m = if Int64.compare m 0L >= 0 then Int64.to_string m else Int64.to_string (Int64.unsigned_div m 10L) ^ Int64.to_string (Int64.unsigned_rem m 10L) (* The first [k] digits of [z] as an integer. *) let prefix z k = let v = ref 0L in for i = 0 to k - 1 do v := add (mul !v 10L) (Int64.of_int (Char.code z.[i] - Char.code '0')) done; !v (* The significand sqlite3AtoF accumulates from [z], and how many of its digits it never reached. It stops once the running value is too large to take another digit -- ((2**64 - 1) - 9) / 10, so nineteen digits always fit and a twentieth sometimes does -- and the digits left are dropped, not rounded, which is the whole of why a literal spelled with more of them reads back below the nearest double rather than at it. *) let atof_limit = 1844674407370955160L let significand z = let n = String.length z in let v = ref 0L and i = ref 0 in while !i < n && Int64.unsigned_compare !v atof_limit < 0 do v := add (mul !v 10L) (Int64.of_int (Char.code z.[!i] - Char.code '0')); incr i done; (!v, n - !i) let real ~negative ~digits ~exponent = let d, dropped = significand digits in let r = convert2 d (exponent + dropped) in if negative then -.r else r (* [z] cut to [k] digits and rounded half up, with [true] when the carry ran out of the leading digit and prepended a [1]. *) let round_half_up z k = if z.[k] < '5' then (String.sub z 0 k, false) else begin let b = Bytes.of_string (String.sub z 0 k) in let i = ref (k - 1) and carried = ref true in while !carried && !i >= 0 do let d = Bytes.get b !i in if d < '9' then begin Bytes.set b !i (Char.chr (Char.code d + 1)); carried := false end else begin Bytes.set b !i '0'; decr i end done; if !carried then ("1" ^ Bytes.to_string b, true) else (Bytes.to_string b, false) end (* [z] without its trailing zeros. The leading digit is never a zero, so at least one digit is always left. *) let strip_zeros z = let n = ref (String.length z) in while z.[!n - 1] = '0' do decr n done; if !n = String.length z then z else String.sub z 0 !n (* [shorter r z n exp point] is the digit count SQLite prefers over 17, when one of the two prefixes it is willing to try reads back as [r] (sqlite3FpDecode's precision-17 shortcut). It looks no further than the first fourteen digits, which is why a value whose shortest round-tripping form needs fifteen still comes out at seventeen. It is what renders 0.1 as "0.1" rather than "0.10000000000000001". *) let shorter r z n exp point = let keeps jj v = if Float.equal r (convert2 v (exp + n - jj)) then jj + 1 else 17 in if z.[15] = '9' && z.[14] = '9' then begin (* the run of nines ending at digit 15, rounded up *) let jj = ref 14 in while !jj > 0 && z.[!jj - 1] = '9' do decr jj done; keeps !jj (if !jj = 0 then 1L else add (prefix z !jj) 1L) end else if point >= n || (z.[15] = '0' && z.[14] = '0' && z.[13] = '0') then begin (* the run of zeros ending at digit 14 *) let jj = ref 13 in while z.[!jj - 1] = '0' do decr jj done; keeps !jj (prefix z !jj) end else 17 (* The digits of a positive, finite, non-zero [r] and their decimal exponent: [r] is [z] read as an unsigned integer times [10 ** exp]. This is sqlite3FpDecode's extraction step, which decodes to the [n] significant digits Fp2Convert10 answers (one more where the mantissa carries into another digit), before any rounding cuts it back. *) let extract r n = let bits = Int64.bits_of_float r in let e = Int64.to_int (band (shr bits 52) 0x7ffL) in let v = band bits 0xfffffffffffffL in let v, e = if e = 0 then let nn = leading_zeros v in (shl v nn, -1074 - nn) else (bor (shl v 11) Int64.min_int, e - 1086) in let m, exp = convert10 v e n in (unsigned_digits m, exp) let not_finite fn f = Fmt.invalid_arg "Decimal.%s: %h is not a finite number" fn f (* A non-positive [round] made a count of digits: the cut falls [-round] places right of the point. At [0] the cut falls just left of the leading digit; rounding half up there carries into a new one, which the C makes room for by borrowing a zero in front and keeping that single digit instead. *) let at_place z n point round = let round = point - round in if round = 0 && z.[0] >= '5' then ("0" ^ z, n + 1, point + 1, 1) else (z, n, point, round) (* sqlite3FpDecode on a positive, finite, non-zero [r]: its digits, rounded half up as [round] and [max] say, without their trailing zeros, and the place of the decimal point. A [round] of zero or below that falls left of the leading digit rounds nothing: every digit decoded is kept. *) let fp_decode r ~round ~max = let z, exp = extract r (if round <= 0 then 18 else min 18 (round + 1)) in let n = String.length z in let point = n + exp in let z, n, point, round = if round > 0 then (z, n, point, round) else at_place z n point round in if round > 0 && (round < n || n > max) then let round = min round max in (* The seventeen-digit shortcut is FpDecode's own, taken on whatever reaches that precision. *) let round = if round = 17 then shorter r z n exp point else round in let digits, carried = round_half_up z round in (strip_zeros digits, if carried then point + 1 else point) else (strip_zeros z, point) let zero = { negative = false; digits = "0"; point = 1 } let decode ~round ~max f = if not (Float.is_finite f) then not_finite "decode" f; if max < 1 then Fmt.invalid_arg "Decimal.decode: max %d is below 1" max; let r = Float.abs f in if Float.equal r 0.0 then zero else let digits, point = fp_decode r ~round ~max in { negative = f < 0.0; digits; point } let of_float f = if not (Float.is_finite f) then not_finite "of_float" f; decode ~round:17 ~max:20 f let of_float_places f ~places = if not (Float.is_finite f) then not_finite "of_float_places" f; if places < 0 then Fmt.invalid_arg "Decimal.of_float_places: negative precision %d" places; let d = decode ~round:(-places) ~max:20 f in (* A value whose cut falls left of its leading digit keeps every digit decoded, all of them past the place asked for: it prints as a zero. *) if d.point + places <= 0 then { d with digits = "0"; point = 1 } else d let to_float { negative; digits; point } = real ~negative ~digits ~exponent:(point - String.length digits) let equal a b = Bool.equal a.negative b.negative && String.equal a.digits b.digits && Int.equal a.point b.point let digit_char d = Char.unsafe_chr (Char.code '0' + d) (* printf writes an exponent with two digits, three past 100. *) let exponent_suffix e = let sign = if e < 0 then '-' else '+' in let e = abs e in let wide = e >= 100 in let b = Bytes.create (if wide then 5 else 4) in Bytes.unsafe_set b 0 'e'; Bytes.unsafe_set b 1 sign; if wide then Bytes.unsafe_set b 2 (digit_char (e / 100)); Bytes.unsafe_set b (Bytes.length b - 2) (digit_char (e / 10 mod 10)); Bytes.unsafe_set b (Bytes.length b - 1) (digit_char (e mod 10)); Bytes.unsafe_to_string b (* The digits before the decimal point, and how many of [digits] they took: one in the exponential form; in the plain form a bare "0" for a value below 1, and otherwise the leading [point] digits, padded with zeros where the value runs past the digits kept. *) let place_integer_part b ~scientific digits point = if scientific then begin Buffer.add_char b digits.[0]; 1 end else if point <= 0 then begin Buffer.add_char b '0'; 0 end else begin let n = String.length digits in let taken = min point n in Buffer.add_string b (String.sub digits 0 taken); if point > n then Buffer.add_string b (String.make (point - n) '0'); taken end (* The "!" flag of SQLite's format drops the trailing zeros and then forces a decimal point back into the mantissa, so the text always reads back as a REAL: "5.0", never "5". The point stops the trailing-zero scan, so the zeros of a whole value are never eaten. *) let keep_decimal_point s = let stop = ref (String.length s) in while s.[!stop - 1] = '0' do decr stop done; let s = String.sub s 0 !stop in if s.[String.length s - 1] = '.' then s ^ "0" else s let to_string { negative; digits; point } = let n = String.length digits in let scientific = point - 1 < -4 || point - 1 > 16 in let b = Buffer.create 32 in if negative then Buffer.add_char b '-'; let placed = place_integer_part b ~scientific digits point in Buffer.add_char b '.'; if (not scientific) && point < 0 then Buffer.add_string b (String.make (-point) '0'); Buffer.add_string b (String.sub digits placed (n - placed)); let s = keep_decimal_point (Buffer.contents b) in if scientific then s ^ exponent_suffix (point - 1) else s let pp ppf t = Fmt.string ppf (to_string t)