Commit 24e5dd05 authored by Marco Bubke's avatar Marco Bubke

Utils: Add compare function for string views

It is more efficient to use compare instead of less and equal together.

Change-Id: I772b03ba02509c0ebc5d5d770be14cf7d5bd431e
Reviewed-by: Tim Jenssen's avatarTim Jenssen <tim.jenssen@qt.io>
parent d45cd9a3
......@@ -146,4 +146,50 @@ bool operator!=(const SmallStringView& first, const SmallStringView& second) noe
return !(first == second);
}
inline
int compare(const SmallStringView& first, const SmallStringView& second) noexcept
{
int sizeDifference = int(first.size() - second.size());
if (sizeDifference == 0)
return std::memcmp(first.data(), second.data(), first.size());
return sizeDifference;
}
namespace Internal {
inline
int reverse_memcmp(const char *first, const char *second, size_t n)
{
const char *currentFirst = first + n;
const char *currentSecond = second + n;
while (n > 0)
{
// If the current characters differ, return an appropriately signed
// value; otherwise, keep searching backwards
if (*currentFirst != *currentSecond)
return *currentFirst - *currentSecond;
--currentFirst;
--currentSecond;
--n;
}
return 0;
}
}
inline
int reverseCompare(const SmallStringView& first, const SmallStringView& second) noexcept
{
int sizeDifference = int(first.size() - second.size());
if (sizeDifference == 0)
return Internal::reverse_memcmp(first.data(), second.data(), first.size());
return sizeDifference;
}
} // namespace Utils
......@@ -1375,3 +1375,24 @@ TEST(SmallString, ShortStringCapacity)
ASSERT_THAT(PathString().shortStringCapacity(), 189);
}
TEST(SmallString, Compare)
{
ASSERT_THAT(Utils::compare("", ""), Eq(0));
ASSERT_THAT(Utils::compare("text", "text"), Eq(0));
ASSERT_THAT(Utils::compare("", "text"), Le(0));
ASSERT_THAT(Utils::compare("textx", "text"), Gt(0));
ASSERT_THAT(Utils::compare("text", "textx"), Le(0));
ASSERT_THAT(Utils::compare("textx", "texta"), Gt(0));
ASSERT_THAT(Utils::compare("texta", "textx"), Le(0));
}
TEST(SmallString, ReverseCompare)
{
ASSERT_THAT(Utils::reverseCompare("", ""), Eq(0));
ASSERT_THAT(Utils::reverseCompare("text", "text"), Eq(0));
ASSERT_THAT(Utils::reverseCompare("", "text"), Le(0));
ASSERT_THAT(Utils::reverseCompare("textx", "text"), Gt(0));
ASSERT_THAT(Utils::reverseCompare("text", "textx"), Le(0));
ASSERT_THAT(Utils::reverseCompare("textx", "texta"), Gt(0));
ASSERT_THAT(Utils::reverseCompare("texta", "textx"), Le(0));
}
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment