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 "pw_unit_test/framework.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.data());
36 it != HalfIterator(kArray.data() + kArray.size());
37 ++it) {
38 EXPECT_EQ(*it, expected);
39 expected += 1;
40 }
41 }
42
TEST(WrappedIterator,IterateBackwards)43 TEST(WrappedIterator, IterateBackwards) {
44 HalfIterator it(kArray.data() + kArray.size());
45
46 int expected = 5;
47 do {
48 --it;
49 EXPECT_EQ(*it, expected);
50 expected -= 1;
51 } while (it != HalfIterator(kArray.data()));
52 }
53
TEST(WrappedIterator,PostIncrement)54 TEST(WrappedIterator, PostIncrement) {
55 HalfIterator it(kArray.data());
56 EXPECT_EQ(it++, HalfIterator(kArray.data()));
57 EXPECT_EQ(it, HalfIterator(kArray.data() + 1));
58 EXPECT_EQ(*it, 1);
59 }
60
TEST(WrappedIterator,PreIncrement)61 TEST(WrappedIterator, PreIncrement) {
62 HalfIterator it(kArray.data());
63 EXPECT_EQ(++it, HalfIterator(kArray.data() + 1));
64 EXPECT_EQ(*it, 1);
65 }
66
TEST(WrappedIterator,PostDecrement)67 TEST(WrappedIterator, PostDecrement) {
68 HalfIterator it(kArray.data() + kArray.size());
69 EXPECT_EQ(it--, HalfIterator(kArray.data() + kArray.size()));
70 EXPECT_EQ(it, HalfIterator(kArray.data() + kArray.size() - 1));
71 EXPECT_EQ(*it, 5);
72 }
73
TEST(WrappedIterator,PreDecrement)74 TEST(WrappedIterator, PreDecrement) {
75 HalfIterator it(kArray.data() + kArray.size());
76 EXPECT_EQ(--it, HalfIterator(kArray.data() + kArray.size() - 1));
77 EXPECT_EQ(*it, 5);
78 }
79
80 } // namespace
81 } // namespace pw::containers
82