File tree Expand file tree Collapse file tree 1 file changed +11
-9
lines changed
Expand file tree Collapse file tree 1 file changed +11
-9
lines changed Original file line number Diff line number Diff line change @@ -95,18 +95,20 @@ T bit_cast(char *c) {
9595/* Byte swap for little-endian systems */
9696template <typename T>
9797T cond_byte_swap (T value) {
98+ static_assert (std::is_trivially_copyable<T>::value, " T must be trivially copyable" );
9899 uint32_t endian_test = 1 ;
99- if (*((char *)&endian_test)) {
100- union {
101- T i;
102- uint8_t b[sizeof (T)];
103- } src = { value }, dst;
104-
105- for (unsigned int i = 0 ; i < sizeof (value); i++) {
106- dst.b [i] = src.b [sizeof (value) - 1 - i];
100+ if (*reinterpret_cast <char *>(&endian_test)) {
101+ uint8_t src[sizeof (T)];
102+ uint8_t dst[sizeof (T)];
103+
104+ std::memcpy (src, &value, sizeof (T));
105+ for (size_t i = 0 ; i < sizeof (T); ++i) {
106+ dst[i] = src[sizeof (T) - 1 - i];
107107 }
108108
109- return dst.i ;
109+ T result;
110+ std::memcpy (&result, dst, sizeof (T));
111+ return result;
110112 }
111113 return value;
112114}
You can’t perform that action at this time.
0 commit comments