StringUtil: Add IsPrintableCharacter and use it

Add a function that safely returns whether a character is printable
i.e. whether 0x20 <= c <= 0x7e is true.

This is done in several places in our codebase and it's easy to run
into undefined behaviour if the C version defined in <cctype>
is used instead of this one, since its behaviour is undefined
if the character is not representable as an unsigned char.

This fixes MemoryViewWidget.
This commit is contained in:
Léo Lam committed 2020-01-16 00:22:26 +01:00
1 parent 1cc7ef356b
commit 89b0ab2d22
7 files changed
+22 -27

No files matched your search

+2 -10
View File
@@ -9,7 +9,6 @@
#include <cinttypes>
#include <cstddef>
#include <cstring>
#include <locale>
#include <map>
#include <optional>
#include <string>
@@ -314,11 +313,7 @@ std::string TMDReader::GetGameID() const
std::memcpy(game_id, m_bytes.data() + offsetof(TMDHeader, title_id) + 4, 4);
std::memcpy(game_id + 4, m_bytes.data() + offsetof(TMDHeader, group_id), 2);
const bool all_printable = std::all_of(std::begin(game_id), std::end(game_id), [](char c) {
return std::isprint(c, std::locale::classic());
});
if (all_printable)
if (std::all_of(std::begin(game_id), std::end(game_id), IsPrintableCharacter))
return std::string(game_id, sizeof(game_id));
return fmt::format("{:016x}", GetTitleId());
@@ -329,10 +324,7 @@ std::string TMDReader::GetGameTDBID() const
const u8* begin = m_bytes.data() + offsetof(TMDHeader, title_id) + 4;
const u8* end = begin + 4;
const bool all_printable =
std::all_of(begin, end, [](char c) { return std::isprint(c, std::locale::classic()); });
if (all_printable)
if (std::all_of(begin, end, IsPrintableCharacter))
return std::string(begin, end);
return fmt::format("{:016x}", GetTitleId());