1
0
Fork 0
forked from suyu/suyu

swap: Get rid of undefined behavior in swapf and swapd

This isn't well-defined in C++.
This commit is contained in:
Lioncash 2016-05-08 23:21:44 -04:00
parent aef4630102
commit 47ca79ba4b

View file

@ -25,6 +25,8 @@
#include <sys/endian.h> #include <sys/endian.h>
#endif #endif
#include <cstring>
#include "common/common_types.h" #include "common/common_types.h"
// GCC 4.6+ // GCC 4.6+
@ -89,27 +91,29 @@ inline u64 swap64(u64 data) {return ((u64)swap32(data) << 32) | swap32(data >> 3
#endif #endif
inline float swapf(float f) { inline float swapf(float f) {
union { static_assert(sizeof(u32) == sizeof(float),
float f; "float must be the same size as uint32_t.");
unsigned int u32;
} dat1, dat2;
dat1.f = f; u32 value;
dat2.u32 = swap32(dat1.u32); std::memcpy(&value, &f, sizeof(u32));
return dat2.f; value = swap32(value);
std::memcpy(&f, &value, sizeof(u32));
return f;
} }
inline double swapd(double f) { inline double swapd(double f) {
union { static_assert(sizeof(u64) == sizeof(double),
double f; "double must be the same size as uint64_t.");
unsigned long long u64;
} dat1, dat2;
dat1.f = f; u64 value;
dat2.u64 = swap64(dat1.u64); std::memcpy(&value, &f, sizeof(u64));
return dat2.f; value = swap64(value);
std::memcpy(&f, &value, sizeof(u64));
return f;
} }
} // Namespace Common } // Namespace Common