blob: bf40ce5b01ec8553c1e5909e66edc8533421b403 [file] [log] [blame]
James Kuszmaulf5eb4682023-09-22 17:16:59 -07001#ifndef AOS_FLATBUFFERS_STATIC_VECTOR_H_
2#define AOS_FLATBUFFERS_STATIC_VECTOR_H_
3#include <span>
4
5#include "flatbuffers/base.h"
James Kuszmaule65fb402024-01-13 14:10:51 -08006#include "flatbuffers/vector.h"
James Kuszmaulf5eb4682023-09-22 17:16:59 -07007#include "glog/logging.h"
8
9#include "aos/containers/inlined_vector.h"
10#include "aos/containers/sized_array.h"
11#include "aos/flatbuffers/base.h"
12
13namespace aos::fbs {
14
15namespace internal {
16// Helper class for managing how we specialize the Vector object for different
17// contained types.
18// Users of the Vector class should never need to care about this.
19// Template arguments:
20// T: The type that the vector stores.
21// kInline: Whether the type in question is stored inline or not.
22// Enable: Used for SFINAE around struct values; can be ignored.
23// The struct provides the following types:
24// Type: The type of the data that will be stored inline in the vector.
25// ObjectType: The type of the actual data (only used for non-inline objects).
26// FlatbufferType: The type used by flatbuffers::Vector to store this type.
27// ConstFlatbufferType: The type used by a const flatbuffers::Vector to store
28// this type.
29// kDataAlign: Alignment required by the stored type.
30// kDataSize: Nominal size required by each non-inline data member. This is
31// what will be initially allocated; once created, individual members may
32// grow to accommodate dynamically lengthed vectors.
33template <typename T, bool kInline, class Enable = void>
34struct InlineWrapper;
35} // namespace internal
36
37// This Vector class provides a mutable, resizeable, flatbuffer vector.
38//
39// Upon creation, the Vector will start with enough space allocated for
40// kStaticLength elements, and must be provided with a memory buffer that
41// is large enough to serialize all the kStaticLength members (kStaticLength may
42// be zero).
43//
44// Once created, the Vector may be grown using calls to reserve().
45// This will result in the Vector attempting to allocate memory via its
46// parent object; such calls may fail if there is no space available in the
47// allocator.
48//
49// Note that if you are using the Vector class in a realtime context (and thus
50// must avoid dynamic memory allocations) you must only be using a Vector of
51// inline data (i.e., scalars, enums, or structs). Flatbuffer tables and strings
52// require overhead to manage and so require some form of dynamic memory
53// allocation. If we discover a strong use-case for such things, then we may
54// provide some interface that allows managing said metadata on the stack or
55// in another realtime-safe manner.
56//
57// Template arguments:
58// T: Type contained by the vector; either a scalar/struct/enum type or a
59// static flatbuffer type of some sort (a String or an implementation of
60// aos::fbs::Table).
61// kStaticLength: Number of elements to statically allocate memory for.
62// May be zero.
63// kInline: Whether the type T will be stored inline in the vector.
64// kForceAlign: Alignment to force for the start of the vector (e.g., for
65// byte arrays it may be desirable to have the entire array aligned).
66// kNullTerminate: Whether to reserve an extra byte past the end of
67// the inline data for null termination. Not included in kStaticLength,
68// so if e.g. you want to store the string "abc" then kStaticLength can
69// be 3 and kNullTerminate can be true and the vector data will take
70// up 4 bytes of memory.
71//
72// Vector buffer memory layout:
73// * Requirements:
74// * Minimum alignment of 4 bytes (for element count).
75// * The start of the vector data must be aligned to either
76// alignof(InlineType) or a user-specified number.
77// * The element count for the vector must immediately precede the vector
78// data (and so may itself not be aligned to alignof(InlineType)).
79// * For non-inlined types, the individual types must be aligned to
80// their own alignment.
81// * In order to accommodate this, the vector buffer as a whole must
82// generally be aligned to the greatest of the above alignments. There
83// are two reasonable ways one could do this:
84// * Require that the 4th byte of the buffer provided by aligned to
85// the maximum alignment of its contents.
86// * Require that the buffer itself by aligned, and provide padding
87// ourselves. The Vector would then have to expose its own offset
88// because it would not start at the start of the buffer.
89// The former requires that the wrapping code understand the internals
90// of how vectors work; the latter generates extra padding and adds
91// extra logic around handling non-zero offsets.
92// To maintain general simplicity, we will use the second condition and eat
93// the cost of the potential extra few bytes of padding.
94// * The layout of the buffer will thus be:
95// [padding; element_count; inline_data; padding; offset_data]
96// The first padding will be of size max(0, kAlign - 4).
97// The element_count is of size 4.
98// The inline_data is of size sizeof(InlineType) * kStaticLength.
99// The second padding is of size
100// (kAlign - ((sizeof(InlineType) * kStaticLength) % kAlign)).
101// The remaining data is only present if kInline is false.
102// The offset data is of size T::kSize * kStaticLength. T::kSize % T::kAlign
103// must be zero.
104// Note that no padding is required on the end because T::kAlign will always
105// end up being equal to the alignment (this can only be violated if
106// kForceAlign is used, but we do not allow that).
James Kuszmaul1c9693f2023-12-08 09:45:26 -0800107// The Vector class leaves any padding uninitialized. Until and unless we
108// determine that it is a performance issue, it is the responsibility of the
109// parent of this object to zero-initialize the memory.
James Kuszmaulf5eb4682023-09-22 17:16:59 -0700110template <typename T, size_t kStaticLength, bool kInline,
111 size_t kForceAlign = 0, bool kNullTerminate = false>
112class Vector : public ResizeableObject {
James Kuszmaul22448052023-12-14 15:55:14 -0800113 template <typename VectorType, typename ValueType>
114 class generic_iterator {
115 public:
116 using iterator_category = std::random_access_iterator_tag;
117 using value_type = ValueType;
118 using difference_type = std::ptrdiff_t;
119 using pointer = value_type *;
120 using reference = value_type &;
121
122 explicit generic_iterator(VectorType *vector, size_t index)
123 : vector_(vector), index_(index) {}
124 generic_iterator(const generic_iterator &) = default;
125 generic_iterator() : vector_(nullptr), index_(0) {}
126 generic_iterator &operator=(const generic_iterator &) = default;
127
128 generic_iterator &operator++() {
129 ++index_;
130 return *this;
131 }
132 generic_iterator operator++(int) {
133 generic_iterator retval = *this;
134 ++(*this);
135 return retval;
136 }
137 generic_iterator &operator--() {
138 --index_;
139 return *this;
140 }
141 generic_iterator operator--(int) {
142 generic_iterator retval = *this;
143 --(*this);
144 return retval;
145 }
146 bool operator==(const generic_iterator &other) const {
147 CHECK_EQ(other.vector_, vector_);
148 return index_ == other.index_;
149 }
150 std::strong_ordering operator<=>(const generic_iterator &other) const {
151 CHECK_EQ(other.vector_, vector_);
152 return index_ <=> other.index_;
153 }
154 reference operator*() const { return vector_->at(index_); }
155 difference_type operator-(const generic_iterator &other) const {
156 CHECK_EQ(other.vector_, vector_);
157 return index_ - other.index_;
158 }
159 generic_iterator operator-(difference_type decrement) const {
160 return generic_iterator(vector_, index_ - decrement);
161 }
162 friend generic_iterator operator-(difference_type decrement,
163 const generic_iterator &rhs) {
164 return rhs - decrement;
165 }
166 generic_iterator operator+(difference_type increment) const {
167 return generic_iterator(vector_, index_ + increment);
168 }
169 friend generic_iterator operator+(difference_type increment,
170 const generic_iterator &rhs) {
171 return rhs + increment;
172 }
173 generic_iterator &operator+=(difference_type increment) {
174 index_ += increment;
175 return *this;
176 }
177 generic_iterator &operator-=(difference_type increment) {
178 index_ -= increment;
179 return *this;
180 }
181 reference operator[](difference_type index) const {
182 return *(*this + index);
183 }
184
185 private:
186 VectorType *vector_;
187 size_t index_;
188 };
189
James Kuszmaulf5eb4682023-09-22 17:16:59 -0700190 public:
James Kuszmaul22448052023-12-14 15:55:14 -0800191 using iterator = generic_iterator<Vector, T>;
192 using const_iterator = generic_iterator<const Vector, const T>;
193
James Kuszmaulf5eb4682023-09-22 17:16:59 -0700194 static_assert(kInline || !kNullTerminate,
195 "It does not make sense to null-terminate vectors of objects.");
196 // Type stored inline in the serialized vector (offsets for tables/strings; T
197 // otherwise).
198 using InlineType = typename internal::InlineWrapper<T, kInline>::Type;
199 // OUt-of-line type for out-of-line T.
200 using ObjectType = typename internal::InlineWrapper<T, kInline>::ObjectType;
201 // Type used as the template parameter to flatbuffers::Vector<>.
202 using FlatbufferType =
203 typename internal::InlineWrapper<T, kInline>::FlatbufferType;
204 using ConstFlatbufferType =
205 typename internal::InlineWrapper<T, kInline>::ConstFlatbufferType;
James Kuszmaul6be41022023-12-20 11:55:28 -0800206 // FlatbufferObjectType corresponds to the type used by the flatbuffer
207 // "object" API (i.e. the FlatbufferT types).
208 // This type will be something unintelligble for inline types.
209 using FlatbufferObjectType =
210 typename internal::InlineWrapper<T, kInline>::FlatbufferObjectType;
James Kuszmaulf5eb4682023-09-22 17:16:59 -0700211 // flatbuffers::Vector type that corresponds to this Vector.
212 typedef flatbuffers::Vector<FlatbufferType> Flatbuffer;
213 typedef const flatbuffers::Vector<ConstFlatbufferType> ConstFlatbuffer;
214 // Alignment of the inline data.
215 static constexpr size_t kInlineAlign =
216 std::max(kForceAlign, alignof(InlineType));
217 // Type used for serializing the length of the vector.
218 typedef uint32_t LengthType;
219 // Overall alignment of this type, and required alignment of the buffer that
220 // must be provided to the Vector.
221 static constexpr size_t kAlign =
222 std::max({alignof(LengthType), kInlineAlign,
223 internal::InlineWrapper<T, kInline>::kDataAlign});
224 // Padding inserted prior to the length element of the vector (to manage
225 // alignment of the data properly; see class comment)
226 static constexpr size_t kPadding1 =
227 std::max<size_t>(0, kAlign - sizeof(LengthType));
228 // Size of the vector length field.
229 static constexpr size_t kLengthSize = sizeof(LengthType);
230 // Size of all the inline vector data, including null termination (prior to
231 // any dynamic increases in size).
232 static constexpr size_t kInlineSize =
233 sizeof(InlineType) * (kStaticLength + (kNullTerminate ? 1 : 0));
234 // Per-element size of any out-of-line data.
235 static constexpr size_t kDataElementSize =
236 internal::InlineWrapper<T, kInline>::kDataSize;
237 // Padding between the inline data and any out-of-line data, to manage
238 // mismatches in alignment between the two.
239 static constexpr size_t kPadding2 = kAlign - (kInlineSize % kAlign);
240 // Total statically allocated space for any out-of-line data ("offset data")
241 // (prior to any dynamic increases in size).
242 static constexpr size_t kOffsetOffsetDataSize =
243 kInline ? 0 : (kStaticLength * kDataElementSize);
244 // Total nominal size of the Vector.
245 static constexpr size_t kSize =
246 kPadding1 + kLengthSize + kInlineSize + kPadding2 + kOffsetOffsetDataSize;
247 // Offset from the start of the provided buffer to where the actual start of
248 // the vector is.
249 static constexpr size_t kOffset = kPadding1;
250 // Constructors; the provided buffer must be aligned to kAlign and be kSize in
251 // length. parent must be non-null.
252 Vector(std::span<uint8_t> buffer, ResizeableObject *parent)
253 : ResizeableObject(buffer, parent) {
254 CHECK_EQ(0u, reinterpret_cast<size_t>(buffer.data()) % kAlign);
255 CHECK_EQ(kSize, buffer.size());
James Kuszmaulf5eb4682023-09-22 17:16:59 -0700256 SetLength(0u);
James Kuszmaulf5eb4682023-09-22 17:16:59 -0700257 if (!kInline) {
258 // Initialize the offsets for any sub-tables. These are used to track
259 // where each table will get serialized in memory as memory gets
260 // resized/moved around.
261 for (size_t index = 0; index < kStaticLength; ++index) {
262 object_absolute_offsets_.emplace_back(kPadding1 + kLengthSize +
263 kInlineSize + kPadding2 +
264 index * kDataElementSize);
265 }
266 }
267 }
268 Vector(const Vector &) = delete;
269 Vector &operator=(const Vector &) = delete;
270 virtual ~Vector() {}
271 // Current allocated length of this vector.
272 // Does not include null termination.
273 size_t capacity() const { return allocated_length_; }
274 // Current length of the vector.
275 // Does not include null termination.
276 size_t size() const { return length_; }
277
278 // Appends an element to the Vector. Used when kInline is false. Returns
279 // nullptr if the append failed due to insufficient capacity. If you need to
280 // increase the capacity() of the vector, call reserve().
281 [[nodiscard]] T *emplace_back();
282 // Appends an element to the Vector. Used when kInline is true. Returns false
283 // if there is insufficient capacity for a new element.
284 [[nodiscard]] bool emplace_back(T element) {
285 static_assert(kInline);
286 return AddInlineElement(element);
287 }
288
289 // Adjusts the allocated size of the vector (does not affect the actual
290 // current length as returned by size()). Returns true on success, and false
291 // if the allocation failed for some reason.
292 // Note that reductions in size will not currently result in the allocated
293 // size actually changing.
294 [[nodiscard]] bool reserve(size_t new_length) {
295 if (new_length > allocated_length_) {
296 const size_t new_elements = new_length - allocated_length_;
297 // First, we must add space for our new inline elements.
298 if (!InsertBytes(
299 inline_data() + allocated_length_ + (kNullTerminate ? 1 : 0),
300 new_elements * sizeof(InlineType), SetZero::kYes)) {
301 return false;
302 }
303 if (!kInline) {
304 // For non-inline objects, create the space required for all the new
305 // object data.
306 const size_t insertion_point = buffer_.size();
307 if (!InsertBytes(buffer_.data() + insertion_point,
308 new_elements * kDataElementSize, SetZero::kYes)) {
309 return false;
310 }
311 for (size_t index = 0; index < new_elements; ++index) {
312 // Note that the already-allocated data may be arbitrarily-sized, so
313 // we cannot use the same static calculation that we do in the
314 // constructor.
315 object_absolute_offsets_.emplace_back(insertion_point +
316 index * kDataElementSize);
317 }
318 objects_.reserve(new_length);
319 }
320 allocated_length_ = new_length;
321 }
322 return true;
323 }
324
325 // Accessors for using the Vector as a flatbuffers::Vector.
326 // Note that these pointers will be unstable if any memory allocations occur
327 // that cause memory to get shifted around.
James Kuszmaulf5eb4682023-09-22 17:16:59 -0700328 ConstFlatbuffer *AsFlatbufferVector() const {
329 return reinterpret_cast<const Flatbuffer *>(vector_buffer().data());
330 }
331
332 // Copies the contents of the provided vector into this; returns false on
333 // failure (e.g., if the provided vector is too long for the amount of space
334 // we can allocate through reserve()).
James Kuszmaul710883b2023-12-14 14:34:48 -0800335 // This is a deep copy, and will call FromFlatbuffer on any constituent
336 // objects.
James Kuszmaulf5eb4682023-09-22 17:16:59 -0700337 [[nodiscard]] bool FromFlatbuffer(ConstFlatbuffer *vector);
James Kuszmaul6be41022023-12-20 11:55:28 -0800338 // The remaining FromFlatbuffer() overloads are for when using the flatbuffer
339 // "object" API, which uses std::vector's for representing vectors.
340 [[nodiscard]] bool FromFlatbuffer(const std::vector<InlineType> &vector) {
341 static_assert(kInline);
342 return FromData(vector.data(), vector.size());
343 }
344 // Overload for vectors of bools, since the standard library may not use a
345 // full byte per vector element.
346 [[nodiscard]] bool FromFlatbuffer(const std::vector<bool> &vector) {
347 static_assert(kInline);
348 // We won't be able to do a clean memcpy because std::vector<bool> may be
349 // implemented using bit-packing.
350 return FromIterator(vector.cbegin(), vector.cend());
351 }
352 // Overload for non-inline types. Note that to avoid having this overload get
353 // resolved with inline types, we make FlatbufferObjectType != InlineType.
354 [[nodiscard]] bool FromFlatbuffer(
355 const std::vector<FlatbufferObjectType> &vector) {
356 static_assert(!kInline);
357 return FromNotInlineIterable(vector);
358 }
359
360 // Copies values from the provided data pointer into the vector, resizing the
361 // vector as needed to match. Returns false on failure (e.g., if the
362 // underlying allocator has insufficient space to perform the copy). Only
363 // works for inline data types.
364 [[nodiscard]] bool FromData(const InlineType *input_data, size_t input_size) {
365 static_assert(kInline);
366 if (!reserve(input_size)) {
367 return false;
368 }
369
370 // We will be overwriting the whole vector very shortly; there is no need to
371 // clear the buffer to zero.
372 resize_inline(input_size, SetZero::kNo);
373
374 memcpy(inline_data(), input_data, size() * sizeof(InlineType));
375 return true;
376 }
377
378 // Copies values from the provided iterators into the vector, resizing the
379 // vector as needed to match. Returns false on failure (e.g., if the
380 // underlying allocator has insufficient space to perform the copy). Only
381 // works for inline data types.
382 // Does not attempt any optimizations if the iterators meet the
383 // std::contiguous_iterator concept; instead, it simply copies each element
384 // out one-by-one.
385 template <typename Iterator>
386 [[nodiscard]] bool FromIterator(Iterator begin, Iterator end) {
387 static_assert(kInline);
388 resize(0);
389 for (Iterator it = begin; it != end; ++it) {
390 if (!reserve(size() + 1)) {
391 return false;
392 }
393 // Should never fail, due to the reserve() above.
394 CHECK(emplace_back(*it));
395 }
396 return true;
397 }
James Kuszmaulf5eb4682023-09-22 17:16:59 -0700398
399 // Returns the element at the provided index. index must be less than size().
400 const T &at(size_t index) const {
401 CHECK_LT(index, length_);
402 return unsafe_at(index);
403 }
404
405 // Same as at(), except that bounds checks are only performed in non-optimized
406 // builds.
407 // TODO(james): The GetInlineElement() call itself does some bounds-checking;
408 // consider down-grading that.
409 const T &unsafe_at(size_t index) const {
410 DCHECK_LT(index, length_);
411 if (kInline) {
412 // This reinterpret_cast is extremely wrong if T != InlineType (this is
413 // fine because we only do this if kInline is true).
414 // TODO(james): Get the templating improved so that we can get away with
415 // specializing at() instead of using if statements. Resolving this will
416 // also allow deduplicating the Resize() calls.
417 // This specialization is difficult because you cannot partially
418 // specialize a templated class method (online things seem to suggest e.g.
419 // using a struct as the template parameter rather than having separate
420 // parameters).
421 return reinterpret_cast<const T &>(GetInlineElement(index));
422 } else {
423 return objects_[index].t;
424 }
425 }
426
427 // Returns a mutable pointer to the element at the provided index. index must
428 // be less than size().
429 T &at(size_t index) {
430 CHECK_LT(index, length_);
431 return unsafe_at(index);
432 }
433
434 // Same as at(), except that bounds checks are only performed in non-optimized
435 // builds.
436 // TODO(james): The GetInlineElement() call itself does some bounds-checking;
437 // consider down-grading that.
438 T &unsafe_at(size_t index) {
439 DCHECK_LT(index, length_);
440 if (kInline) {
441 // This reinterpret_cast is extremely wrong if T != InlineType (this is
442 // fine because we only do this if kInline is true).
443 // TODO(james): Get the templating improved so that we can get away with
444 // specializing at() instead of using if statements. Resolving this will
445 // also allow deduplicating the Resize() calls.
446 // This specialization is difficult because you cannot partially
447 // specialize a templated class method (online things seem to suggest e.g.
448 // using a struct as the template parameter rather than having separate
449 // parameters).
450 return reinterpret_cast<T &>(GetInlineElement(index));
451 } else {
452 return objects_[index].t;
453 }
454 }
455
456 const T &operator[](size_t index) const { return at(index); }
457 T &operator[](size_t index) { return at(index); }
458
459 // Resizes the vector to the requested size.
460 // size must be less than or equal to the current capacity() of the vector.
461 // Does not allocate additional memory (call reserve() to allocate additional
462 // memory).
463 // Zero-initializes all inline element; initializes all subtable/string
464 // elements to extant but empty objects.
465 void resize(size_t size);
466
467 // Resizes an inline vector to the requested size.
468 // When changing the size of the vector, the removed/inserted elements will be
469 // set to zero if requested. Otherwise, they will be left uninitialized.
470 void resize_inline(size_t size, SetZero set_zero) {
471 CHECK_LE(size, allocated_length_);
472 static_assert(
473 kInline,
474 "Vector::resize_inline() only works for inline vector types (scalars, "
475 "enums, structs).");
476 if (size == length_) {
477 return;
478 }
479 if (set_zero == SetZero::kYes) {
480 memset(
481 reinterpret_cast<void *>(inline_data() + std::min(size, length_)), 0,
482 std::abs(static_cast<ssize_t>(length_) - static_cast<ssize_t>(size)) *
483 sizeof(InlineType));
484 }
485 length_ = size;
486 SetLength(length_);
487 }
488 // Resizes a vector of offsets to the requested size.
489 // If the size is increased, the new elements will be initialized
490 // to empty but extant objects for non-inlined types (so, zero-length
491 // vectors/strings; objects that exist but have no fields populated).
492 // Note that this is always equivalent to resize().
493 void resize_not_inline(size_t size) {
494 CHECK_LE(size, allocated_length_);
495 static_assert(!kInline,
496 "Vector::resize_not_inline() only works for offset vector "
497 "types (objects, strings).");
498 if (size == length_) {
499 return;
500 } else if (length_ > size) {
501 // TODO: Remove any excess allocated memory.
502 length_ = size;
503 SetLength(length_);
504 return;
505 } else {
506 while (length_ < size) {
507 CHECK_NOTNULL(emplace_back());
508 }
509 }
510 }
511
512 // Accessors directly to the inline data of a vector.
513 const T *data() const {
514 static_assert(kInline,
515 "If you have a use-case for directly accessing the "
516 "flatbuffer data pointer for vectors of "
517 "objects/strings, please start a discussion.");
518 return inline_data();
519 }
520
521 T *data() {
522 static_assert(kInline,
523 "If you have a use-case for directly accessing the "
524 "flatbuffer data pointer for vectors of "
525 "objects/strings, please start a discussion.");
526 return inline_data();
527 }
528
James Kuszmaul22448052023-12-14 15:55:14 -0800529 // Iterators to allow easy use with standard C++ features.
530 iterator begin() { return iterator(this, 0); }
531 iterator end() { return iterator(this, size()); }
532 const_iterator begin() const { return const_iterator(this, 0); }
533 const_iterator end() const { return const_iterator(this, size()); }
534
James Kuszmaulf5eb4682023-09-22 17:16:59 -0700535 std::string SerializationDebugString() const {
536 std::stringstream str;
537 str << "Raw Size: " << kSize << " alignment: " << kAlign
538 << " allocated length: " << allocated_length_ << " inline alignment "
539 << kInlineAlign << " kPadding1 " << kPadding1 << "\n";
540 str << "Observed length " << GetLength() << " (expected " << length_
541 << ")\n";
542 str << "Inline Size " << kInlineSize << " Inline bytes/value:\n";
543 // TODO(james): Get pretty-printing for structs so we can provide better
544 // debug.
545 internal::DebugBytes(
546 internal::GetSubSpan(vector_buffer(), kLengthSize,
547 sizeof(InlineType) * allocated_length_),
548 str);
549 str << "kPadding2 " << kPadding2 << " offset data size "
550 << kOffsetOffsetDataSize << "\n";
551 return str.str();
552 }
553
554 protected:
555 friend struct internal::TableMover<
556 Vector<T, kStaticLength, kInline, kForceAlign, kNullTerminate>>;
557 // protected so that the String class can access the move constructor.
558 Vector(Vector &&) = default;
559
560 private:
561 // See kAlign and kOffset.
562 size_t Alignment() const final { return kAlign; }
563 size_t AbsoluteOffsetOffset() const override { return kOffset; }
564 // Returns a buffer that starts at the start of the vector itself (past any
565 // padding).
566 std::span<uint8_t> vector_buffer() {
567 return internal::GetSubSpan(buffer(), kPadding1);
568 }
569 std::span<const uint8_t> vector_buffer() const {
570 return internal::GetSubSpan(buffer(), kPadding1);
571 }
572
573 bool AddInlineElement(InlineType e) {
574 if (length_ == allocated_length_) {
575 return false;
576 }
577 SetInlineElement(length_, e);
578 ++length_;
579 SetLength(length_);
580 return true;
581 }
582
583 void SetInlineElement(size_t index, InlineType value) {
584 CHECK_LT(index, allocated_length_);
585 inline_data()[index] = value;
586 }
587
588 InlineType &GetInlineElement(size_t index) {
589 CHECK_LT(index, allocated_length_);
590 return inline_data()[index];
591 }
592
593 const InlineType &GetInlineElement(size_t index) const {
594 CHECK_LT(index, allocated_length_);
595 return inline_data()[index];
596 }
597
598 // Returns a pointer to the start of the inline data itself.
599 InlineType *inline_data() {
600 return reinterpret_cast<InlineType *>(vector_buffer().data() + kLengthSize);
601 }
602 const InlineType *inline_data() const {
603 return reinterpret_cast<const InlineType *>(vector_buffer().data() +
604 kLengthSize);
605 }
606
607 // Updates the length of the vector to match the provided length. Does not set
608 // the length_ member.
609 void SetLength(LengthType length) {
610 *reinterpret_cast<LengthType *>(vector_buffer().data()) = length;
611 if (kNullTerminate) {
612 memset(reinterpret_cast<void *>(inline_data() + length), 0,
613 sizeof(InlineType));
614 }
615 }
616 LengthType GetLength() const {
617 return *reinterpret_cast<const LengthType *>(vector_buffer().data());
618 }
619
620 // Overrides to allow ResizeableObject to manage memory adjustments.
621 size_t NumberOfSubObjects() const final {
622 return kInline ? 0 : allocated_length_;
623 }
624 using ResizeableObject::SubObject;
625 SubObject GetSubObject(size_t index) final {
626 return SubObject{
627 reinterpret_cast<uoffset_t *>(&GetInlineElement(index)),
628 // In order to let this compile regardless of whether type T is an
629 // object type or not, we just use a reinterpret_cast.
630 (index < length_)
631 ? reinterpret_cast<ResizeableObject *>(&objects_[index].t)
632 : nullptr,
633 &object_absolute_offsets_[index]};
634 }
635 // Implementation that handles copying from a flatbuffers::Vector of an inline
636 // data type.
637 [[nodiscard]] bool FromInlineFlatbuffer(ConstFlatbuffer *vector) {
James Kuszmaul6be41022023-12-20 11:55:28 -0800638 return FromData(
639 reinterpret_cast<const InlineType *>(CHECK_NOTNULL(vector)->Data()),
640 vector->size());
James Kuszmaulf5eb4682023-09-22 17:16:59 -0700641 }
642
643 // Implementation that handles copying from a flatbuffers::Vector of a
644 // not-inline data type.
James Kuszmaul6be41022023-12-20 11:55:28 -0800645 template <typename Iterable>
646 [[nodiscard]] bool FromNotInlineIterable(const Iterable &vector) {
647 if (!reserve(vector.size())) {
James Kuszmaulf5eb4682023-09-22 17:16:59 -0700648 return false;
649 }
650 // "Clear" the vector.
651 resize_not_inline(0);
652
James Kuszmaul6be41022023-12-20 11:55:28 -0800653 for (const auto &entry : vector) {
James Kuszmaulf5eb4682023-09-22 17:16:59 -0700654 if (!CHECK_NOTNULL(emplace_back())->FromFlatbuffer(entry)) {
655 return false;
656 }
657 }
658 return true;
659 }
660
James Kuszmaul6be41022023-12-20 11:55:28 -0800661 [[nodiscard]] bool FromNotInlineFlatbuffer(const Flatbuffer *vector) {
662 return FromNotInlineIterable(*vector);
663 }
664
James Kuszmaulf5eb4682023-09-22 17:16:59 -0700665 // In order to allow for easy partial template specialization, we use a
666 // non-member class to call FromInline/FromNotInlineFlatbuffer and
667 // resize_inline/resize_not_inline. There are not actually any great ways to
668 // do this with just our own class member functions, so instead we make these
669 // methods members of a friend of the Vector class; we then partially
670 // specialize the entire InlineWrapper class and use it to isolate anything
671 // that needs to have a common user interface while still having separate
672 // actual logic.
673 template <typename T_, bool kInline_, class Enable_>
674 friend struct internal::InlineWrapper;
675
676 // Note: The objects here really want to be owned by this object (as opposed
677 // to e.g. returning a stack-allocated object from the emplace_back() methods
678 // that the user then owns). There are two main challenges with have the user
679 // own the object on question:
680 // 1. We can't have >1 reference floating around, or else one object's state
681 // can become out of date. This forces us to do ref-counting and could
682 // make certain types of code obnoxious to write.
683 // 2. Once the user-created object goes out of scope, we lose all of its
684 // internal state. In _theory_ it should be possible to reconstruct most
685 // of the relevant state by examining the contents of the buffer, but
686 // doing so would be cumbersome.
687 aos::InlinedVector<internal::TableMover<ObjectType>,
688 kInline ? 0 : kStaticLength>
689 objects_;
690 aos::InlinedVector<size_t, kInline ? 0 : kStaticLength>
691 object_absolute_offsets_;
692 // Current actual length of the vector.
693 size_t length_ = 0;
694 // Current length that we have allocated space available for.
695 size_t allocated_length_ = kStaticLength;
696};
697
698template <typename T, size_t kStaticLength, bool kInline, size_t kForceAlign,
699 bool kNullTerminate>
700T *Vector<T, kStaticLength, kInline, kForceAlign,
701 kNullTerminate>::emplace_back() {
702 static_assert(!kInline);
703 if (length_ >= allocated_length_) {
704 return nullptr;
705 }
706 const size_t object_start = object_absolute_offsets_[length_];
707 std::span<uint8_t> object_buffer =
708 internal::GetSubSpan(buffer(), object_start, T::kSize);
709 objects_.emplace_back(object_buffer, this);
710 const uoffset_t offset =
711 object_start - (reinterpret_cast<size_t>(&GetInlineElement(length_)) -
712 reinterpret_cast<size_t>(buffer().data()));
713 CHECK(AddInlineElement(offset));
714 return &objects_[objects_.size() - 1].t;
715}
716
717// The String class is a special version of the Vector that is always
718// null-terminated, always contains 1-byte character elements, and which has a
719// few extra methods for convenient string access.
720template <size_t kStaticLength>
721class String : public Vector<char, kStaticLength, true, 0, true> {
722 public:
723 typedef Vector<char, kStaticLength, true, 0, true> VectorType;
724 typedef flatbuffers::String Flatbuffer;
James Kuszmaul6be41022023-12-20 11:55:28 -0800725 typedef std::string FlatbufferObjectType;
James Kuszmaulf5eb4682023-09-22 17:16:59 -0700726 String(std::span<uint8_t> buffer, ResizeableObject *parent)
727 : VectorType(buffer, parent) {}
728 virtual ~String() {}
729 void SetString(std::string_view string) {
730 CHECK_LT(string.size(), VectorType::capacity());
731 VectorType::resize_inline(string.size(), SetZero::kNo);
732 memcpy(VectorType::data(), string.data(), string.size());
733 }
James Kuszmaul6be41022023-12-20 11:55:28 -0800734 using VectorType::FromFlatbuffer;
735 [[nodiscard]] bool FromFlatbuffer(const std::string &string) {
736 return VectorType::FromData(string.data(), string.size());
737 }
James Kuszmaulf5eb4682023-09-22 17:16:59 -0700738 std::string_view string_view() const {
739 return std::string_view(VectorType::data(), VectorType::size());
740 }
741 std::string str() const {
742 return std::string(VectorType::data(), VectorType::size());
743 }
744 const char *c_str() const { return VectorType::data(); }
745
746 private:
747 friend struct internal::TableMover<String<kStaticLength>>;
748 String(String &&) = default;
749};
750
751namespace internal {
752// Specialization for all non-inline vector types. All of these types will just
753// use offsets for their inline data and have appropriate member types/constants
754// for the remaining fields.
755template <typename T>
756struct InlineWrapper<T, false, void> {
757 typedef uoffset_t Type;
758 typedef T ObjectType;
759 typedef flatbuffers::Offset<typename T::Flatbuffer> FlatbufferType;
760 typedef flatbuffers::Offset<typename T::Flatbuffer> ConstFlatbufferType;
James Kuszmaul6be41022023-12-20 11:55:28 -0800761 typedef T::FlatbufferObjectType FlatbufferObjectType;
James Kuszmaulf5eb4682023-09-22 17:16:59 -0700762 static_assert((T::kSize % T::kAlign) == 0);
763 static constexpr size_t kDataAlign = T::kAlign;
764 static constexpr size_t kDataSize = T::kSize;
765 template <typename StaticVector>
766 static bool FromFlatbuffer(
767 StaticVector *to, const typename StaticVector::ConstFlatbuffer *from) {
768 return to->FromNotInlineFlatbuffer(from);
769 }
770 template <typename StaticVector>
771 static void ResizeVector(StaticVector *target, size_t size) {
772 target->resize_not_inline(size);
773 }
774};
775// Specialization for "normal" scalar inline data (ints, floats, doubles,
776// enums).
777template <typename T>
778struct InlineWrapper<T, true,
779 typename std::enable_if_t<!std::is_class<T>::value>> {
780 typedef T Type;
781 typedef T ObjectType;
782 typedef T FlatbufferType;
783 typedef T ConstFlatbufferType;
James Kuszmaul6be41022023-12-20 11:55:28 -0800784 typedef T *FlatbufferObjectType;
James Kuszmaulf5eb4682023-09-22 17:16:59 -0700785 static constexpr size_t kDataAlign = alignof(T);
786 static constexpr size_t kDataSize = sizeof(T);
787 template <typename StaticVector>
788 static bool FromFlatbuffer(
789 StaticVector *to, const typename StaticVector::ConstFlatbuffer *from) {
790 return to->FromInlineFlatbuffer(from);
791 }
792 template <typename StaticVector>
793 static void ResizeVector(StaticVector *target, size_t size) {
794 target->resize_inline(size, SetZero::kYes);
795 }
796};
797// Specialization for booleans, given that flatbuffers uses uint8_t's for bools.
798template <>
799struct InlineWrapper<bool, true, void> {
800 typedef uint8_t Type;
801 typedef uint8_t ObjectType;
802 typedef uint8_t FlatbufferType;
803 typedef uint8_t ConstFlatbufferType;
James Kuszmaul6be41022023-12-20 11:55:28 -0800804 typedef uint8_t *FlatbufferObjectType;
James Kuszmaulf5eb4682023-09-22 17:16:59 -0700805 static constexpr size_t kDataAlign = 1u;
806 static constexpr size_t kDataSize = 1u;
807 template <typename StaticVector>
808 static bool FromFlatbuffer(
809 StaticVector *to, const typename StaticVector::ConstFlatbuffer *from) {
810 return to->FromInlineFlatbuffer(from);
811 }
812 template <typename StaticVector>
813 static void ResizeVector(StaticVector *target, size_t size) {
814 target->resize_inline(size, SetZero::kYes);
815 }
816};
817// Specialization for flatbuffer structs.
818// The flatbuffers codegen uses struct pointers rather than references or the
819// such, so it needs to be treated special.
820template <typename T>
821struct InlineWrapper<T, true,
822 typename std::enable_if_t<std::is_class<T>::value>> {
823 typedef T Type;
824 typedef T ObjectType;
825 typedef T *FlatbufferType;
826 typedef const T *ConstFlatbufferType;
James Kuszmaul6be41022023-12-20 11:55:28 -0800827 typedef T *FlatbufferObjectType;
James Kuszmaulf5eb4682023-09-22 17:16:59 -0700828 static constexpr size_t kDataAlign = alignof(T);
829 static constexpr size_t kDataSize = sizeof(T);
830 template <typename StaticVector>
831 static bool FromFlatbuffer(
832 StaticVector *to, const typename StaticVector::ConstFlatbuffer *from) {
833 return to->FromInlineFlatbuffer(from);
834 }
835 template <typename StaticVector>
836 static void ResizeVector(StaticVector *target, size_t size) {
837 target->resize_inline(size, SetZero::kYes);
838 }
839};
840} // namespace internal
841 //
842template <typename T, size_t kStaticLength, bool kInline, size_t kForceAlign,
843 bool kNullTerminate>
844bool Vector<T, kStaticLength, kInline, kForceAlign,
845 kNullTerminate>::FromFlatbuffer(ConstFlatbuffer *vector) {
846 return internal::InlineWrapper<T, kInline>::FromFlatbuffer(this, vector);
847}
848
849template <typename T, size_t kStaticLength, bool kInline, size_t kForceAlign,
850 bool kNullTerminate>
851void Vector<T, kStaticLength, kInline, kForceAlign, kNullTerminate>::resize(
852 size_t size) {
853 internal::InlineWrapper<T, kInline>::ResizeVector(this, size);
854}
855
856} // namespace aos::fbs
857#endif // AOS_FLATBUFFERS_STATIC_VECTOR_H_