From 3b341de8357a31decae27b84b98e442cc954dbca Mon Sep 17 00:00:00 2001 From: Ted John Date: Fri, 24 Feb 2017 21:48:06 +0000 Subject: [PATCH] Fix String::Trim and add test --- src/openrct2/core/String.cpp | 27 ++++++++++----------------- test/tests/StringTest.cpp | 27 +++++++++++++++++++++++++++ test/tests/tests.vcxproj | 3 +-- 3 files changed, 38 insertions(+), 19 deletions(-) create mode 100644 test/tests/StringTest.cpp diff --git a/src/openrct2/core/String.cpp b/src/openrct2/core/String.cpp index 6921dc3eca..5f3fafd435 100644 --- a/src/openrct2/core/String.cpp +++ b/src/openrct2/core/String.cpp @@ -399,36 +399,29 @@ namespace String codepoint_t codepoint; const utf8 * ch = s.c_str(); const utf8 * nextCh; - const utf8 * firstNonWhitespace = nullptr; - const utf8 * lastNonWhitespace = nullptr; + const utf8 * startSubstr = nullptr; + const utf8 * endSubstr = nullptr; while ((codepoint = GetNextCodepoint(ch, &nextCh)) != '\0') { bool isWhiteSpace = codepoint <= WCHAR_MAX && iswspace((wchar_t)codepoint); if (!isWhiteSpace) { - if (firstNonWhitespace == nullptr) + if (startSubstr == nullptr) { - firstNonWhitespace = ch; + startSubstr = ch; } - lastNonWhitespace = ch; + endSubstr = ch; } ch = nextCh; } - if (firstNonWhitespace != nullptr && - firstNonWhitespace != s.c_str()) - { - size_t newStringSize = ch - firstNonWhitespace; - return std::string(firstNonWhitespace, newStringSize); - } - else if (lastNonWhitespace != nullptr) - { - size_t newStringSize = lastNonWhitespace - s.c_str() + 1; - return std::string(s.c_str(), newStringSize); - } - else + if (startSubstr == nullptr) { + // String is all whitespace return std::string(); } + + size_t stringLength = endSubstr - startSubstr + 1; + return std::string(startSubstr, stringLength); } } diff --git a/test/tests/StringTest.cpp b/test/tests/StringTest.cpp new file mode 100644 index 0000000000..46c4bb8be9 --- /dev/null +++ b/test/tests/StringTest.cpp @@ -0,0 +1,27 @@ +#include +#include +#include +#include + +using TCase = std::tuple; + +class StringTest : public testing::TestWithParam +{ +}; + +INSTANTIATE_TEST_CASE_P(TrimData, StringTest, testing::Values( + TCase("string", "string"), + TCase(" string", "string"), + TCase("string ", "string"), + TCase(" some string ", "some string"), + TCase(" ", ""), + TCase("", "") +)); +TEST_P(StringTest, Trim) +{ + auto testCase = GetParam(); + std::string input = std::get<0>(testCase); + std::string expected = std::get<1>(testCase); + std::string actual = String::Trim(input); + ASSERT_EQ(expected, actual); +} diff --git a/test/tests/tests.vcxproj b/test/tests/tests.vcxproj index 29d46cc6ab..02dc0344b5 100644 --- a/test/tests/tests.vcxproj +++ b/test/tests/tests.vcxproj @@ -45,7 +45,6 @@ Console - @@ -56,7 +55,7 @@ + - \ No newline at end of file