Vectors#
pw_containers: Generic collections of objects for embedded devices
A vector is a one-dimensional array with a variable length. Pigweed’s vector type differs from the standard library in that it is backed by a fixed-size buffer.
pw::Vector#
Vectors must be declared with an explicit maximum size
(e.g. Vector<int, 10>
) but vectors can be used and referred to without the
max size template parameter (e.g. Vector<int>
).
To allow referring to a pw::Vector
without an explicit maximum size, all
Vector classes inherit from the generic Vector<T>
, which stores the maximum
size in a variable. This allows Vectors to be used without having to know
their maximum size at compile time. It also keeps code size small since
function implementations are shared for all maximum sizes.
Example#
1class Publisher {
2 public:
3 using Subscriber = pw::Function<void(const Message&)>;
4 static constexpr size_t kMaxSubscribers = 10;
5
6 pw::Status Subscribe(Subscriber&& subscriber) {
7 // Check if the vector's fixed capacity has been exhausted.
8 if (subscribers_.full()) {
9 return pw::Status::ResourceExhausted();
10 }
11
12 // Add the subscriber to the vector.
13 subscribers_.emplace_back(std::move(subscriber));
14 return pw::OkStatus();
15 }
16
17 void Publish(const Message& message) {
18 // Iterate over the vector.
19 for (auto& subscriber : subscribers_) {
20 subscriber(message);
21 }
22 }
23
24 private:
25 pw::Vector<Subscriber, kMaxSubscribers> subscribers_;
26};
API reference#
The Vector class is similar to std::vector
, except it is backed by a
fixed-size buffer.
Size report#
The tables below illustrate the following scenarios:
The memory and code size cost incurred by a adding a single
Vector
.The memory and code size cost incurred by adding another
Vector
with the same type as the first scenario, but with a different size. AsVector
is templated on both type and size, a different size results in additional code being generated.The memory and code size cost incurred by adding another
Vector
with the same size as the first scenario, but with a different type. AsVector
is templated on both type and size, a different size results in additional code being generated.
Note
The size report that is usually displayed here is temporarily unavailable while we migrate the pigweed.dev build system from GN to Bazel. See b/388905812 for updates.