xref: /aosp_15_r20/external/pigweed/pw_containers/examples/intrusive_list.cc (revision 61c4878ac05f98d0ceed94b57d316916de578985)
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/intrusive_list.h"
16 
17 #include "pw_unit_test/framework.h"
18 
19 namespace examples {
20 
21 // DOCSTAG: [pw_containers-intrusive_list]
22 
23 using pw::containers::future::IntrusiveList;
24 
25 class IntWrapper : public IntrusiveList<IntWrapper>::Item {
26  public:
IntWrapper(int value)27   IntWrapper(int value) : value_(value) {}
value() const28   int value() const { return value_; }
29 
30  private:
31   const int value_;
32 };
33 
34 // This example is adapted from https://en.cppreference.com/w/cpp/container/list
CreateAndSum()35 int CreateAndSum() {
36   // Create a list containing integers
37   std::array<IntWrapper, 4> wrappers = {{{6}, {7}, {3}, {0}}};
38   IntrusiveList<IntWrapper> list(wrappers.begin(), wrappers.end());
39 
40   // Add an integer to the front of the list
41   IntWrapper eight(8);
42   list.push_front(eight);
43 
44   // Add an integer to the back of the list
45   IntWrapper nine(9);
46   list.push_back(nine);
47 
48   // Insert an integer before 3 by searching
49   IntWrapper five(5);
50   auto it = list.begin();
51   while (it != list.end()) {
52     if (it->value() == 3) {
53       list.insert(it, five);
54       break;
55     }
56     ++it;
57   }
58 
59   // Sum the list
60   int sum = 0;
61   for (const auto& wrapper : list) {
62     sum += wrapper.value();
63   }
64 
65   // It is an error for items to go out of scope while still listed, or for a
66   // list to go out of scope while it still has items.
67   list.clear();
68 
69   return sum;
70 }
71 
72 // DOCSTAG: [pw_containers-intrusive_list]
73 
74 }  // namespace examples
75 
76 namespace {
77 
TEST(IntrusiveListExampleTest,CreateAndSum)78 TEST(IntrusiveListExampleTest, CreateAndSum) {
79   EXPECT_EQ(examples::CreateAndSum(), 8 + 6 + 7 + 5 + 3 + 0 + 9);
80 }
81 
82 }  // namespace
83