1 // Copyright 2014 The Chromium Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style license that can be 3 // found in the LICENSE file. 4 5 // Slightly adapted for inclusion in V8. 6 // Copyright 2014 the V8 project authors. All rights reserved. 7 8 #ifndef V8_BASE_ADAPTERS_H_ 9 #define V8_BASE_ADAPTERS_H_ 10 11 #include <iterator> 12 13 #include "src/base/macros.h" 14 15 namespace v8 { 16 namespace base { 17 18 // Internal adapter class for implementing base::Reversed. 19 template <typename T> 20 class ReversedAdapter { 21 public: 22 using Iterator = 23 std::reverse_iterator<decltype(std::begin(std::declval<T>()))>; 24 ReversedAdapter(T & t)25 explicit ReversedAdapter(T& t) : t_(t) {} 26 ReversedAdapter(const ReversedAdapter& ra) = default; 27 28 // TODO(clemensh): Use std::rbegin/std::rend once we have C++14 support. begin()29 Iterator begin() const { return Iterator(std::end(t_)); } end()30 Iterator end() const { return Iterator(std::begin(t_)); } 31 32 private: 33 T& t_; 34 35 DISALLOW_ASSIGN(ReversedAdapter); 36 }; 37 38 // Reversed returns a container adapter usable in a range-based "for" statement 39 // for iterating a reversible container in reverse order. 40 // 41 // Example: 42 // 43 // std::vector<int> v = ...; 44 // for (int i : base::Reversed(v)) { 45 // // iterates through v from back to front 46 // } 47 template <typename T> Reversed(T & t)48ReversedAdapter<T> Reversed(T& t) { 49 return ReversedAdapter<T>(t); 50 } 51 52 } // namespace base 53 } // namespace v8 54 55 #endif // V8_BASE_ADAPTERS_H_ 56