string: add string_less comparator

This commit is contained in:
Danny Robson 2019-05-01 12:38:55 +10:00
parent ed8db05fed
commit 46c2153434
2 changed files with 43 additions and 0 deletions

View File

@ -11,6 +11,10 @@
#include "debug.hpp"
#include "view.hpp"
#include <string>
#include <type_traits>
namespace cruft {
std::string to_utf8 (const wchar_t*);
std::string to_utf8 (const std::wstring&);
@ -194,4 +198,21 @@ namespace cruft {
return val;
}
///////////////////////////////////////////////////////////////////////////
/// A comparator for string-like objects that uses strcmp rather than
/// pointer comparison.
///
/// TODO: handle string and string_view objects
struct string_less {
template <
typename CharT,
typename = std::void_t<typename std::char_traits<CharT>::char_type>
>
bool operator() (CharT const *a, CharT const *b) const noexcept
{
return strcmp (a, b) < 0;
}
};
}

View File

@ -143,6 +143,27 @@ test_contains (cruft::TAP::logger &tap)
}
///////////////////////////////////////////////////////////////////////////////
void test_comparator (cruft::TAP::logger &tap)
{
cruft::string_less cmp;
struct {
char const *a;
char const *b;
bool less;
char const *message;
} const TESTS[] = {
{ "a", "b", true, "single char less-than" },
{ "b", "a", false, "single char not-less-than" },
{ "a", "aa", true, "single/double char less-than" },
};
for (auto const &t: TESTS)
tap.expect_eq (cmp (t.a, t.b), t.less, "string_less, %!", t.message);
}
///////////////////////////////////////////////////////////////////////////////
int
main (int, char**)
@ -152,6 +173,7 @@ main (int, char**)
test_tokeniser (tap);
test_position (tap);
test_contains (tap);
test_comparator (tap);
return tap.status ();
}