StringUtil: Fix incorrect value of endptr

And add associated unit tests.
This commit is contained in:
Stenzek 2023-05-24 19:34:04 +10:00 committed by refractionpcsx2
parent 1fa6614cd5
commit 884086ba76
2 changed files with 35 additions and 8 deletions

View File

@ -100,10 +100,7 @@ namespace StringUtil
return std::nullopt;
if (endptr)
{
const size_t remaining_len = end - ptr - 1;
*endptr = (remaining_len > 0) ? std::string_view(result.ptr, remaining_len) : std::string_view();
}
*endptr = (result.ptr < end) ? std::string_view(result.ptr, end - result.ptr) : std::string_view();
return value;
}
@ -131,10 +128,7 @@ namespace StringUtil
return std::nullopt;
if (endptr)
{
const size_t remaining_len = end - ptr - 1;
*endptr = (remaining_len > 0) ? std::string_view(result.ptr, remaining_len) : std::string_view();
}
*endptr = (result.ptr < end) ? std::string_view(result.ptr, end - result.ptr) : std::string_view();
return value;
}

View File

@ -43,6 +43,39 @@ TEST(StringUtil, FromChars)
ASSERT_EQ(StringUtil::FromChars<int>("ff", 16).value_or(0), 255);
}
TEST(StringUtil, FromCharsWithEndPtr)
{
using namespace std::literals;
std::string_view endptr;
ASSERT_EQ(StringUtil::FromChars<u32>("123x456", 16, &endptr), std::optional<u32>(0x123));
ASSERT_EQ(endptr, "x456"sv);
ASSERT_EQ(StringUtil::FromChars<u32>("0x1234", 16, &endptr), std::optional<u32>(0u));
ASSERT_EQ(endptr, "x1234"sv);
ASSERT_EQ(StringUtil::FromChars<u32>("1234", 16, &endptr), std::optional<u32>(0x1234u));
ASSERT_TRUE(endptr.empty());
ASSERT_EQ(StringUtil::FromChars<u32>("abcdefg", 16, &endptr), std::optional<u32>(0xabcdef));
ASSERT_EQ(endptr, "g"sv);
ASSERT_EQ(StringUtil::FromChars<u32>("123abc", 10, &endptr), std::optional<u32>(123));
ASSERT_EQ(endptr, "abc"sv);
ASSERT_EQ(StringUtil::FromChars<float>("1.0g", &endptr), std::optional<float>(1.0f));
ASSERT_EQ(endptr, "g"sv);
ASSERT_EQ(StringUtil::FromChars<float>("2x", &endptr), std::optional<float>(2.0f));
ASSERT_EQ(endptr, "x"sv);
ASSERT_EQ(StringUtil::FromChars<float>(".1p", &endptr), std::optional<float>(0.1f));
ASSERT_EQ(endptr, "p"sv);
ASSERT_EQ(StringUtil::FromChars<float>("1", &endptr), std::optional<float>(1.0f));
ASSERT_TRUE(endptr.empty());
}
#if 0
// NOTE: These tests are disabled, because they require the da_DK locale to actually be present.
// Which probably isn't going to be the case on the CI.