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
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -937,6 +937,7 @@ decode-buffer contract:
| `read(std::string &)` | Must **pre-size** the string; reads into existing storage | Auto-sizes via `assign` |
| `read(std::string_view &)` | Not available | Not available either — deliberately, and asking for one is a compile error naming the owning alternatives |
| Wrapper-array collectors | `FixedStringSeq` / `FixedBlobSeq` / `StringSeq` / `BlobSeq` for string and blob elements, `FixedMessageSeq` / `MessageSeq` (in `sofab/seq.hpp`) for struct, union and native-scalar row elements, `FixedRowSeq` / `RowSeq` (same header) for a row the stream cannot read on its own — a row that is itself a wrapper sequence, or an enum/boolean row — whose read the caller hands in as a reader, plus `read(std::vector<std::string>&)` and `read(std::vector<std::vector<uint8_t>>&)` | `StringSeq` / `BlobSeq` / `MessageSeq` / `RowSeq`, same placement rule; the fixed-capacity twins are this port's, since the heap-free containers are what they fill |
| Float-array default test | `bitsEqual(a, b)` (in `sofab/floats.hpp`) — true iff both `float` / `double` arrays have the same length and the same IEEE-754 bit pattern at every index, so `-0.0` differs from `+0.0` and a NaN equals only a bit-identical NaN; one `memcmp` after the length check, header-only, 0 B when unused | The same helper; takes any contiguous container (`std::vector`, `InlineVector<T,N>`, `std::array`, `std::span`, `std::initializer_list`) on either side |
| Heap-free field types | `FixedString<N>`, `FixedBytes<N>`, `InlineVector<T,N>` | The same three, deliberately identical in name and behaviour, so generated code for a bounded field is the same either way |
| `write()` of an `enum` array | Takes the container of scoped enums as stored — `std::vector<Gear>` or `InlineVector<Gear,N>` with `enum class Gear : int8_t` — and encodes it at the enum's declared underlying width, which is also what picks the signed or unsigned array wire type | The same, spelled the same, for the same bytes: one expression in generated code compiles against either port, and neither needs a converted copy |
| Build-time capability flags | Honors the C core's `SOFAB_DISABLE_*` switches (`FP64`/`INT64`/`ARRAY` → `static_assert` on use; `FIXLEN`/`SEQUENCE` → hard `#error`) | None — every type always compiled in |
Expand Down
93 changes: 93 additions & 0 deletions src/include/sofab/floats.hpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
/*!
* @file floats.hpp
* @brief SofaBuffers C++ - bit-pattern equality for float arrays.
*
* Part of the **static-helper layer** (see @ref seq.hpp): code whose shape is
* the same for every schema, so it lives here once instead of being emitted
* into every generated header.
*
* A generated encoder omits a field iff its value equals its declared default
* (MESSAGE_SPEC §2), and floats round-trip bit for bit (CORELIB_PLAN §4.6).
* "Equals" for a float array is therefore a comparison of IEEE-754 bit
* patterns, never of values: `-0.0` differs from `+0.0`, and a NaN equals
* another NaN only when every bit, payload included, is identical. The
* container `operator==` (an elementwise IEEE `==`) gets both wrong and would
* drop a `-0.0` element that has to reach the wire.
*
* The helper is header-only, inline and stateless: a translation unit that
* does not call it pays 0 bytes, and the C library is untouched.
*
* Include `sofab/sofab.hpp`; it pulls this in. Including this header alone
* works too and means the same thing.
*
* SPDX-License-Identifier: MIT
*/

#ifndef SOFAB_FLOATS_HPP
#define SOFAB_FLOATS_HPP

/**
* @addtogroup cpp_api
* @{
*/

/* includes *******************************************************************/
#include <cstddef>
#include <cstring>
#include <iterator>
#include <type_traits>

/* functions ******************************************************************/
namespace sofab
{
/*!
* @brief True iff both float arrays have the same length and the same bit
* pattern at every index.
*
* The length is compared first (early exit); the elements are then compared
* with one block `memcmp` over `n * sizeof(T)` bytes, so there is no IEEE
* `==` anywhere. Nothing is allocated or modified.
*
* @tparam T `float` (32-bit pattern) or `double` (64-bit pattern).
* @param a First array, or any pointer when @p na is 0.
* @param na Length of @p a in elements.
* @param b Second array, or any pointer when @p nb is 0.
* @param nb Length of @p b in elements.
*/
template <typename T>
inline bool bitsEqual(const T *a, std::size_t na, const T *b, std::size_t nb) noexcept
{
static_assert(std::is_same_v<T, float> || std::is_same_v<T, double>,
"bitsEqual compares float or double arrays");
if (na != nb)
{
return false;
}
// memcmp with a null pointer is undefined even for a zero length, and an
// empty std::vector may hand one out.
return na == 0 || std::memcmp(a, b, na * sizeof(T)) == 0;
}

/*!
* @brief Container form of @ref bitsEqual: anything contiguous that
* `std::data` / `std::size` accept and that holds `float` or `double`.
*
* Takes a mutable field (`std::vector`, @ref InlineVector, `std::array`)
* and a constant default (a temporary of the same type, a `std::span`,
* a `std::initializer_list`) alike, and the two need not be the same
* container type — only the same element type.
*/
template <typename A, typename B>
inline bool bitsEqual(const A &a, const B &b) noexcept
{
using T = std::remove_cv_t<std::remove_pointer_t<decltype(std::data(a))>>;
static_assert(std::is_same_v<T, std::remove_cv_t<std::remove_pointer_t<decltype(std::data(b))>>>,
"bitsEqual compares two arrays of the same element type");
return bitsEqual<T>(std::data(a), static_cast<std::size_t>(std::size(a)),
std::data(b), static_cast<std::size_t>(std::size(b)));
}
}

/** @} */ // end of addtogroup

#endif // SOFAB_FLOATS_HPP
3 changes: 3 additions & 0 deletions src/include/sofab/sofab.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -3849,4 +3849,7 @@ namespace sofab
* include guards resolve either way round. */
#include "sofab/seq.hpp"

/* The float-array bit-pattern equality the generated default test calls. */
#include "sofab/floats.hpp"

#endif // SOFAB_HPP
1 change: 1 addition & 0 deletions test/cpp/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ add_executable(sofabpptest
test_ostream.cpp
test_istream.cpp
test_seq.cpp
test_floats.cpp
test_receiver_limits.cpp
test_allocation.cpp
test_vector_blocks.cpp
Expand Down
230 changes: 230 additions & 0 deletions test/cpp/test_floats.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,230 @@
/*!
* @file test_floats.cpp
* @brief SofaBuffers test for the float-array bit-pattern equality (floats.hpp)
*
* SPDX-License-Identifier: MIT
*
* The generated encoder omits a field iff it equals its default, and floats
* round-trip bit for bit (CORELIB_PLAN §4.6), so "equals" is a comparison of
* IEEE-754 bit patterns. Nothing on the wire shows an array compared by value
* instead: the shared vectors carry the bytes, not the omission decision. The
* -0.0 / NaN cases are therefore pinned here.
*/

#include "sofab/sofab.hpp"

#include <catch2/catch_template_test_macros.hpp>
#include <catch2/catch_test_macros.hpp>
#include <array>
#include <cstddef>
#include <cstdint>
#include <cstring>
#include <initializer_list>
#include <limits>
#include <span>
#include <vector>

namespace
{

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

template <typename T>
typename Bits<T>::U bitsOf(T v)
{
typename Bits<T>::U u;
std::memcpy(&u, &v, sizeof u);
return u;
}

template <typename T>
T fromBits(typename Bits<T>::U u)
{
T v;
std::memcpy(&v, &u, sizeof v);
return v;
}

//! The specification, written as a plain loop: no IEEE ==, no memcmp.
template <typename T>
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 (bitsOf(a[i]) != bitsOf(b[i])) { return false; }
}
return true;
}

//! Deterministic xorshift64, so a failure reproduces.
struct Rng
{
uint64_t s = 0x9E3779B97F4A7C15ull;
uint64_t next()
{
s ^= s << 13;
s ^= s >> 7;
s ^= s << 17;
return s;
}
};

template <typename T>
std::vector<T> ramp(std::size_t n)
{
std::vector<T> v(n);
for (std::size_t i = 0; i < n; ++i) { v[i] = static_cast<T>(i) * T(0.5) + T(1); }
return v;
}

} // namespace

TEMPLATE_TEST_CASE("bitsEqual: empty, single, equal, self", "[floats]", float, double)
{
using T = TestType;
const std::vector<T> none;
CHECK(sofab::bitsEqual(none, none));
CHECK(sofab::bitsEqual(none, std::vector<T>{}));
CHECK(sofab::bitsEqual<T>(nullptr, 0, nullptr, 0));

CHECK(sofab::bitsEqual(std::vector<T>{T(1.5)}, std::vector<T>{T(1.5)}));
CHECK_FALSE(sofab::bitsEqual(std::vector<T>{T(1.5)}, std::vector<T>{T(2.5)}));

const auto v = ramp<T>(5);
CHECK(sofab::bitsEqual(v, v));
CHECK(sofab::bitsEqual(v, ramp<T>(5)));
}

TEMPLATE_TEST_CASE("bitsEqual: -0.0 differs from +0.0 at every position", "[floats]", float, double)
{
using T = TestType;
CHECK_FALSE(sofab::bitsEqual(std::vector<T>{T(-0.0), T(1.5)}, std::vector<T>{T(0.0), T(1.5)}));
CHECK_FALSE(sofab::bitsEqual(std::vector<T>{T(1.0), T(-0.0), T(2.0)},
std::vector<T>{T(1.0), T(0.0), T(2.0)}));
CHECK_FALSE(sofab::bitsEqual(std::vector<T>{T(0.0), T(1.5), T(-0.0)},
std::vector<T>{T(0.0), T(1.5), T(0.0)}));
CHECK_FALSE(sofab::bitsEqual(std::vector<T>{T(0.0)}, std::vector<T>{T(-0.0)}));
CHECK_FALSE(sofab::bitsEqual(std::vector<T>{T(-0.0)}, std::vector<T>{T(0.0)}));
CHECK(sofab::bitsEqual(std::vector<T>{T(-0.0)}, std::vector<T>{T(-0.0)}));
// The IEEE comparison it replaces calls them equal; that is the bug.
CHECK(std::vector<T>{T(-0.0), T(1.5)} == std::vector<T>{T(0.0), T(1.5)});
}

TEMPLATE_TEST_CASE("bitsEqual: NaN equals itself only bit for bit", "[floats]", float, double)
{
using T = TestType;
using U = typename Bits<T>::U;
const T qnan = std::numeric_limits<T>::quiet_NaN();
const T snan = std::numeric_limits<T>::signaling_NaN();
const U qbits = bitsOf(qnan);
const T payload = fromBits<T>(qbits ^ U(1)); // differs on every NaN encoding (MIPS legacy has the low bit set)
const T negnan = fromBits<T>(qbits | (U(1) << (sizeof(U) * 8 - 1)));

CHECK(sofab::bitsEqual(std::vector<T>{qnan}, std::vector<T>{qnan}));
CHECK(sofab::bitsEqual(std::vector<T>{qnan}, std::vector<T>{fromBits<T>(qbits)}));
CHECK(sofab::bitsEqual(std::vector<T>{snan}, std::vector<T>{snan}));
CHECK_FALSE(sofab::bitsEqual(std::vector<T>{qnan}, std::vector<T>{payload}));
CHECK_FALSE(sofab::bitsEqual(std::vector<T>{qnan}, std::vector<T>{negnan}));
CHECK_FALSE(sofab::bitsEqual(std::vector<T>{qnan}, std::vector<T>{snan}));
CHECK_FALSE(sofab::bitsEqual(std::vector<T>{qnan}, std::vector<T>{T(1)}));
// IEEE == says a NaN never equals itself; the bit pattern says it does.
CHECK(qnan != qnan);
}

TEMPLATE_TEST_CASE("bitsEqual: infinities and subnormals", "[floats]", float, double)
{
using T = TestType;
const T inf = std::numeric_limits<T>::infinity();
const T tiny = std::numeric_limits<T>::denorm_min();
CHECK(sofab::bitsEqual(std::vector<T>{inf, -inf}, std::vector<T>{inf, -inf}));
CHECK_FALSE(sofab::bitsEqual(std::vector<T>{inf}, std::vector<T>{-inf}));
CHECK_FALSE(sofab::bitsEqual(std::vector<T>{-inf}, std::vector<T>{inf}));
CHECK(sofab::bitsEqual(std::vector<T>{tiny, -tiny}, std::vector<T>{tiny, -tiny}));
CHECK_FALSE(sofab::bitsEqual(std::vector<T>{tiny}, std::vector<T>{T(0)}));
CHECK_FALSE(sofab::bitsEqual(std::vector<T>{tiny}, std::vector<T>{-tiny}));
CHECK_FALSE(sofab::bitsEqual(std::vector<T>{tiny}, std::vector<T>{fromBits<T>(2)}));
}

TEMPLATE_TEST_CASE("bitsEqual: a length mismatch is unequal, either way round", "[floats]", float, double)
{
using T = TestType;
const std::vector<T> two{T(1), T(2)};
const std::vector<T> three{T(1), T(2), T(3)};
const std::vector<T> none;
CHECK_FALSE(sofab::bitsEqual(two, three));
CHECK_FALSE(sofab::bitsEqual(three, two));
CHECK_FALSE(sofab::bitsEqual(none, two));
CHECK_FALSE(sofab::bitsEqual(two, none));
// The pointer form compares the lengths first, so a short b is never read
// out to a's length.
CHECK_FALSE(sofab::bitsEqual<T>(three.data(), 3, two.data(), 2));
CHECK_FALSE(sofab::bitsEqual<T>(two.data(), 2, three.data(), 3));
}

TEMPLATE_TEST_CASE("bitsEqual: one differing element in a long array", "[floats]", float, double)
{
using T = TestType;
for (std::size_t n : {std::size_t{65}, std::size_t{256}, std::size_t{4097}})
{
const auto base = ramp<T>(n);
CHECK(sofab::bitsEqual(base, ramp<T>(n)));
for (std::size_t at : {std::size_t{0}, n / 2, n - 1})
{
auto other = base;
other[at] = fromBits<T>(bitsOf(other[at]) ^ 1); // the last mantissa bit
CHECK_FALSE(sofab::bitsEqual(base, other));
CHECK_FALSE(sofab::bitsEqual(other, base));

auto zero = base;
auto negz = base;
zero[at] = T(0.0);
negz[at] = T(-0.0);
CHECK_FALSE(sofab::bitsEqual(zero, negz));
}
}
}

TEMPLATE_TEST_CASE("bitsEqual: takes the containers a generated default test passes", "[floats]", float, double)
{
using T = TestType;
const sofab::InlineVector<T, 3> inl = {T(0.0), T(1.5)};
CHECK(sofab::bitsEqual(inl, sofab::InlineVector<T, 3>{T(0.0), T(1.5)}));
CHECK_FALSE(sofab::bitsEqual(inl, sofab::InlineVector<T, 3>{T(-0.0), T(1.5)}));

const std::vector<T> vec = {T(0.0), T(1.5)};
CHECK(sofab::bitsEqual(vec, std::vector<T>{T(0.0), T(1.5)}));
CHECK_FALSE(sofab::bitsEqual(vec, std::vector<T>{T(-0.0), T(1.5)}));

// A mutable field against a constant default of a different container type.
static constexpr std::array<T, 2> dflt = {T(0.0), T(1.5)};
CHECK(sofab::bitsEqual(inl, dflt));
CHECK(sofab::bitsEqual(vec, std::span<const T>(dflt)));
CHECK(sofab::bitsEqual(vec, std::initializer_list<T>{T(0.0), T(1.5)}));
CHECK_FALSE(sofab::bitsEqual(vec, std::initializer_list<T>{T(0.0), T(-1.5)}));
}

TEMPLATE_TEST_CASE("bitsEqual: agrees with a plain bit loop on random input", "[floats]", float, double)
{
using T = TestType;
using U = typename Bits<T>::U;
Rng rng;
for (int round = 0; round < 2000; ++round)
{
const std::size_t n = rng.next() % 40;
std::vector<T> a(n);
for (auto &x : a) { x = fromBits<T>(static_cast<U>(rng.next())); } // any pattern, NaNs included
std::vector<T> b = a;
switch (rng.next() % 4)
{
case 0: break; // identical
case 1: if (n) { b[rng.next() % n] = fromBits<T>(static_cast<U>(rng.next())); } break;
case 2: if (n) { b[rng.next() % n] = -b[rng.next() % n]; } break;
default: b.push_back(T(0)); break; // length differs
}
CHECK(sofab::bitsEqual(a, b) == refEqual(a, b));
CHECK(sofab::bitsEqual(b, a) == refEqual(b, a));
}
}
Loading