Commit fa64df9d authored by Dominik Charousset's avatar Dominik Charousset

Fix unsafe use of strncmp

parent 91148be1
...@@ -102,16 +102,18 @@ string_view string_view::substr(size_type pos, size_type n) const noexcept { ...@@ -102,16 +102,18 @@ string_view string_view::substr(size_type pos, size_type n) const noexcept {
} }
int string_view::compare(string_view str) const noexcept { int string_view::compare(string_view str) const noexcept {
auto s0 = size(); // TODO: use lexicographical_compare_three_way when switching to C++20
auto s1 = str.size(); auto i0 = begin();
auto fallback = [](int x, int y) { auto e0 = end();
return x == 0 ? y : x; auto i1 = str.begin();
}; auto e1 = str.end();
if (s0 == s1) while (i0 != e0 && i1 != e1)
return strncmp(data(), str.data(), s0); if (auto diff = *i0++ - *i1++; diff != 0)
else if (s0 < s1) return diff;
return fallback(strncmp(data(), str.data(), s0), -1); if (i0 == e0)
return fallback(strncmp(data(), str.data(), s1), 1); return i1 != e1 ? -1 : 0;
else
return i1 == e1 ? 1 : 0;
} }
int string_view::compare(size_type pos1, size_type n1, int string_view::compare(size_type pos1, size_type n1,
......
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