1 // Copyright 2021 The Pigweed Authors
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License"); you may not
4 // use this file except in compliance with the License. You may obtain a copy of
5 // the License at
6 //
7 // https://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
11 // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12 // License for the specific language governing permissions and limitations under
13 // the License.
14
15 #include "pw_containers/wrapped_iterator.h"
16
17 #include <array>
18
19 #include "gtest/gtest.h"
20
21 namespace pw::containers {
22 namespace {
23
24 class HalfIterator : public WrappedIterator<HalfIterator, const int*, int> {
25 public:
HalfIterator(const int * it)26 constexpr HalfIterator(const int* it) : WrappedIterator(it) {}
27
operator *() const28 int operator*() const { return value() / 2; }
29 };
30
31 constexpr std::array<int, 6> kArray{0, 2, 4, 6, 8, 10};
32
TEST(WrappedIterator,IterateForwards)33 TEST(WrappedIterator, IterateForwards) {
34 int expected = 0;
35 for (HalfIterator it(kArray.begin()); it != HalfIterator(kArray.end());
36 ++it) {
37 EXPECT_EQ(*it, expected);
38 expected += 1;
39 }
40 }
41
TEST(WrappedIterator,IterateBackwards)42 TEST(WrappedIterator, IterateBackwards) {
43 HalfIterator it(kArray.end());
44
45 int expected = 5;
46 do {
47 --it;
48 EXPECT_EQ(*it, expected);
49 expected -= 1;
50 } while (it != HalfIterator(kArray.begin()));
51 }
52
TEST(WrappedIterator,PostIncrement)53 TEST(WrappedIterator, PostIncrement) {
54 HalfIterator it(kArray.begin());
55 EXPECT_EQ(it++, HalfIterator(kArray.begin()));
56 EXPECT_EQ(it, HalfIterator(kArray.begin() + 1));
57 EXPECT_EQ(*it, 1);
58 }
59
TEST(WrappedIterator,PreIncrement)60 TEST(WrappedIterator, PreIncrement) {
61 HalfIterator it(kArray.begin());
62 EXPECT_EQ(++it, HalfIterator(kArray.begin() + 1));
63 EXPECT_EQ(*it, 1);
64 }
65
TEST(WrappedIterator,PostDecrement)66 TEST(WrappedIterator, PostDecrement) {
67 HalfIterator it(kArray.end());
68 EXPECT_EQ(it--, HalfIterator(kArray.end()));
69 EXPECT_EQ(it, HalfIterator(kArray.end() - 1));
70 EXPECT_EQ(*it, 5);
71 }
72
TEST(WrappedIterator,PreDecrement)73 TEST(WrappedIterator, PreDecrement) {
74 HalfIterator it(kArray.end());
75 EXPECT_EQ(--it, HalfIterator(kArray.end() - 1));
76 EXPECT_EQ(*it, 5);
77 }
78
79 } // namespace
80 } // namespace pw::containers
81