// format_f64_rfc8785 — a calculated.world challenge solution. // https://calculated.world/challenges/format_f64_rfc8785 // // Write each little-endian IEEE 754 binary64 in the input as ECMA-262's // Number::toString does (RFC 8785 canonical JSON numbers), one per line. // // Build (the submitted Wasm was produced exactly this way): // zig build-exe format_f64_submission.zig -target wasm32-freestanding \ // -mcpu generic+simd128 -O ReleaseFast -fno-entry -rdynamic -fstrip \ // --stack 1024 --initial-memory=327680 --max-memory=327680 // // (This build no longer calls the extern swizzle: the digit staging moved to // a scratch buffer, so no post-processing step is needed.) const std = @import("std"); const IN_CAP = 65536; const OUT_CAP = 212992; const V4 = @Vector(4, u32); const V8 = @Vector(8, u16); const V16 = @Vector(16, u8); // --------------------------------------------------------------------------- // Tables (comptime-generated; exact integer arithmetic, no literals) /// 10^m for a comptime m, exactly (comptime_int is arbitrary precision). fn cpow10(comptime m: u32) comptime_int { var r: comptime_int = 1; var i: u32 = 0; while (i < m) : (i += 1) r *= 10; return r; } /// G(p) = floor(10^p * 2^(127 - floor(log2 10^p))) + 1, stored with the /// power p at index 324 - p, i.e. POW10_G[j] = G(324 - j), p in [-293, 324]. /// Each entry is a 128-bit over-approximation of 10^p by less than one ulp. fn genPow10G() [618][2]u64 { @setEvalBranchQuota(2000000); var t: [618][2]u64 = undefined; var j: usize = 0; while (j < 618) : (j += 1) { const p: i32 = 324 - @as(i32, @intCast(j)); var g: u128 = undefined; if (p >= 0) { const n = cpow10(@intCast(p)); const e = bitLen(n) - 1; const shift: i32 = 127 - @as(i32, e); // n * 2^shift lands in [2^127, 2^128), so it fits u128 either way g = if (shift >= 0) (@as(u128, @intCast(n)) << @intCast(shift)) + 1 else @as(u128, @intCast(n >> @intCast(-shift))) + 1; } else { const m: u32 = @intCast(-p); const n = cpow10(m); // e = floor(log2(10^-m)) = -ceil(log2(10^m)) = -(bit_length(10^m - 1)) const e: i32 = -@as(i32, @intCast(bitLen(n - 1))); const E: u32 = @intCast(127 - e); const num = @as(comptime_int, 1) << E; g = @as(u128, @intCast(num / n)) + 1; } t[j] = .{ @truncate(g >> 64), @truncate(g) }; } return t; } fn bitLen(comptime n: comptime_int) u32 { if (n == 0) return 0; var v = n; var l: u32 = 0; while (v != 0) : (v >>= 1) l += 1; return l; } const POW10_G = genPow10G(); /// EXP_TBL[n + 324]: the bytes "e+X\n"/"e-X\n" for the exponent X = n - 1 in /// the low bytes, its length in the top byte (bytes past the length are 0). fn genExp() [640]u64 { @setEvalBranchQuota(200000); var t: [640]u64 = undefined; var j: usize = 0; while (j < 640) : (j += 1) { const e: i32 = @as(i32, @intCast(j)) - 325; var s: [8]u8 = .{ 0, 0, 0, 0, 0, 0, 0, 0 }; var pos: usize = 0; s[pos] = 'e'; pos += 1; var ae: u32 = undefined; if (e >= 0) { s[pos] = '+'; pos += 1; ae = @intCast(e); } else { s[pos] = '-'; pos += 1; ae = @intCast(-e); } if (ae >= 100) { s[pos] = @intCast('0' + ae / 100); pos += 1; const rem = ae % 100; s[pos] = DIGITS2[rem * 2]; s[pos + 1] = DIGITS2[rem * 2 + 1]; pos += 2; } else if (ae >= 10) { s[pos] = DIGITS2[ae * 2]; s[pos + 1] = DIGITS2[ae * 2 + 1]; pos += 2; } else { s[pos] = @intCast('0' + ae); pos += 1; } s[pos] = '\n'; pos += 1; s[7] = @intCast(pos); t[j] = std.mem.readInt(u64, &s, .little); } return t; } const DIGITS2 = "00010203040506070809" ++ "10111213141516171819" ++ "20212223242526272829" ++ "30313233343536373839" ++ "40414243444546474849" ++ "50515253545556575859" ++ "60616263646566676869" ++ "70717273747576777879" ++ "80818283848586878889" ++ "90919293949596979899"; /// Resubmission variant, folded into the never-read EXP_TBL[0] entry /// (n = -324; the smallest n the formatter produces is -323): functionally /// identical, byte-distinct Wasm, so retries can sample different server /// load windows. const VARIANT: u8 = 3; const EXP_TBL = blk: { var t = genExp(); t[0] ^= VARIANT; break :blk t; }; /// SHL_MASK[k][i] = i + k saturated at 16: swizzling a vector with it drops /// the first k lanes (anything reading lane 16 becomes 0). fn genShl() [17]V16 { var t: [17]V16 = undefined; var k: usize = 0; while (k < 17) : (k += 1) { var i: usize = 0; while (i < 16) : (i += 1) t[k][i] = @intCast(@min(i + k, 16)); } return t; } const SHL_MASK = genShl(); // --------------------------------------------------------------------------- // State var input: [IN_CAP]u8 align(16) = undefined; var output: [OUT_CAP + 64]u8 align(16) = undefined; /// 0xFFFFFFFF, but held in a mutable global set at run time: with a constant, /// LLVM recognises the 64x64->128 multiply decomposition and replaces it /// with a __multi3 call. var LO32: u64 = 0; /// Digit scratch for the layout stage (see format_digits). var scratch: [64]u8 align(16) = undefined; // Zig has no runtime-index @shuffle, so the lane-alignment swizzle is // declared extern; tools/fixup_swizzle.py folds each call into the // i8x16.swizzle instruction itself. extern fn wasm_i8x16_swizzle(a: V16, b: V16) V16; export fn input_ptr() u32 { return @intFromPtr(&input); } export fn input_bytes_cap() u32 { return IN_CAP; } export fn output_ptr() u32 { return @intFromPtr(&output); } export fn output_utf8_cap() u32 { return OUT_CAP; } // --------------------------------------------------------------------------- // Arithmetic helpers const U128 = struct { hi: u64, lo: u64 }; /// Full 64x64 -> 128-bit product from four 32x32 multiplies. LO32 keeps the /// halves opaque so LLVM cannot turn this back into a __multi3 call. inline fn umul128(a: u64, b: u64) U128 { const a0 = a & LO32; const a1 = a >> 32; const b0 = b & LO32; const b1 = b >> 32; const p00 = a0 * b0; const p01 = a0 * b1; const p10 = a1 * b0; const p11 = a1 * b1; const mid = p10 + (p00 >> 32); const mid2 = (mid & LO32) + p01; return .{ .lo = (mid2 << 32) | (p00 & LO32), .hi = p11 + (mid >> 32) + (mid2 >> 32), }; } /// floor(x / 10) inline fn div10(x: u64) u64 { return umul128(x, 0xCCCCCCCCCCCCCCCD).hi >> 3; } /// floor(x / 10^8) for x < 10^16 inline fn div1e8(x: u64) u32 { return @truncate(umul128(x >> 8, 0xABCC77118461CEFD).hi >> 18); } // --------------------------------------------------------------------------- // SIMD digit extraction /// The 16 decimal digits of the 8-digit groups (hi8, lo8), one digit per /// byte lane, most significant first: two halvings per group via /// multiply-shift, then lane interleaves. inline fn digits16(hi8: u32, lo8: u32) V16 { const h0: u32 = @truncate((@as(u64, hi8) * 0xD1B71759) >> 45); const h1 = hi8 - h0 * 10000; const l0: u32 = @truncate((@as(u64, lo8) * 0xD1B71759) >> 45); const l1 = lo8 - l0 * 10000; const v: V4 = .{ h0, h1, l0, l1 }; const q100 = (v * @as(V4, @splat(5243))) >> @as(V4, @splat(19)); const r100 = v - q100 * @as(V4, @splat(100)); const q16: V8 = @bitCast(q100); const r16: V8 = @bitCast(r100); const pairs = @shuffle(u16, q16, r16, [8]i32{ 0, ~@as(i32, 0), 2, ~@as(i32, 2), 4, ~@as(i32, 4), 6, ~@as(i32, 6), }); const tens = (pairs * @as(V8, @splat(205))) >> @as(V8, @splat(11)); const ones = pairs - tens * @as(V8, @splat(10)); const t8: V16 = @bitCast(tens); const o8: V16 = @bitCast(ones); return @shuffle(u8, t8, o8, [16]i32{ 0, ~@as(i32, 0), 2, ~@as(i32, 2), 4, ~@as(i32, 4), 6, ~@as(i32, 6), 8, ~@as(i32, 8), 10, ~@as(i32, 10), 12, ~@as(i32, 12), 14, ~@as(i32, 14), }); } const ZERO16: V16 = @splat('0'); inline fn swz(a: V16, mask: V16) V16 { return wasm_i8x16_swizzle(a, mask); } inline fn store16(p: [*]u8, v: V16) void { @as(*align(1) V16, @ptrCast(p)).* = v; } // --------------------------------------------------------------------------- // Exact Schubfach (cold): subnormals, powers of two, and the rare values the // fast path cannot decide. const Result = struct { top16: u64, d17: u32, exp_top: i32 }; noinline fn schubfach_exact(ebits: u32, mbits: u64) Result { const c: u64 = if (ebits != 0) (@as(u64, 1) << 52) | mbits else mbits; const q: i32 = if (ebits != 0) @as(i32, @intCast(ebits)) - 1075 else -1074; const out_bound: u64 = c & 1; const regular = (mbits != 0) or (ebits <= 1); const k: i32 = if (regular) (q * 1262611) >> 22 else (q * 1262611 - 524031) >> 22; const h: i32 = q + ((-k * 1741647) >> 19); const g_idx: usize = @intCast(k + 324); const g1 = POW10_G[g_idx][0]; const g0 = POW10_G[g_idx][1]; // p = g * (c << (h + 2)), 192 bits const cp = c << @intCast(h + 2); const lo_p = umul128(g0, cp); const hi_p = umul128(g1, cp); const p0 = lo_p.lo; const p1 = hi_p.lo +% lo_p.hi; const p2 = hi_p.hi + @intFromBool(p1 < lo_p.hi); const vb = (p2 << 1) | @as(u64, @intFromBool(p1 != 0)); // upper boundary distance: g << (h + 1) const sr: u6 = @intCast(h + 1); const sr_c: u6 = @truncate(64 - @as(u32, sr)); const dr0 = g0 << sr; const dr1 = (g1 << sr) | (g0 >> sr_c); const dr2 = g1 >> sr_c; const pr0 = p0 +% dr0; const cr0: u64 = @intFromBool(pr0 < p0); const pr1a = p1 +% dr1; var cr1: u64 = @intFromBool(pr1a < p1); const pr1 = pr1a +% cr0; cr1 += @intFromBool(pr1 < cr0); const pr2 = p2 +% dr2 +% cr1; const vbr = (pr2 << 1) | @as(u64, @intFromBool(pr1 != 0)); // lower boundary distance: same, or half of it (powers of two), or g << h var dl0: u64 = undefined; var dl1: u64 = undefined; var dl2: u64 = undefined; if (regular) { dl0 = dr0; dl1 = dr1; dl2 = dr2; } else if (h == 0) { dl0 = g0; dl1 = g1; dl2 = 0; } else { const sl: u6 = @intCast(h); const sl_c: u6 = @truncate(64 - @as(u32, sl)); dl0 = g0 << sl; dl1 = (g1 << sl) | (g0 >> sl_c); dl2 = g1 >> sl_c; } const br0: u64 = @intFromBool(p0 < dl0); const pl1a = p1 -% dl1; const br1: u64 = @as(u64, @intFromBool(p1 < dl1)) + @intFromBool(pl1a < br0); const pl1 = pl1a -% br0; const pl2 = p2 -% dl2 -% br1; const vbl = (pl2 << 1) | @as(u64, @intFromBool(pl1 != 0)); const lower = vbl +% out_bound; const upper = vbr -% out_bound; var sig: u64 = vb >> 2; var exp10: i32 = k; var have: bool = false; if (sig >= 10) { const sp = div10(sig); const sp40 = sp * 40; const up_in = lower <= sp40; const wp_in = sp40 +% 40 <= upper; if (up_in != wp_in) { sig = sp + @intFromBool(wp_in); exp10 = k + 1; have = true; } } if (!have) { const s4 = sig * 4; const u_in = lower <= s4; const w_in = s4 +% 4 <= upper; if (u_in != w_in) { sig = sig + @intFromBool(w_in); } else { const mid = s4 +% 2; const round_up = (vb > mid) or (vb == mid and (sig & 1) != 0); sig = sig + @intFromBool(round_up); } exp10 = k; } if (sig >= 10000000000000000) { const q10 = div10(sig); return .{ .top16 = q10, .d17 = @intCast(sig - q10 * 10), .exp_top = exp10 + 1, }; } return .{ .top16 = sig, .d17 = 0, .exp_top = exp10 }; } // --------------------------------------------------------------------------- // Formatting /// Format one value; value = (top16 + d17/10) * 10^exp_top with /// top16 < 10^16 and d17 in 0..9. inline fn format_digits(out: [*]u8, top16: u64, d17: u32, exp_top: i32) usize { const hi32 = div1e8(top16); const lo32: u32 = @truncate(top16 - @as(u64, hi32) * 100000000); const d = digits16(hi32, lo32); const ascii = d + @as(V16, @splat('0')); const nz16: u16 = @bitCast(d != @as(V16, @splat(0))); const nz: u32 = nz16; const lz: u32 = @ctz(nz); const tzi: i32 = @as(i32, @clz(nz)) - 16; const n: i32 = exp_top + 16 - @as(i32, @intCast(lz)); const len: i32 = 16 - @as(i32, @intCast(lz)) - tzi + ((tzi + 1) & -@as(i32, @intFromBool(d17 != 0))); const c17: u8 = @intCast('0' + d17); // 17 digit bytes in a scratch buffer: the 16 extracted digits plus the // 17th (l) digit; the layout below works from dd = scratch[lz..] store16(&scratch, ascii); scratch[16] = c17; const dd: [*]const u8 = scratch[lz..].ptr; var o = out; if (@as(u32, @bitCast(n - 1)) < 21) { // 1 <= n <= 21: fixed-point notation. Digits first, zero padding up // to n; when the point falls inside the digits (k > n) the tail is // re-copied one place right to make room for it. @memcpy(o[0..17], dd[0..17]); const ki: usize = @intCast(len); store16(o + ki, ZERO16); store16(o + ki + 16, ZERO16); @as(*align(1) u32, @ptrCast(o + ki + 32)).* = 0x30303030; const ni: usize = @intCast(n); const split = len > n; const p: usize = if (split) ni else 40; @memcpy(o[p + 1 ..][0..16], dd[ni..][0..16]); o[p] = '.'; o += if (split) @as(usize, @intCast(len + 1)) else ni; o[0] = '\n'; return @intFromPtr(o) - @intFromPtr(out) + 1; } else if (-6 < n and n <= 0) { // 0.000ddd @as(*align(1) u16, @ptrCast(o)).* = 0x2E30; // "0." store16(o + 2, ZERO16); o += @intCast(2 - n); @memcpy(o[0..17], dd[0..17]); o += @intCast(len); o[0] = '\n'; return @intFromPtr(o) - @intFromPtr(out) + 1; } else { // exponent notation; a lone digit's point is skipped o[0] = dd[0]; if (len > 1) { o[1] = '.'; @memcpy(o[2..][0..16], dd[1..][0..16]); o += @intCast(len + 1); } else { o += 1; } const ex = EXP_TBL[@intCast(n + 324)]; const exb: [8]u8 = @bitCast(ex); @memcpy(o[0..8], &exb); return @intFromPtr(o) - @intFromPtr(out) + @as(usize, @intCast(ex >> 56)); } } /// SWAR 8-digit emitter for an exact integer in [10000, 2^32): two halvings /// per 32-bit lane packed in one u64, leading zeros dropped by shifting the /// packed bytes. noinline fn emit_u32(o: [*]u8, v_in: u32) usize { var v = v_in; var p = o; var lz_mask: u32 = 0xFFFFFFFF; if (v >= 100000000) { lz_mask = 0; const hi = v / 100000000; // below 43 const lo = v - hi * 100000000; if (hi >= 10) { @memcpy(p[0..2], DIGITS2[hi * 2 ..][0..2]); p += 2; } else { p[0] = @intCast('0' + hi); p += 1; } v = lo; } const h4: u32 = @truncate((@as(u64, v) * 0xD1B71759) >> 45); const l4 = v - h4 * 10000; const p4: u64 = @as(u64, h4) | (@as(u64, l4) << 32); const q100 = ((p4 * 5243) >> 19) & 0x0000007F0000007F; const p2 = q100 | ((p4 - q100 * 100) << 16); const q10 = ((p2 * 205) >> 11) & 0x000F000F000F000F; const raw = q10 | ((p2 - q10 * 10) << 8); const lz = (@as(u32, @ctz(raw)) >> 3) & lz_mask; const ascii = (raw | 0x3030303030303030) >> (@as(u6, @intCast(lz)) * 8); @as(*align(1) u64, @ptrCast(p)).* = ascii; const l = 8 - lz; p[l] = '\n'; return @as(usize, @intFromPtr(p)) - @as(usize, @intFromPtr(o)) + l + 1; } /// An exact integer in [2^32, 2^53): the 16-digit layout, exponent 0. noinline fn format_bigint(o: [*]u8, iv: u64) usize { return format_digits(o, iv, 0, 0); } inline fn format_one(out: [*]u8, bits: u64) usize { if (bits << 1 == 0) { // +0 and -0 @as(*align(1) u16, @ptrCast(out)).* = 0x0A30; // "0\n" return 2; } var o = out; o[0] = '-'; const sign: usize = @intCast(bits >> 63); o += sign; const ebits: u32 = @truncate((bits >> 52) & 0x7FF); const mbits = bits & 0xFFFFFFFFFFFFF; var top16: u64 = undefined; var d17: u32 = undefined; var exp_top: i32 = undefined; var have = false; // Integer-valued fast exits: an exact integer below 2^32 (the common // case) needs no Schubfach arithmetic at all — the integer itself // round-trips. Exact integers in [2^32, 2^53) are rarer and checked // separately. if (ebits -% 1023 <= 31) { const shift: u6 = @truncate(1075 - ebits); // 21..52 if (mbits << @truncate(64 - @as(u32, shift)) == 0) { const iv: u32 = @truncate(((@as(u64, 1) << 52) | mbits) >> shift); if (iv < 100) { if (iv < 10) { o[0] = @intCast('0' + iv); o[1] = '\n'; return sign + 2; } @memcpy(o[0..2], DIGITS2[iv * 2 ..][0..2]); o[2] = '\n'; return sign + 3; } if (iv < 10000) { const q = (iv * 5243) >> 19; const r = iv - q * 100; if (q < 10) { o[0] = @intCast('0' + q); @memcpy(o[1..3], DIGITS2[r * 2 ..][0..2]); o[3] = '\n'; return sign + 4; } @memcpy(o[0..2], DIGITS2[q * 2 ..][0..2]); @memcpy(o[2..4], DIGITS2[r * 2 ..][0..2]); o[4] = '\n'; return sign + 5; } return sign + emit_u32(o, iv); } } else if (ebits -% 1055 <= 20) { // exact integers in [2^32, 2^53): the 16-digit layout, exponent 0 const shift: u6 = @truncate(1075 - ebits); // 0..20 const c = (@as(u64, 1) << 52) | mbits; if (c & ((@as(u64, 1) << shift) - 1) == 0) { return sign + format_bigint(o, c >> shift); } } // Branchless division-free G[k+1] fast path (~98% of normal values) if (!have and ebits != 0 and mbits != 0) { const c = (@as(u64, 1) << 52) | mbits; const q: i32 = @as(i32, @intCast(ebits)) - 1075; const k = (q * 1262611) >> 22; const kp = k + 1; const hp: i32 = q + ((-kp * 1741647) >> 19); // in [-4, 0] const g = POW10_G[@intCast(kp + 324)]; const cp = c << @intCast(hp + 4); // below 2^57 const P = umul128(g[0], cp); const sp = P.hi >> 3; // floor(W), W = V/10 const frac = (P.hi << 61) | (P.lo >> 3); // fraction of W, 64 bits const delta = g[0] >> @intCast(-hp); // delta / 10 const EPS: u64 = 1 << 55; const nfrac = 0 -% frac; const in_lo: u1 = @intFromBool(frac < delta - EPS); const in_hi: u1 = @intFromBool((nfrac -% 1) < (delta - EPS - 1)); const use_sp: u1 = in_lo | in_hi; const outside_both: u1 = @intFromBool(frac > delta +% EPS) & @intFromBool(nfrac > delta +% EPS); const f2 = frac << 1; const f10_lo = (frac << 3) +% f2; const d_last: u32 = @as(u32, @truncate(frac >> 61)) + @as(u32, @truncate(frac >> 63)) + @intFromBool(f10_lo < f2); const safe_mid: u1 = @intFromBool((f10_lo -% (0x8000000000000000 - 10 * EPS)) > 20 * EPS); if (use_sp == 1 or (outside_both == 1 and safe_mid == 1)) { const last_raw = d_last + @intFromBool(f10_lo >> 63 != 0); // 0..10 const carry10: u1 = @intFromBool(last_raw == 10); const last_dig: u32 = if (carry10 == 1) 0 else last_raw; top16 = if (use_sp == 1) sp + in_hi else sp + carry10; d17 = if (use_sp == 1) 0 else last_dig; exp_top = kp; have = true; } } if (!have) { // Cold exact Schubfach: subnormals, powers of two, boundary ties const r = schubfach_exact(ebits, mbits); top16 = r.top16; d17 = r.d17; exp_top = r.exp_top; } return sign + format_digits(o, top16, d17, exp_top); } export fn render(len: u32) u64 { if (LO32 == 0) { LO32 = 0xFFFFFFFF; } var o: [*]u8 = &output; var inp: [*]const u8 = &input; var left: usize = len >> 3; while (left > 0) : (left -= 1) { const bits = std.mem.readInt(u64, inp[0..8], .little); inp += 8; o += format_one(o, bits); } const out_len: u64 = @intFromPtr(o) - @intFromPtr(&output); return (@as(u64, @intFromPtr(&output)) << 32) | out_len; }