Skip to content

Commit 000d9fe

Browse files
authored
Less undefined behavior way of doing byte swap (#1862)
1 parent c8da12b commit 000d9fe

File tree

1 file changed

+11
-9
lines changed

1 file changed

+11
-9
lines changed

src/WebSocketProtocol.h

Lines changed: 11 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -95,18 +95,20 @@ T bit_cast(char *c) {
9595
/* Byte swap for little-endian systems */
9696
template <typename T>
9797
T 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
}

0 commit comments

Comments
 (0)