From 365251bcfa90effcf4cde08c7274b8cd0af052aa Mon Sep 17 00:00:00 2001 From: Andreas Steinbart Date: Sun, 4 Oct 2026 08:14:06 +0000 Subject: [PATCH] feat(bits-equal): bitsEqual, bit-pattern equality for float arrays (generator#636) An array field is omitted when it equals its declared default, and floats round-trip bit for bit. An IEEE elementwise compare calls [-0.0, 1.5] equal to [0.0, 1.5] and drops the -0.0 element. sofab::bitsEqual compares length first, then the IEEE-754 bit pattern of every element (32 bits for float, 64 for double) in one memcmp; it takes vector, InlineVector, array, span, C arrays or a braced default on either side. The helper is schema-independent, so it lives in the corelib (its own header, bits_equal.hpp) and generated code calls it instead of emitting a comparison per field. New suite test_bits_equal covers signed zero, NaN payloads, infinities, subnormals, length mismatches, arrays over 64 elements and a cross-check against a reference bit loop; the header is at 100% line and branch coverage. --- README.md | 19 +++- include/sofab/bits_equal.hpp | 92 +++++++++++++++++++ include/sofab/sofab.hpp | 2 + test/CMakeLists.txt | 7 ++ test/test_bits_equal.cpp | 169 +++++++++++++++++++++++++++++++++++ 5 files changed, 288 insertions(+), 1 deletion(-) create mode 100644 include/sofab/bits_equal.hpp create mode 100644 test/test_bits_equal.cpp diff --git a/README.md b/README.md index 9385a3a..9fe4efd 100644 --- a/README.md +++ b/README.md @@ -409,6 +409,20 @@ sofab::read(is, c); Like `StringSeq`, `RowSeq` takes the schema `count` and the receiver cap as constructor arguments, so neither can be left out. +#### Float arrays: `sofab::bitsEqual` + +An array field is omitted from the encoding when it equals its declared default +(MESSAGE_SPEC §2), and floats round-trip bit for bit (CORELIB_PLAN §4.6), so the +comparison must be on bit patterns, not IEEE `==`: `[-0.0, 1.5]` is not +`[0.0, 1.5]`, and a NaN equals another NaN only when every bit is the same. +`sofab::bitsEqual(a, b)` (in `sofab/bits_equal.hpp`, included by `sofab.hpp`) is +true iff both sequences have the same length and the same 32-bit (`float`) or +64-bit (`double`) pattern at every index. It takes any contiguous sized range of +`float` or `double` on either side (`std::vector`, `sofab::InlineVector`, +`std::array`, `std::span`, a C array) or a braced list as the second argument, +and compares the length first, then the bytes in one `memcmp`. It allocates +nothing. + #### Strict UTF-8 validation (`SOFAB_STRICT_UTF8`, default ON) A `string` carries UTF-8 text; `blob` is the type for opaque bytes. With @@ -740,10 +754,13 @@ is unchanged and every other build option (`SOFAB_ENABLE_COVERAGE`, peer. CI builds and conformance-tests the default, strict configuration as well as the non-strict one. -Six suites run under CTest: +Seven suites run under CTest: - **`test_roundtrip`** — encode/decode/nested/chunked/skip, the three-valued outcome, malformed input, the terminal latch, and §2 sequence framing. +- **`test_bits_equal`** — `sofab::bitsEqual`: signed zero, NaN payloads, + infinities, subnormals, length mismatch, long arrays, both widths, and a + cross-check against a plain bit loop. - **`test_vectors`** — replays the shared `assets/test_vectors.json` for encode, decode, byte-at-a-time streaming and field skipping (every vector carrying `skip_ids`, whole and one byte at a time): the `vectors`, `invalid_utf8`, diff --git a/include/sofab/bits_equal.hpp b/include/sofab/bits_equal.hpp new file mode 100644 index 0000000..507ebfb --- /dev/null +++ b/include/sofab/bits_equal.hpp @@ -0,0 +1,92 @@ +/*! + * @file bits_equal.hpp + * @brief Bit-pattern equality for float arrays (`sofab::bitsEqual`). + * + * A generated encoder omits a field iff its value equals its declared default + * (MESSAGE_SPEC §2), and CORELIB_PLAN §4.6 makes floats round-trip bit for bit. + * An IEEE `==` over the elements contradicts both: `-0.0 == +0.0`, so an array + * `[-0.0, 1.5]` would be taken for the default `[0.0, 1.5]` and its first element + * dropped, and `NaN != NaN` would write a default array that holds a NaN. + * + * `bitsEqual` is the comparison the omission test needs: equal length and, at + * every index, an identical IEEE-754 bit pattern (32 bits for `float`, 64 for + * `double`). `+0.0` and `-0.0` differ; two NaNs are equal exactly when their bit + * patterns, payload included, are identical. No IEEE `==` is involved. + * + * Schema-independent by construction: the element type is a template argument and + * the bound is the argument's own length, so generated code calls it instead of + * emitting a loop per field. + * + * SPDX-License-Identifier: MIT + */ + +#ifndef SOFAB_BITS_EQUAL_HPP +#define SOFAB_BITS_EQUAL_HPP + +#include +#include +#include +#include +#include +#include +#include + +namespace sofab +{ + namespace detail + { + /*! @brief `float` or `double`, the two element types of an fp array. */ + template + concept FloatElement = std::same_as || std::same_as; + + /*! @brief Length check, then one block compare of the object representation. */ + template + inline bool bitsEqualSpan(std::span a, std::span b) noexcept + { + if (a.size() != b.size()) { return false; } + /* memcmp with a null pointer is undefined even for a zero count, and an + * empty std::vector or a default-constructed span has no storage. */ + if (a.empty()) { return true; } + return std::memcmp(a.data(), b.data(), a.size() * sizeof(T)) == 0; + } + } // namespace detail + + /*! + * @brief True iff @p a and @p b have the same length and every element pair has + * the same IEEE-754 bit pattern. + * + * Accepts anything contiguous and sized whose element type is `float` or + * `double`, on both sides: `std::vector`, `sofab::InlineVector`, `std::array`, + * `std::span`, a C array, or a braced list (`bitsEqual(v, {0.0f, 1.5f})` + * binds a `std::initializer_list`). Both sides must have the same + * element type. The length is compared first; nothing is allocated or + * modified. + * + * @return `false` on a length mismatch or any differing bit pattern. + */ + template + requires std::ranges::sized_range && std::ranges::sized_range + && detail::FloatElement>> + && std::same_as>, + std::remove_cv_t>> + inline bool bitsEqual(const A &a, const B &b) noexcept + { + using T = std::remove_cv_t>; + return detail::bitsEqualSpan( + std::span(std::ranges::data(a), std::ranges::size(a)), + std::span(std::ranges::data(b), std::ranges::size(b))); + } + + /*! @brief Braced-list default: `bitsEqual(field, {0.0f, 1.5f})`. */ + template + requires std::ranges::sized_range + && std::same_as>, T> + inline bool bitsEqual(const A &a, std::initializer_list b) noexcept + { + return detail::bitsEqualSpan( + std::span(std::ranges::data(a), std::ranges::size(a)), + std::span(b.begin(), b.size())); + } +} // namespace sofab + +#endif // SOFAB_BITS_EQUAL_HPP diff --git a/include/sofab/sofab.hpp b/include/sofab/sofab.hpp index 131126b..e56d181 100644 --- a/include/sofab/sofab.hpp +++ b/include/sofab/sofab.hpp @@ -44,6 +44,8 @@ #include #include +#include "sofab/bits_equal.hpp" + /** * @def SOFAB_STRICT_UTF8 * @brief Compile-time gate for strict UTF-8 validation of `string` payloads diff --git a/test/CMakeLists.txt b/test/CMakeLists.txt index a256d98..0f0ee5c 100644 --- a/test/CMakeLists.txt +++ b/test/CMakeLists.txt @@ -16,6 +16,12 @@ target_compile_definitions(test_roundtrip PRIVATE target_link_libraries(test_roundtrip PRIVATE sofab_cpp) add_test(NAME test_roundtrip COMMAND test_roundtrip) +# sofab::bitsEqual: bit-pattern equality of float arrays (the default-omission test). +add_executable(test_bits_equal test_bits_equal.cpp) +target_compile_options(test_bits_equal PRIVATE -Wall -Wextra -Wpedantic -Werror) +target_link_libraries(test_bits_equal PRIVATE sofab_cpp) +add_test(NAME test_bits_equal COMMAND test_bits_equal) + # The README's generator example, compiled and run. The example lives here as a # real translation unit; the test also checks that README.md still shows exactly # these lines, so a documented example cannot drift from one that compiles. @@ -66,5 +72,6 @@ set_tests_properties(test_vendored_provenance PROPERTIES SKIP_RETURN_CODE 77) if(SOFAB_ENABLE_COVERAGE) target_link_libraries(test_roundtrip PRIVATE sofab_coverage) + target_link_libraries(test_bits_equal PRIVATE sofab_coverage) target_link_libraries(test_vectors PRIVATE sofab_coverage) endif() diff --git a/test/test_bits_equal.cpp b/test/test_bits_equal.cpp new file mode 100644 index 0000000..b1c82a6 --- /dev/null +++ b/test/test_bits_equal.cpp @@ -0,0 +1,169 @@ +/*! + * @file test_bits_equal.cpp + * @brief Checks for sofab::bitsEqual, the bit-pattern equality of float arrays. + * + * The generated encoder omits an array field iff it equals its default, so the + * comparison must see what the wire sees: `-0.0` is not `+0.0`, and a NaN equals + * another NaN only when every bit, payload included, is the same. + * + * SPDX-License-Identifier: MIT + */ + +#include "sofab/sofab.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include + +static int g_checks = 0; +static int g_failures = 0; + +#define CHECK(cond, what) do { \ + ++g_checks; \ + if (!(cond)) { ++g_failures; std::printf("FAIL: %s (line %d)\n", what, __LINE__); } \ +} while (0) + +/* The reference: a plain loop over the integer bit patterns. */ +template +static bool refEqual(const std::vector &a, const std::vector &b) +{ + if (a.size() != b.size()) return false; + for (std::size_t i = 0; i < a.size(); ++i) + if (std::bit_cast(a[i]) != std::bit_cast(b[i])) return false; + return true; +} + +template struct Bits; +template <> struct Bits { using U = std::uint32_t; }; +template <> struct Bits { using U = std::uint64_t; }; + +template +static T fromBits(typename Bits::U u) { return std::bit_cast(u); } + +template +static void checkWidth(const char *tn) +{ + using U = typename Bits::U; + char msg[160]; + auto say = [&](const char *s) { std::snprintf(msg, sizeof msg, "%s: %s", tn, s); return msg; }; + + const T pz = T(0), nz = -T(0); + const T qnan = std::numeric_limits::quiet_NaN(); + /* same quiet NaN, different payload: set the lowest mantissa bit */ + const T qnan2 = fromBits(static_cast(std::bit_cast(qnan) | U(1))); + /* signalling NaN: quiet bit clear, payload non-zero */ + const T snan = std::numeric_limits::signaling_NaN(); + const T inf = std::numeric_limits::infinity(); + const T den = std::numeric_limits::denorm_min(); + + /* empty and one element */ + { + std::vector e1, e2; + CHECK(sofab::bitsEqual(e1, e2), say("empty equals empty")); + CHECK(!sofab::bitsEqual(e1, std::vector{pz}), say("empty vs one")); + CHECK(!sofab::bitsEqual(std::vector{pz}, e1), say("one vs empty")); + CHECK(sofab::bitsEqual(std::vector{T(1.5)}, std::vector{T(1.5)}), say("one equal")); + CHECK(!sofab::bitsEqual(std::vector{T(1.5)}, std::vector{T(2.5)}), say("one differs")); + } + /* signed zero at the first, a middle and the last index */ + for (std::size_t at : {std::size_t{0}, std::size_t{2}, std::size_t{4}}) { + std::vector a(5, T(1.5)), b(5, T(1.5)); + a[at] = nz; b[at] = pz; + CHECK(!sofab::bitsEqual(a, b), say("-0.0 vs +0.0 differs")); + CHECK(!sofab::bitsEqual(b, a), say("+0.0 vs -0.0 differs")); + b[at] = nz; + CHECK(sofab::bitsEqual(a, b), say("-0.0 vs -0.0 equal")); + /* the IEEE compare this replaces says equal: the bug under test */ + a[at] = nz; b[at] = pz; + CHECK(a == b, say("sanity: IEEE == would call them equal")); + } + /* NaN, infinities, subnormals */ + CHECK(sofab::bitsEqual(std::vector{qnan}, std::vector{qnan}), say("same NaN bits equal")); + CHECK(!sofab::bitsEqual(std::vector{qnan}, std::vector{qnan2}), say("NaN payload differs")); + CHECK(sofab::bitsEqual(std::vector{snan}, std::vector{snan}), say("same sNaN bits equal")); + CHECK(!sofab::bitsEqual(std::vector{qnan}, std::vector{snan}), say("qNaN vs sNaN differ")); + CHECK(sofab::bitsEqual(std::vector{inf, -inf}, std::vector{inf, -inf}), say("infinities equal")); + CHECK(!sofab::bitsEqual(std::vector{inf}, std::vector{-inf}), say("+inf vs -inf")); + CHECK(sofab::bitsEqual(std::vector{den, -den}, std::vector{den, -den}), say("subnormals equal")); + CHECK(!sofab::bitsEqual(std::vector{den}, std::vector{-den}), say("subnormal sign")); + CHECK(!sofab::bitsEqual(std::vector{den}, std::vector{pz}), say("subnormal vs zero")); + + /* length mismatch both ways, equal prefix */ + { + std::vector a{T(1), T(2), T(3)}, b{T(1), T(2)}; + CHECK(!sofab::bitsEqual(a, b), say("longer vs shorter")); + CHECK(!sofab::bitsEqual(b, a), say("shorter vs longer")); + } + /* longer than 64 elements, exactly one differing element */ + for (std::size_t n : {std::size_t{65}, std::size_t{256}, std::size_t{1000}}) { + std::vector a(n); + for (std::size_t i = 0; i < n; ++i) a[i] = T(i) * T(0.25) - T(7); + CHECK(sofab::bitsEqual(a, a), say("array against itself")); + for (std::size_t at : {std::size_t{0}, n / 2, n - 1}) { + std::vector b = a; + CHECK(sofab::bitsEqual(a, b), say("long copy equal")); + b[at] = fromBits(static_cast(std::bit_cast(b[at]) ^ U(1))); + CHECK(!sofab::bitsEqual(a, b), say("one ULP differs in a long array")); + b = a; b[at] = (std::bit_cast(a[at]) == std::bit_cast(pz)) ? nz : -a[at]; + CHECK(!sofab::bitsEqual(a, b), say("one sign differs in a long array")); + } + } + /* the container shapes the generated code passes */ + { + sofab::InlineVector f{pz, T(1.5)}; + CHECK(sofab::bitsEqual(f, sofab::InlineVector{pz, T(1.5)}), say("InlineVector, default")); + CHECK(sofab::bitsEqual(f, std::vector{pz, T(1.5)}), say("InlineVector vs vector")); + CHECK(sofab::bitsEqual(f, {pz, T(1.5)}), say("braced default")); + CHECK(!sofab::bitsEqual(f, {nz, T(1.5)}), say("braced default, -0.0")); + CHECK(!sofab::bitsEqual(f, {pz}), say("braced default, shorter")); + f.assign({nz, T(1.5)}); + CHECK(!sofab::bitsEqual(f, sofab::InlineVector{pz, T(1.5)}), say("InlineVector -0.0")); + std::array arr{pz, T(1.5)}; + const T carr[2] = {pz, T(1.5)}; + CHECK(sofab::bitsEqual(arr, carr), say("std::array vs C array")); + CHECK(sofab::bitsEqual(std::span(arr), std::span(arr)), say("span const vs mutable")); + CHECK(sofab::bitsEqual(std::span{}, std::vector{}), say("empty span vs empty vector")); + } + /* deterministic cross-check against the reference loop */ + { + std::uint64_t s = 0x9e3779b97f4a7c15ull; + auto next = [&] { s ^= s << 13; s ^= s >> 7; s ^= s << 17; return s; }; + bool agree = true; + for (int round = 0; round < 2000; ++round) { + std::size_t n = next() % 20; + std::vector a(n), b; + for (auto &x : a) { + /* mix special patterns and arbitrary bits */ + switch (next() % 6) { + case 0: x = pz; break; + case 1: x = nz; break; + case 2: x = qnan; break; + case 3: x = qnan2; break; + default: x = fromBits(static_cast(next())); break; + } + } + b = a; + switch (next() % 4) { + case 0: break; + case 1: if (n) b[next() % n] = fromBits(static_cast(next())); break; + case 2: if (n) { T &x = b[next() % n]; x = std::bit_cast(x) == std::bit_cast(pz) ? nz : pz; } break; + default: b.push_back(pz); break; + } + if (sofab::bitsEqual(a, b) != refEqual(a, b)) agree = false; + } + CHECK(agree, say("agrees with the reference bit loop")); + } +} + +int main() +{ + checkWidth("fp32"); + checkWidth("fp64"); + std::printf("%d checks, %d failures\n", g_checks, g_failures); + return g_failures == 0 ? 0 : 1; +}