]> git.ipfire.org Git - thirdparty/pdns.git/commitdiff
Introduce pdns_ilexicographical_compare_three_way()...
authorMiod Vallat <miod.vallat@powerdns.com>
Thu, 26 Jun 2025 06:23:11 +0000 (08:23 +0200)
committerMiod Vallat <miod.vallat@powerdns.com>
Thu, 26 Jun 2025 06:23:11 +0000 (08:23 +0200)
...and rewrite pdns_ilexicographical_compare() and pdns_iequals() as
trivial wrappers around it.

Signed-off-by: Miod Vallat <miod.vallat@powerdns.com>
pdns/misc.hh

index eb4ee3afc30beb35a1aa3a99c586e58dffe6b8cf..b6c3f44e4e96a46c8f2381c3f46b9a75452eafcb 100644 (file)
@@ -372,23 +372,35 @@ inline bool operator<(const struct timespec& lhs, const struct timespec& rhs)
 }
 
 
-inline bool pdns_ilexicographical_compare(const std::string& a, const std::string& b)  __attribute__((pure));
-inline bool pdns_ilexicographical_compare(const std::string& a, const std::string& b)
+inline int pdns_ilexicographical_compare_three_way(std::string_view a, std::string_view b)  __attribute__((pure));
+inline int pdns_ilexicographical_compare_three_way(std::string_view a, std::string_view b)
 {
-  const unsigned char *aPtr = (const unsigned char*)a.c_str(), *bPtr = (const unsigned char*)b.c_str();
+  const unsigned char *aPtr = (const unsigned char*)a.data(), *bPtr = (const unsigned char*)b.data();
   const unsigned char *aEptr = aPtr + a.length(), *bEptr = bPtr + b.length();
   while(aPtr != aEptr && bPtr != bEptr) {
     if (*aPtr != *bPtr) {
       if (int rc = dns_tolower(*aPtr) - dns_tolower(*bPtr); rc != 0) {
-        return rc < 0;
+        return rc;
       }
     }
     aPtr++;
     bPtr++;
   }
-  if(aPtr == aEptr && bPtr == bEptr) // strings are equal (in length)
-    return false;
-  return aPtr == aEptr; // true if first string was shorter
+  if (aPtr == aEptr) {
+    if (bPtr != bEptr) {
+      return -1; // a < b
+    }
+  }
+  else {
+    return 1; // a > b
+  }
+  return 0; // a == b
+}
+
+inline bool pdns_ilexicographical_compare(const std::string& a, const std::string& b)  __attribute__((pure));
+inline bool pdns_ilexicographical_compare(const std::string& a, const std::string& b)
+{
+  return pdns_ilexicographical_compare_three_way(a, b) < 0;
 }
 
 inline bool pdns_iequals(const std::string& a, const std::string& b) __attribute__((pure));
@@ -397,15 +409,7 @@ inline bool pdns_iequals(const std::string& a, const std::string& b)
   if (a.length() != b.length())
     return false;
 
-  const char *aPtr = a.c_str(), *bPtr = b.c_str();
-  const char *aEptr = aPtr + a.length();
-  while(aPtr != aEptr) {
-    if((*aPtr != *bPtr) && (dns_tolower(*aPtr) != dns_tolower(*bPtr)))
-      return false;
-    aPtr++;
-    bPtr++;
-  }
-  return true;
+  return pdns_ilexicographical_compare_three_way(a, b) == 0;
 }
 
 inline bool pdns_iequals_ch(const char a, const char b) __attribute__((pure));