1 // Copyright 2024 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 "pw_unit_test/framework.h"
18
19 namespace examples {
20
21 // DOCSTAG: [pw_containers-wrapped_iterator]
22
23 using pw::containers::WrappedIterator;
24
25 // Multiplies values in a std::array by two.
26 class DoubleIterator : public WrappedIterator<DoubleIterator, const int*, int> {
27 public:
DoubleIterator(const int * it)28 constexpr DoubleIterator(const int* it) : WrappedIterator(it) {}
operator *() const29 int operator*() const { return value() * 2; }
30 };
31
32 // Returns twice the sum of the elements in a array of integers.
33 template <size_t kArraySize>
DoubleSum(const std::array<int,kArraySize> & c)34 int DoubleSum(const std::array<int, kArraySize>& c) {
35 int sum = 0;
36 for (DoubleIterator it(c.data()); it != DoubleIterator(c.data() + c.size());
37 ++it) {
38 // The iterator yields doubles instead of the original values.
39 sum += *it;
40 }
41 return sum;
42 }
43
44 // DOCSTAG: [pw_containers-wrapped_iterator]
45
46 } // namespace examples
47
48 namespace {
49
TEST(WrappedIteratorExampleTest,DoubleSum)50 TEST(WrappedIteratorExampleTest, DoubleSum) {
51 constexpr std::array<int, 6> kArray{0, 1, 2, 3, 4, 5};
52 EXPECT_EQ(examples::DoubleSum(kArray), 30);
53 }
54
55 } // namespace
56