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