Fix unaligned loads and stores

This commit is contained in:
Peter Dimov
2017-12-23 18:40:09 +02:00
parent 62802fee96
commit e93f6a2270

View File

@@ -47,6 +47,7 @@
#include <boost/core/scoped_enum.hpp> #include <boost/core/scoped_enum.hpp>
#include <iosfwd> #include <iosfwd>
#include <climits> #include <climits>
#include <cstring>
# if CHAR_BIT != 8 # if CHAR_BIT != 8
# error Platforms with CHAR_BIT != 8 are not supported # error Platforms with CHAR_BIT != 8 are not supported
@@ -295,7 +296,12 @@ namespace endian
// case since sizeof(T) and n_bytes are known at compile // case since sizeof(T) and n_bytes are known at compile
// time. // time.
{ {
return *reinterpret_cast<T const *>(bytes); // Avoids -fsanitize=undefined violations due to unaligned loads
// All major x86 compilers optimize a short-sized memcpy into a single instruction
T t;
std::memcpy( &t, bytes, sizeof(T) );
return t;
} }
# endif # endif
return unrolled_byte_loops<T, n_bytes>::load_little return unrolled_byte_loops<T, n_bytes>::load_little
@@ -321,7 +327,10 @@ namespace endian
// case since sizeof(T) and n_bytes are known at compile // case since sizeof(T) and n_bytes are known at compile
// time. // time.
{ {
*reinterpret_cast<T *>(bytes) = value; // Avoids -fsanitize=undefined violations due to unaligned stores
// All major x86 compilers optimize a short-sized memcpy into a single instruction
std::memcpy( bytes, &value, sizeof(T) );
return; return;
} }
# endif # endif