Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 18 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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`,
Expand Down
92 changes: 92 additions & 0 deletions include/sofab/bits_equal.hpp
Original file line number Diff line number Diff line change
@@ -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 <concepts>
#include <cstddef>
#include <cstring>
#include <initializer_list>
#include <ranges>
#include <span>
#include <type_traits>

namespace sofab
{
namespace detail
{
/*! @brief `float` or `double`, the two element types of an fp array. */
template <typename T>
concept FloatElement = std::same_as<T, float> || std::same_as<T, double>;

/*! @brief Length check, then one block compare of the object representation. */
template <FloatElement T>
inline bool bitsEqualSpan(std::span<const T> a, std::span<const T> 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<float>`). 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 <std::ranges::contiguous_range A, std::ranges::contiguous_range B>
requires std::ranges::sized_range<A> && std::ranges::sized_range<B>
&& detail::FloatElement<std::remove_cv_t<std::ranges::range_value_t<A>>>
&& std::same_as<std::remove_cv_t<std::ranges::range_value_t<A>>,
std::remove_cv_t<std::ranges::range_value_t<B>>>
inline bool bitsEqual(const A &a, const B &b) noexcept
{
using T = std::remove_cv_t<std::ranges::range_value_t<A>>;
return detail::bitsEqualSpan<T>(
std::span<const T>(std::ranges::data(a), std::ranges::size(a)),
std::span<const T>(std::ranges::data(b), std::ranges::size(b)));
}

/*! @brief Braced-list default: `bitsEqual(field, {0.0f, 1.5f})`. */
template <detail::FloatElement T, std::ranges::contiguous_range A>
requires std::ranges::sized_range<A>
&& std::same_as<std::remove_cv_t<std::ranges::range_value_t<A>>, T>
inline bool bitsEqual(const A &a, std::initializer_list<T> b) noexcept
{
return detail::bitsEqualSpan<T>(
std::span<const T>(std::ranges::data(a), std::ranges::size(a)),
std::span<const T>(b.begin(), b.size()));
}
} // namespace sofab

#endif // SOFAB_BITS_EQUAL_HPP
2 changes: 2 additions & 0 deletions include/sofab/sofab.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,8 @@
#include <type_traits>
#include <vector>

#include "sofab/bits_equal.hpp"

/**
* @def SOFAB_STRICT_UTF8
* @brief Compile-time gate for strict UTF-8 validation of `string` payloads
Expand Down
7 changes: 7 additions & 0 deletions test/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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()
169 changes: 169 additions & 0 deletions test/test_bits_equal.cpp
Original file line number Diff line number Diff line change
@@ -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 <array>
#include <bit>
#include <cmath>
#include <cstdint>
#include <cstdio>
#include <limits>
#include <span>
#include <vector>

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 <typename T, typename U>
static bool refEqual(const std::vector<T> &a, const std::vector<T> &b)
{
if (a.size() != b.size()) return false;
for (std::size_t i = 0; i < a.size(); ++i)
if (std::bit_cast<U>(a[i]) != std::bit_cast<U>(b[i])) return false;
return true;
}

template <typename T> struct Bits;
template <> struct Bits<float> { using U = std::uint32_t; };
template <> struct Bits<double> { using U = std::uint64_t; };

template <typename T>
static T fromBits(typename Bits<T>::U u) { return std::bit_cast<T>(u); }

template <typename T>
static void checkWidth(const char *tn)
{
using U = typename Bits<T>::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<T>::quiet_NaN();
/* same quiet NaN, different payload: set the lowest mantissa bit */
const T qnan2 = fromBits<T>(static_cast<U>(std::bit_cast<U>(qnan) | U(1)));
/* signalling NaN: quiet bit clear, payload non-zero */
const T snan = std::numeric_limits<T>::signaling_NaN();
const T inf = std::numeric_limits<T>::infinity();
const T den = std::numeric_limits<T>::denorm_min();

/* empty and one element */
{
std::vector<T> e1, e2;
CHECK(sofab::bitsEqual(e1, e2), say("empty equals empty"));
CHECK(!sofab::bitsEqual(e1, std::vector<T>{pz}), say("empty vs one"));
CHECK(!sofab::bitsEqual(std::vector<T>{pz}, e1), say("one vs empty"));
CHECK(sofab::bitsEqual(std::vector<T>{T(1.5)}, std::vector<T>{T(1.5)}), say("one equal"));
CHECK(!sofab::bitsEqual(std::vector<T>{T(1.5)}, std::vector<T>{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<T> 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<T>{qnan}, std::vector<T>{qnan}), say("same NaN bits equal"));
CHECK(!sofab::bitsEqual(std::vector<T>{qnan}, std::vector<T>{qnan2}), say("NaN payload differs"));
CHECK(sofab::bitsEqual(std::vector<T>{snan}, std::vector<T>{snan}), say("same sNaN bits equal"));
CHECK(!sofab::bitsEqual(std::vector<T>{qnan}, std::vector<T>{snan}), say("qNaN vs sNaN differ"));
CHECK(sofab::bitsEqual(std::vector<T>{inf, -inf}, std::vector<T>{inf, -inf}), say("infinities equal"));
CHECK(!sofab::bitsEqual(std::vector<T>{inf}, std::vector<T>{-inf}), say("+inf vs -inf"));
CHECK(sofab::bitsEqual(std::vector<T>{den, -den}, std::vector<T>{den, -den}), say("subnormals equal"));
CHECK(!sofab::bitsEqual(std::vector<T>{den}, std::vector<T>{-den}), say("subnormal sign"));
CHECK(!sofab::bitsEqual(std::vector<T>{den}, std::vector<T>{pz}), say("subnormal vs zero"));

/* length mismatch both ways, equal prefix */
{
std::vector<T> 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<T> 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<T> b = a;
CHECK(sofab::bitsEqual(a, b), say("long copy equal"));
b[at] = fromBits<T>(static_cast<U>(std::bit_cast<U>(b[at]) ^ U(1)));
CHECK(!sofab::bitsEqual(a, b), say("one ULP differs in a long array"));
b = a; b[at] = (std::bit_cast<U>(a[at]) == std::bit_cast<U>(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<T, 3> f{pz, T(1.5)};
CHECK(sofab::bitsEqual(f, sofab::InlineVector<T, 3>{pz, T(1.5)}), say("InlineVector, default"));
CHECK(sofab::bitsEqual(f, std::vector<T>{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<T, 3>{pz, T(1.5)}), say("InlineVector -0.0"));
std::array<T, 2> 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<const T>(arr), std::span<T>(arr)), say("span const vs mutable"));
CHECK(sofab::bitsEqual(std::span<const T>{}, std::vector<T>{}), 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<T> 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<T>(static_cast<U>(next())); break;
}
}
b = a;
switch (next() % 4) {
case 0: break;
case 1: if (n) b[next() % n] = fromBits<T>(static_cast<U>(next())); break;
case 2: if (n) { T &x = b[next() % n]; x = std::bit_cast<U>(x) == std::bit_cast<U>(pz) ? nz : pz; } break;
default: b.push_back(pz); break;
}
if (sofab::bitsEqual(a, b) != refEqual<T, U>(a, b)) agree = false;
}
CHECK(agree, say("agrees with the reference bit loop"));
}
}

int main()
{
checkWidth<float>("fp32");
checkWidth<double>("fp64");
std::printf("%d checks, %d failures\n", g_checks, g_failures);
return g_failures == 0 ? 0 : 1;
}
Loading