From 5c8f61af8652d30219f2eb5857f7fc4f595e070e Mon Sep 17 00:00:00 2001 From: Emily Mabrey Date: Wed, 4 Aug 2021 17:05:58 -0400 Subject: [PATCH] Improve changes to `ProjectSerializer.cpp` Remove pointless addition of null-terminator bytes. Replace `static_cast` usage with `memcpy` for aliasing reasons. Signed-off-by: Emily Mabrey Reference-to: https://github.com/tenacityteam/tenacity/pull/422 Helped-by: nyanpasu64 --- src/ProjectSerializer.cpp | 44 ++++++++++++++++++++++----------------- 1 file changed, 25 insertions(+), 19 deletions(-) diff --git a/src/ProjectSerializer.cpp b/src/ProjectSerializer.cpp index c008a95a0..9533229aa 100644 --- a/src/ProjectSerializer.cpp +++ b/src/ProjectSerializer.cpp @@ -20,6 +20,7 @@ #include #include #include +#include /// /// ProjectSerializer class @@ -389,7 +390,7 @@ wxString ProjectSerializer::Decode(const wxMemoryBuffer &buffer) XMLStringWriter out; - std::vector bytes; + std::vector bytes_vector; IdMap mIds; std::vector mIdStack; char mCharSize = 0; @@ -407,30 +408,35 @@ wxString ProjectSerializer::Decode(const wxMemoryBuffer &buffer) return iter->second; }; - auto ReadString = [&mCharSize, &in, &bytes](size_t len) -> wxString + auto ReadString = [&mCharSize, &in, &bytes_vector](size_t len) -> wxString { - bytes.reserve( len + 4 ); - auto data = bytes.data(); - in.Read( data, len ); - // Make a null terminator of the widest type - memset( data + len, '\0', 4 ); + bytes_vector.reserve(len); + bytes_vector.resize(len); + + //Read the input memory into the internal array of the vector + in.Read( bytes_vector.data(), len); switch (mCharSize) { case 1: - wxASSERT(sizeof(decltype(*data)) == sizeof(char)); - // The void* silences the CodeQL CWE-704 detection - return wxUString().assignFromUTF8(static_cast(static_cast(data)), len); - + { + wxASSERT(sizeof(decltype(*bytes_vector.data())) == sizeof(char)); + // The void* silences the CodeQL CWE-704 detection + return wxUString().assignFromUTF8(bytes_vector.data(), len); + } case 2: - wxASSERT(sizeof(wxChar16) == 2 * sizeof(char)); - // The void* silences the CodeQL CWE-704 detection - return wxUString().assignFromUTF16(static_cast(static_cast(data)), len / 2); - + { + wxASSERT(sizeof(wxChar16) == 2 * sizeof(char)); + std::vector converted_data_16(len / 2); + std::memcpy(converted_data_16.data(), bytes_vector.data(), len); + return wxUString().assignFromUTF16(converted_data_16.data(), converted_data_16.size()); + } case 4: - wxASSERT(sizeof(wxChar32) == 4 * sizeof(char)); - // The void* silences the CodeQL CWE-704 detection - return wxUString().assign(static_cast(static_cast(data)), len / 4); - + { + wxASSERT(sizeof(wxChar32) == 4 * sizeof(char)); + std::vector converted_data_32(len / 4); + std::memcpy(converted_data_32.data(), bytes_vector.data(), len); + return wxUString().assign(converted_data_32.data(), converted_data_32.size()); + } default: wxASSERT_MSG(false, wxT("Characters size not 1, 2, or 4")); return wxUString();