Skip to content

Commit 7666b0a

Browse files
committed
use memcpy instead of union is (de)serialization of floats and doubles
1 parent 8461241 commit 7666b0a

File tree

1 file changed

+11
-22
lines changed

1 file changed

+11
-22
lines changed

library/core/Serialization.cc

Lines changed: 11 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -144,22 +144,16 @@ inline namespace v1 {
144144
}
145145

146146
void Serializer::writeFloat(float data) {
147-
union {
148-
float f32;
149-
uint32_t u32;
150-
};
151-
152-
f32 = data;
147+
static_assert(sizeof(uint32_t) == sizeof(float), "float should be 32 bits");
148+
uint32_t u32;
149+
std::memcpy(&u32, &data, sizeof(float));
153150
writeBigEndian32(u32);
154151
}
155152

156153
void Serializer::writeDouble(double data) {
157-
union {
158-
double f64;
159-
uint64_t u64;
160-
};
161-
162-
f64 = data;
154+
static_assert(sizeof(uint64_t) == sizeof(double), "double should be 64 bits");
155+
uint64_t u64;
156+
std::memcpy(&u64, &data, sizeof(double));
163157
writeBigEndian64(u64);
164158
}
165159

@@ -421,31 +415,26 @@ inline namespace v1 {
421415
}
422416

423417
bool Deserializer::readFloat(float& data) {
424-
union {
425-
float f32;
426-
uint32_t u32;
427-
};
418+
uint32_t u32;
428419

429420
if (!readBigEndian32(u32)) {
430421
Log::error("Asking for float but the file is at the end.\n");
431422
return false;
432423
}
433424

434-
data = f32;
425+
std::memcpy(&data, &u32, sizeof(float));
435426
return true;
436427
}
437428

438429
bool Deserializer::readDouble(double& data) {
439-
union {
440-
double f64;
441-
uint64_t u64;
442-
};
430+
uint64_t u64;
443431

444432
if (!readBigEndian64(u64)) {
433+
Log::error("Asking for double but the file is at the end.\n");
445434
return false;
446435
}
447436

448-
data = f64;
437+
std::memcpy(&data, &u64, sizeof(double));
449438
return true;
450439
}
451440

0 commit comments

Comments
 (0)