James Kuszmaul | f5eb468 | 2023-09-22 17:16:59 -0700 | [diff] [blame] | 1 | #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 | |
| 12 | namespace aos::fbs { |
| 13 | |
| 14 | namespace 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. |
| 32 | template <typename T, bool kInline, class Enable = void> |
| 33 | struct 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 Kuszmaul | 1c9693f | 2023-12-08 09:45:26 -0800 | [diff] [blame] | 106 | // 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 Kuszmaul | f5eb468 | 2023-09-22 17:16:59 -0700 | [diff] [blame] | 109 | template <typename T, size_t kStaticLength, bool kInline, |
| 110 | size_t kForceAlign = 0, bool kNullTerminate = false> |
| 111 | class 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 Kuszmaul | f5eb468 | 2023-09-22 17:16:59 -0700 | [diff] [blame] | 170 | SetLength(0u); |
James Kuszmaul | f5eb468 | 2023-09-22 17:16:59 -0700 | [diff] [blame] | 171 | 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. |
James Kuszmaul | f5eb468 | 2023-09-22 17:16:59 -0700 | [diff] [blame] | 242 | ConstFlatbuffer *AsFlatbufferVector() const { |
| 243 | return reinterpret_cast<const Flatbuffer *>(vector_buffer().data()); |
| 244 | } |
| 245 | |
| 246 | // Copies the contents of the provided vector into this; returns false on |
| 247 | // failure (e.g., if the provided vector is too long for the amount of space |
| 248 | // we can allocate through reserve()). |
James Kuszmaul | 710883b | 2023-12-14 14:34:48 -0800 | [diff] [blame^] | 249 | // This is a deep copy, and will call FromFlatbuffer on any constituent |
| 250 | // objects. |
James Kuszmaul | f5eb468 | 2023-09-22 17:16:59 -0700 | [diff] [blame] | 251 | [[nodiscard]] bool FromFlatbuffer(ConstFlatbuffer *vector); |
| 252 | |
| 253 | // Returns the element at the provided index. index must be less than size(). |
| 254 | const T &at(size_t index) const { |
| 255 | CHECK_LT(index, length_); |
| 256 | return unsafe_at(index); |
| 257 | } |
| 258 | |
| 259 | // Same as at(), except that bounds checks are only performed in non-optimized |
| 260 | // builds. |
| 261 | // TODO(james): The GetInlineElement() call itself does some bounds-checking; |
| 262 | // consider down-grading that. |
| 263 | const T &unsafe_at(size_t index) const { |
| 264 | DCHECK_LT(index, length_); |
| 265 | if (kInline) { |
| 266 | // This reinterpret_cast is extremely wrong if T != InlineType (this is |
| 267 | // fine because we only do this if kInline is true). |
| 268 | // TODO(james): Get the templating improved so that we can get away with |
| 269 | // specializing at() instead of using if statements. Resolving this will |
| 270 | // also allow deduplicating the Resize() calls. |
| 271 | // This specialization is difficult because you cannot partially |
| 272 | // specialize a templated class method (online things seem to suggest e.g. |
| 273 | // using a struct as the template parameter rather than having separate |
| 274 | // parameters). |
| 275 | return reinterpret_cast<const T &>(GetInlineElement(index)); |
| 276 | } else { |
| 277 | return objects_[index].t; |
| 278 | } |
| 279 | } |
| 280 | |
| 281 | // Returns a mutable pointer to the element at the provided index. index must |
| 282 | // be less than size(). |
| 283 | T &at(size_t index) { |
| 284 | CHECK_LT(index, length_); |
| 285 | return unsafe_at(index); |
| 286 | } |
| 287 | |
| 288 | // Same as at(), except that bounds checks are only performed in non-optimized |
| 289 | // builds. |
| 290 | // TODO(james): The GetInlineElement() call itself does some bounds-checking; |
| 291 | // consider down-grading that. |
| 292 | T &unsafe_at(size_t index) { |
| 293 | DCHECK_LT(index, length_); |
| 294 | if (kInline) { |
| 295 | // This reinterpret_cast is extremely wrong if T != InlineType (this is |
| 296 | // fine because we only do this if kInline is true). |
| 297 | // TODO(james): Get the templating improved so that we can get away with |
| 298 | // specializing at() instead of using if statements. Resolving this will |
| 299 | // also allow deduplicating the Resize() calls. |
| 300 | // This specialization is difficult because you cannot partially |
| 301 | // specialize a templated class method (online things seem to suggest e.g. |
| 302 | // using a struct as the template parameter rather than having separate |
| 303 | // parameters). |
| 304 | return reinterpret_cast<T &>(GetInlineElement(index)); |
| 305 | } else { |
| 306 | return objects_[index].t; |
| 307 | } |
| 308 | } |
| 309 | |
| 310 | const T &operator[](size_t index) const { return at(index); } |
| 311 | T &operator[](size_t index) { return at(index); } |
| 312 | |
| 313 | // Resizes the vector to the requested size. |
| 314 | // size must be less than or equal to the current capacity() of the vector. |
| 315 | // Does not allocate additional memory (call reserve() to allocate additional |
| 316 | // memory). |
| 317 | // Zero-initializes all inline element; initializes all subtable/string |
| 318 | // elements to extant but empty objects. |
| 319 | void resize(size_t size); |
| 320 | |
| 321 | // Resizes an inline vector to the requested size. |
| 322 | // When changing the size of the vector, the removed/inserted elements will be |
| 323 | // set to zero if requested. Otherwise, they will be left uninitialized. |
| 324 | void resize_inline(size_t size, SetZero set_zero) { |
| 325 | CHECK_LE(size, allocated_length_); |
| 326 | static_assert( |
| 327 | kInline, |
| 328 | "Vector::resize_inline() only works for inline vector types (scalars, " |
| 329 | "enums, structs)."); |
| 330 | if (size == length_) { |
| 331 | return; |
| 332 | } |
| 333 | if (set_zero == SetZero::kYes) { |
| 334 | memset( |
| 335 | reinterpret_cast<void *>(inline_data() + std::min(size, length_)), 0, |
| 336 | std::abs(static_cast<ssize_t>(length_) - static_cast<ssize_t>(size)) * |
| 337 | sizeof(InlineType)); |
| 338 | } |
| 339 | length_ = size; |
| 340 | SetLength(length_); |
| 341 | } |
| 342 | // Resizes a vector of offsets to the requested size. |
| 343 | // If the size is increased, the new elements will be initialized |
| 344 | // to empty but extant objects for non-inlined types (so, zero-length |
| 345 | // vectors/strings; objects that exist but have no fields populated). |
| 346 | // Note that this is always equivalent to resize(). |
| 347 | void resize_not_inline(size_t size) { |
| 348 | CHECK_LE(size, allocated_length_); |
| 349 | static_assert(!kInline, |
| 350 | "Vector::resize_not_inline() only works for offset vector " |
| 351 | "types (objects, strings)."); |
| 352 | if (size == length_) { |
| 353 | return; |
| 354 | } else if (length_ > size) { |
| 355 | // TODO: Remove any excess allocated memory. |
| 356 | length_ = size; |
| 357 | SetLength(length_); |
| 358 | return; |
| 359 | } else { |
| 360 | while (length_ < size) { |
| 361 | CHECK_NOTNULL(emplace_back()); |
| 362 | } |
| 363 | } |
| 364 | } |
| 365 | |
| 366 | // Accessors directly to the inline data of a vector. |
| 367 | const T *data() const { |
| 368 | static_assert(kInline, |
| 369 | "If you have a use-case for directly accessing the " |
| 370 | "flatbuffer data pointer for vectors of " |
| 371 | "objects/strings, please start a discussion."); |
| 372 | return inline_data(); |
| 373 | } |
| 374 | |
| 375 | T *data() { |
| 376 | static_assert(kInline, |
| 377 | "If you have a use-case for directly accessing the " |
| 378 | "flatbuffer data pointer for vectors of " |
| 379 | "objects/strings, please start a discussion."); |
| 380 | return inline_data(); |
| 381 | } |
| 382 | |
| 383 | std::string SerializationDebugString() const { |
| 384 | std::stringstream str; |
| 385 | str << "Raw Size: " << kSize << " alignment: " << kAlign |
| 386 | << " allocated length: " << allocated_length_ << " inline alignment " |
| 387 | << kInlineAlign << " kPadding1 " << kPadding1 << "\n"; |
| 388 | str << "Observed length " << GetLength() << " (expected " << length_ |
| 389 | << ")\n"; |
| 390 | str << "Inline Size " << kInlineSize << " Inline bytes/value:\n"; |
| 391 | // TODO(james): Get pretty-printing for structs so we can provide better |
| 392 | // debug. |
| 393 | internal::DebugBytes( |
| 394 | internal::GetSubSpan(vector_buffer(), kLengthSize, |
| 395 | sizeof(InlineType) * allocated_length_), |
| 396 | str); |
| 397 | str << "kPadding2 " << kPadding2 << " offset data size " |
| 398 | << kOffsetOffsetDataSize << "\n"; |
| 399 | return str.str(); |
| 400 | } |
| 401 | |
| 402 | protected: |
| 403 | friend struct internal::TableMover< |
| 404 | Vector<T, kStaticLength, kInline, kForceAlign, kNullTerminate>>; |
| 405 | // protected so that the String class can access the move constructor. |
| 406 | Vector(Vector &&) = default; |
| 407 | |
| 408 | private: |
| 409 | // See kAlign and kOffset. |
| 410 | size_t Alignment() const final { return kAlign; } |
| 411 | size_t AbsoluteOffsetOffset() const override { return kOffset; } |
| 412 | // Returns a buffer that starts at the start of the vector itself (past any |
| 413 | // padding). |
| 414 | std::span<uint8_t> vector_buffer() { |
| 415 | return internal::GetSubSpan(buffer(), kPadding1); |
| 416 | } |
| 417 | std::span<const uint8_t> vector_buffer() const { |
| 418 | return internal::GetSubSpan(buffer(), kPadding1); |
| 419 | } |
| 420 | |
| 421 | bool AddInlineElement(InlineType e) { |
| 422 | if (length_ == allocated_length_) { |
| 423 | return false; |
| 424 | } |
| 425 | SetInlineElement(length_, e); |
| 426 | ++length_; |
| 427 | SetLength(length_); |
| 428 | return true; |
| 429 | } |
| 430 | |
| 431 | void SetInlineElement(size_t index, InlineType value) { |
| 432 | CHECK_LT(index, allocated_length_); |
| 433 | inline_data()[index] = value; |
| 434 | } |
| 435 | |
| 436 | InlineType &GetInlineElement(size_t index) { |
| 437 | CHECK_LT(index, allocated_length_); |
| 438 | return inline_data()[index]; |
| 439 | } |
| 440 | |
| 441 | const InlineType &GetInlineElement(size_t index) const { |
| 442 | CHECK_LT(index, allocated_length_); |
| 443 | return inline_data()[index]; |
| 444 | } |
| 445 | |
| 446 | // Returns a pointer to the start of the inline data itself. |
| 447 | InlineType *inline_data() { |
| 448 | return reinterpret_cast<InlineType *>(vector_buffer().data() + kLengthSize); |
| 449 | } |
| 450 | const InlineType *inline_data() const { |
| 451 | return reinterpret_cast<const InlineType *>(vector_buffer().data() + |
| 452 | kLengthSize); |
| 453 | } |
| 454 | |
| 455 | // Updates the length of the vector to match the provided length. Does not set |
| 456 | // the length_ member. |
| 457 | void SetLength(LengthType length) { |
| 458 | *reinterpret_cast<LengthType *>(vector_buffer().data()) = length; |
| 459 | if (kNullTerminate) { |
| 460 | memset(reinterpret_cast<void *>(inline_data() + length), 0, |
| 461 | sizeof(InlineType)); |
| 462 | } |
| 463 | } |
| 464 | LengthType GetLength() const { |
| 465 | return *reinterpret_cast<const LengthType *>(vector_buffer().data()); |
| 466 | } |
| 467 | |
| 468 | // Overrides to allow ResizeableObject to manage memory adjustments. |
| 469 | size_t NumberOfSubObjects() const final { |
| 470 | return kInline ? 0 : allocated_length_; |
| 471 | } |
| 472 | using ResizeableObject::SubObject; |
| 473 | SubObject GetSubObject(size_t index) final { |
| 474 | return SubObject{ |
| 475 | reinterpret_cast<uoffset_t *>(&GetInlineElement(index)), |
| 476 | // In order to let this compile regardless of whether type T is an |
| 477 | // object type or not, we just use a reinterpret_cast. |
| 478 | (index < length_) |
| 479 | ? reinterpret_cast<ResizeableObject *>(&objects_[index].t) |
| 480 | : nullptr, |
| 481 | &object_absolute_offsets_[index]}; |
| 482 | } |
| 483 | // Implementation that handles copying from a flatbuffers::Vector of an inline |
| 484 | // data type. |
| 485 | [[nodiscard]] bool FromInlineFlatbuffer(ConstFlatbuffer *vector) { |
| 486 | if (!reserve(CHECK_NOTNULL(vector)->size())) { |
| 487 | return false; |
| 488 | } |
| 489 | |
| 490 | // We will be overwriting the whole vector very shortly; there is no need to |
| 491 | // clear the buffer to zero. |
| 492 | resize_inline(vector->size(), SetZero::kNo); |
| 493 | |
| 494 | memcpy(inline_data(), vector->Data(), size() * sizeof(InlineType)); |
| 495 | return true; |
| 496 | } |
| 497 | |
| 498 | // Implementation that handles copying from a flatbuffers::Vector of a |
| 499 | // not-inline data type. |
| 500 | [[nodiscard]] bool FromNotInlineFlatbuffer(const Flatbuffer *vector) { |
| 501 | if (!reserve(vector->size())) { |
| 502 | return false; |
| 503 | } |
| 504 | // "Clear" the vector. |
| 505 | resize_not_inline(0); |
| 506 | |
| 507 | for (const typename T::Flatbuffer *entry : *vector) { |
| 508 | if (!CHECK_NOTNULL(emplace_back())->FromFlatbuffer(entry)) { |
| 509 | return false; |
| 510 | } |
| 511 | } |
| 512 | return true; |
| 513 | } |
| 514 | |
| 515 | // In order to allow for easy partial template specialization, we use a |
| 516 | // non-member class to call FromInline/FromNotInlineFlatbuffer and |
| 517 | // resize_inline/resize_not_inline. There are not actually any great ways to |
| 518 | // do this with just our own class member functions, so instead we make these |
| 519 | // methods members of a friend of the Vector class; we then partially |
| 520 | // specialize the entire InlineWrapper class and use it to isolate anything |
| 521 | // that needs to have a common user interface while still having separate |
| 522 | // actual logic. |
| 523 | template <typename T_, bool kInline_, class Enable_> |
| 524 | friend struct internal::InlineWrapper; |
| 525 | |
| 526 | // Note: The objects here really want to be owned by this object (as opposed |
| 527 | // to e.g. returning a stack-allocated object from the emplace_back() methods |
| 528 | // that the user then owns). There are two main challenges with have the user |
| 529 | // own the object on question: |
| 530 | // 1. We can't have >1 reference floating around, or else one object's state |
| 531 | // can become out of date. This forces us to do ref-counting and could |
| 532 | // make certain types of code obnoxious to write. |
| 533 | // 2. Once the user-created object goes out of scope, we lose all of its |
| 534 | // internal state. In _theory_ it should be possible to reconstruct most |
| 535 | // of the relevant state by examining the contents of the buffer, but |
| 536 | // doing so would be cumbersome. |
| 537 | aos::InlinedVector<internal::TableMover<ObjectType>, |
| 538 | kInline ? 0 : kStaticLength> |
| 539 | objects_; |
| 540 | aos::InlinedVector<size_t, kInline ? 0 : kStaticLength> |
| 541 | object_absolute_offsets_; |
| 542 | // Current actual length of the vector. |
| 543 | size_t length_ = 0; |
| 544 | // Current length that we have allocated space available for. |
| 545 | size_t allocated_length_ = kStaticLength; |
| 546 | }; |
| 547 | |
| 548 | template <typename T, size_t kStaticLength, bool kInline, size_t kForceAlign, |
| 549 | bool kNullTerminate> |
| 550 | T *Vector<T, kStaticLength, kInline, kForceAlign, |
| 551 | kNullTerminate>::emplace_back() { |
| 552 | static_assert(!kInline); |
| 553 | if (length_ >= allocated_length_) { |
| 554 | return nullptr; |
| 555 | } |
| 556 | const size_t object_start = object_absolute_offsets_[length_]; |
| 557 | std::span<uint8_t> object_buffer = |
| 558 | internal::GetSubSpan(buffer(), object_start, T::kSize); |
| 559 | objects_.emplace_back(object_buffer, this); |
| 560 | const uoffset_t offset = |
| 561 | object_start - (reinterpret_cast<size_t>(&GetInlineElement(length_)) - |
| 562 | reinterpret_cast<size_t>(buffer().data())); |
| 563 | CHECK(AddInlineElement(offset)); |
| 564 | return &objects_[objects_.size() - 1].t; |
| 565 | } |
| 566 | |
| 567 | // The String class is a special version of the Vector that is always |
| 568 | // null-terminated, always contains 1-byte character elements, and which has a |
| 569 | // few extra methods for convenient string access. |
| 570 | template <size_t kStaticLength> |
| 571 | class String : public Vector<char, kStaticLength, true, 0, true> { |
| 572 | public: |
| 573 | typedef Vector<char, kStaticLength, true, 0, true> VectorType; |
| 574 | typedef flatbuffers::String Flatbuffer; |
| 575 | String(std::span<uint8_t> buffer, ResizeableObject *parent) |
| 576 | : VectorType(buffer, parent) {} |
| 577 | virtual ~String() {} |
| 578 | void SetString(std::string_view string) { |
| 579 | CHECK_LT(string.size(), VectorType::capacity()); |
| 580 | VectorType::resize_inline(string.size(), SetZero::kNo); |
| 581 | memcpy(VectorType::data(), string.data(), string.size()); |
| 582 | } |
| 583 | std::string_view string_view() const { |
| 584 | return std::string_view(VectorType::data(), VectorType::size()); |
| 585 | } |
| 586 | std::string str() const { |
| 587 | return std::string(VectorType::data(), VectorType::size()); |
| 588 | } |
| 589 | const char *c_str() const { return VectorType::data(); } |
| 590 | |
| 591 | private: |
| 592 | friend struct internal::TableMover<String<kStaticLength>>; |
| 593 | String(String &&) = default; |
| 594 | }; |
| 595 | |
| 596 | namespace internal { |
| 597 | // Specialization for all non-inline vector types. All of these types will just |
| 598 | // use offsets for their inline data and have appropriate member types/constants |
| 599 | // for the remaining fields. |
| 600 | template <typename T> |
| 601 | struct InlineWrapper<T, false, void> { |
| 602 | typedef uoffset_t Type; |
| 603 | typedef T ObjectType; |
| 604 | typedef flatbuffers::Offset<typename T::Flatbuffer> FlatbufferType; |
| 605 | typedef flatbuffers::Offset<typename T::Flatbuffer> ConstFlatbufferType; |
| 606 | static_assert((T::kSize % T::kAlign) == 0); |
| 607 | static constexpr size_t kDataAlign = T::kAlign; |
| 608 | static constexpr size_t kDataSize = T::kSize; |
| 609 | template <typename StaticVector> |
| 610 | static bool FromFlatbuffer( |
| 611 | StaticVector *to, const typename StaticVector::ConstFlatbuffer *from) { |
| 612 | return to->FromNotInlineFlatbuffer(from); |
| 613 | } |
| 614 | template <typename StaticVector> |
| 615 | static void ResizeVector(StaticVector *target, size_t size) { |
| 616 | target->resize_not_inline(size); |
| 617 | } |
| 618 | }; |
| 619 | // Specialization for "normal" scalar inline data (ints, floats, doubles, |
| 620 | // enums). |
| 621 | template <typename T> |
| 622 | struct InlineWrapper<T, true, |
| 623 | typename std::enable_if_t<!std::is_class<T>::value>> { |
| 624 | typedef T Type; |
| 625 | typedef T ObjectType; |
| 626 | typedef T FlatbufferType; |
| 627 | typedef T ConstFlatbufferType; |
| 628 | static constexpr size_t kDataAlign = alignof(T); |
| 629 | static constexpr size_t kDataSize = sizeof(T); |
| 630 | template <typename StaticVector> |
| 631 | static bool FromFlatbuffer( |
| 632 | StaticVector *to, const typename StaticVector::ConstFlatbuffer *from) { |
| 633 | return to->FromInlineFlatbuffer(from); |
| 634 | } |
| 635 | template <typename StaticVector> |
| 636 | static void ResizeVector(StaticVector *target, size_t size) { |
| 637 | target->resize_inline(size, SetZero::kYes); |
| 638 | } |
| 639 | }; |
| 640 | // Specialization for booleans, given that flatbuffers uses uint8_t's for bools. |
| 641 | template <> |
| 642 | struct InlineWrapper<bool, true, void> { |
| 643 | typedef uint8_t Type; |
| 644 | typedef uint8_t ObjectType; |
| 645 | typedef uint8_t FlatbufferType; |
| 646 | typedef uint8_t ConstFlatbufferType; |
| 647 | static constexpr size_t kDataAlign = 1u; |
| 648 | static constexpr size_t kDataSize = 1u; |
| 649 | template <typename StaticVector> |
| 650 | static bool FromFlatbuffer( |
| 651 | StaticVector *to, const typename StaticVector::ConstFlatbuffer *from) { |
| 652 | return to->FromInlineFlatbuffer(from); |
| 653 | } |
| 654 | template <typename StaticVector> |
| 655 | static void ResizeVector(StaticVector *target, size_t size) { |
| 656 | target->resize_inline(size, SetZero::kYes); |
| 657 | } |
| 658 | }; |
| 659 | // Specialization for flatbuffer structs. |
| 660 | // The flatbuffers codegen uses struct pointers rather than references or the |
| 661 | // such, so it needs to be treated special. |
| 662 | template <typename T> |
| 663 | struct InlineWrapper<T, true, |
| 664 | typename std::enable_if_t<std::is_class<T>::value>> { |
| 665 | typedef T Type; |
| 666 | typedef T ObjectType; |
| 667 | typedef T *FlatbufferType; |
| 668 | typedef const T *ConstFlatbufferType; |
| 669 | static constexpr size_t kDataAlign = alignof(T); |
| 670 | static constexpr size_t kDataSize = sizeof(T); |
| 671 | template <typename StaticVector> |
| 672 | static bool FromFlatbuffer( |
| 673 | StaticVector *to, const typename StaticVector::ConstFlatbuffer *from) { |
| 674 | return to->FromInlineFlatbuffer(from); |
| 675 | } |
| 676 | template <typename StaticVector> |
| 677 | static void ResizeVector(StaticVector *target, size_t size) { |
| 678 | target->resize_inline(size, SetZero::kYes); |
| 679 | } |
| 680 | }; |
| 681 | } // namespace internal |
| 682 | // |
| 683 | template <typename T, size_t kStaticLength, bool kInline, size_t kForceAlign, |
| 684 | bool kNullTerminate> |
| 685 | bool Vector<T, kStaticLength, kInline, kForceAlign, |
| 686 | kNullTerminate>::FromFlatbuffer(ConstFlatbuffer *vector) { |
| 687 | return internal::InlineWrapper<T, kInline>::FromFlatbuffer(this, vector); |
| 688 | } |
| 689 | |
| 690 | template <typename T, size_t kStaticLength, bool kInline, size_t kForceAlign, |
| 691 | bool kNullTerminate> |
| 692 | void Vector<T, kStaticLength, kInline, kForceAlign, kNullTerminate>::resize( |
| 693 | size_t size) { |
| 694 | internal::InlineWrapper<T, kInline>::ResizeVector(this, size); |
| 695 | } |
| 696 | |
| 697 | } // namespace aos::fbs |
| 698 | #endif // AOS_FLATBUFFERS_STATIC_VECTOR_H_ |