From a88fb9809dae046915dabf5a0c12e9837f7b5727 Mon Sep 17 00:00:00 2001 From: Danny Robson Date: Tue, 15 Feb 2022 13:22:03 +1000 Subject: [PATCH] string: correct the lower comparator for cstrings --- string.hpp | 4 ++-- test/string.cpp | 47 +++++++++++++++++++++++++++++++++++++++++++---- 2 files changed, 45 insertions(+), 6 deletions(-) diff --git a/string.hpp b/string.hpp index 78b61805..64a5f0d1 100644 --- a/string.hpp +++ b/string.hpp @@ -312,7 +312,7 @@ namespace cruft::string { struct less { bool operator() (char const *a, char const *b) const noexcept { - for (; a && b; ++a, ++b) { + for (; *a && *b; ++a, ++b) { auto const &a_val = TransformV (*a); auto const &b_val = TransformV (*b); @@ -322,7 +322,7 @@ namespace cruft::string { return false; } - return a == nullptr && b != nullptr; + return *a == '\0' && *b != '\0'; } bool operator() (std::string const &a, std::string const & b) const noexcept diff --git a/test/string.cpp b/test/string.cpp index ee5c959f..e9ff3424 100644 --- a/test/string.cpp +++ b/test/string.cpp @@ -226,7 +226,46 @@ void test_comparator_less (cruft::TAP::logger &tap) /////////////////////////////////////////////////////////////////////////////// -void test_comparator_lower (cruft::TAP::logger &tap) +void test_less_lower (cruft::TAP::logger &tap) +{ + struct { + char const *a; + char const *b; + bool expected; + char const *message; + } const TESTS[] = { + { "a", "b", true, "single letter lhs" }, + { "b", "a", false, "single letter rhs" }, + + { "a", "a", false, "single lower equal" }, + { "a", "A", false, "lower, upper singles" }, + { "A", "a", false, "upper, lower singles" }, + + { "a", "aa", true, "shorter lhs" }, + { "aa", "a", false, "shorter hhs" }, + + { "date", "User-Agent", true, "lower lhs, upper rhs" }, + }; + + cruft::string::less_lower cmp; + + for (auto const &t: TESTS) { + tap.expect_eq (cmp (t.a, t.b), t.expected, "less::lower, pointers, {}", t.message); + tap.expect_eq ( + cmp ( + std::string_view {t.a}, + std::string_view {t.b} + ), + t.expected, + "less::lower, string_view, {}", + t.message + ); + } +} + + +/////////////////////////////////////////////////////////////////////////////// +void test_equality_lower (cruft::TAP::logger &tap) { struct { char const *a; @@ -243,9 +282,8 @@ void test_comparator_lower (cruft::TAP::logger &tap) cruft::string::equality::lower cmp; - for (auto const &t: TESTS) { + for (auto const &t: TESTS) tap.expect_eq (cmp (t.a, t.b), t.equal, "equality::lower, pointers, {}", t.message); - } } @@ -261,7 +299,8 @@ main (int, char**) test_position (tap); test_contains (tap); test_comparator_less (tap); - test_comparator_lower (tap); + test_less_lower (tap); + test_equality_lower (tap); return tap.status (); } \ No newline at end of file