// format_f64_rfc8785: write each IEEE 754 binary64 as ECMA-262 Number::toString // does (RFC 8785 number canonicalisation), one per line. // // Shortest round-trip digits follow the Schubfach algorithm (Raffaello // Giulietti, "The Schubfach way to render doubles"; exact routine after // Alexander Bolz's Drachennest formulation). Nearly every value is settled by // a fast path that uses one approximate 128-bit product and no division, and // defers to the exact routine whenever a comparison is too close to trust. // The sixteen leading digits are produced together with SIMD. // // The table of 128-bit powers of ten is not stored in the binary: it is built // on the first call from a 192-bit running value, which is enough precision // for every entry to come out exactly (checked offline against big integers). package format_f64_rfc8785 import "base:intrinsics" IN_CAP :: 65536 OUT_CAP :: 212992 input: [IN_CAP]u8 output: [OUT_CAP + 64]u8 // G[k + 293] = ceil(10^k / 2^(floor(log2(10^k)) - 127)) as {high, low}, k in [-293, 324] G: [618][2]u64 // EXP[n + 324]: the text "e+X" / "e-X" for exponent X = n - 1 in its low bytes, its length in the top byte EXP: [640]u64 // LO32 is 0xFFFFFFFF, but held in a variable set at run time: with a constant // LLVM recognises the 64x64->128 multiply and replaces it with a __multi3 call. LO32: u64 @(export) input_ptr :: proc "c" () -> u32 {return u32(uintptr(&input))} @(export) input_bytes_cap :: proc "c" () -> u32 {return IN_CAP} @(export) output_ptr :: proc "c" () -> u32 {return u32(uintptr(&output))} @(export) output_utf8_cap :: proc "c" () -> u32 {return OUT_CAP} store_g :: #force_inline proc "contextless" (idx: int, v: ^[6]u32, inexact: bool) { hi := u64(v[5]) << 32 | u64(v[4]) lo := u64(v[3]) << 32 | u64(v[2]) if inexact || (v[1] | v[0]) != 0 { lo += 1 hi += u64(lo == 0) } G[idx] = {hi, lo} } @(cold) init :: proc "contextless" () { LO32 = 0xFFFFFFFF for j in 0 ..< 640 { e := j - 325 ae := u64(-e if e < 0 else e) w := u64('e') | u64('-' if e < 0 else '+') << 8 pos: u64 = 16 if ae >= 100 { w |= ('0' + ae / 100) << pos pos += 8 } if ae >= 10 { w |= ('0' + ae / 10 % 10) << pos pos += 8 } w |= ('0' + ae % 10) << pos EXP[j] = w | (pos / 8 + 1) << 56 } // 10^0 .. 10^324: multiply a normalised 192-bit value by ten, rounding down v: [6]u32 v[5] = 0x80000000 inexact := false for k in 0 ..= 324 { store_g(293 + k, &v, inexact) carry: u64 = 0 for i in 0 ..< 6 { t := u64(v[i]) * 10 + carry v[i] = u32(t) carry = t >> 32 } s: u32 = 4 if carry >= 8 else 3 if v[0] & ((1 << s) - 1) != 0 {inexact = true} for i in 0 ..< 5 { v[i] = v[i] >> s | v[i + 1] << (32 - s) } v[5] = v[5] >> s | u32(carry) << (32 - s) } // 10^-1 .. 10^-293: divide by ten, keeping the value normalised v = {} v[5] = 0x80000000 for k in 1 ..= 293 { s: u32 = 4 if v[5] < 0xA0000000 else 3 rem := u64(v[5] >> (32 - s)) for i := 5; i >= 0; i -= 1 { low: u32 = v[i - 1] >> (32 - s) if i > 0 else 0 cur := rem << 32 | u64(v[i] << s | low) q := cur / 10 v[i] = u32(q) rem = cur - q * 10 } store_g(293 - k, &v, true) } } mul128 :: #force_inline proc "contextless" (a, b, lo32: u64) -> (hi, lo: u64) { a0 := a & lo32 a1 := a >> 32 b0 := b & lo32 b1 := b >> 32 p00 := a0 * b0 p01 := a0 * b1 p10 := a1 * b0 p11 := a1 * b1 mid := p10 + (p00 >> 32) + (p01 & lo32) lo = mid << 32 | (p00 & lo32) hi = p11 + (mid >> 32) + (p01 >> 32) return } mulhi :: #force_inline proc "contextless" (a, b: u64) -> u64 { a0 := a & 0xFFFFFFFF a1 := a >> 32 b0 := b & 0xFFFFFFFF b1 := b >> 32 p01 := a0 * b1 mid := a1 * b0 + (a0 * b0 >> 32) + (p01 & 0xFFFFFFFF) return a1 * b1 + (mid >> 32) + (p01 >> 32) } // Exact Schubfach. The shortest decimal that rounds back to c * 2^q is // (10 * s + l) * 10^e10, where l is one digit; trailing zeros may remain. // Only reached for subnormals, powers of two and the rare values the fast // path in to_decimal cannot decide. to_decimal_exact :: #force_no_inline proc "contextless" (c: u64, q: i32, closer: bool) -> (s: u64, l: u32, e10: i32) { lo32 := LO32 odd := c & 1 k := (q * 1262611 - (524031 if closer else 0)) >> 22 h := u32(q + ((-k * 1741647) >> 19) + 1) // 1..4 g := &G[293 - k] ghi, glo := g[0], g[1] // p2:p1:p0 = g * (4c << h) cp := c << ((h + 2) & 63) a1, a0 := mul128(cp, glo, lo32) b1, b0 := mul128(cp, ghi, lo32) p0 := a0 p1 := b0 + a1 p2 := b1 + u64(p1 < b0) // d2:d1:d0 = g * (2 << h), the distance to the upper boundary s1 := (h + 1) & 63 s2 := (63 - h) & 63 d0 := glo << s1 d1 := ghi << s1 | glo >> s2 d2 := ghi >> s2 r0 := p0 + d0 c0 := u64(r0 < p0) r1 := p1 + d1 c1 := u64(r1 < p1) r1 += c0 c1 |= u64(r1 < c0) r2 := p2 + d2 + c1 vbr := r2 | u64(r1 > 1) if closer { // lower distance is half the upper one d0 = d0 >> 1 | d1 << 63 d1 = d1 >> 1 | d2 << 63 d2 >>= 1 } bw0 := u64(p0 < d0) l1 := p1 - d1 bw1 := u64(p1 < d1) | u64(l1 < bw0) l1 -= bw0 l2 := p2 - d2 - bw1 vbl := l2 | u64(l1 > 1) vb := p2 | u64(p1 > 1) lower := vbl + odd upper := vbr - odd m := vb >> 2 e10 = k pick: { if m >= 10 { sp := mulhi(m, 0xCCCCCCCCCCCCCCCD) >> 3 // m / 10 sp40 := sp * 40 up_in := lower <= sp40 wp_in := sp40 + 40 <= upper if up_in != wp_in { m = sp + u64(wp_in) e10 = k + 1 break pick } } m4 := m << 2 u_in := lower <= m4 w_in := m4 + 4 <= upper if u_in != w_in { m += u64(w_in) } else { mid := m4 + 2 m += u64(vb > mid || (vb == mid && m & 1 != 0)) } } s = mulhi(m, 0xCCCCCCCCCCCCCCCD) >> 3 l = u32(m - s * 10) return } // Comparisons in the fast path are trusted only when the two sides differ by // more than MARGIN (in units of 2^-60). The approximate product leaves the // fraction of V/10 short by less than 2^27 units and the fraction of V by // less than 2^31, so 2^34 keeps at least an 8x reserve. MARGIN :: u64(1) << 34 ONE :: u64(1) << 60 HALF :: u64(1) << 59 // The shortest decimal that rounds back to the finite, non-zero double with // these bits (sign ignored) is (10 * s + l) * 10^e10, where s is below 10^16 // and l is one digit; trailing zeros may remain. to_decimal :: #force_inline proc "contextless" (bits: u64) -> (s: u64, l: u32, e10: i32) { frac := bits & 0xFFFFFFFFFFFFF bexp := u32(bits >> 52) & 0x7FF if bexp == 0 { return to_decimal_exact(frac, -1074, false) } c := frac | 0x10000000000000 q := i32(bexp) - 1075 nq := u32(-q) if nq < 53 && c & (u64(1) << (nq & 63) - 1) == 0 { return c >> (nq & 63), 0, -1 // an integer below 2^53 } if frac == 0 { return to_decimal_exact(c, q, bexp > 1) } // Let V = c * 2^q / 10^k, which has 16 or 17 integer digits, and let delta // be half the gap to the neighbouring doubles on the same scale. Then: // - if a multiple of ten lies within delta of V, it is the answer; // - otherwise the answer is V rounded to the nearest integer. // W = V / 10 is computed directly, so floor(W) is the leading sixteen // digits and ten times its fraction gives the last digit and the part to // round. W comes from five 32x32 multiplies and slightly underestimates; // whenever a comparison is closer than MARGIN the exact routine decides // instead, which also covers every tie and parity rule. k := (q * 1262611) >> 22 sh := u32(q + (((-k - 1) * 1741647) >> 19) + 4) // 0..3 g := &G[292 - k] // 10^(-k-1) ghi, glo := g[0], g[1] cs := c << (sh & 63) // below 2^56 ch := cs >> 32 cl := cs & 0xFFFFFFFF g3 := ghi >> 32 g2 := ghi & 0xFFFFFFFF g1 := glo >> 32 pb := ch * g2 pc := cl * g3 pmid := (pb & 0xFFFFFFFF) + (pc & 0xFFFFFFFF) + (ch * g1 >> 32) + (cl * g2 >> 32) p2 := ch * g3 + (pb >> 32) + (pc >> 32) + (pmid >> 32) // floor(8W) sp := p2 >> 3 // floor(W) phi := (p2 & 7) << 57 | (pmid & 0xFFFFFFFF) << 25 // fraction of W, 60 bits del := ghi >> ((8 - sh) & 63) // delta / 10, 60 bits t := phi * 10 // last digit and fraction of V, 4.60 fixed point f := t & (ONE - 1) down := phi < del up := ONE - phi < del // no multiple of ten in range: the last digit, rounded (a carry out of it // would mean a multiple of ten was in range after all) l = 0 if down || up else u32(t >> 60) + u32(f > HALF) if phi + MARGIN >= ONE || phi - del + MARGIN <= 2 * MARGIN || ONE - phi - del + MARGIN <= 2 * MARGIN || f + MARGIN >= ONE || f - HALF + MARGIN <= 2 * MARGIN || l > 9 { return to_decimal_exact(c, q, false) } return sp + u64(up), l, k } V4 :: #simd[4]u32 V8 :: #simd[8]u16 V16 :: #simd[16]u8 @(export) render :: proc "c" (len: u32) -> u64 { if LO32 == 0 { init() } n_in := min(len, IN_CAP) &~ 7 inp := ([^]u8)(&input) end := inp[n_in:] out := ([^]u8)(&output) o := out tbuf: [64]u8 = --- t := ([^]u8)(&tbuf) for ; inp != end; inp = inp[8:] { bits := intrinsics.unaligned_load((^u64)(inp)) if bits << 1 == 0 { intrinsics.unaligned_store((^u16)(o), u16(0x0A30)) // "0\n" o = o[2:] continue } o[0] = '-' o = o[bits >> 63:] s, l, e10 := to_decimal(bits) // sixteen zero-padded digits of s: two 8-digit halves, four 4-digit // groups, then pairs and single digits a vector at a time hi := mulhi(s, 0xABCC77118461CEFD) >> 26 // s / 10^8 a := u32(hi) b := u32(s - hi * 100000000) ah := u32(u64(a) * 109951163 >> 40) // a / 10^4 bh := u32(u64(b) * 109951163 >> 40) x := V4{ah, a - ah * 10000, bh, b - bh * 10000} xq := intrinsics.simd_shr_masked(x * V4(5243), V4(19)) // x / 100 y := transmute(V8)(xq | intrinsics.simd_shl_masked(x - xq * V4(100), V4(16))) yq := intrinsics.simd_shr_masked(y * V8(103), V8(10)) // y / 10 dg := transmute(V16)(yq | intrinsics.simd_shl_masked(y - yq * V8(10), V8(8))) intrinsics.unaligned_store((^V16)(t), dg + V16('0')) t[16] = u8('0' + l) // leading zeros, and the position after the last non-zero digit nz := u32(transmute(u16)intrinsics.simd_extract_msbs(intrinsics.simd_lanes_ne(dg, V16(0)))) lz := u32(intrinsics.count_trailing_zeros(nz | 0x10000)) tz := 32 - u32(intrinsics.count_leading_zeros(nz | u32(l != 0) << 16)) d := t[lz:] k := i32(tz - lz) // significant digits n := i32(17 - lz) + e10 // digits before the decimal point if u32(n - 1) < 21 { // digits, padded with zeros up to the point when k < n; when // k > n the tail is re-copied one place right to make room for // the point (otherwise that copy lands harmlessly past the line) intrinsics.mem_copy_non_overlapping(o, d, 17) z := o[k:] intrinsics.unaligned_store((^u64)(z), u64(0x3030303030303030)) intrinsics.unaligned_store((^u64)(z[8:]), u64(0x3030303030303030)) intrinsics.unaligned_store((^u32)(z[16:]), u32(0x30303030)) split := k > n p := n if split else 40 intrinsics.mem_copy_non_overlapping(o[p + 1:], d[n:], 16) o[p] = '.' o = o[(k + 1) if split else n:] } else if u32(n + 5) < 6 { // 0.000ddd intrinsics.unaligned_store((^u64)(o), u64(0x3030303030302E30)) // "0.000000" intrinsics.mem_copy_non_overlapping(o[2 - n:], d, 17) o = o[2 - n + k:] } else { // exponent notation; a lone digit's point is overwritten by the e o[0] = d[0] o[1] = '.' intrinsics.mem_copy_non_overlapping(o[2:], d[1:], 16) o = o[k + i32(k > 1):] ex := EXP[n + 324] intrinsics.unaligned_store((^u64)(o), ex) o = o[ex >> 56:] } o[0] = '\n' o = o[1:] } return u64(uintptr(out)) << 32 | u64(uintptr(o) - uintptr(out)) }