• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2023 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 #pragma once
16 #include <pw_assert/check.h>
17 
18 #include <cstddef>
19 #include <queue>
20 
21 #include "pw_bluetooth_sapphire/internal/host/common/inspect.h"
22 
23 namespace bt {
24 
25 // This class is intended to represent a list node in Inspect, which doesn't
26 // support lists natively. Furthermore, it makes sure that the number of list
27 // items doesn't exceed |capacity|.
28 //
29 // Each item in BoundedInspectListNode is represented as a child node with name
30 // as index. This index is always increasing and does not wrap around. For
31 // example, if capacity is 3, then the children names are `[0, 1, 2]` on the
32 // first three additions. When a new node is added, `0` is popped, and the
33 // children names are `[1, 2, 3]`.
34 //
35 // Example Usage:
36 //    BoundedInspectListNode list(/*capacity=*/2);
37 //    list.AttachInspect(parent_node);
38 //
39 //    auto& item_0 = list.CreateItem();
40 //    item_0.node.RecordInt("property_0", 0);
41 //
42 //    auto& item_1 = list.CreateItem();
43 //    item_1.node.RecordInt("property_A", 1);
44 //    item_1.node.RecordInt("property_B", 2);
45 //
46 // Inspect Tree:
47 //     example_list:
48 //         0:
49 //             property_0: 0
50 //         1:
51 //             property_A: 1
52 //             property_B: 2
53 class BoundedInspectListNode {
54  public:
55   struct Item {
56     // The list child node with the index as it's name (0, 1, 2...).
57     inspect::Node node;
58   };
59 
BoundedInspectListNode(size_t capacity)60   explicit BoundedInspectListNode(size_t capacity) : capacity_(capacity) {
61     PW_CHECK(capacity_ > 0u);
62   }
63   ~BoundedInspectListNode() = default;
64 
65   // Attach this node as a child of |parent| with the name |name|.
66   void AttachInspect(inspect::Node& parent, std::string name);
67 
68   // Add an item to the list, removing a previous item if the list is at
69   // capacity. The returned item reference is valid until the next item is added
70   // (or this list node is destroyed).
71   Item& CreateItem();
72 
73  private:
74   inspect::Node list_node_;
75   size_t next_index_ = 0;
76   const size_t capacity_;
77   std::queue<Item> items_;
78 };
79 
80 }  // namespace bt
81