Adding range-based STL-like helper APIs. llvm::distance() is the range version of...
[oota-llvm.git] / include / llvm / ADT / iterator_range.h
1 //===- iterator_range.h - A range adaptor for iterators ---------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 /// \file
10 /// This provides a very simple, boring adaptor for a begin and end iterator
11 /// into a range type. This should be used to build range views that work well
12 /// with range based for loops and range based constructors.
13 ///
14 /// Note that code here follows more standards-based coding conventions as it
15 /// is mirroring proposed interfaces for standardization.
16 ///
17 //===----------------------------------------------------------------------===//
18
19 #ifndef LLVM_ADT_ITERATOR_RANGE_H
20 #define LLVM_ADT_ITERATOR_RANGE_H
21
22 #include <utility>
23
24 namespace llvm {
25
26 template <typename Range>
27 struct range_traits {
28   typedef typename Range::difference_type difference_type;
29 };
30
31 /// \brief A range adaptor for a pair of iterators.
32 ///
33 /// This just wraps two iterators into a range-compatible interface. Nothing
34 /// fancy at all.
35 template <typename IteratorT>
36 class iterator_range {
37   IteratorT begin_iterator, end_iterator;
38
39 public:
40   // FIXME: We should be using iterator_traits to determine the
41   // difference_type, but most of our iterators do not expose anything like it.
42   typedef int difference_type;
43
44   iterator_range() {}
45   iterator_range(IteratorT begin_iterator, IteratorT end_iterator)
46       : begin_iterator(std::move(begin_iterator)),
47         end_iterator(std::move(end_iterator)) {}
48
49   IteratorT begin() const { return begin_iterator; }
50   IteratorT end() const { return end_iterator; }
51 };
52
53 /// \brief Determine the distance between the end() and begin() iterators of
54 /// a range. Analogous to std::distance().
55 template <class Range>\r
56 typename range_traits<Range>::difference_type distance(Range R) {\r
57   return std::distance(R.begin(), R.end());\r
58 }
59
60 /// \brief Copies members of a range into the output iterator provided.
61 /// Analogous to std::copy.
62 template <class Range, class OutputIterator>
63 OutputIterator copy(Range In, OutputIterator Result) {
64   return std::copy(In.begin(), In.end(), Result);
65 }
66 }
67
68 #endif