Make iree_string_view_compare behave like standard string comparisons
The current implementation compares size first and then uses lexicographic comparison. This is different from standard string comparisons, and therefore surprising. Instead, compare lexicographically first and tie-break with size.
PiperOrigin-RevId: 293154653
diff --git a/iree/base/api.cc b/iree/base/api.cc
index 386a538..28ced9d 100644
--- a/iree/base/api.cc
+++ b/iree/base/api.cc
@@ -160,12 +160,10 @@
IREE_API_EXPORT int IREE_API_CALL
iree_string_view_compare(iree_string_view_t lhs, iree_string_view_t rhs) {
- if (lhs.size < rhs.size) {
- return -1;
- } else if (lhs.size > rhs.size) {
- return 1;
- }
- return strncmp(lhs.data, rhs.data, rhs.size);
+ size_t min_size = std::min(lhs.size, rhs.size);
+ int cmp = strncmp(lhs.data, rhs.data, min_size);
+ if (cmp != 0) return cmp;
+ return rhs.size - lhs.size;
}
IREE_API_EXPORT bool IREE_API_CALL iree_string_view_starts_with(
diff --git a/iree/base/api.h b/iree/base/api.h
index 2f2ecea..1e7658c 100644
--- a/iree/base/api.h
+++ b/iree/base/api.h
@@ -393,7 +393,7 @@
IREE_API_EXPORT iree_string_view_t IREE_API_CALL
iree_make_cstring_view(const char* str);
-// Like strncmp but with iree_string_view_t values.
+// Like std::string::compare but with iree_string_view_t values.
IREE_API_EXPORT int IREE_API_CALL
iree_string_view_compare(iree_string_view_t lhs, iree_string_view_t rhs);