From 46c21534341de712d39bca7b4a872b0f5c6f6541 Mon Sep 17 00:00:00 2001 From: Danny Robson Date: Wed, 1 May 2019 12:38:55 +1000 Subject: [PATCH] string: add string_less comparator --- string.hpp | 21 +++++++++++++++++++++ test/string.cpp | 22 ++++++++++++++++++++++ 2 files changed, 43 insertions(+) diff --git a/string.hpp b/string.hpp index cec21941..19177ece 100644 --- a/string.hpp +++ b/string.hpp @@ -11,6 +11,10 @@ #include "debug.hpp" #include "view.hpp" +#include +#include + + 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::char_type> + > + bool operator() (CharT const *a, CharT const *b) const noexcept + { + return strcmp (a, b) < 0; + } + }; } diff --git a/test/string.cpp b/test/string.cpp index 11056f81..529b2ded 100644 --- a/test/string.cpp +++ b/test/string.cpp @@ -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 (); } \ No newline at end of file