1 // Copyright 2025 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/vector.h"
16
17 #include <cstddef>
18
19 #include "pw_function/function.h"
20 #include "pw_status/status.h"
21 #include "pw_unit_test/framework.h"
22
23 namespace examples {
24
25 struct Message {};
26
27 // DOCSTAG: [pw_containers-vector]
28
29 class Publisher {
30 public:
31 using Subscriber = pw::Function<void(const Message&)>;
32 static constexpr size_t kMaxSubscribers = 10;
33
Subscribe(Subscriber && subscriber)34 pw::Status Subscribe(Subscriber&& subscriber) {
35 // Check if the vector's fixed capacity has been exhausted.
36 if (subscribers_.full()) {
37 return pw::Status::ResourceExhausted();
38 }
39
40 // Add the subscriber to the vector.
41 subscribers_.emplace_back(std::move(subscriber));
42 return pw::OkStatus();
43 }
44
Publish(const Message & message)45 void Publish(const Message& message) {
46 // Iterate over the vector.
47 for (auto& subscriber : subscribers_) {
48 subscriber(message);
49 }
50 }
51
52 private:
53 pw::Vector<Subscriber, kMaxSubscribers> subscribers_;
54 };
55
56 // DOCSTAG: [pw_containers-vector]
57
58 } // namespace examples
59
60 namespace {
61
TEST(VectorExampleTest,PublishMessages)62 TEST(VectorExampleTest, PublishMessages) {
63 examples::Publisher publisher;
64 examples::Message ignored;
65 size_t count1 = 0;
66 size_t count2 = 0;
67 auto status = pw::OkStatus();
68
69 status =
70 publisher.Subscribe([&count1](const examples::Message&) { ++count1; });
71 EXPECT_EQ(status, pw::OkStatus());
72 publisher.Publish(ignored);
73 EXPECT_EQ(count1, 1U);
74 EXPECT_EQ(count2, 0U);
75
76 status =
77 publisher.Subscribe([&count2](const examples::Message&) { ++count2; });
78 EXPECT_EQ(status, pw::OkStatus());
79 publisher.Publish(ignored);
80 publisher.Publish(ignored);
81 EXPECT_EQ(count1, 3U);
82 EXPECT_EQ(count2, 2U);
83 }
84
85 } // namespace
86