CPlayerState: Remove undefined behavior within CPlayerState constructor

Type-punning via a union is currently undefined behavior according to
the C++ standard, so we can use std::memcpy instead to accomplish the
same thing.
This commit is contained in:
Lioncash 2020-03-21 00:37:06 -04:00
parent ba6f55a928
commit ff703b1189
1 changed files with 13 additions and 12 deletions

View File

@ -2,6 +2,7 @@
#include <algorithm> #include <algorithm>
#include <array> #include <array>
#include <cstring>
#include "Runtime/CMemoryCardSys.hpp" #include "Runtime/CMemoryCardSys.hpp"
#include "Runtime/CStateManager.hpp" #include "Runtime/CStateManager.hpp"
@ -81,12 +82,12 @@ CPlayerState::CPlayerState() : x188_staticIntf(5) {
CPlayerState::CPlayerState(CBitStreamReader& stream) : x188_staticIntf(5) { CPlayerState::CPlayerState(CBitStreamReader& stream) : x188_staticIntf(5) {
x0_24_alive = true; x0_24_alive = true;
x4_enabledItems = u32(stream.ReadEncoded(32)); x4_enabledItems = u32(stream.ReadEncoded(32));
union {
float fHP; const u32 integralHP = u32(stream.ReadEncoded(32));
u32 iHP; float realHP;
} hp; std::memcpy(&realHP, &integralHP, sizeof(float));
hp.iHP = u32(stream.ReadEncoded(32));
xc_health.SetHP(hp.fHP); xc_health.SetHP(realHP);
x8_currentBeam = EBeamId(stream.ReadEncoded(CBitStreamReader::GetBitCount(5))); x8_currentBeam = EBeamId(stream.ReadEncoded(CBitStreamReader::GetBitCount(5)));
x20_currentSuit = EPlayerSuit(stream.ReadEncoded(CBitStreamReader::GetBitCount(4))); x20_currentSuit = EPlayerSuit(stream.ReadEncoded(CBitStreamReader::GetBitCount(4)));
x24_powerups.resize(41); x24_powerups.resize(41);
@ -113,12 +114,12 @@ CPlayerState::CPlayerState(CBitStreamReader& stream) : x188_staticIntf(5) {
void CPlayerState::PutTo(CBitStreamWriter& stream) { void CPlayerState::PutTo(CBitStreamWriter& stream) {
stream.WriteEncoded(x4_enabledItems, 32); stream.WriteEncoded(x4_enabledItems, 32);
union {
float fHP; const float realHP = xc_health.GetHP();
u32 iHP; u32 integralHP;
} hp; std::memcpy(&integralHP, &realHP, sizeof(u32));
hp.fHP = xc_health.GetHP();
stream.WriteEncoded(hp.iHP, 32); stream.WriteEncoded(integralHP, 32);
stream.WriteEncoded(u32(x8_currentBeam), CBitStreamWriter::GetBitCount(5)); stream.WriteEncoded(u32(x8_currentBeam), CBitStreamWriter::GetBitCount(5));
stream.WriteEncoded(u32(x20_currentSuit), CBitStreamWriter::GetBitCount(4)); stream.WriteEncoded(u32(x20_currentSuit), CBitStreamWriter::GetBitCount(4));
for (size_t i = 0; i < x24_powerups.size(); ++i) { for (size_t i = 0; i < x24_powerups.size(); ++i) {