// This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at https://mozilla.org/MPL/2.0/. // // SPDX-License-Identifier: MPL-2.0 // Copyright (c) 2026 Jairus Tanaka import { JSON } from ".."; import { expect, fuzz, FuzzSeed } from "as-test"; @inline function sameBitsF32(left: f32, right: f32): bool { return reinterpret(left) == reinterpret(right); } @inline function sameBitsF64(left: f64, right: f64): bool { return reinterpret(left) == reinterpret(right); } function makeFiniteBitsF32(seed: FuzzSeed): u32 { const bits = seed.u32(); return (bits & 0x7f800000) == 0x7f800000 ? bits & 0x807fffff : bits; } function makeFiniteBitsF64(seed: FuzzSeed): u64 { const bits = ((seed.u32()) << 32) | (seed.u32()); return (bits & 0x7ff0000000000000) == 0x7ff0000000000000 ? bits & 0x800fffffffffffff : bits; } @inline function sameJsonFloatF32(left: f32, right: f32): bool { return left == 0.0 ? right == 0.0 : sameBitsF32(left, right); } @inline function sameJsonFloatF64(left: f64, right: f64): bool { return left == 0.0 ? right == 0.0 : sameBitsF64(left, right); } fuzz("f32 stringify/parse roundtrips finite values", (bits: u32): bool => { const value = reinterpret(bits); const encoded = JSON.stringify(value); const decoded = JSON.parse(encoded); expect(sameJsonFloatF32(value, decoded)).toBe(true); expect(JSON.stringify(decoded)).toBe(encoded); return sameJsonFloatF32(value, decoded); }).generate((seed: FuzzSeed, run: (bits: u32) => bool): void => { run(makeFiniteBitsF32(seed)); }, 5_000_000); fuzz( "f64 stringify/parse roundtrips finite values", (high: u32, low: u32): bool => { const bits = ((high) << 32) | (low); const value = reinterpret(bits); const encoded = JSON.stringify(value); const decoded = JSON.parse(encoded); expect(sameJsonFloatF64(value, decoded)).toBe(true); expect(JSON.stringify(decoded)).toBe(encoded); return sameJsonFloatF64(value, decoded); }, ).generate((seed: FuzzSeed, run: (high: u32, low: u32) => bool): void => { const bits = makeFiniteBitsF64(seed); run((bits >>> 32), bits); }, 5_000_000);