ADT: Add range helpers for pointer_ and pointee_iterator

git-svn-id: https://llvm.org/svn/llvm-project/llvm/trunk@298841 91177308-0d34-0410-b5e6-96231b3b80d8
This commit is contained in:
Justin Bogner 2017-03-27 12:56:12 +00:00
parent cd2a3f9e73
commit acec6edc61
2 changed files with 35 additions and 0 deletions

View File

@ -10,6 +10,7 @@
#ifndef LLVM_ADT_ITERATOR_H
#define LLVM_ADT_ITERATOR_H
#include "llvm/ADT/iterator_range.h"
#include <cstddef>
#include <iterator>
#include <type_traits>
@ -290,6 +291,15 @@ struct pointee_iterator
T &operator*() const { return **this->I; }
};
template <typename RangeT, typename WrappedIteratorT =
decltype(std::begin(std::declval<RangeT>()))>
iterator_range<pointee_iterator<WrappedIteratorT>>
make_pointee_range(RangeT &&Range) {
using PointeeIteratorT = pointee_iterator<WrappedIteratorT>;
return make_range(PointeeIteratorT(std::begin(std::forward<RangeT>(Range))),
PointeeIteratorT(std::end(std::forward<RangeT>(Range))));
}
template <typename WrappedIteratorT,
typename T = decltype(&*std::declval<WrappedIteratorT>())>
class pointer_iterator
@ -307,6 +317,15 @@ public:
const T &operator*() const { return Ptr = &*this->I; }
};
template <typename RangeT, typename WrappedIteratorT =
decltype(std::begin(std::declval<RangeT>()))>
iterator_range<pointer_iterator<WrappedIteratorT>>
make_pointer_range(RangeT &&Range) {
using PointerIteratorT = pointer_iterator<WrappedIteratorT>;
return make_range(PointerIteratorT(std::begin(std::forward<RangeT>(Range))),
PointerIteratorT(std::end(std::forward<RangeT>(Range))));
}
} // end namespace llvm
#endif // LLVM_ADT_ITERATOR_H

View File

@ -118,6 +118,15 @@ TEST(PointeeIteratorTest, SmartPointer) {
EXPECT_EQ(End, I);
}
TEST(PointeeIteratorTest, Range) {
int A[] = {1, 2, 3, 4};
SmallVector<int *, 4> V{&A[0], &A[1], &A[2], &A[3]};
int I = 0;
for (int II : make_pointee_range(V))
EXPECT_EQ(A[I++], II);
}
TEST(FilterIteratorTest, Lambda) {
auto IsOdd = [](int N) { return N % 2 == 1; };
int A[] = {0, 1, 2, 3, 4, 5, 6};
@ -211,6 +220,13 @@ TEST(PointerIterator, Const) {
EXPECT_EQ(A + 4, std::next(*Begin, 4));
}
TEST(PointerIterator, Range) {
int A[] = {1, 2, 3, 4};
int I = 0;
for (int *P : make_pointer_range(A))
EXPECT_EQ(A + I++, P);
}
TEST(ZipIteratorTest, Basic) {
using namespace std;
const SmallVector<unsigned, 6> pi{3, 1, 4, 1, 5, 9};