[llvm] 6b4b8dc - [ADT] Relax iterator constraints on all_equal (#106400)
via llvm-commits
llvm-commits at lists.llvm.org
Wed Aug 28 13:02:38 PDT 2024
Author: aws-taylor
Date: 2024-08-28T16:02:35-04:00
New Revision: 6b4b8dc4a45dccec43a9c0d76a80ebae50df55b0
URL: https://github.com/llvm/llvm-project/commit/6b4b8dc4a45dccec43a9c0d76a80ebae50df55b0
DIFF: https://github.com/llvm/llvm-project/commit/6b4b8dc4a45dccec43a9c0d76a80ebae50df55b0.diff
LOG: [ADT] Relax iterator constraints on all_equal (#106400)
The previous `all_equal` implementation contained `Begin + 1`, which
implicitly requires `Begin` to model the
[random_access_iterator](https://en.cppreference.com/w/cpp/iterator/random_access_iterator)
concept due to the usage of the `+` operator. By swapping this out with
`std::next`, this method can be used with weaker iterator concepts, such
as
[forward_iterator](https://en.cppreference.com/w/cpp/iterator/forward_iterator).
---------
Co-authored-by: Jakub Kuderski <kubakuderski at gmail.com>
Added:
Modified:
llvm/include/llvm/ADT/STLExtras.h
llvm/unittests/ADT/STLExtrasTest.cpp
Removed:
################################################################################
diff --git a/llvm/include/llvm/ADT/STLExtras.h b/llvm/include/llvm/ADT/STLExtras.h
index b2df0cd650ad7b..e11d6cac7685e4 100644
--- a/llvm/include/llvm/ADT/STLExtras.h
+++ b/llvm/include/llvm/ADT/STLExtras.h
@@ -2062,7 +2062,7 @@ bool equal(L &&LRange, R &&RRange, BinaryPredicate P) {
template <typename R> bool all_equal(R &&Range) {
auto Begin = adl_begin(Range);
auto End = adl_end(Range);
- return Begin == End || std::equal(Begin + 1, End, Begin);
+ return Begin == End || std::equal(std::next(Begin), End, Begin);
}
/// Returns true if all Values in the initializer lists are equal or the list
diff --git a/llvm/unittests/ADT/STLExtrasTest.cpp b/llvm/unittests/ADT/STLExtrasTest.cpp
index b7dc15bf60af51..ee8299c9b48612 100644
--- a/llvm/unittests/ADT/STLExtrasTest.cpp
+++ b/llvm/unittests/ADT/STLExtrasTest.cpp
@@ -15,6 +15,7 @@
#include <climits>
#include <cstddef>
#include <initializer_list>
+#include <iterator>
#include <list>
#include <tuple>
#include <type_traits>
@@ -831,6 +832,26 @@ TEST(STLExtrasTest, AllEqual) {
EXPECT_FALSE(all_equal(V));
}
+// Test to verify that all_equal works with a container that does not
+// model the random access iterator concept.
+TEST(STLExtrasTest, AllEqualNonRandomAccess) {
+ std::list<int> V;
+ static_assert(!std::is_convertible_v<
+ std::iterator_traits<decltype(V)::iterator>::iterator_category,
+ std::random_access_iterator_tag>);
+ EXPECT_TRUE(all_equal(V));
+
+ V.push_back(1);
+ EXPECT_TRUE(all_equal(V));
+
+ V.push_back(1);
+ V.push_back(1);
+ EXPECT_TRUE(all_equal(V));
+
+ V.push_back(2);
+ EXPECT_FALSE(all_equal(V));
+}
+
TEST(STLExtrasTest, AllEqualInitializerList) {
EXPECT_TRUE(all_equal({1}));
EXPECT_TRUE(all_equal({1, 1}));
More information about the llvm-commits
mailing list