Poco::trim*() code cleanup - use ptrdiff_t instead of int; additional test cases

This commit is contained in:
Günter Obiltschnig 2021-06-14 21:55:13 +02:00
parent 2f9c7cd6d3
commit 7d267378f5
2 changed files with 32 additions and 8 deletions

View File

@ -58,7 +58,7 @@ S trimRight(const S& str)
/// Returns a copy of str with all trailing
/// whitespace removed.
{
int pos = int(str.size()) - 1;
std::ptrdiff_t pos = static_cast<std::ptrdiff_t>(str.size()) - 1;
while (pos >= 0 && Ascii::isSpace(str[pos])) --pos;
return S(str, 0, pos + 1);
@ -69,7 +69,7 @@ template <class S>
S& trimRightInPlace(S& str)
/// Removes all trailing whitespace in str.
{
int pos = int(str.size()) - 1;
std::ptrdiff_t pos = static_cast<std::ptrdiff_t>(str.size()) - 1;
while (pos >= 0 && Ascii::isSpace(str[pos])) --pos;
str.resize(pos + 1);
@ -83,8 +83,8 @@ S trim(const S& str)
/// Returns a copy of str with all leading and
/// trailing whitespace removed.
{
int first = 0;
int last = int(str.size()) - 1;
std::ptrdiff_t first = 0;
std::ptrdiff_t last = static_cast<std::ptrdiff_t>(str.size()) - 1;
while (first <= last && Ascii::isSpace(str[first])) ++first;
while (last >= first && Ascii::isSpace(str[last])) --last;
@ -97,8 +97,8 @@ template <class S>
S& trimInPlace(S& str)
/// Removes all leading and trailing whitespace in str.
{
int first = 0;
int last = int(str.size()) - 1;
std::ptrdiff_t first = 0;
std::ptrdiff_t last = static_cast<std::ptrdiff_t>(str.size()) - 1;
while (first <= last && Ascii::isSpace(str[first])) ++first;
while (last >= first && Ascii::isSpace(str[last])) --last;

View File

@ -89,8 +89,12 @@ void StringTest::testTrimLeft()
std::string s = " abc ";
assertTrue (trimLeft(s) == "abc ");
{
std::string s = " ab c ";
assertTrue (trimLeft(s) == "ab c ");
std::string s = " ab c ";
assertTrue (trimLeft(s) == "ab c ");
}
{
std::string s;
assertTrue (trimLeft(s) == "");
}
}
@ -109,6 +113,10 @@ void StringTest::testTrimLeftInPlace()
std::string s = " ab c ";
assertTrue (trimLeftInPlace(s) == "ab c ");
}
{
std::string s;
assertTrue (trimLeftInPlace(s) == "");
}
}
@ -126,6 +134,10 @@ void StringTest::testTrimRight()
std::string s = " ab c ";
assertTrue (trimRight(s) == " ab c");
}
{
std::string s;
assertTrue (trimRight(s) == "");
}
}
@ -143,6 +155,10 @@ void StringTest::testTrimRightInPlace()
std::string s = " ab c ";
assertTrue (trimRightInPlace(s) == " ab c");
}
{
std::string s;
assertTrue (trimRightInPlace(s) == "");
}
}
@ -160,6 +176,10 @@ void StringTest::testTrim()
std::string s = " ab c ";
assertTrue (trim(s) == "ab c");
}
{
std::string s;
assertTrue (trim(s) == "");
}
}
@ -177,6 +197,10 @@ void StringTest::testTrimInPlace()
std::string s = " ab c ";
assertTrue (trimInPlace(s) == "ab c");
}
{
std::string s;
assertTrue (trimInPlace(s) == "");
}
}