Skip to content

Commit

Permalink
Extend base::Reversed to support iterating arrays
Browse files Browse the repository at this point in the history
C++11's range-based for syntax supports iterating arrays,
so it makes sense to support arrays in base::Reversed too.

Review URL: https://codereview.chromium.org/1360423002

Cr-Commit-Position: refs/heads/master@{#354181}
  • Loading branch information
mdempsky authored and Commit bot committed Oct 15, 2015
1 parent 92a1f51 commit 1379782
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 2 deletions.
25 changes: 24 additions & 1 deletion base/containers/adapters.h
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,10 @@
#ifndef BASE_CONTAINERS_ADAPTERS_H_
#define BASE_CONTAINERS_ADAPTERS_H_

#include <stddef.h>

#include <iterator>

#include "base/macros.h"

namespace base {
Expand All @@ -15,11 +19,13 @@ namespace internal {
template <typename T>
class ReversedAdapter {
public:
typedef decltype(static_cast<T*>(nullptr)->rbegin()) Iterator;
using Iterator = decltype(static_cast<T*>(nullptr)->rbegin());

explicit ReversedAdapter(T& t) : t_(t) {}
ReversedAdapter(const ReversedAdapter& ra) : t_(ra.t_) {}

// TODO(mdempsky): Once we can use C++14 library features, use std::rbegin
// and std::rend instead, so we can remove the specialization below.
Iterator begin() const { return t_.rbegin(); }
Iterator end() const { return t_.rend(); }

Expand All @@ -29,6 +35,23 @@ class ReversedAdapter {
DISALLOW_ASSIGN(ReversedAdapter);
};

template <typename T, size_t N>
class ReversedAdapter<T[N]> {
public:
using Iterator = std::reverse_iterator<T*>;

explicit ReversedAdapter(T (&t)[N]) : t_(t) {}
ReversedAdapter(const ReversedAdapter& ra) : t_(ra.t_) {}

Iterator begin() const { return Iterator(&t_[N]); }
Iterator end() const { return Iterator(&t_[0]); }

private:
T (&t_)[N];

DISALLOW_ASSIGN(ReversedAdapter);
};

} // namespace internal

// Reversed returns a container adapter usable in a range-based "for" statement
Expand Down
14 changes: 13 additions & 1 deletion base/containers/adapters_unittest.cc
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,19 @@ TEST(AdaptersTest, Reversed) {
EXPECT_EQ(101, v[2]);
}

TEST(AdaptersTest, ConstReversed) {
TEST(AdaptersTest, ReversedArray) {
int v[3] = {3, 2, 1};
int j = 0;
for (int& i : base::Reversed(v)) {
EXPECT_EQ(++j, i);
i += 100;
}
EXPECT_EQ(103, v[0]);
EXPECT_EQ(102, v[1]);
EXPECT_EQ(101, v[2]);
}

TEST(AdaptersTest, ReversedConst) {
std::vector<int> v;
v.push_back(3);
v.push_back(2);
Expand Down

0 comments on commit 1379782

Please sign in to comment.