Skip to content

Commit

Permalink
tests: Avoid type punning doubles to uint64_t
Browse files Browse the repository at this point in the history
When GCC is run with -fstrict-aliasing it complains about type punning
from a double to a uint64_t. The recommended way to avoid this problem
is to use memcpy. The compiler ought to be clever enough to realise that
it doesn't actually need to do any copying.

(This is a deliberately different choice to the implementation in
MessageIStream::read in the hope that it means that we're testing the
implementation correctly.)
  • Loading branch information
mikecrowe committed Jul 14, 2020
1 parent db9a721 commit a9e8a32
Show file tree
Hide file tree
Showing 3 changed files with 7 additions and 3 deletions.
4 changes: 3 additions & 1 deletion tests/dbus_messageistream_unittest.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,9 @@ namespace test {
double value = 0.75483;
MessageIStream leStream((const uint8_t*)&value, sizeof(double), false);

uint64_t swapped_value = __bswap_64(*reinterpret_cast<uint64_t*>(&value));
uint64_t swapped_value;
memcpy(&swapped_value, &value, sizeof(value));
swapped_value = __bswap_64(swapped_value);
MessageIStream beStream((const uint8_t*)&swapped_value, sizeof(double),
true);

Expand Down
3 changes: 2 additions & 1 deletion tests/dbus_type_dictentry_unittest.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,8 @@ namespace test {
while (data.size() % 8 != 0)
data.push_back('\0');

uint64_t value1 = *reinterpret_cast<const uint64_t*>(&value.first);
uint64_t value1;
memcpy(&value1, &value.first, sizeof(value1));
if (byteOrder != __BYTE_ORDER) {
value1 = __bswap_64(value1);
}
Expand Down
3 changes: 2 additions & 1 deletion tests/dbus_type_double_unittest.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,8 @@ namespace test {
void TestUnmarshallFromMessageIStream(Type::Double& dbusType, double value,
unsigned byteOrder)
{
uint64_t u = *reinterpret_cast<uint64_t*>(&value);
uint64_t u;
memcpy(&u, &value, sizeof(u));

// __FLOAT_WORD_ORDER__ is the same as __BYTE_ORDER__ on almost
// everything in the world. We only swap or not so we couldn't
Expand Down

0 comments on commit a9e8a32

Please sign in to comment.