From be94096dfb0c4862e2314cbae4120d7360b08ef2 Mon Sep 17 00:00:00 2001 From: Samer Afach Date: Mon, 17 Feb 2020 20:53:50 +0100 Subject: Fix a violation of C++ standard rules that unions cannot be switched. --- src/serialize.h | 25 +++++++++++++------------ 1 file changed, 13 insertions(+), 12 deletions(-) (limited to 'src') diff --git a/src/serialize.h b/src/serialize.h index cee7225bcb..4a6c5e26e4 100644 --- a/src/serialize.h +++ b/src/serialize.h @@ -9,6 +9,7 @@ #include #include +#include #include #include #include @@ -139,27 +140,27 @@ template inline uint64_t ser_readdata64(Stream &s) } inline uint64_t ser_double_to_uint64(double x) { - union { double x; uint64_t y; } tmp; - tmp.x = x; - return tmp.y; + uint64_t tmp; + std::memcpy(&tmp, &x, sizeof(x)); + return tmp; } inline uint32_t ser_float_to_uint32(float x) { - union { float x; uint32_t y; } tmp; - tmp.x = x; - return tmp.y; + uint32_t tmp; + std::memcpy(&tmp, &x, sizeof(x)); + return tmp; } inline double ser_uint64_to_double(uint64_t y) { - union { double x; uint64_t y; } tmp; - tmp.y = y; - return tmp.x; + double tmp; + std::memcpy(&tmp, &y, sizeof(y)); + return tmp; } inline float ser_uint32_to_float(uint32_t y) { - union { float x; uint32_t y; } tmp; - tmp.y = y; - return tmp.x; + float tmp; + std::memcpy(&tmp, &y, sizeof(y)); + return tmp; } -- cgit v1.2.3 From 0653939ac130eddffe40c53ac418bea305d3bf82 Mon Sep 17 00:00:00 2001 From: Samer Afach Date: Wed, 19 Feb 2020 18:44:46 +0100 Subject: Add static_asserts to ser_X_to_Y() methods --- src/serialize.h | 4 ++++ 1 file changed, 4 insertions(+) (limited to 'src') diff --git a/src/serialize.h b/src/serialize.h index 4a6c5e26e4..0a43913f83 100644 --- a/src/serialize.h +++ b/src/serialize.h @@ -142,24 +142,28 @@ inline uint64_t ser_double_to_uint64(double x) { uint64_t tmp; std::memcpy(&tmp, &x, sizeof(x)); + static_assert(sizeof(tmp) == sizeof(x), "double and uint64_t assumed to have the same size"); return tmp; } inline uint32_t ser_float_to_uint32(float x) { uint32_t tmp; std::memcpy(&tmp, &x, sizeof(x)); + static_assert(sizeof(tmp) == sizeof(x), "float and uint32_t assumed to have the same size"); return tmp; } inline double ser_uint64_to_double(uint64_t y) { double tmp; std::memcpy(&tmp, &y, sizeof(y)); + static_assert(sizeof(tmp) == sizeof(y), "double and uint64_t assumed to have the same size"); return tmp; } inline float ser_uint32_to_float(uint32_t y) { float tmp; std::memcpy(&tmp, &y, sizeof(y)); + static_assert(sizeof(tmp) == sizeof(y), "float and uint32_t assumed to have the same size"); return tmp; } -- cgit v1.2.3