| 1 | /* |
| 2 | * Copyright 2014 Google Inc. All rights reserved. |
| 3 | * |
| 4 | * Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | * you may not use this file except in compliance with the License. |
| 6 | * You may obtain a copy of the License at |
| 7 | * |
| 8 | * http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | * |
| 10 | * Unless required by applicable law or agreed to in writing, software |
| 11 | * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | * See the License for the specific language governing permissions and |
| 14 | * limitations under the License. |
| 15 | */ |
| 16 | |
| 17 | #ifndef FLATBUFFERS_H_ |
| 18 | #define FLATBUFFERS_H_ |
| 19 | |
| 20 | #include "flatbuffers/base.h" |
| 21 | |
| 22 | namespace flatbuffers { |
| 23 | // Wrapper for uoffset_t to allow safe template specialization. |
| 24 | // Value is allowed to be 0 to indicate a null object (see e.g. AddOffset). |
| 25 | template<typename T> struct Offset { |
| 26 | uoffset_t o; |
| 27 | Offset() : o(0) {} |
| 28 | Offset(uoffset_t _o) : o(_o) {} |
| 29 | Offset<void> Union() const { return Offset<void>(o); } |
| 30 | bool IsNull() const { return !o; } |
| 31 | }; |
| 32 | |
| 33 | inline void EndianCheck() { |
| 34 | int endiantest = 1; |
| 35 | // If this fails, see FLATBUFFERS_LITTLEENDIAN above. |
| 36 | FLATBUFFERS_ASSERT(*reinterpret_cast<char *>(&endiantest) == |
| 37 | FLATBUFFERS_LITTLEENDIAN); |
| 38 | (void)endiantest; |
| 39 | } |
| 40 | |
| 41 | template<typename T> FLATBUFFERS_CONSTEXPR size_t AlignOf() { |
| 42 | // clang-format off |
| 43 | #ifdef _MSC_VER |
| 44 | return __alignof(T); |
| 45 | #else |
| 46 | #ifndef alignof |
| 47 | return __alignof__(T); |
| 48 | #else |
| 49 | return alignof(T); |
| 50 | #endif |
| 51 | #endif |
| 52 | // clang-format on |
| 53 | } |
| 54 | |
| 55 | // When we read serialized data from memory, in the case of most scalars, |
| 56 | // we want to just read T, but in the case of Offset, we want to actually |
| 57 | // perform the indirection and return a pointer. |
| 58 | // The template specialization below does just that. |
| 59 | // It is wrapped in a struct since function templates can't overload on the |
| 60 | // return type like this. |
| 61 | // The typedef is for the convenience of callers of this function |
| 62 | // (avoiding the need for a trailing return decltype) |
| 63 | template<typename T> struct IndirectHelper { |
| 64 | typedef T return_type; |
| 65 | typedef T mutable_return_type; |
| 66 | static const size_t element_stride = sizeof(T); |
| 67 | static return_type Read(const uint8_t *p, uoffset_t i) { |
| 68 | return EndianScalar((reinterpret_cast<const T *>(p))[i]); |
| 69 | } |
| 70 | }; |
| 71 | template<typename T> struct IndirectHelper<Offset<T>> { |
| 72 | typedef const T *return_type; |
| 73 | typedef T *mutable_return_type; |
| 74 | static const size_t element_stride = sizeof(uoffset_t); |
| 75 | static return_type Read(const uint8_t *p, uoffset_t i) { |
| 76 | p += i * sizeof(uoffset_t); |
| 77 | return reinterpret_cast<return_type>(p + ReadScalar<uoffset_t>(p)); |
| 78 | } |
| 79 | }; |
| 80 | template<typename T> struct IndirectHelper<const T *> { |
| 81 | typedef const T *return_type; |
| 82 | typedef T *mutable_return_type; |
| 83 | static const size_t element_stride = sizeof(T); |
| 84 | static return_type Read(const uint8_t *p, uoffset_t i) { |
| 85 | return reinterpret_cast<const T *>(p + i * sizeof(T)); |
| 86 | } |
| 87 | }; |
| 88 | |
| 89 | // An STL compatible iterator implementation for Vector below, effectively |
| 90 | // calling Get() for every element. |
| 91 | template<typename T, typename IT> struct VectorIterator { |
| 92 | typedef std::random_access_iterator_tag iterator_category; |
| 93 | typedef IT value_type; |
| 94 | typedef ptrdiff_t difference_type; |
| 95 | typedef IT *pointer; |
| 96 | typedef IT &reference; |
| 97 | |
| 98 | VectorIterator(const uint8_t *data, uoffset_t i) |
| 99 | : data_(data + IndirectHelper<T>::element_stride * i) {} |
| 100 | VectorIterator(const VectorIterator &other) : data_(other.data_) {} |
| 101 | |
| 102 | VectorIterator &operator=(const VectorIterator &other) { |
| 103 | data_ = other.data_; |
| 104 | return *this; |
| 105 | } |
| 106 | |
| 107 | VectorIterator &operator=(VectorIterator &&other) { |
| 108 | data_ = other.data_; |
| 109 | return *this; |
| 110 | } |
| 111 | |
| 112 | bool operator==(const VectorIterator &other) const { |
| 113 | return data_ == other.data_; |
| 114 | } |
| 115 | |
| 116 | bool operator<(const VectorIterator &other) const { |
| 117 | return data_ < other.data_; |
| 118 | } |
| 119 | |
| 120 | bool operator!=(const VectorIterator &other) const { |
| 121 | return data_ != other.data_; |
| 122 | } |
| 123 | |
| 124 | difference_type operator-(const VectorIterator &other) const { |
| 125 | return (data_ - other.data_) / IndirectHelper<T>::element_stride; |
| 126 | } |
| 127 | |
| 128 | IT operator*() const { return IndirectHelper<T>::Read(data_, 0); } |
| 129 | |
| 130 | IT operator->() const { return IndirectHelper<T>::Read(data_, 0); } |
| 131 | |
| 132 | VectorIterator &operator++() { |
| 133 | data_ += IndirectHelper<T>::element_stride; |
| 134 | return *this; |
| 135 | } |
| 136 | |
| 137 | VectorIterator operator++(int) { |
| 138 | VectorIterator temp(data_, 0); |
| 139 | data_ += IndirectHelper<T>::element_stride; |
| 140 | return temp; |
| 141 | } |
| 142 | |
| 143 | VectorIterator operator+(const uoffset_t &offset) const { |
| 144 | return VectorIterator(data_ + offset * IndirectHelper<T>::element_stride, |
| 145 | 0); |
| 146 | } |
| 147 | |
| 148 | VectorIterator &operator+=(const uoffset_t &offset) { |
| 149 | data_ += offset * IndirectHelper<T>::element_stride; |
| 150 | return *this; |
| 151 | } |
| 152 | |
| 153 | VectorIterator &operator--() { |
| 154 | data_ -= IndirectHelper<T>::element_stride; |
| 155 | return *this; |
| 156 | } |
| 157 | |
| 158 | VectorIterator operator--(int) { |
| 159 | VectorIterator temp(data_, 0); |
| 160 | data_ -= IndirectHelper<T>::element_stride; |
| 161 | return temp; |
| 162 | } |
| 163 | |
| 164 | VectorIterator operator-(const uoffset_t &offset) { |
| 165 | return VectorIterator(data_ - offset * IndirectHelper<T>::element_stride, |
| 166 | 0); |
| 167 | } |
| 168 | |
| 169 | VectorIterator &operator-=(const uoffset_t &offset) { |
| 170 | data_ -= offset * IndirectHelper<T>::element_stride; |
| 171 | return *this; |
| 172 | } |
| 173 | |
| 174 | private: |
| 175 | const uint8_t *data_; |
| 176 | }; |
| 177 | |
| 178 | struct String; |
| 179 | |
| 180 | // This is used as a helper type for accessing vectors. |
| 181 | // Vector::data() assumes the vector elements start after the length field. |
| 182 | template<typename T> class Vector { |
| 183 | public: |
| 184 | typedef VectorIterator<T, typename IndirectHelper<T>::mutable_return_type> |
| 185 | iterator; |
| 186 | typedef VectorIterator<T, typename IndirectHelper<T>::return_type> |
| 187 | const_iterator; |
| 188 | |
| 189 | uoffset_t size() const { return EndianScalar(length_); } |
| 190 | |
| 191 | // Deprecated: use size(). Here for backwards compatibility. |
| 192 | uoffset_t Length() const { return size(); } |
| 193 | |
| 194 | typedef typename IndirectHelper<T>::return_type return_type; |
| 195 | typedef typename IndirectHelper<T>::mutable_return_type mutable_return_type; |
| 196 | |
| 197 | return_type Get(uoffset_t i) const { |
| 198 | FLATBUFFERS_ASSERT(i < size()); |
| 199 | return IndirectHelper<T>::Read(Data(), i); |
| 200 | } |
| 201 | |
| 202 | return_type operator[](uoffset_t i) const { return Get(i); } |
| 203 | |
| 204 | // If this is a Vector of enums, T will be its storage type, not the enum |
| 205 | // type. This function makes it convenient to retrieve value with enum |
| 206 | // type E. |
| 207 | template<typename E> E GetEnum(uoffset_t i) const { |
| 208 | return static_cast<E>(Get(i)); |
| 209 | } |
| 210 | |
| 211 | // If this a vector of unions, this does the cast for you. There's no check |
| 212 | // to make sure this is the right type! |
| 213 | template<typename U> const U *GetAs(uoffset_t i) const { |
| 214 | return reinterpret_cast<const U *>(Get(i)); |
| 215 | } |
| 216 | |
| 217 | // If this a vector of unions, this does the cast for you. There's no check |
| 218 | // to make sure this is actually a string! |
| 219 | const String *GetAsString(uoffset_t i) const { |
| 220 | return reinterpret_cast<const String *>(Get(i)); |
| 221 | } |
| 222 | |
| 223 | const void *GetStructFromOffset(size_t o) const { |
| 224 | return reinterpret_cast<const void *>(Data() + o); |
| 225 | } |
| 226 | |
| 227 | iterator begin() { return iterator(Data(), 0); } |
| 228 | const_iterator begin() const { return const_iterator(Data(), 0); } |
| 229 | |
| 230 | iterator end() { return iterator(Data(), size()); } |
| 231 | const_iterator end() const { return const_iterator(Data(), size()); } |
| 232 | |
| 233 | // Change elements if you have a non-const pointer to this object. |
| 234 | // Scalars only. See reflection.h, and the documentation. |
| 235 | void Mutate(uoffset_t i, const T &val) { |
| 236 | FLATBUFFERS_ASSERT(i < size()); |
| 237 | WriteScalar(data() + i, val); |
| 238 | } |
| 239 | |
| 240 | // Change an element of a vector of tables (or strings). |
| 241 | // "val" points to the new table/string, as you can obtain from |
| 242 | // e.g. reflection::AddFlatBuffer(). |
| 243 | void MutateOffset(uoffset_t i, const uint8_t *val) { |
| 244 | FLATBUFFERS_ASSERT(i < size()); |
| 245 | static_assert(sizeof(T) == sizeof(uoffset_t), "Unrelated types" ); |
| 246 | WriteScalar(data() + i, |
| 247 | static_cast<uoffset_t>(val - (Data() + i * sizeof(uoffset_t)))); |
| 248 | } |
| 249 | |
| 250 | // Get a mutable pointer to tables/strings inside this vector. |
| 251 | mutable_return_type GetMutableObject(uoffset_t i) const { |
| 252 | FLATBUFFERS_ASSERT(i < size()); |
| 253 | return const_cast<mutable_return_type>(IndirectHelper<T>::Read(Data(), i)); |
| 254 | } |
| 255 | |
| 256 | // The raw data in little endian format. Use with care. |
| 257 | const uint8_t *Data() const { |
| 258 | return reinterpret_cast<const uint8_t *>(&length_ + 1); |
| 259 | } |
| 260 | |
| 261 | uint8_t *Data() { return reinterpret_cast<uint8_t *>(&length_ + 1); } |
| 262 | |
| 263 | // Similarly, but typed, much like std::vector::data |
| 264 | const T *data() const { return reinterpret_cast<const T *>(Data()); } |
| 265 | T *data() { return reinterpret_cast<T *>(Data()); } |
| 266 | |
| 267 | template<typename K> return_type LookupByKey(K key) const { |
| 268 | void *search_result = std::bsearch( |
| 269 | &key, Data(), size(), IndirectHelper<T>::element_stride, KeyCompare<K>); |
| 270 | |
| 271 | if (!search_result) { |
| 272 | return nullptr; // Key not found. |
| 273 | } |
| 274 | |
| 275 | const uint8_t *element = reinterpret_cast<const uint8_t *>(search_result); |
| 276 | |
| 277 | return IndirectHelper<T>::Read(element, 0); |
| 278 | } |
| 279 | |
| 280 | protected: |
| 281 | // This class is only used to access pre-existing data. Don't ever |
| 282 | // try to construct these manually. |
| 283 | Vector(); |
| 284 | |
| 285 | uoffset_t length_; |
| 286 | |
| 287 | private: |
| 288 | // This class is a pointer. Copying will therefore create an invalid object. |
| 289 | // Private and unimplemented copy constructor. |
| 290 | Vector(const Vector &); |
| 291 | |
| 292 | template<typename K> static int KeyCompare(const void *ap, const void *bp) { |
| 293 | const K *key = reinterpret_cast<const K *>(ap); |
| 294 | const uint8_t *data = reinterpret_cast<const uint8_t *>(bp); |
| 295 | auto table = IndirectHelper<T>::Read(data, 0); |
| 296 | |
| 297 | // std::bsearch compares with the operands transposed, so we negate the |
| 298 | // result here. |
| 299 | return -table->KeyCompareWithValue(*key); |
| 300 | } |
| 301 | }; |
| 302 | |
| 303 | // Represent a vector much like the template above, but in this case we |
| 304 | // don't know what the element types are (used with reflection.h). |
| 305 | class VectorOfAny { |
| 306 | public: |
| 307 | uoffset_t size() const { return EndianScalar(length_); } |
| 308 | |
| 309 | const uint8_t *Data() const { |
| 310 | return reinterpret_cast<const uint8_t *>(&length_ + 1); |
| 311 | } |
| 312 | uint8_t *Data() { return reinterpret_cast<uint8_t *>(&length_ + 1); } |
| 313 | |
| 314 | protected: |
| 315 | VectorOfAny(); |
| 316 | |
| 317 | uoffset_t length_; |
| 318 | |
| 319 | private: |
| 320 | VectorOfAny(const VectorOfAny &); |
| 321 | }; |
| 322 | |
| 323 | #ifndef FLATBUFFERS_CPP98_STL |
| 324 | template<typename T, typename U> |
| 325 | Vector<Offset<T>> *VectorCast(Vector<Offset<U>> *ptr) { |
| 326 | static_assert(std::is_base_of<T, U>::value, "Unrelated types" ); |
| 327 | return reinterpret_cast<Vector<Offset<T>> *>(ptr); |
| 328 | } |
| 329 | |
| 330 | template<typename T, typename U> |
| 331 | const Vector<Offset<T>> *VectorCast(const Vector<Offset<U>> *ptr) { |
| 332 | static_assert(std::is_base_of<T, U>::value, "Unrelated types" ); |
| 333 | return reinterpret_cast<const Vector<Offset<T>> *>(ptr); |
| 334 | } |
| 335 | #endif |
| 336 | |
| 337 | // Convenient helper function to get the length of any vector, regardless |
| 338 | // of whether it is null or not (the field is not set). |
| 339 | template<typename T> static inline size_t VectorLength(const Vector<T> *v) { |
| 340 | return v ? v->Length() : 0; |
| 341 | } |
| 342 | |
| 343 | struct String : public Vector<char> { |
| 344 | const char *c_str() const { return reinterpret_cast<const char *>(Data()); } |
| 345 | std::string str() const { return std::string(c_str(), Length()); } |
| 346 | |
| 347 | // clang-format off |
| 348 | #ifdef FLATBUFFERS_HAS_STRING_VIEW |
| 349 | flatbuffers::string_view string_view() const { |
| 350 | return flatbuffers::string_view(c_str(), Length()); |
| 351 | } |
| 352 | #endif // FLATBUFFERS_HAS_STRING_VIEW |
| 353 | // clang-format on |
| 354 | |
| 355 | bool operator<(const String &o) const { |
| 356 | return strcmp(c_str(), o.c_str()) < 0; |
| 357 | } |
| 358 | }; |
| 359 | |
| 360 | // Convenience function to get std::string from a String returning an empty |
| 361 | // string on null pointer. |
| 362 | static inline std::string GetString(const String * str) { |
| 363 | return str ? str->str() : "" ; |
| 364 | } |
| 365 | |
| 366 | // Convenience function to get char* from a String returning an empty string on |
| 367 | // null pointer. |
| 368 | static inline const char * GetCstring(const String * str) { |
| 369 | return str ? str->c_str() : "" ; |
| 370 | } |
| 371 | |
| 372 | // Allocator interface. This is flatbuffers-specific and meant only for |
| 373 | // `vector_downward` usage. |
| 374 | class Allocator { |
| 375 | public: |
| 376 | virtual ~Allocator() {} |
| 377 | |
| 378 | // Allocate `size` bytes of memory. |
| 379 | virtual uint8_t *allocate(size_t size) = 0; |
| 380 | |
| 381 | // Deallocate `size` bytes of memory at `p` allocated by this allocator. |
| 382 | virtual void deallocate(uint8_t *p, size_t size) = 0; |
| 383 | |
| 384 | // Reallocate `new_size` bytes of memory, replacing the old region of size |
| 385 | // `old_size` at `p`. In contrast to a normal realloc, this grows downwards, |
| 386 | // and is intended specifcally for `vector_downward` use. |
| 387 | // `in_use_back` and `in_use_front` indicate how much of `old_size` is |
| 388 | // actually in use at each end, and needs to be copied. |
| 389 | virtual uint8_t *reallocate_downward(uint8_t *old_p, size_t old_size, |
| 390 | size_t new_size, size_t in_use_back, |
| 391 | size_t in_use_front) { |
| 392 | FLATBUFFERS_ASSERT(new_size > old_size); // vector_downward only grows |
| 393 | uint8_t *new_p = allocate(new_size); |
| 394 | memcpy_downward(old_p, old_size, new_p, new_size, in_use_back, |
| 395 | in_use_front); |
| 396 | deallocate(old_p, old_size); |
| 397 | return new_p; |
| 398 | } |
| 399 | |
| 400 | protected: |
| 401 | // Called by `reallocate_downward` to copy memory from `old_p` of `old_size` |
| 402 | // to `new_p` of `new_size`. Only memory of size `in_use_front` and |
| 403 | // `in_use_back` will be copied from the front and back of the old memory |
| 404 | // allocation. |
| 405 | void memcpy_downward(uint8_t *old_p, size_t old_size, |
| 406 | uint8_t *new_p, size_t new_size, |
| 407 | size_t in_use_back, size_t in_use_front) { |
| 408 | memcpy(new_p + new_size - in_use_back, old_p + old_size - in_use_back, |
| 409 | in_use_back); |
| 410 | memcpy(new_p, old_p, in_use_front); |
| 411 | } |
| 412 | }; |
| 413 | |
| 414 | // DefaultAllocator uses new/delete to allocate memory regions |
| 415 | class DefaultAllocator : public Allocator { |
| 416 | public: |
| 417 | uint8_t *allocate(size_t size) FLATBUFFERS_OVERRIDE { |
| 418 | return new uint8_t[size]; |
| 419 | } |
| 420 | |
| 421 | void deallocate(uint8_t *p, size_t) FLATBUFFERS_OVERRIDE { |
| 422 | delete[] p; |
| 423 | } |
| 424 | }; |
| 425 | |
| 426 | // These functions allow for a null allocator to mean use the default allocator, |
| 427 | // as used by DetachedBuffer and vector_downward below. |
| 428 | // This is to avoid having a statically or dynamically allocated default |
| 429 | // allocator, or having to move it between the classes that may own it. |
| 430 | inline uint8_t *Allocate(Allocator *allocator, size_t size) { |
| 431 | return allocator ? allocator->allocate(size) |
| 432 | : DefaultAllocator().allocate(size); |
| 433 | } |
| 434 | |
| 435 | inline void Deallocate(Allocator *allocator, uint8_t *p, size_t size) { |
| 436 | if (allocator) allocator->deallocate(p, size); |
| 437 | else DefaultAllocator().deallocate(p, size); |
| 438 | } |
| 439 | |
| 440 | inline uint8_t *ReallocateDownward(Allocator *allocator, uint8_t *old_p, |
| 441 | size_t old_size, size_t new_size, |
| 442 | size_t in_use_back, size_t in_use_front) { |
| 443 | return allocator |
| 444 | ? allocator->reallocate_downward(old_p, old_size, new_size, |
| 445 | in_use_back, in_use_front) |
| 446 | : DefaultAllocator().reallocate_downward(old_p, old_size, new_size, |
| 447 | in_use_back, in_use_front); |
| 448 | } |
| 449 | |
| 450 | // DetachedBuffer is a finished flatbuffer memory region, detached from its |
| 451 | // builder. The original memory region and allocator are also stored so that |
| 452 | // the DetachedBuffer can manage the memory lifetime. |
| 453 | class DetachedBuffer { |
| 454 | public: |
| 455 | DetachedBuffer() |
| 456 | : allocator_(nullptr), |
| 457 | own_allocator_(false), |
| 458 | buf_(nullptr), |
| 459 | reserved_(0), |
| 460 | cur_(nullptr), |
| 461 | size_(0) {} |
| 462 | |
| 463 | DetachedBuffer(Allocator *allocator, bool own_allocator, uint8_t *buf, |
| 464 | size_t reserved, uint8_t *cur, size_t sz) |
| 465 | : allocator_(allocator), |
| 466 | own_allocator_(own_allocator), |
| 467 | buf_(buf), |
| 468 | reserved_(reserved), |
| 469 | cur_(cur), |
| 470 | size_(sz) {} |
| 471 | |
| 472 | DetachedBuffer(DetachedBuffer &&other) |
| 473 | : allocator_(other.allocator_), |
| 474 | own_allocator_(other.own_allocator_), |
| 475 | buf_(other.buf_), |
| 476 | reserved_(other.reserved_), |
| 477 | cur_(other.cur_), |
| 478 | size_(other.size_) { |
| 479 | other.reset(); |
| 480 | } |
| 481 | |
| 482 | DetachedBuffer &operator=(DetachedBuffer &&other) { |
| 483 | destroy(); |
| 484 | |
| 485 | allocator_ = other.allocator_; |
| 486 | own_allocator_ = other.own_allocator_; |
| 487 | buf_ = other.buf_; |
| 488 | reserved_ = other.reserved_; |
| 489 | cur_ = other.cur_; |
| 490 | size_ = other.size_; |
| 491 | |
| 492 | other.reset(); |
| 493 | |
| 494 | return *this; |
| 495 | } |
| 496 | |
| 497 | ~DetachedBuffer() { destroy(); } |
| 498 | |
| 499 | const uint8_t *data() const { return cur_; } |
| 500 | |
| 501 | uint8_t *data() { return cur_; } |
| 502 | |
| 503 | size_t size() const { return size_; } |
| 504 | |
| 505 | // clang-format off |
| 506 | #if 0 // disabled for now due to the ordering of classes in this header |
| 507 | template <class T> |
| 508 | bool Verify() const { |
| 509 | Verifier verifier(data(), size()); |
| 510 | return verifier.Verify<T>(nullptr); |
| 511 | } |
| 512 | |
| 513 | template <class T> |
| 514 | const T* GetRoot() const { |
| 515 | return flatbuffers::GetRoot<T>(data()); |
| 516 | } |
| 517 | |
| 518 | template <class T> |
| 519 | T* GetRoot() { |
| 520 | return flatbuffers::GetRoot<T>(data()); |
| 521 | } |
| 522 | #endif |
| 523 | // clang-format on |
| 524 | |
| 525 | // These may change access mode, leave these at end of public section |
| 526 | FLATBUFFERS_DELETE_FUNC(DetachedBuffer(const DetachedBuffer &other)) |
| 527 | FLATBUFFERS_DELETE_FUNC( |
| 528 | DetachedBuffer &operator=(const DetachedBuffer &other)) |
| 529 | |
| 530 | protected: |
| 531 | Allocator *allocator_; |
| 532 | bool own_allocator_; |
| 533 | uint8_t *buf_; |
| 534 | size_t reserved_; |
| 535 | uint8_t *cur_; |
| 536 | size_t size_; |
| 537 | |
| 538 | inline void destroy() { |
| 539 | if (buf_) Deallocate(allocator_, buf_, reserved_); |
| 540 | if (own_allocator_ && allocator_) { delete allocator_; } |
| 541 | reset(); |
| 542 | } |
| 543 | |
| 544 | inline void reset() { |
| 545 | allocator_ = nullptr; |
| 546 | own_allocator_ = false; |
| 547 | buf_ = nullptr; |
| 548 | reserved_ = 0; |
| 549 | cur_ = nullptr; |
| 550 | size_ = 0; |
| 551 | } |
| 552 | }; |
| 553 | |
| 554 | // This is a minimal replication of std::vector<uint8_t> functionality, |
| 555 | // except growing from higher to lower addresses. i.e push_back() inserts data |
| 556 | // in the lowest address in the vector. |
| 557 | // Since this vector leaves the lower part unused, we support a "scratch-pad" |
| 558 | // that can be stored there for temporary data, to share the allocated space. |
| 559 | // Essentially, this supports 2 std::vectors in a single buffer. |
| 560 | class vector_downward { |
| 561 | public: |
| 562 | explicit vector_downward(size_t initial_size, |
| 563 | Allocator *allocator, |
| 564 | bool own_allocator, |
| 565 | size_t buffer_minalign) |
| 566 | : allocator_(allocator), |
| 567 | own_allocator_(own_allocator), |
| 568 | initial_size_(initial_size), |
| 569 | buffer_minalign_(buffer_minalign), |
| 570 | reserved_(0), |
| 571 | buf_(nullptr), |
| 572 | cur_(nullptr), |
| 573 | scratch_(nullptr) {} |
| 574 | |
| 575 | vector_downward(vector_downward &&other) |
| 576 | : allocator_(other.allocator_), |
| 577 | own_allocator_(other.own_allocator_), |
| 578 | initial_size_(other.initial_size_), |
| 579 | buffer_minalign_(other.buffer_minalign_), |
| 580 | reserved_(other.reserved_), |
| 581 | buf_(other.buf_), |
| 582 | cur_(other.cur_), |
| 583 | scratch_(other.scratch_) { |
| 584 | other.allocator_ = nullptr; |
| 585 | other.own_allocator_ = false; |
| 586 | // No change in other.initial_size_ |
| 587 | // No change in other.buffer_minalign_ |
| 588 | other.reserved_ = 0; |
| 589 | other.buf_ = nullptr; |
| 590 | other.cur_ = nullptr; |
| 591 | other.scratch_ = nullptr; |
| 592 | } |
| 593 | |
| 594 | vector_downward &operator=(vector_downward &&other) { |
| 595 | // Move construct a temporary and swap idiom |
| 596 | vector_downward temp(std::move(other)); |
| 597 | swap(temp); |
| 598 | return *this; |
| 599 | } |
| 600 | |
| 601 | ~vector_downward() { |
| 602 | clear_buffer(); |
| 603 | clear_allocator(); |
| 604 | } |
| 605 | |
| 606 | void reset() { |
| 607 | clear_buffer(); |
| 608 | clear(); |
| 609 | } |
| 610 | |
| 611 | void clear() { |
| 612 | if (buf_) { |
| 613 | cur_ = buf_ + reserved_; |
| 614 | } else { |
| 615 | reserved_ = 0; |
| 616 | cur_ = nullptr; |
| 617 | } |
| 618 | clear_scratch(); |
| 619 | } |
| 620 | |
| 621 | void clear_scratch() { |
| 622 | scratch_ = buf_; |
| 623 | } |
| 624 | |
| 625 | void clear_allocator() { |
| 626 | if (own_allocator_ && allocator_) { delete allocator_; } |
| 627 | allocator_ = nullptr; |
| 628 | own_allocator_ = false; |
| 629 | } |
| 630 | |
| 631 | void clear_buffer() { |
| 632 | if (buf_) Deallocate(allocator_, buf_, reserved_); |
| 633 | buf_ = nullptr; |
| 634 | } |
| 635 | |
| 636 | // Relinquish the pointer to the caller. |
| 637 | uint8_t *release_raw(size_t &allocated_bytes, size_t &offset) { |
| 638 | auto *buf = buf_; |
| 639 | allocated_bytes = reserved_; |
| 640 | offset = static_cast<size_t>(cur_ - buf_); |
| 641 | |
| 642 | buf_ = nullptr; |
| 643 | clear_allocator(); |
| 644 | clear(); |
| 645 | return buf; |
| 646 | } |
| 647 | |
| 648 | // Relinquish the pointer to the caller. |
| 649 | DetachedBuffer release() { |
| 650 | DetachedBuffer fb(allocator_, own_allocator_, buf_, reserved_, cur_, |
| 651 | size()); |
| 652 | allocator_ = nullptr; |
| 653 | own_allocator_ = false; |
| 654 | buf_ = nullptr; |
| 655 | clear(); |
| 656 | return fb; |
| 657 | } |
| 658 | |
| 659 | size_t ensure_space(size_t len) { |
| 660 | FLATBUFFERS_ASSERT(cur_ >= scratch_ && scratch_ >= buf_); |
| 661 | if (len > static_cast<size_t>(cur_ - scratch_)) { reallocate(len); } |
| 662 | // Beyond this, signed offsets may not have enough range: |
| 663 | // (FlatBuffers > 2GB not supported). |
| 664 | FLATBUFFERS_ASSERT(size() < FLATBUFFERS_MAX_BUFFER_SIZE); |
| 665 | return len; |
| 666 | } |
| 667 | |
| 668 | inline uint8_t *make_space(size_t len) { |
| 669 | size_t space = ensure_space(len); |
| 670 | cur_ -= space; |
| 671 | return cur_; |
| 672 | } |
| 673 | |
| 674 | // Returns nullptr if using the DefaultAllocator. |
| 675 | Allocator *get_custom_allocator() { return allocator_; } |
| 676 | |
| 677 | uoffset_t size() const { |
| 678 | return static_cast<uoffset_t>(reserved_ - (cur_ - buf_)); |
| 679 | } |
| 680 | |
| 681 | uoffset_t scratch_size() const { |
| 682 | return static_cast<uoffset_t>(scratch_ - buf_); |
| 683 | } |
| 684 | |
| 685 | size_t capacity() const { return reserved_; } |
| 686 | |
| 687 | uint8_t *data() const { |
| 688 | FLATBUFFERS_ASSERT(cur_); |
| 689 | return cur_; |
| 690 | } |
| 691 | |
| 692 | uint8_t *scratch_data() const { |
| 693 | FLATBUFFERS_ASSERT(buf_); |
| 694 | return buf_; |
| 695 | } |
| 696 | |
| 697 | uint8_t *scratch_end() const { |
| 698 | FLATBUFFERS_ASSERT(scratch_); |
| 699 | return scratch_; |
| 700 | } |
| 701 | |
| 702 | uint8_t *data_at(size_t offset) const { return buf_ + reserved_ - offset; } |
| 703 | |
| 704 | void push(const uint8_t *bytes, size_t num) { |
| 705 | memcpy(make_space(num), bytes, num); |
| 706 | } |
| 707 | |
| 708 | // Specialized version of push() that avoids memcpy call for small data. |
| 709 | template<typename T> void push_small(const T &little_endian_t) { |
| 710 | make_space(sizeof(T)); |
| 711 | *reinterpret_cast<T *>(cur_) = little_endian_t; |
| 712 | } |
| 713 | |
| 714 | template<typename T> void scratch_push_small(const T &t) { |
| 715 | ensure_space(sizeof(T)); |
| 716 | *reinterpret_cast<T *>(scratch_) = t; |
| 717 | scratch_ += sizeof(T); |
| 718 | } |
| 719 | |
| 720 | // fill() is most frequently called with small byte counts (<= 4), |
| 721 | // which is why we're using loops rather than calling memset. |
| 722 | void fill(size_t zero_pad_bytes) { |
| 723 | make_space(zero_pad_bytes); |
| 724 | for (size_t i = 0; i < zero_pad_bytes; i++) cur_[i] = 0; |
| 725 | } |
| 726 | |
| 727 | // Version for when we know the size is larger. |
| 728 | void fill_big(size_t zero_pad_bytes) { |
| 729 | memset(make_space(zero_pad_bytes), 0, zero_pad_bytes); |
| 730 | } |
| 731 | |
| 732 | void pop(size_t bytes_to_remove) { cur_ += bytes_to_remove; } |
| 733 | void scratch_pop(size_t bytes_to_remove) { scratch_ -= bytes_to_remove; } |
| 734 | |
| 735 | void swap(vector_downward &other) { |
| 736 | using std::swap; |
| 737 | swap(allocator_, other.allocator_); |
| 738 | swap(own_allocator_, other.own_allocator_); |
| 739 | swap(initial_size_, other.initial_size_); |
| 740 | swap(buffer_minalign_, other.buffer_minalign_); |
| 741 | swap(reserved_, other.reserved_); |
| 742 | swap(buf_, other.buf_); |
| 743 | swap(cur_, other.cur_); |
| 744 | swap(scratch_, other.scratch_); |
| 745 | } |
| 746 | |
| 747 | void swap_allocator(vector_downward &other) { |
| 748 | using std::swap; |
| 749 | swap(allocator_, other.allocator_); |
| 750 | swap(own_allocator_, other.own_allocator_); |
| 751 | } |
| 752 | |
| 753 | private: |
| 754 | // You shouldn't really be copying instances of this class. |
| 755 | FLATBUFFERS_DELETE_FUNC(vector_downward(const vector_downward &)) |
| 756 | FLATBUFFERS_DELETE_FUNC(vector_downward &operator=(const vector_downward &)) |
| 757 | |
| 758 | Allocator *allocator_; |
| 759 | bool own_allocator_; |
| 760 | size_t initial_size_; |
| 761 | size_t buffer_minalign_; |
| 762 | size_t reserved_; |
| 763 | uint8_t *buf_; |
| 764 | uint8_t *cur_; // Points at location between empty (below) and used (above). |
| 765 | uint8_t *scratch_; // Points to the end of the scratchpad in use. |
| 766 | |
| 767 | void reallocate(size_t len) { |
| 768 | auto old_reserved = reserved_; |
| 769 | auto old_size = size(); |
| 770 | auto old_scratch_size = scratch_size(); |
| 771 | reserved_ += (std::max)(len, |
| 772 | old_reserved ? old_reserved / 2 : initial_size_); |
| 773 | reserved_ = (reserved_ + buffer_minalign_ - 1) & ~(buffer_minalign_ - 1); |
| 774 | if (buf_) { |
| 775 | buf_ = ReallocateDownward(allocator_, buf_, old_reserved, reserved_, |
| 776 | old_size, old_scratch_size); |
| 777 | } else { |
| 778 | buf_ = Allocate(allocator_, reserved_); |
| 779 | } |
| 780 | cur_ = buf_ + reserved_ - old_size; |
| 781 | scratch_ = buf_ + old_scratch_size; |
| 782 | } |
| 783 | }; |
| 784 | |
| 785 | // Converts a Field ID to a virtual table offset. |
| 786 | inline voffset_t FieldIndexToOffset(voffset_t field_id) { |
| 787 | // Should correspond to what EndTable() below builds up. |
| 788 | const int fixed_fields = 2; // Vtable size and Object Size. |
| 789 | return static_cast<voffset_t>((field_id + fixed_fields) * sizeof(voffset_t)); |
| 790 | } |
| 791 | |
| 792 | template<typename T, typename Alloc> |
| 793 | const T *data(const std::vector<T, Alloc> &v) { |
| 794 | return v.empty() ? nullptr : &v.front(); |
| 795 | } |
| 796 | template<typename T, typename Alloc> T *data(std::vector<T, Alloc> &v) { |
| 797 | return v.empty() ? nullptr : &v.front(); |
| 798 | } |
| 799 | |
| 800 | /// @endcond |
| 801 | |
| 802 | /// @addtogroup flatbuffers_cpp_api |
| 803 | /// @{ |
| 804 | /// @class FlatBufferBuilder |
| 805 | /// @brief Helper class to hold data needed in creation of a FlatBuffer. |
| 806 | /// To serialize data, you typically call one of the `Create*()` functions in |
| 807 | /// the generated code, which in turn call a sequence of `StartTable`/ |
| 808 | /// `PushElement`/`AddElement`/`EndTable`, or the builtin `CreateString`/ |
| 809 | /// `CreateVector` functions. Do this is depth-first order to build up a tree to |
| 810 | /// the root. `Finish()` wraps up the buffer ready for transport. |
| 811 | class FlatBufferBuilder { |
| 812 | public: |
| 813 | /// @brief Default constructor for FlatBufferBuilder. |
| 814 | /// @param[in] initial_size The initial size of the buffer, in bytes. Defaults |
| 815 | /// to `1024`. |
| 816 | /// @param[in] allocator An `Allocator` to use. If null will use |
| 817 | /// `DefaultAllocator`. |
| 818 | /// @param[in] own_allocator Whether the builder/vector should own the |
| 819 | /// allocator. Defaults to / `false`. |
| 820 | /// @param[in] buffer_minalign Force the buffer to be aligned to the given |
| 821 | /// minimum alignment upon reallocation. Only needed if you intend to store |
| 822 | /// types with custom alignment AND you wish to read the buffer in-place |
| 823 | /// directly after creation. |
| 824 | explicit FlatBufferBuilder(size_t initial_size = 1024, |
| 825 | Allocator *allocator = nullptr, |
| 826 | bool own_allocator = false, |
| 827 | size_t buffer_minalign = |
| 828 | AlignOf<largest_scalar_t>()) |
| 829 | : buf_(initial_size, allocator, own_allocator, buffer_minalign), |
| 830 | num_field_loc(0), |
| 831 | max_voffset_(0), |
| 832 | nested(false), |
| 833 | finished(false), |
| 834 | minalign_(1), |
| 835 | force_defaults_(false), |
| 836 | dedup_vtables_(true), |
| 837 | string_pool(nullptr) { |
| 838 | EndianCheck(); |
| 839 | } |
| 840 | |
| 841 | /// @brief Move constructor for FlatBufferBuilder. |
| 842 | FlatBufferBuilder(FlatBufferBuilder &&other) |
| 843 | : buf_(1024, nullptr, false, AlignOf<largest_scalar_t>()), |
| 844 | num_field_loc(0), |
| 845 | max_voffset_(0), |
| 846 | nested(false), |
| 847 | finished(false), |
| 848 | minalign_(1), |
| 849 | force_defaults_(false), |
| 850 | dedup_vtables_(true), |
| 851 | string_pool(nullptr) { |
| 852 | EndianCheck(); |
| 853 | // Default construct and swap idiom. |
| 854 | // Lack of delegating constructors in vs2010 makes it more verbose than needed. |
| 855 | Swap(other); |
| 856 | } |
| 857 | |
| 858 | /// @brief Move assignment operator for FlatBufferBuilder. |
| 859 | FlatBufferBuilder &operator=(FlatBufferBuilder &&other) { |
| 860 | // Move construct a temporary and swap idiom |
| 861 | FlatBufferBuilder temp(std::move(other)); |
| 862 | Swap(temp); |
| 863 | return *this; |
| 864 | } |
| 865 | |
| 866 | void Swap(FlatBufferBuilder &other) { |
| 867 | using std::swap; |
| 868 | buf_.swap(other.buf_); |
| 869 | swap(num_field_loc, other.num_field_loc); |
| 870 | swap(max_voffset_, other.max_voffset_); |
| 871 | swap(nested, other.nested); |
| 872 | swap(finished, other.finished); |
| 873 | swap(minalign_, other.minalign_); |
| 874 | swap(force_defaults_, other.force_defaults_); |
| 875 | swap(dedup_vtables_, other.dedup_vtables_); |
| 876 | swap(string_pool, other.string_pool); |
| 877 | } |
| 878 | |
| 879 | ~FlatBufferBuilder() { |
| 880 | if (string_pool) delete string_pool; |
| 881 | } |
| 882 | |
| 883 | void Reset() { |
| 884 | Clear(); // clear builder state |
| 885 | buf_.reset(); // deallocate buffer |
| 886 | } |
| 887 | |
| 888 | /// @brief Reset all the state in this FlatBufferBuilder so it can be reused |
| 889 | /// to construct another buffer. |
| 890 | void Clear() { |
| 891 | ClearOffsets(); |
| 892 | buf_.clear(); |
| 893 | nested = false; |
| 894 | finished = false; |
| 895 | minalign_ = 1; |
| 896 | if (string_pool) string_pool->clear(); |
| 897 | } |
| 898 | |
| 899 | /// @brief The current size of the serialized buffer, counting from the end. |
| 900 | /// @return Returns an `uoffset_t` with the current size of the buffer. |
| 901 | uoffset_t GetSize() const { return buf_.size(); } |
| 902 | |
| 903 | /// @brief Get the serialized buffer (after you call `Finish()`). |
| 904 | /// @return Returns an `uint8_t` pointer to the FlatBuffer data inside the |
| 905 | /// buffer. |
| 906 | uint8_t *GetBufferPointer() const { |
| 907 | Finished(); |
| 908 | return buf_.data(); |
| 909 | } |
| 910 | |
| 911 | /// @brief Get a pointer to an unfinished buffer. |
| 912 | /// @return Returns a `uint8_t` pointer to the unfinished buffer. |
| 913 | uint8_t *GetCurrentBufferPointer() const { return buf_.data(); } |
| 914 | |
| 915 | /// @brief Get the released pointer to the serialized buffer. |
| 916 | /// @warning Do NOT attempt to use this FlatBufferBuilder afterwards! |
| 917 | /// @return A `FlatBuffer` that owns the buffer and its allocator and |
| 918 | /// behaves similar to a `unique_ptr` with a deleter. |
| 919 | /// Deprecated: use Release() instead |
| 920 | DetachedBuffer ReleaseBufferPointer() { |
| 921 | Finished(); |
| 922 | return buf_.release(); |
| 923 | } |
| 924 | |
| 925 | /// @brief Get the released DetachedBuffer. |
| 926 | /// @return A `DetachedBuffer` that owns the buffer and its allocator. |
| 927 | DetachedBuffer Release() { |
| 928 | Finished(); |
| 929 | return buf_.release(); |
| 930 | } |
| 931 | |
| 932 | /// @brief Get the released pointer to the serialized buffer. |
| 933 | /// @param The size of the memory block containing |
| 934 | /// the serialized `FlatBuffer`. |
| 935 | /// @param The offset from the released pointer where the finished |
| 936 | /// `FlatBuffer` starts. |
| 937 | /// @return A raw pointer to the start of the memory block containing |
| 938 | /// the serialized `FlatBuffer`. |
| 939 | /// @remark If the allocator is owned, it gets deleted during this call. |
| 940 | uint8_t *ReleaseRaw(size_t &size, size_t &offset) { |
| 941 | Finished(); |
| 942 | return buf_.release_raw(size, offset); |
| 943 | } |
| 944 | |
| 945 | /// @brief get the minimum alignment this buffer needs to be accessed |
| 946 | /// properly. This is only known once all elements have been written (after |
| 947 | /// you call Finish()). You can use this information if you need to embed |
| 948 | /// a FlatBuffer in some other buffer, such that you can later read it |
| 949 | /// without first having to copy it into its own buffer. |
| 950 | size_t GetBufferMinAlignment() { |
| 951 | Finished(); |
| 952 | return minalign_; |
| 953 | } |
| 954 | |
| 955 | /// @cond FLATBUFFERS_INTERNAL |
| 956 | void Finished() const { |
| 957 | // If you get this assert, you're attempting to get access a buffer |
| 958 | // which hasn't been finished yet. Be sure to call |
| 959 | // FlatBufferBuilder::Finish with your root table. |
| 960 | // If you really need to access an unfinished buffer, call |
| 961 | // GetCurrentBufferPointer instead. |
| 962 | FLATBUFFERS_ASSERT(finished); |
| 963 | } |
| 964 | /// @endcond |
| 965 | |
| 966 | /// @brief In order to save space, fields that are set to their default value |
| 967 | /// don't get serialized into the buffer. |
| 968 | /// @param[in] bool fd When set to `true`, always serializes default values that are set. |
| 969 | /// Optional fields which are not set explicitly, will still not be serialized. |
| 970 | void ForceDefaults(bool fd) { force_defaults_ = fd; } |
| 971 | |
| 972 | /// @brief By default vtables are deduped in order to save space. |
| 973 | /// @param[in] bool dedup When set to `true`, dedup vtables. |
| 974 | void DedupVtables(bool dedup) { dedup_vtables_ = dedup; } |
| 975 | |
| 976 | /// @cond FLATBUFFERS_INTERNAL |
| 977 | void Pad(size_t num_bytes) { buf_.fill(num_bytes); } |
| 978 | |
| 979 | void TrackMinAlign(size_t elem_size) { |
| 980 | if (elem_size > minalign_) minalign_ = elem_size; |
| 981 | } |
| 982 | |
| 983 | void Align(size_t elem_size) { |
| 984 | TrackMinAlign(elem_size); |
| 985 | buf_.fill(PaddingBytes(buf_.size(), elem_size)); |
| 986 | } |
| 987 | |
| 988 | void PushFlatBuffer(const uint8_t *bytes, size_t size) { |
| 989 | PushBytes(bytes, size); |
| 990 | finished = true; |
| 991 | } |
| 992 | |
| 993 | void PushBytes(const uint8_t *bytes, size_t size) { buf_.push(bytes, size); } |
| 994 | |
| 995 | void PopBytes(size_t amount) { buf_.pop(amount); } |
| 996 | |
| 997 | template<typename T> void AssertScalarT() { |
| 998 | // The code assumes power of 2 sizes and endian-swap-ability. |
| 999 | static_assert(flatbuffers::is_scalar<T>::value, "T must be a scalar type" ); |
| 1000 | } |
| 1001 | |
| 1002 | // Write a single aligned scalar to the buffer |
| 1003 | template<typename T> uoffset_t PushElement(T element) { |
| 1004 | AssertScalarT<T>(); |
| 1005 | T litle_endian_element = EndianScalar(element); |
| 1006 | Align(sizeof(T)); |
| 1007 | buf_.push_small(litle_endian_element); |
| 1008 | return GetSize(); |
| 1009 | } |
| 1010 | |
| 1011 | template<typename T> uoffset_t PushElement(Offset<T> off) { |
| 1012 | // Special case for offsets: see ReferTo below. |
| 1013 | return PushElement(ReferTo(off.o)); |
| 1014 | } |
| 1015 | |
| 1016 | // When writing fields, we track where they are, so we can create correct |
| 1017 | // vtables later. |
| 1018 | void TrackField(voffset_t field, uoffset_t off) { |
| 1019 | FieldLoc fl = { off, field }; |
| 1020 | buf_.scratch_push_small(fl); |
| 1021 | num_field_loc++; |
| 1022 | max_voffset_ = (std::max)(max_voffset_, field); |
| 1023 | } |
| 1024 | |
| 1025 | // Like PushElement, but additionally tracks the field this represents. |
| 1026 | template<typename T> void AddElement(voffset_t field, T e, T def) { |
| 1027 | // We don't serialize values equal to the default. |
| 1028 | if (e == def && !force_defaults_) return; |
| 1029 | auto off = PushElement(e); |
| 1030 | TrackField(field, off); |
| 1031 | } |
| 1032 | |
| 1033 | template<typename T> void AddOffset(voffset_t field, Offset<T> off) { |
| 1034 | if (off.IsNull()) return; // Don't store. |
| 1035 | AddElement(field, ReferTo(off.o), static_cast<uoffset_t>(0)); |
| 1036 | } |
| 1037 | |
| 1038 | template<typename T> void AddStruct(voffset_t field, const T *structptr) { |
| 1039 | if (!structptr) return; // Default, don't store. |
| 1040 | Align(AlignOf<T>()); |
| 1041 | buf_.push_small(*structptr); |
| 1042 | TrackField(field, GetSize()); |
| 1043 | } |
| 1044 | |
| 1045 | void AddStructOffset(voffset_t field, uoffset_t off) { |
| 1046 | TrackField(field, off); |
| 1047 | } |
| 1048 | |
| 1049 | // Offsets initially are relative to the end of the buffer (downwards). |
| 1050 | // This function converts them to be relative to the current location |
| 1051 | // in the buffer (when stored here), pointing upwards. |
| 1052 | uoffset_t ReferTo(uoffset_t off) { |
| 1053 | // Align to ensure GetSize() below is correct. |
| 1054 | Align(sizeof(uoffset_t)); |
| 1055 | // Offset must refer to something already in buffer. |
| 1056 | FLATBUFFERS_ASSERT(off && off <= GetSize()); |
| 1057 | return GetSize() - off + static_cast<uoffset_t>(sizeof(uoffset_t)); |
| 1058 | } |
| 1059 | |
| 1060 | void NotNested() { |
| 1061 | // If you hit this, you're trying to construct a Table/Vector/String |
| 1062 | // during the construction of its parent table (between the MyTableBuilder |
| 1063 | // and table.Finish(). |
| 1064 | // Move the creation of these sub-objects to above the MyTableBuilder to |
| 1065 | // not get this assert. |
| 1066 | // Ignoring this assert may appear to work in simple cases, but the reason |
| 1067 | // it is here is that storing objects in-line may cause vtable offsets |
| 1068 | // to not fit anymore. It also leads to vtable duplication. |
| 1069 | FLATBUFFERS_ASSERT(!nested); |
| 1070 | // If you hit this, fields were added outside the scope of a table. |
| 1071 | FLATBUFFERS_ASSERT(!num_field_loc); |
| 1072 | } |
| 1073 | |
| 1074 | // From generated code (or from the parser), we call StartTable/EndTable |
| 1075 | // with a sequence of AddElement calls in between. |
| 1076 | uoffset_t StartTable() { |
| 1077 | NotNested(); |
| 1078 | nested = true; |
| 1079 | return GetSize(); |
| 1080 | } |
| 1081 | |
| 1082 | // This finishes one serialized object by generating the vtable if it's a |
| 1083 | // table, comparing it against existing vtables, and writing the |
| 1084 | // resulting vtable offset. |
| 1085 | uoffset_t EndTable(uoffset_t start) { |
| 1086 | // If you get this assert, a corresponding StartTable wasn't called. |
| 1087 | FLATBUFFERS_ASSERT(nested); |
| 1088 | // Write the vtable offset, which is the start of any Table. |
| 1089 | // We fill it's value later. |
| 1090 | auto vtableoffsetloc = PushElement<soffset_t>(0); |
| 1091 | // Write a vtable, which consists entirely of voffset_t elements. |
| 1092 | // It starts with the number of offsets, followed by a type id, followed |
| 1093 | // by the offsets themselves. In reverse: |
| 1094 | // Include space for the last offset and ensure empty tables have a |
| 1095 | // minimum size. |
| 1096 | max_voffset_ = |
| 1097 | (std::max)(static_cast<voffset_t>(max_voffset_ + sizeof(voffset_t)), |
| 1098 | FieldIndexToOffset(0)); |
| 1099 | buf_.fill_big(max_voffset_); |
| 1100 | auto table_object_size = vtableoffsetloc - start; |
| 1101 | // Vtable use 16bit offsets. |
| 1102 | FLATBUFFERS_ASSERT(table_object_size < 0x10000); |
| 1103 | WriteScalar<voffset_t>(buf_.data() + sizeof(voffset_t), |
| 1104 | static_cast<voffset_t>(table_object_size)); |
| 1105 | WriteScalar<voffset_t>(buf_.data(), max_voffset_); |
| 1106 | // Write the offsets into the table |
| 1107 | for (auto it = buf_.scratch_end() - num_field_loc * sizeof(FieldLoc); |
| 1108 | it < buf_.scratch_end(); it += sizeof(FieldLoc)) { |
| 1109 | auto field_location = reinterpret_cast<FieldLoc *>(it); |
| 1110 | auto pos = static_cast<voffset_t>(vtableoffsetloc - field_location->off); |
| 1111 | // If this asserts, it means you've set a field twice. |
| 1112 | FLATBUFFERS_ASSERT( |
| 1113 | !ReadScalar<voffset_t>(buf_.data() + field_location->id)); |
| 1114 | WriteScalar<voffset_t>(buf_.data() + field_location->id, pos); |
| 1115 | } |
| 1116 | ClearOffsets(); |
| 1117 | auto vt1 = reinterpret_cast<voffset_t *>(buf_.data()); |
| 1118 | auto vt1_size = ReadScalar<voffset_t>(vt1); |
| 1119 | auto vt_use = GetSize(); |
| 1120 | // See if we already have generated a vtable with this exact same |
| 1121 | // layout before. If so, make it point to the old one, remove this one. |
| 1122 | if (dedup_vtables_) { |
| 1123 | for (auto it = buf_.scratch_data(); it < buf_.scratch_end(); |
| 1124 | it += sizeof(uoffset_t)) { |
| 1125 | auto vt_offset_ptr = reinterpret_cast<uoffset_t *>(it); |
| 1126 | auto vt2 = reinterpret_cast<voffset_t *>(buf_.data_at(*vt_offset_ptr)); |
| 1127 | auto vt2_size = *vt2; |
| 1128 | if (vt1_size != vt2_size || memcmp(vt2, vt1, vt1_size)) continue; |
| 1129 | vt_use = *vt_offset_ptr; |
| 1130 | buf_.pop(GetSize() - vtableoffsetloc); |
| 1131 | break; |
| 1132 | } |
| 1133 | } |
| 1134 | // If this is a new vtable, remember it. |
| 1135 | if (vt_use == GetSize()) { buf_.scratch_push_small(vt_use); } |
| 1136 | // Fill the vtable offset we created above. |
| 1137 | // The offset points from the beginning of the object to where the |
| 1138 | // vtable is stored. |
| 1139 | // Offsets default direction is downward in memory for future format |
| 1140 | // flexibility (storing all vtables at the start of the file). |
| 1141 | WriteScalar(buf_.data_at(vtableoffsetloc), |
| 1142 | static_cast<soffset_t>(vt_use) - |
| 1143 | static_cast<soffset_t>(vtableoffsetloc)); |
| 1144 | |
| 1145 | nested = false; |
| 1146 | return vtableoffsetloc; |
| 1147 | } |
| 1148 | |
| 1149 | // DEPRECATED: call the version above instead. |
| 1150 | uoffset_t EndTable(uoffset_t start, voffset_t /*numfields*/) { |
| 1151 | return EndTable(start); |
| 1152 | } |
| 1153 | |
| 1154 | // This checks a required field has been set in a given table that has |
| 1155 | // just been constructed. |
| 1156 | template<typename T> void Required(Offset<T> table, voffset_t field); |
| 1157 | |
| 1158 | uoffset_t StartStruct(size_t alignment) { |
| 1159 | Align(alignment); |
| 1160 | return GetSize(); |
| 1161 | } |
| 1162 | |
| 1163 | uoffset_t EndStruct() { return GetSize(); } |
| 1164 | |
| 1165 | void ClearOffsets() { |
| 1166 | buf_.scratch_pop(num_field_loc * sizeof(FieldLoc)); |
| 1167 | num_field_loc = 0; |
| 1168 | max_voffset_ = 0; |
| 1169 | } |
| 1170 | |
| 1171 | // Aligns such that when "len" bytes are written, an object can be written |
| 1172 | // after it with "alignment" without padding. |
| 1173 | void PreAlign(size_t len, size_t alignment) { |
| 1174 | TrackMinAlign(alignment); |
| 1175 | buf_.fill(PaddingBytes(GetSize() + len, alignment)); |
| 1176 | } |
| 1177 | template<typename T> void PreAlign(size_t len) { |
| 1178 | AssertScalarT<T>(); |
| 1179 | PreAlign(len, sizeof(T)); |
| 1180 | } |
| 1181 | /// @endcond |
| 1182 | |
| 1183 | /// @brief Store a string in the buffer, which can contain any binary data. |
| 1184 | /// @param[in] str A const char pointer to the data to be stored as a string. |
| 1185 | /// @param[in] len The number of bytes that should be stored from `str`. |
| 1186 | /// @return Returns the offset in the buffer where the string starts. |
| 1187 | Offset<String> CreateString(const char *str, size_t len) { |
| 1188 | NotNested(); |
| 1189 | PreAlign<uoffset_t>(len + 1); // Always 0-terminated. |
| 1190 | buf_.fill(1); |
| 1191 | PushBytes(reinterpret_cast<const uint8_t *>(str), len); |
| 1192 | PushElement(static_cast<uoffset_t>(len)); |
| 1193 | return Offset<String>(GetSize()); |
| 1194 | } |
| 1195 | |
| 1196 | /// @brief Store a string in the buffer, which is null-terminated. |
| 1197 | /// @param[in] str A const char pointer to a C-string to add to the buffer. |
| 1198 | /// @return Returns the offset in the buffer where the string starts. |
| 1199 | Offset<String> CreateString(const char *str) { |
| 1200 | return CreateString(str, strlen(str)); |
| 1201 | } |
| 1202 | |
| 1203 | /// @brief Store a string in the buffer, which is null-terminated. |
| 1204 | /// @param[in] str A char pointer to a C-string to add to the buffer. |
| 1205 | /// @return Returns the offset in the buffer where the string starts. |
| 1206 | Offset<String> CreateString(char *str) { |
| 1207 | return CreateString(str, strlen(str)); |
| 1208 | } |
| 1209 | |
| 1210 | /// @brief Store a string in the buffer, which can contain any binary data. |
| 1211 | /// @param[in] str A const reference to a std::string to store in the buffer. |
| 1212 | /// @return Returns the offset in the buffer where the string starts. |
| 1213 | Offset<String> CreateString(const std::string &str) { |
| 1214 | return CreateString(str.c_str(), str.length()); |
| 1215 | } |
| 1216 | |
| 1217 | // clang-format off |
| 1218 | #ifdef FLATBUFFERS_HAS_STRING_VIEW |
| 1219 | /// @brief Store a string in the buffer, which can contain any binary data. |
| 1220 | /// @param[in] str A const string_view to copy in to the buffer. |
| 1221 | /// @return Returns the offset in the buffer where the string starts. |
| 1222 | Offset<String> CreateString(flatbuffers::string_view str) { |
| 1223 | return CreateString(str.data(), str.size()); |
| 1224 | } |
| 1225 | #endif // FLATBUFFERS_HAS_STRING_VIEW |
| 1226 | // clang-format on |
| 1227 | |
| 1228 | /// @brief Store a string in the buffer, which can contain any binary data. |
| 1229 | /// @param[in] str A const pointer to a `String` struct to add to the buffer. |
| 1230 | /// @return Returns the offset in the buffer where the string starts |
| 1231 | Offset<String> CreateString(const String *str) { |
| 1232 | return str ? CreateString(str->c_str(), str->Length()) : 0; |
| 1233 | } |
| 1234 | |
| 1235 | /// @brief Store a string in the buffer, which can contain any binary data. |
| 1236 | /// @param[in] str A const reference to a std::string like type with support |
| 1237 | /// of T::c_str() and T::length() to store in the buffer. |
| 1238 | /// @return Returns the offset in the buffer where the string starts. |
| 1239 | template<typename T> Offset<String> CreateString(const T &str) { |
| 1240 | return CreateString(str.c_str(), str.length()); |
| 1241 | } |
| 1242 | |
| 1243 | /// @brief Store a string in the buffer, which can contain any binary data. |
| 1244 | /// If a string with this exact contents has already been serialized before, |
| 1245 | /// instead simply returns the offset of the existing string. |
| 1246 | /// @param[in] str A const char pointer to the data to be stored as a string. |
| 1247 | /// @param[in] len The number of bytes that should be stored from `str`. |
| 1248 | /// @return Returns the offset in the buffer where the string starts. |
| 1249 | Offset<String> CreateSharedString(const char *str, size_t len) { |
| 1250 | if (!string_pool) |
| 1251 | string_pool = new StringOffsetMap(StringOffsetCompare(buf_)); |
| 1252 | auto size_before_string = buf_.size(); |
| 1253 | // Must first serialize the string, since the set is all offsets into |
| 1254 | // buffer. |
| 1255 | auto off = CreateString(str, len); |
| 1256 | auto it = string_pool->find(off); |
| 1257 | // If it exists we reuse existing serialized data! |
| 1258 | if (it != string_pool->end()) { |
| 1259 | // We can remove the string we serialized. |
| 1260 | buf_.pop(buf_.size() - size_before_string); |
| 1261 | return *it; |
| 1262 | } |
| 1263 | // Record this string for future use. |
| 1264 | string_pool->insert(off); |
| 1265 | return off; |
| 1266 | } |
| 1267 | |
| 1268 | /// @brief Store a string in the buffer, which null-terminated. |
| 1269 | /// If a string with this exact contents has already been serialized before, |
| 1270 | /// instead simply returns the offset of the existing string. |
| 1271 | /// @param[in] str A const char pointer to a C-string to add to the buffer. |
| 1272 | /// @return Returns the offset in the buffer where the string starts. |
| 1273 | Offset<String> CreateSharedString(const char *str) { |
| 1274 | return CreateSharedString(str, strlen(str)); |
| 1275 | } |
| 1276 | |
| 1277 | /// @brief Store a string in the buffer, which can contain any binary data. |
| 1278 | /// If a string with this exact contents has already been serialized before, |
| 1279 | /// instead simply returns the offset of the existing string. |
| 1280 | /// @param[in] str A const reference to a std::string to store in the buffer. |
| 1281 | /// @return Returns the offset in the buffer where the string starts. |
| 1282 | Offset<String> CreateSharedString(const std::string &str) { |
| 1283 | return CreateSharedString(str.c_str(), str.length()); |
| 1284 | } |
| 1285 | |
| 1286 | /// @brief Store a string in the buffer, which can contain any binary data. |
| 1287 | /// If a string with this exact contents has already been serialized before, |
| 1288 | /// instead simply returns the offset of the existing string. |
| 1289 | /// @param[in] str A const pointer to a `String` struct to add to the buffer. |
| 1290 | /// @return Returns the offset in the buffer where the string starts |
| 1291 | Offset<String> CreateSharedString(const String *str) { |
| 1292 | return CreateSharedString(str->c_str(), str->Length()); |
| 1293 | } |
| 1294 | |
| 1295 | /// @cond FLATBUFFERS_INTERNAL |
| 1296 | uoffset_t EndVector(size_t len) { |
| 1297 | FLATBUFFERS_ASSERT(nested); // Hit if no corresponding StartVector. |
| 1298 | nested = false; |
| 1299 | return PushElement(static_cast<uoffset_t>(len)); |
| 1300 | } |
| 1301 | |
| 1302 | void StartVector(size_t len, size_t elemsize) { |
| 1303 | NotNested(); |
| 1304 | nested = true; |
| 1305 | PreAlign<uoffset_t>(len * elemsize); |
| 1306 | PreAlign(len * elemsize, elemsize); // Just in case elemsize > uoffset_t. |
| 1307 | } |
| 1308 | |
| 1309 | // Call this right before StartVector/CreateVector if you want to force the |
| 1310 | // alignment to be something different than what the element size would |
| 1311 | // normally dictate. |
| 1312 | // This is useful when storing a nested_flatbuffer in a vector of bytes, |
| 1313 | // or when storing SIMD floats, etc. |
| 1314 | void ForceVectorAlignment(size_t len, size_t elemsize, size_t alignment) { |
| 1315 | PreAlign(len * elemsize, alignment); |
| 1316 | } |
| 1317 | |
| 1318 | // Similar to ForceVectorAlignment but for String fields. |
| 1319 | void ForceStringAlignment(size_t len, size_t alignment) { |
| 1320 | PreAlign((len + 1) * sizeof(char), alignment); |
| 1321 | } |
| 1322 | |
| 1323 | /// @endcond |
| 1324 | |
| 1325 | /// @brief Serialize an array into a FlatBuffer `vector`. |
| 1326 | /// @tparam T The data type of the array elements. |
| 1327 | /// @param[in] v A pointer to the array of type `T` to serialize into the |
| 1328 | /// buffer as a `vector`. |
| 1329 | /// @param[in] len The number of elements to serialize. |
| 1330 | /// @return Returns a typed `Offset` into the serialized data indicating |
| 1331 | /// where the vector is stored. |
| 1332 | template<typename T> Offset<Vector<T>> CreateVector(const T *v, size_t len) { |
| 1333 | // If this assert hits, you're specifying a template argument that is |
| 1334 | // causing the wrong overload to be selected, remove it. |
| 1335 | AssertScalarT<T>(); |
| 1336 | StartVector(len, sizeof(T)); |
| 1337 | // clang-format off |
| 1338 | #if FLATBUFFERS_LITTLEENDIAN |
| 1339 | PushBytes(reinterpret_cast<const uint8_t *>(v), len * sizeof(T)); |
| 1340 | #else |
| 1341 | if (sizeof(T) == 1) { |
| 1342 | PushBytes(reinterpret_cast<const uint8_t *>(v), len); |
| 1343 | } else { |
| 1344 | for (auto i = len; i > 0; ) { |
| 1345 | PushElement(v[--i]); |
| 1346 | } |
| 1347 | } |
| 1348 | #endif |
| 1349 | // clang-format on |
| 1350 | return Offset<Vector<T>>(EndVector(len)); |
| 1351 | } |
| 1352 | |
| 1353 | template<typename T> |
| 1354 | Offset<Vector<Offset<T>>> CreateVector(const Offset<T> *v, size_t len) { |
| 1355 | StartVector(len, sizeof(Offset<T>)); |
| 1356 | for (auto i = len; i > 0;) { PushElement(v[--i]); } |
| 1357 | return Offset<Vector<Offset<T>>>(EndVector(len)); |
| 1358 | } |
| 1359 | |
| 1360 | /// @brief Serialize a `std::vector` into a FlatBuffer `vector`. |
| 1361 | /// @tparam T The data type of the `std::vector` elements. |
| 1362 | /// @param v A const reference to the `std::vector` to serialize into the |
| 1363 | /// buffer as a `vector`. |
| 1364 | /// @return Returns a typed `Offset` into the serialized data indicating |
| 1365 | /// where the vector is stored. |
| 1366 | template<typename T> Offset<Vector<T>> CreateVector(const std::vector<T> &v) { |
| 1367 | return CreateVector(data(v), v.size()); |
| 1368 | } |
| 1369 | |
| 1370 | // vector<bool> may be implemented using a bit-set, so we can't access it as |
| 1371 | // an array. Instead, read elements manually. |
| 1372 | // Background: https://isocpp.org/blog/2012/11/on-vectorbool |
| 1373 | Offset<Vector<uint8_t>> CreateVector(const std::vector<bool> &v) { |
| 1374 | StartVector(v.size(), sizeof(uint8_t)); |
| 1375 | for (auto i = v.size(); i > 0;) { |
| 1376 | PushElement(static_cast<uint8_t>(v[--i])); |
| 1377 | } |
| 1378 | return Offset<Vector<uint8_t>>(EndVector(v.size())); |
| 1379 | } |
| 1380 | |
| 1381 | // clang-format off |
| 1382 | #ifndef FLATBUFFERS_CPP98_STL |
| 1383 | /// @brief Serialize values returned by a function into a FlatBuffer `vector`. |
| 1384 | /// This is a convenience function that takes care of iteration for you. |
| 1385 | /// @tparam T The data type of the `std::vector` elements. |
| 1386 | /// @param f A function that takes the current iteration 0..vector_size-1 and |
| 1387 | /// returns any type that you can construct a FlatBuffers vector out of. |
| 1388 | /// @return Returns a typed `Offset` into the serialized data indicating |
| 1389 | /// where the vector is stored. |
| 1390 | template<typename T> Offset<Vector<T>> CreateVector(size_t vector_size, |
| 1391 | const std::function<T (size_t i)> &f) { |
| 1392 | std::vector<T> elems(vector_size); |
| 1393 | for (size_t i = 0; i < vector_size; i++) elems[i] = f(i); |
| 1394 | return CreateVector(elems); |
| 1395 | } |
| 1396 | #endif |
| 1397 | // clang-format on |
| 1398 | |
| 1399 | /// @brief Serialize values returned by a function into a FlatBuffer `vector`. |
| 1400 | /// This is a convenience function that takes care of iteration for you. |
| 1401 | /// @tparam T The data type of the `std::vector` elements. |
| 1402 | /// @param f A function that takes the current iteration 0..vector_size-1, |
| 1403 | /// and the state parameter returning any type that you can construct a |
| 1404 | /// FlatBuffers vector out of. |
| 1405 | /// @param state State passed to f. |
| 1406 | /// @return Returns a typed `Offset` into the serialized data indicating |
| 1407 | /// where the vector is stored. |
| 1408 | template<typename T, typename F, typename S> |
| 1409 | Offset<Vector<T>> CreateVector(size_t vector_size, F f, S *state) { |
| 1410 | std::vector<T> elems(vector_size); |
| 1411 | for (size_t i = 0; i < vector_size; i++) elems[i] = f(i, state); |
| 1412 | return CreateVector(elems); |
| 1413 | } |
| 1414 | |
| 1415 | /// @brief Serialize a `std::vector<std::string>` into a FlatBuffer `vector`. |
| 1416 | /// This is a convenience function for a common case. |
| 1417 | /// @param v A const reference to the `std::vector` to serialize into the |
| 1418 | /// buffer as a `vector`. |
| 1419 | /// @return Returns a typed `Offset` into the serialized data indicating |
| 1420 | /// where the vector is stored. |
| 1421 | Offset<Vector<Offset<String>>> CreateVectorOfStrings( |
| 1422 | const std::vector<std::string> &v) { |
| 1423 | std::vector<Offset<String>> offsets(v.size()); |
| 1424 | for (size_t i = 0; i < v.size(); i++) offsets[i] = CreateString(v[i]); |
| 1425 | return CreateVector(offsets); |
| 1426 | } |
| 1427 | |
| 1428 | /// @brief Serialize an array of structs into a FlatBuffer `vector`. |
| 1429 | /// @tparam T The data type of the struct array elements. |
| 1430 | /// @param[in] v A pointer to the array of type `T` to serialize into the |
| 1431 | /// buffer as a `vector`. |
| 1432 | /// @param[in] len The number of elements to serialize. |
| 1433 | /// @return Returns a typed `Offset` into the serialized data indicating |
| 1434 | /// where the vector is stored. |
| 1435 | template<typename T> |
| 1436 | Offset<Vector<const T *>> CreateVectorOfStructs(const T *v, size_t len) { |
| 1437 | StartVector(len * sizeof(T) / AlignOf<T>(), AlignOf<T>()); |
| 1438 | PushBytes(reinterpret_cast<const uint8_t *>(v), sizeof(T) * len); |
| 1439 | return Offset<Vector<const T *>>(EndVector(len)); |
| 1440 | } |
| 1441 | |
| 1442 | /// @brief Serialize an array of native structs into a FlatBuffer `vector`. |
| 1443 | /// @tparam T The data type of the struct array elements. |
| 1444 | /// @tparam S The data type of the native struct array elements. |
| 1445 | /// @param[in] v A pointer to the array of type `S` to serialize into the |
| 1446 | /// buffer as a `vector`. |
| 1447 | /// @param[in] len The number of elements to serialize. |
| 1448 | /// @return Returns a typed `Offset` into the serialized data indicating |
| 1449 | /// where the vector is stored. |
| 1450 | template<typename T, typename S> |
| 1451 | Offset<Vector<const T *>> CreateVectorOfNativeStructs(const S *v, |
| 1452 | size_t len) { |
| 1453 | extern T Pack(const S &); |
| 1454 | typedef T (*Pack_t)(const S &); |
| 1455 | std::vector<T> vv(len); |
| 1456 | std::transform(v, v + len, vv.begin(), *(Pack_t)&Pack); |
| 1457 | return CreateVectorOfStructs<T>(vv.data(), vv.size()); |
| 1458 | } |
| 1459 | |
| 1460 | // clang-format off |
| 1461 | #ifndef FLATBUFFERS_CPP98_STL |
| 1462 | /// @brief Serialize an array of structs into a FlatBuffer `vector`. |
| 1463 | /// @tparam T The data type of the struct array elements. |
| 1464 | /// @param[in] f A function that takes the current iteration 0..vector_size-1 |
| 1465 | /// and a pointer to the struct that must be filled. |
| 1466 | /// @return Returns a typed `Offset` into the serialized data indicating |
| 1467 | /// where the vector is stored. |
| 1468 | /// This is mostly useful when flatbuffers are generated with mutation |
| 1469 | /// accessors. |
| 1470 | template<typename T> Offset<Vector<const T *>> CreateVectorOfStructs( |
| 1471 | size_t vector_size, const std::function<void(size_t i, T *)> &filler) { |
| 1472 | T* structs = StartVectorOfStructs<T>(vector_size); |
| 1473 | for (size_t i = 0; i < vector_size; i++) { |
| 1474 | filler(i, structs); |
| 1475 | structs++; |
| 1476 | } |
| 1477 | return EndVectorOfStructs<T>(vector_size); |
| 1478 | } |
| 1479 | #endif |
| 1480 | // clang-format on |
| 1481 | |
| 1482 | /// @brief Serialize an array of structs into a FlatBuffer `vector`. |
| 1483 | /// @tparam T The data type of the struct array elements. |
| 1484 | /// @param[in] f A function that takes the current iteration 0..vector_size-1, |
| 1485 | /// a pointer to the struct that must be filled and the state argument. |
| 1486 | /// @param[in] state Arbitrary state to pass to f. |
| 1487 | /// @return Returns a typed `Offset` into the serialized data indicating |
| 1488 | /// where the vector is stored. |
| 1489 | /// This is mostly useful when flatbuffers are generated with mutation |
| 1490 | /// accessors. |
| 1491 | template<typename T, typename F, typename S> |
| 1492 | Offset<Vector<const T *>> CreateVectorOfStructs(size_t vector_size, F f, |
| 1493 | S *state) { |
| 1494 | T *structs = StartVectorOfStructs<T>(vector_size); |
| 1495 | for (size_t i = 0; i < vector_size; i++) { |
| 1496 | f(i, structs, state); |
| 1497 | structs++; |
| 1498 | } |
| 1499 | return EndVectorOfStructs<T>(vector_size); |
| 1500 | } |
| 1501 | |
| 1502 | /// @brief Serialize a `std::vector` of structs into a FlatBuffer `vector`. |
| 1503 | /// @tparam T The data type of the `std::vector` struct elements. |
| 1504 | /// @param[in]] v A const reference to the `std::vector` of structs to |
| 1505 | /// serialize into the buffer as a `vector`. |
| 1506 | /// @return Returns a typed `Offset` into the serialized data indicating |
| 1507 | /// where the vector is stored. |
| 1508 | template<typename T, typename Alloc> |
| 1509 | Offset<Vector<const T *>> CreateVectorOfStructs( |
| 1510 | const std::vector<T, Alloc> &v) { |
| 1511 | return CreateVectorOfStructs(data(v), v.size()); |
| 1512 | } |
| 1513 | |
| 1514 | /// @brief Serialize a `std::vector` of native structs into a FlatBuffer |
| 1515 | /// `vector`. |
| 1516 | /// @tparam T The data type of the `std::vector` struct elements. |
| 1517 | /// @tparam S The data type of the `std::vector` native struct elements. |
| 1518 | /// @param[in]] v A const reference to the `std::vector` of structs to |
| 1519 | /// serialize into the buffer as a `vector`. |
| 1520 | /// @return Returns a typed `Offset` into the serialized data indicating |
| 1521 | /// where the vector is stored. |
| 1522 | template<typename T, typename S> |
| 1523 | Offset<Vector<const T *>> CreateVectorOfNativeStructs( |
| 1524 | const std::vector<S> &v) { |
| 1525 | return CreateVectorOfNativeStructs<T, S>(data(v), v.size()); |
| 1526 | } |
| 1527 | |
| 1528 | /// @cond FLATBUFFERS_INTERNAL |
| 1529 | template<typename T> struct StructKeyComparator { |
| 1530 | bool operator()(const T &a, const T &b) const { |
| 1531 | return a.KeyCompareLessThan(&b); |
| 1532 | } |
| 1533 | |
| 1534 | private: |
| 1535 | StructKeyComparator &operator=(const StructKeyComparator &); |
| 1536 | }; |
| 1537 | /// @endcond |
| 1538 | |
| 1539 | /// @brief Serialize a `std::vector` of structs into a FlatBuffer `vector` |
| 1540 | /// in sorted order. |
| 1541 | /// @tparam T The data type of the `std::vector` struct elements. |
| 1542 | /// @param[in]] v A const reference to the `std::vector` of structs to |
| 1543 | /// serialize into the buffer as a `vector`. |
| 1544 | /// @return Returns a typed `Offset` into the serialized data indicating |
| 1545 | /// where the vector is stored. |
| 1546 | template<typename T> |
| 1547 | Offset<Vector<const T *>> CreateVectorOfSortedStructs(std::vector<T> *v) { |
| 1548 | return CreateVectorOfSortedStructs(data(*v), v->size()); |
| 1549 | } |
| 1550 | |
| 1551 | /// @brief Serialize a `std::vector` of native structs into a FlatBuffer |
| 1552 | /// `vector` in sorted order. |
| 1553 | /// @tparam T The data type of the `std::vector` struct elements. |
| 1554 | /// @tparam S The data type of the `std::vector` native struct elements. |
| 1555 | /// @param[in]] v A const reference to the `std::vector` of structs to |
| 1556 | /// serialize into the buffer as a `vector`. |
| 1557 | /// @return Returns a typed `Offset` into the serialized data indicating |
| 1558 | /// where the vector is stored. |
| 1559 | template<typename T, typename S> |
| 1560 | Offset<Vector<const T *>> CreateVectorOfSortedNativeStructs( |
| 1561 | std::vector<S> *v) { |
| 1562 | return CreateVectorOfSortedNativeStructs<T, S>(data(*v), v->size()); |
| 1563 | } |
| 1564 | |
| 1565 | /// @brief Serialize an array of structs into a FlatBuffer `vector` in sorted |
| 1566 | /// order. |
| 1567 | /// @tparam T The data type of the struct array elements. |
| 1568 | /// @param[in] v A pointer to the array of type `T` to serialize into the |
| 1569 | /// buffer as a `vector`. |
| 1570 | /// @param[in] len The number of elements to serialize. |
| 1571 | /// @return Returns a typed `Offset` into the serialized data indicating |
| 1572 | /// where the vector is stored. |
| 1573 | template<typename T> |
| 1574 | Offset<Vector<const T *>> CreateVectorOfSortedStructs(T *v, size_t len) { |
| 1575 | std::sort(v, v + len, StructKeyComparator<T>()); |
| 1576 | return CreateVectorOfStructs(v, len); |
| 1577 | } |
| 1578 | |
| 1579 | /// @brief Serialize an array of native structs into a FlatBuffer `vector` in |
| 1580 | /// sorted order. |
| 1581 | /// @tparam T The data type of the struct array elements. |
| 1582 | /// @tparam S The data type of the native struct array elements. |
| 1583 | /// @param[in] v A pointer to the array of type `S` to serialize into the |
| 1584 | /// buffer as a `vector`. |
| 1585 | /// @param[in] len The number of elements to serialize. |
| 1586 | /// @return Returns a typed `Offset` into the serialized data indicating |
| 1587 | /// where the vector is stored. |
| 1588 | template<typename T, typename S> |
| 1589 | Offset<Vector<const T *>> CreateVectorOfSortedNativeStructs(S *v, |
| 1590 | size_t len) { |
| 1591 | extern T Pack(const S &); |
| 1592 | typedef T (*Pack_t)(const S &); |
| 1593 | std::vector<T> vv(len); |
| 1594 | std::transform(v, v + len, vv.begin(), *(Pack_t)&Pack); |
| 1595 | return CreateVectorOfSortedStructs<T>(vv, len); |
| 1596 | } |
| 1597 | |
| 1598 | /// @cond FLATBUFFERS_INTERNAL |
| 1599 | template<typename T> struct TableKeyComparator { |
| 1600 | TableKeyComparator(vector_downward &buf) : buf_(buf) {} |
| 1601 | bool operator()(const Offset<T> &a, const Offset<T> &b) const { |
| 1602 | auto table_a = reinterpret_cast<T *>(buf_.data_at(a.o)); |
| 1603 | auto table_b = reinterpret_cast<T *>(buf_.data_at(b.o)); |
| 1604 | return table_a->KeyCompareLessThan(table_b); |
| 1605 | } |
| 1606 | vector_downward &buf_; |
| 1607 | |
| 1608 | private: |
| 1609 | TableKeyComparator &operator=(const TableKeyComparator &); |
| 1610 | }; |
| 1611 | /// @endcond |
| 1612 | |
| 1613 | /// @brief Serialize an array of `table` offsets as a `vector` in the buffer |
| 1614 | /// in sorted order. |
| 1615 | /// @tparam T The data type that the offset refers to. |
| 1616 | /// @param[in] v An array of type `Offset<T>` that contains the `table` |
| 1617 | /// offsets to store in the buffer in sorted order. |
| 1618 | /// @param[in] len The number of elements to store in the `vector`. |
| 1619 | /// @return Returns a typed `Offset` into the serialized data indicating |
| 1620 | /// where the vector is stored. |
| 1621 | template<typename T> |
| 1622 | Offset<Vector<Offset<T>>> CreateVectorOfSortedTables(Offset<T> *v, |
| 1623 | size_t len) { |
| 1624 | std::sort(v, v + len, TableKeyComparator<T>(buf_)); |
| 1625 | return CreateVector(v, len); |
| 1626 | } |
| 1627 | |
| 1628 | /// @brief Serialize an array of `table` offsets as a `vector` in the buffer |
| 1629 | /// in sorted order. |
| 1630 | /// @tparam T The data type that the offset refers to. |
| 1631 | /// @param[in] v An array of type `Offset<T>` that contains the `table` |
| 1632 | /// offsets to store in the buffer in sorted order. |
| 1633 | /// @return Returns a typed `Offset` into the serialized data indicating |
| 1634 | /// where the vector is stored. |
| 1635 | template<typename T> |
| 1636 | Offset<Vector<Offset<T>>> CreateVectorOfSortedTables( |
| 1637 | std::vector<Offset<T>> *v) { |
| 1638 | return CreateVectorOfSortedTables(data(*v), v->size()); |
| 1639 | } |
| 1640 | |
| 1641 | /// @brief Specialized version of `CreateVector` for non-copying use cases. |
| 1642 | /// Write the data any time later to the returned buffer pointer `buf`. |
| 1643 | /// @param[in] len The number of elements to store in the `vector`. |
| 1644 | /// @param[in] elemsize The size of each element in the `vector`. |
| 1645 | /// @param[out] buf A pointer to a `uint8_t` pointer that can be |
| 1646 | /// written to at a later time to serialize the data into a `vector` |
| 1647 | /// in the buffer. |
| 1648 | uoffset_t CreateUninitializedVector(size_t len, size_t elemsize, |
| 1649 | uint8_t **buf) { |
| 1650 | NotNested(); |
| 1651 | StartVector(len, elemsize); |
| 1652 | buf_.make_space(len * elemsize); |
| 1653 | auto vec_start = GetSize(); |
| 1654 | auto vec_end = EndVector(len); |
| 1655 | *buf = buf_.data_at(vec_start); |
| 1656 | return vec_end; |
| 1657 | } |
| 1658 | |
| 1659 | /// @brief Specialized version of `CreateVector` for non-copying use cases. |
| 1660 | /// Write the data any time later to the returned buffer pointer `buf`. |
| 1661 | /// @tparam T The data type of the data that will be stored in the buffer |
| 1662 | /// as a `vector`. |
| 1663 | /// @param[in] len The number of elements to store in the `vector`. |
| 1664 | /// @param[out] buf A pointer to a pointer of type `T` that can be |
| 1665 | /// written to at a later time to serialize the data into a `vector` |
| 1666 | /// in the buffer. |
| 1667 | template<typename T> |
| 1668 | Offset<Vector<T>> CreateUninitializedVector(size_t len, T **buf) { |
| 1669 | AssertScalarT<T>(); |
| 1670 | return CreateUninitializedVector(len, sizeof(T), |
| 1671 | reinterpret_cast<uint8_t **>(buf)); |
| 1672 | } |
| 1673 | |
| 1674 | template<typename T> |
| 1675 | Offset<Vector<const T*>> CreateUninitializedVectorOfStructs(size_t len, T **buf) { |
| 1676 | return CreateUninitializedVector(len, sizeof(T), |
| 1677 | reinterpret_cast<uint8_t **>(buf)); |
| 1678 | } |
| 1679 | |
| 1680 | /// @brief Write a struct by itself, typically to be part of a union. |
| 1681 | template<typename T> Offset<const T *> CreateStruct(const T &structobj) { |
| 1682 | NotNested(); |
| 1683 | Align(AlignOf<T>()); |
| 1684 | buf_.push_small(structobj); |
| 1685 | return Offset<const T *>(GetSize()); |
| 1686 | } |
| 1687 | |
| 1688 | /// @brief The length of a FlatBuffer file header. |
| 1689 | static const size_t kFileIdentifierLength = 4; |
| 1690 | |
| 1691 | /// @brief Finish serializing a buffer by writing the root offset. |
| 1692 | /// @param[in] file_identifier If a `file_identifier` is given, the buffer |
| 1693 | /// will be prefixed with a standard FlatBuffers file header. |
| 1694 | template<typename T> |
| 1695 | void Finish(Offset<T> root, const char *file_identifier = nullptr) { |
| 1696 | Finish(root.o, file_identifier, false); |
| 1697 | } |
| 1698 | |
| 1699 | /// @brief Finish a buffer with a 32 bit size field pre-fixed (size of the |
| 1700 | /// buffer following the size field). These buffers are NOT compatible |
| 1701 | /// with standard buffers created by Finish, i.e. you can't call GetRoot |
| 1702 | /// on them, you have to use GetSizePrefixedRoot instead. |
| 1703 | /// All >32 bit quantities in this buffer will be aligned when the whole |
| 1704 | /// size pre-fixed buffer is aligned. |
| 1705 | /// These kinds of buffers are useful for creating a stream of FlatBuffers. |
| 1706 | template<typename T> |
| 1707 | void FinishSizePrefixed(Offset<T> root, |
| 1708 | const char *file_identifier = nullptr) { |
| 1709 | Finish(root.o, file_identifier, true); |
| 1710 | } |
| 1711 | |
| 1712 | protected: |
| 1713 | // You shouldn't really be copying instances of this class. |
| 1714 | FlatBufferBuilder(const FlatBufferBuilder &); |
| 1715 | FlatBufferBuilder &operator=(const FlatBufferBuilder &); |
| 1716 | |
| 1717 | void Finish(uoffset_t root, const char *file_identifier, bool size_prefix) { |
| 1718 | NotNested(); |
| 1719 | buf_.clear_scratch(); |
| 1720 | // This will cause the whole buffer to be aligned. |
| 1721 | PreAlign((size_prefix ? sizeof(uoffset_t) : 0) + sizeof(uoffset_t) + |
| 1722 | (file_identifier ? kFileIdentifierLength : 0), |
| 1723 | minalign_); |
| 1724 | if (file_identifier) { |
| 1725 | FLATBUFFERS_ASSERT(strlen(file_identifier) == kFileIdentifierLength); |
| 1726 | PushBytes(reinterpret_cast<const uint8_t *>(file_identifier), |
| 1727 | kFileIdentifierLength); |
| 1728 | } |
| 1729 | PushElement(ReferTo(root)); // Location of root. |
| 1730 | if (size_prefix) { PushElement(GetSize()); } |
| 1731 | finished = true; |
| 1732 | } |
| 1733 | |
| 1734 | struct FieldLoc { |
| 1735 | uoffset_t off; |
| 1736 | voffset_t id; |
| 1737 | }; |
| 1738 | |
| 1739 | vector_downward buf_; |
| 1740 | |
| 1741 | // Accumulating offsets of table members while it is being built. |
| 1742 | // We store these in the scratch pad of buf_, after the vtable offsets. |
| 1743 | uoffset_t num_field_loc; |
| 1744 | // Track how much of the vtable is in use, so we can output the most compact |
| 1745 | // possible vtable. |
| 1746 | voffset_t max_voffset_; |
| 1747 | |
| 1748 | // Ensure objects are not nested. |
| 1749 | bool nested; |
| 1750 | |
| 1751 | // Ensure the buffer is finished before it is being accessed. |
| 1752 | bool finished; |
| 1753 | |
| 1754 | size_t minalign_; |
| 1755 | |
| 1756 | bool force_defaults_; // Serialize values equal to their defaults anyway. |
| 1757 | |
| 1758 | bool dedup_vtables_; |
| 1759 | |
| 1760 | struct StringOffsetCompare { |
| 1761 | StringOffsetCompare(const vector_downward &buf) : buf_(&buf) {} |
| 1762 | bool operator()(const Offset<String> &a, const Offset<String> &b) const { |
| 1763 | auto stra = reinterpret_cast<const String *>(buf_->data_at(a.o)); |
| 1764 | auto strb = reinterpret_cast<const String *>(buf_->data_at(b.o)); |
| 1765 | return strncmp(stra->c_str(), strb->c_str(), |
| 1766 | (std::min)(stra->size(), strb->size()) + 1) < 0; |
| 1767 | } |
| 1768 | const vector_downward *buf_; |
| 1769 | }; |
| 1770 | |
| 1771 | // For use with CreateSharedString. Instantiated on first use only. |
| 1772 | typedef std::set<Offset<String>, StringOffsetCompare> StringOffsetMap; |
| 1773 | StringOffsetMap *string_pool; |
| 1774 | |
| 1775 | private: |
| 1776 | // Allocates space for a vector of structures. |
| 1777 | // Must be completed with EndVectorOfStructs(). |
| 1778 | template<typename T> T *StartVectorOfStructs(size_t vector_size) { |
| 1779 | StartVector(vector_size * sizeof(T) / AlignOf<T>(), AlignOf<T>()); |
| 1780 | return reinterpret_cast<T *>(buf_.make_space(vector_size * sizeof(T))); |
| 1781 | } |
| 1782 | |
| 1783 | // End the vector of structues in the flatbuffers. |
| 1784 | // Vector should have previously be started with StartVectorOfStructs(). |
| 1785 | template<typename T> |
| 1786 | Offset<Vector<const T *>> EndVectorOfStructs(size_t vector_size) { |
| 1787 | return Offset<Vector<const T *>>(EndVector(vector_size)); |
| 1788 | } |
| 1789 | }; |
| 1790 | /// @} |
| 1791 | |
| 1792 | /// @cond FLATBUFFERS_INTERNAL |
| 1793 | // Helpers to get a typed pointer to the root object contained in the buffer. |
| 1794 | template<typename T> T *GetMutableRoot(void *buf) { |
| 1795 | EndianCheck(); |
| 1796 | return reinterpret_cast<T *>( |
| 1797 | reinterpret_cast<uint8_t *>(buf) + |
| 1798 | EndianScalar(*reinterpret_cast<uoffset_t *>(buf))); |
| 1799 | } |
| 1800 | |
| 1801 | template<typename T> const T *GetRoot(const void *buf) { |
| 1802 | return GetMutableRoot<T>(const_cast<void *>(buf)); |
| 1803 | } |
| 1804 | |
| 1805 | template<typename T> const T *GetSizePrefixedRoot(const void *buf) { |
| 1806 | return GetRoot<T>(reinterpret_cast<const uint8_t *>(buf) + sizeof(uoffset_t)); |
| 1807 | } |
| 1808 | |
| 1809 | /// Helpers to get a typed pointer to objects that are currently being built. |
| 1810 | /// @warning Creating new objects will lead to reallocations and invalidates |
| 1811 | /// the pointer! |
| 1812 | template<typename T> |
| 1813 | T *GetMutableTemporaryPointer(FlatBufferBuilder &fbb, Offset<T> offset) { |
| 1814 | return reinterpret_cast<T *>(fbb.GetCurrentBufferPointer() + fbb.GetSize() - |
| 1815 | offset.o); |
| 1816 | } |
| 1817 | |
| 1818 | template<typename T> |
| 1819 | const T *GetTemporaryPointer(FlatBufferBuilder &fbb, Offset<T> offset) { |
| 1820 | return GetMutableTemporaryPointer<T>(fbb, offset); |
| 1821 | } |
| 1822 | |
| 1823 | /// @brief Get a pointer to the the file_identifier section of the buffer. |
| 1824 | /// @return Returns a const char pointer to the start of the file_identifier |
| 1825 | /// characters in the buffer. The returned char * has length |
| 1826 | /// 'flatbuffers::FlatBufferBuilder::kFileIdentifierLength'. |
| 1827 | /// This function is UNDEFINED for FlatBuffers whose schema does not include |
| 1828 | /// a file_identifier (likely points at padding or the start of a the root |
| 1829 | /// vtable). |
| 1830 | inline const char *GetBufferIdentifier(const void *buf, bool size_prefixed = false) { |
| 1831 | return reinterpret_cast<const char *>(buf) + |
| 1832 | ((size_prefixed) ? 2 * sizeof(uoffset_t) : sizeof(uoffset_t)); |
| 1833 | } |
| 1834 | |
| 1835 | // Helper to see if the identifier in a buffer has the expected value. |
| 1836 | inline bool BufferHasIdentifier(const void *buf, const char *identifier, bool size_prefixed = false) { |
| 1837 | return strncmp(GetBufferIdentifier(buf, size_prefixed), identifier, |
| 1838 | FlatBufferBuilder::kFileIdentifierLength) == 0; |
| 1839 | } |
| 1840 | |
| 1841 | // Helper class to verify the integrity of a FlatBuffer |
| 1842 | class Verifier FLATBUFFERS_FINAL_CLASS { |
| 1843 | public: |
| 1844 | Verifier(const uint8_t *buf, size_t buf_len, uoffset_t _max_depth = 64, |
| 1845 | uoffset_t _max_tables = 1000000) |
| 1846 | : buf_(buf), |
| 1847 | size_(buf_len), |
| 1848 | depth_(0), |
| 1849 | max_depth_(_max_depth), |
| 1850 | num_tables_(0), |
| 1851 | max_tables_(_max_tables) |
| 1852 | // clang-format off |
| 1853 | #ifdef FLATBUFFERS_TRACK_VERIFIER_BUFFER_SIZE |
| 1854 | , upper_bound_(0) |
| 1855 | #endif |
| 1856 | // clang-format on |
| 1857 | { |
| 1858 | assert(size_ < FLATBUFFERS_MAX_BUFFER_SIZE); |
| 1859 | } |
| 1860 | |
| 1861 | // Central location where any verification failures register. |
| 1862 | bool Check(bool ok) const { |
| 1863 | // clang-format off |
| 1864 | #ifdef FLATBUFFERS_DEBUG_VERIFICATION_FAILURE |
| 1865 | FLATBUFFERS_ASSERT(ok); |
| 1866 | #endif |
| 1867 | #ifdef FLATBUFFERS_TRACK_VERIFIER_BUFFER_SIZE |
| 1868 | if (!ok) |
| 1869 | upper_bound_ = 0; |
| 1870 | #endif |
| 1871 | // clang-format on |
| 1872 | return ok; |
| 1873 | } |
| 1874 | |
| 1875 | // Verify any range within the buffer. |
| 1876 | bool Verify(size_t elem, size_t elem_len) const { |
| 1877 | // clang-format off |
| 1878 | #ifdef FLATBUFFERS_TRACK_VERIFIER_BUFFER_SIZE |
| 1879 | auto upper_bound = elem + elem_len; |
| 1880 | if (upper_bound_ < upper_bound) |
| 1881 | upper_bound_ = upper_bound; |
| 1882 | #endif |
| 1883 | // clang-format on |
| 1884 | return Check(elem_len < size_ && elem <= size_ - elem_len); |
| 1885 | } |
| 1886 | |
| 1887 | template<typename T> bool VerifyAlignment(size_t elem) const { |
| 1888 | return (elem & (sizeof(T) - 1)) == 0; |
| 1889 | } |
| 1890 | |
| 1891 | // Verify a range indicated by sizeof(T). |
| 1892 | template<typename T> bool Verify(size_t elem) const { |
| 1893 | return VerifyAlignment<T>(elem) && Verify(elem, sizeof(T)); |
| 1894 | } |
| 1895 | |
| 1896 | // Verify relative to a known-good base pointer. |
| 1897 | bool Verify(const uint8_t *base, voffset_t elem_off, size_t elem_len) const { |
| 1898 | return Verify(static_cast<size_t>(base - buf_) + elem_off, elem_len); |
| 1899 | } |
| 1900 | |
| 1901 | template<typename T> bool Verify(const uint8_t *base, voffset_t elem_off) |
| 1902 | const { |
| 1903 | return Verify(static_cast<size_t>(base - buf_) + elem_off, sizeof(T)); |
| 1904 | } |
| 1905 | |
| 1906 | // Verify a pointer (may be NULL) of a table type. |
| 1907 | template<typename T> bool VerifyTable(const T *table) { |
| 1908 | return !table || table->Verify(*this); |
| 1909 | } |
| 1910 | |
| 1911 | // Verify a pointer (may be NULL) of any vector type. |
| 1912 | template<typename T> bool VerifyVector(const Vector<T> *vec) const { |
| 1913 | return !vec || VerifyVectorOrString(reinterpret_cast<const uint8_t *>(vec), |
| 1914 | sizeof(T)); |
| 1915 | } |
| 1916 | |
| 1917 | // Verify a pointer (may be NULL) of a vector to struct. |
| 1918 | template<typename T> bool VerifyVector(const Vector<const T *> *vec) const { |
| 1919 | return VerifyVector(reinterpret_cast<const Vector<T> *>(vec)); |
| 1920 | } |
| 1921 | |
| 1922 | // Verify a pointer (may be NULL) to string. |
| 1923 | bool VerifyString(const String *str) const { |
| 1924 | size_t end; |
| 1925 | return !str || |
| 1926 | (VerifyVectorOrString(reinterpret_cast<const uint8_t *>(str), |
| 1927 | 1, &end) && |
| 1928 | Verify(end, 1) && // Must have terminator |
| 1929 | Check(buf_[end] == '\0')); // Terminating byte must be 0. |
| 1930 | } |
| 1931 | |
| 1932 | // Common code between vectors and strings. |
| 1933 | bool VerifyVectorOrString(const uint8_t *vec, size_t elem_size, |
| 1934 | size_t *end = nullptr) const { |
| 1935 | auto veco = static_cast<size_t>(vec - buf_); |
| 1936 | // Check we can read the size field. |
| 1937 | if (!Verify<uoffset_t>(veco)) return false; |
| 1938 | // Check the whole array. If this is a string, the byte past the array |
| 1939 | // must be 0. |
| 1940 | auto size = ReadScalar<uoffset_t>(vec); |
| 1941 | auto max_elems = FLATBUFFERS_MAX_BUFFER_SIZE / elem_size; |
| 1942 | if (!Check(size < max_elems)) |
| 1943 | return false; // Protect against byte_size overflowing. |
| 1944 | auto byte_size = sizeof(size) + elem_size * size; |
| 1945 | if (end) *end = veco + byte_size; |
| 1946 | return Verify(veco, byte_size); |
| 1947 | } |
| 1948 | |
| 1949 | // Special case for string contents, after the above has been called. |
| 1950 | bool VerifyVectorOfStrings(const Vector<Offset<String>> *vec) const { |
| 1951 | if (vec) { |
| 1952 | for (uoffset_t i = 0; i < vec->size(); i++) { |
| 1953 | if (!VerifyString(vec->Get(i))) return false; |
| 1954 | } |
| 1955 | } |
| 1956 | return true; |
| 1957 | } |
| 1958 | |
| 1959 | // Special case for table contents, after the above has been called. |
| 1960 | template<typename T> bool VerifyVectorOfTables(const Vector<Offset<T>> *vec) { |
| 1961 | if (vec) { |
| 1962 | for (uoffset_t i = 0; i < vec->size(); i++) { |
| 1963 | if (!vec->Get(i)->Verify(*this)) return false; |
| 1964 | } |
| 1965 | } |
| 1966 | return true; |
| 1967 | } |
| 1968 | |
| 1969 | bool VerifyTableStart(const uint8_t *table) { |
| 1970 | // Check the vtable offset. |
| 1971 | auto tableo = static_cast<size_t>(table - buf_); |
| 1972 | if (!Verify<soffset_t>(tableo)) return false; |
| 1973 | // This offset may be signed, but doing the substraction unsigned always |
| 1974 | // gives the result we want. |
| 1975 | auto vtableo = tableo - static_cast<size_t>(ReadScalar<soffset_t>(table)); |
| 1976 | // Check the vtable size field, then check vtable fits in its entirety. |
| 1977 | return VerifyComplexity() && Verify<voffset_t>(vtableo) && |
| 1978 | VerifyAlignment<voffset_t>(ReadScalar<voffset_t>(buf_ + vtableo)) && |
| 1979 | Verify(vtableo, ReadScalar<voffset_t>(buf_ + vtableo)); |
| 1980 | } |
| 1981 | |
| 1982 | template<typename T> |
| 1983 | bool VerifyBufferFromStart(const char *identifier, size_t start) { |
| 1984 | if (identifier && |
| 1985 | (size_ < 2 * sizeof(flatbuffers::uoffset_t) || |
| 1986 | !BufferHasIdentifier(buf_ + start, identifier))) { |
| 1987 | return false; |
| 1988 | } |
| 1989 | |
| 1990 | // Call T::Verify, which must be in the generated code for this type. |
| 1991 | auto o = VerifyOffset(start); |
| 1992 | return o && reinterpret_cast<const T *>(buf_ + start + o)->Verify(*this) |
| 1993 | // clang-format off |
| 1994 | #ifdef FLATBUFFERS_TRACK_VERIFIER_BUFFER_SIZE |
| 1995 | && GetComputedSize() |
| 1996 | #endif |
| 1997 | ; |
| 1998 | // clang-format on |
| 1999 | } |
| 2000 | |
| 2001 | // Verify this whole buffer, starting with root type T. |
| 2002 | template<typename T> bool VerifyBuffer() { return VerifyBuffer<T>(nullptr); } |
| 2003 | |
| 2004 | template<typename T> bool VerifyBuffer(const char *identifier) { |
| 2005 | return VerifyBufferFromStart<T>(identifier, 0); |
| 2006 | } |
| 2007 | |
| 2008 | template<typename T> bool VerifySizePrefixedBuffer(const char *identifier) { |
| 2009 | return Verify<uoffset_t>(0U) && |
| 2010 | ReadScalar<uoffset_t>(buf_) == size_ - sizeof(uoffset_t) && |
| 2011 | VerifyBufferFromStart<T>(identifier, sizeof(uoffset_t)); |
| 2012 | } |
| 2013 | |
| 2014 | uoffset_t VerifyOffset(size_t start) const { |
| 2015 | if (!Verify<uoffset_t>(start)) return 0; |
| 2016 | auto o = ReadScalar<uoffset_t>(buf_ + start); |
| 2017 | // May not point to itself. |
| 2018 | Check(o != 0); |
| 2019 | // Can't wrap around / buffers are max 2GB. |
| 2020 | if (!Check(static_cast<soffset_t>(o) >= 0)) return 0; |
| 2021 | // Must be inside the buffer to create a pointer from it (pointer outside |
| 2022 | // buffer is UB). |
| 2023 | if (!Verify(start + o, 1)) return 0; |
| 2024 | return o; |
| 2025 | } |
| 2026 | |
| 2027 | uoffset_t VerifyOffset(const uint8_t *base, voffset_t start) const { |
| 2028 | return VerifyOffset(static_cast<size_t>(base - buf_) + start); |
| 2029 | } |
| 2030 | |
| 2031 | // Called at the start of a table to increase counters measuring data |
| 2032 | // structure depth and amount, and possibly bails out with false if |
| 2033 | // limits set by the constructor have been hit. Needs to be balanced |
| 2034 | // with EndTable(). |
| 2035 | bool VerifyComplexity() { |
| 2036 | depth_++; |
| 2037 | num_tables_++; |
| 2038 | return Check(depth_ <= max_depth_ && num_tables_ <= max_tables_); |
| 2039 | } |
| 2040 | |
| 2041 | // Called at the end of a table to pop the depth count. |
| 2042 | bool EndTable() { |
| 2043 | depth_--; |
| 2044 | return true; |
| 2045 | } |
| 2046 | |
| 2047 | // clang-format off |
| 2048 | #ifdef FLATBUFFERS_TRACK_VERIFIER_BUFFER_SIZE |
| 2049 | // Returns the message size in bytes |
| 2050 | size_t GetComputedSize() const { |
| 2051 | uintptr_t size = upper_bound_; |
| 2052 | // Align the size to uoffset_t |
| 2053 | size = (size - 1 + sizeof(uoffset_t)) & ~(sizeof(uoffset_t) - 1); |
| 2054 | return (size > size_) ? 0 : size; |
| 2055 | } |
| 2056 | #endif |
| 2057 | // clang-format on |
| 2058 | |
| 2059 | private: |
| 2060 | const uint8_t *buf_; |
| 2061 | size_t size_; |
| 2062 | uoffset_t depth_; |
| 2063 | uoffset_t max_depth_; |
| 2064 | uoffset_t num_tables_; |
| 2065 | uoffset_t max_tables_; |
| 2066 | // clang-format off |
| 2067 | #ifdef FLATBUFFERS_TRACK_VERIFIER_BUFFER_SIZE |
| 2068 | mutable size_t upper_bound_; |
| 2069 | #endif |
| 2070 | // clang-format on |
| 2071 | }; |
| 2072 | |
| 2073 | // Convenient way to bundle a buffer and its length, to pass it around |
| 2074 | // typed by its root. |
| 2075 | // A BufferRef does not own its buffer. |
| 2076 | struct BufferRefBase {}; // for std::is_base_of |
| 2077 | template<typename T> struct BufferRef : BufferRefBase { |
| 2078 | BufferRef() : buf(nullptr), len(0), must_free(false) {} |
| 2079 | BufferRef(uint8_t *_buf, uoffset_t _len) |
| 2080 | : buf(_buf), len(_len), must_free(false) {} |
| 2081 | |
| 2082 | ~BufferRef() { |
| 2083 | if (must_free) free(buf); |
| 2084 | } |
| 2085 | |
| 2086 | const T *GetRoot() const { return flatbuffers::GetRoot<T>(buf); } |
| 2087 | |
| 2088 | bool Verify() { |
| 2089 | Verifier verifier(buf, len); |
| 2090 | return verifier.VerifyBuffer<T>(nullptr); |
| 2091 | } |
| 2092 | |
| 2093 | uint8_t *buf; |
| 2094 | uoffset_t len; |
| 2095 | bool must_free; |
| 2096 | }; |
| 2097 | |
| 2098 | // "structs" are flat structures that do not have an offset table, thus |
| 2099 | // always have all members present and do not support forwards/backwards |
| 2100 | // compatible extensions. |
| 2101 | |
| 2102 | class Struct FLATBUFFERS_FINAL_CLASS { |
| 2103 | public: |
| 2104 | template<typename T> T GetField(uoffset_t o) const { |
| 2105 | return ReadScalar<T>(&data_[o]); |
| 2106 | } |
| 2107 | |
| 2108 | template<typename T> T GetStruct(uoffset_t o) const { |
| 2109 | return reinterpret_cast<T>(&data_[o]); |
| 2110 | } |
| 2111 | |
| 2112 | const uint8_t *GetAddressOf(uoffset_t o) const { return &data_[o]; } |
| 2113 | uint8_t *GetAddressOf(uoffset_t o) { return &data_[o]; } |
| 2114 | |
| 2115 | private: |
| 2116 | uint8_t data_[1]; |
| 2117 | }; |
| 2118 | |
| 2119 | // "tables" use an offset table (possibly shared) that allows fields to be |
| 2120 | // omitted and added at will, but uses an extra indirection to read. |
| 2121 | class Table { |
| 2122 | public: |
| 2123 | const uint8_t *GetVTable() const { |
| 2124 | return data_ - ReadScalar<soffset_t>(data_); |
| 2125 | } |
| 2126 | |
| 2127 | // This gets the field offset for any of the functions below it, or 0 |
| 2128 | // if the field was not present. |
| 2129 | voffset_t GetOptionalFieldOffset(voffset_t field) const { |
| 2130 | // The vtable offset is always at the start. |
| 2131 | auto vtable = GetVTable(); |
| 2132 | // The first element is the size of the vtable (fields + type id + itself). |
| 2133 | auto vtsize = ReadScalar<voffset_t>(vtable); |
| 2134 | // If the field we're accessing is outside the vtable, we're reading older |
| 2135 | // data, so it's the same as if the offset was 0 (not present). |
| 2136 | return field < vtsize ? ReadScalar<voffset_t>(vtable + field) : 0; |
| 2137 | } |
| 2138 | |
| 2139 | template<typename T> T GetField(voffset_t field, T defaultval) const { |
| 2140 | auto field_offset = GetOptionalFieldOffset(field); |
| 2141 | return field_offset ? ReadScalar<T>(data_ + field_offset) : defaultval; |
| 2142 | } |
| 2143 | |
| 2144 | template<typename P> P GetPointer(voffset_t field) { |
| 2145 | auto field_offset = GetOptionalFieldOffset(field); |
| 2146 | auto p = data_ + field_offset; |
| 2147 | return field_offset ? reinterpret_cast<P>(p + ReadScalar<uoffset_t>(p)) |
| 2148 | : nullptr; |
| 2149 | } |
| 2150 | template<typename P> P GetPointer(voffset_t field) const { |
| 2151 | return const_cast<Table *>(this)->GetPointer<P>(field); |
| 2152 | } |
| 2153 | |
| 2154 | template<typename P> P GetStruct(voffset_t field) const { |
| 2155 | auto field_offset = GetOptionalFieldOffset(field); |
| 2156 | auto p = const_cast<uint8_t *>(data_ + field_offset); |
| 2157 | return field_offset ? reinterpret_cast<P>(p) : nullptr; |
| 2158 | } |
| 2159 | |
| 2160 | template<typename T> bool SetField(voffset_t field, T val, T def) { |
| 2161 | auto field_offset = GetOptionalFieldOffset(field); |
| 2162 | if (!field_offset) return val == def; |
| 2163 | WriteScalar(data_ + field_offset, val); |
| 2164 | return true; |
| 2165 | } |
| 2166 | |
| 2167 | bool SetPointer(voffset_t field, const uint8_t *val) { |
| 2168 | auto field_offset = GetOptionalFieldOffset(field); |
| 2169 | if (!field_offset) return false; |
| 2170 | WriteScalar(data_ + field_offset, |
| 2171 | static_cast<uoffset_t>(val - (data_ + field_offset))); |
| 2172 | return true; |
| 2173 | } |
| 2174 | |
| 2175 | uint8_t *GetAddressOf(voffset_t field) { |
| 2176 | auto field_offset = GetOptionalFieldOffset(field); |
| 2177 | return field_offset ? data_ + field_offset : nullptr; |
| 2178 | } |
| 2179 | const uint8_t *GetAddressOf(voffset_t field) const { |
| 2180 | return const_cast<Table *>(this)->GetAddressOf(field); |
| 2181 | } |
| 2182 | |
| 2183 | bool CheckField(voffset_t field) const { |
| 2184 | return GetOptionalFieldOffset(field) != 0; |
| 2185 | } |
| 2186 | |
| 2187 | // Verify the vtable of this table. |
| 2188 | // Call this once per table, followed by VerifyField once per field. |
| 2189 | bool VerifyTableStart(Verifier &verifier) const { |
| 2190 | return verifier.VerifyTableStart(data_); |
| 2191 | } |
| 2192 | |
| 2193 | // Verify a particular field. |
| 2194 | template<typename T> |
| 2195 | bool VerifyField(const Verifier &verifier, voffset_t field) const { |
| 2196 | // Calling GetOptionalFieldOffset should be safe now thanks to |
| 2197 | // VerifyTable(). |
| 2198 | auto field_offset = GetOptionalFieldOffset(field); |
| 2199 | // Check the actual field. |
| 2200 | return !field_offset || verifier.Verify<T>(data_, field_offset); |
| 2201 | } |
| 2202 | |
| 2203 | // VerifyField for required fields. |
| 2204 | template<typename T> |
| 2205 | bool VerifyFieldRequired(const Verifier &verifier, voffset_t field) const { |
| 2206 | auto field_offset = GetOptionalFieldOffset(field); |
| 2207 | return verifier.Check(field_offset != 0) && |
| 2208 | verifier.Verify<T>(data_, field_offset); |
| 2209 | } |
| 2210 | |
| 2211 | // Versions for offsets. |
| 2212 | bool VerifyOffset(const Verifier &verifier, voffset_t field) const { |
| 2213 | auto field_offset = GetOptionalFieldOffset(field); |
| 2214 | return !field_offset || verifier.VerifyOffset(data_, field_offset); |
| 2215 | } |
| 2216 | |
| 2217 | bool VerifyOffsetRequired(const Verifier &verifier, voffset_t field) const { |
| 2218 | auto field_offset = GetOptionalFieldOffset(field); |
| 2219 | return verifier.Check(field_offset != 0) && |
| 2220 | verifier.VerifyOffset(data_, field_offset); |
| 2221 | } |
| 2222 | |
| 2223 | private: |
| 2224 | // private constructor & copy constructor: you obtain instances of this |
| 2225 | // class by pointing to existing data only |
| 2226 | Table(); |
| 2227 | Table(const Table &other); |
| 2228 | |
| 2229 | uint8_t data_[1]; |
| 2230 | }; |
| 2231 | |
| 2232 | template<typename T> void FlatBufferBuilder::Required(Offset<T> table, |
| 2233 | voffset_t field) { |
| 2234 | auto table_ptr = reinterpret_cast<const Table *>(buf_.data_at(table.o)); |
| 2235 | bool ok = table_ptr->GetOptionalFieldOffset(field) != 0; |
| 2236 | // If this fails, the caller will show what field needs to be set. |
| 2237 | FLATBUFFERS_ASSERT(ok); |
| 2238 | (void)ok; |
| 2239 | } |
| 2240 | |
| 2241 | /// @brief This can compute the start of a FlatBuffer from a root pointer, i.e. |
| 2242 | /// it is the opposite transformation of GetRoot(). |
| 2243 | /// This may be useful if you want to pass on a root and have the recipient |
| 2244 | /// delete the buffer afterwards. |
| 2245 | inline const uint8_t *GetBufferStartFromRootPointer(const void *root) { |
| 2246 | auto table = reinterpret_cast<const Table *>(root); |
| 2247 | auto vtable = table->GetVTable(); |
| 2248 | // Either the vtable is before the root or after the root. |
| 2249 | auto start = (std::min)(vtable, reinterpret_cast<const uint8_t *>(root)); |
| 2250 | // Align to at least sizeof(uoffset_t). |
| 2251 | start = reinterpret_cast<const uint8_t *>(reinterpret_cast<uintptr_t>(start) & |
| 2252 | ~(sizeof(uoffset_t) - 1)); |
| 2253 | // Additionally, there may be a file_identifier in the buffer, and the root |
| 2254 | // offset. The buffer may have been aligned to any size between |
| 2255 | // sizeof(uoffset_t) and FLATBUFFERS_MAX_ALIGNMENT (see "force_align"). |
| 2256 | // Sadly, the exact alignment is only known when constructing the buffer, |
| 2257 | // since it depends on the presence of values with said alignment properties. |
| 2258 | // So instead, we simply look at the next uoffset_t values (root, |
| 2259 | // file_identifier, and alignment padding) to see which points to the root. |
| 2260 | // None of the other values can "impersonate" the root since they will either |
| 2261 | // be 0 or four ASCII characters. |
| 2262 | static_assert(FlatBufferBuilder::kFileIdentifierLength == sizeof(uoffset_t), |
| 2263 | "file_identifier is assumed to be the same size as uoffset_t" ); |
| 2264 | for (auto possible_roots = FLATBUFFERS_MAX_ALIGNMENT / sizeof(uoffset_t) + 1; |
| 2265 | possible_roots; possible_roots--) { |
| 2266 | start -= sizeof(uoffset_t); |
| 2267 | if (ReadScalar<uoffset_t>(start) + start == |
| 2268 | reinterpret_cast<const uint8_t *>(root)) |
| 2269 | return start; |
| 2270 | } |
| 2271 | // We didn't find the root, either the "root" passed isn't really a root, |
| 2272 | // or the buffer is corrupt. |
| 2273 | // Assert, because calling this function with bad data may cause reads |
| 2274 | // outside of buffer boundaries. |
| 2275 | FLATBUFFERS_ASSERT(false); |
| 2276 | return nullptr; |
| 2277 | } |
| 2278 | |
| 2279 | /// @brief This return the prefixed size of a FlatBuffer. |
| 2280 | inline uoffset_t GetPrefixedSize(const uint8_t* buf){ return ReadScalar<uoffset_t>(buf); } |
| 2281 | |
| 2282 | // Base class for native objects (FlatBuffer data de-serialized into native |
| 2283 | // C++ data structures). |
| 2284 | // Contains no functionality, purely documentative. |
| 2285 | struct NativeTable {}; |
| 2286 | |
| 2287 | /// @brief Function types to be used with resolving hashes into objects and |
| 2288 | /// back again. The resolver gets a pointer to a field inside an object API |
| 2289 | /// object that is of the type specified in the schema using the attribute |
| 2290 | /// `cpp_type` (it is thus important whatever you write to this address |
| 2291 | /// matches that type). The value of this field is initially null, so you |
| 2292 | /// may choose to implement a delayed binding lookup using this function |
| 2293 | /// if you wish. The resolver does the opposite lookup, for when the object |
| 2294 | /// is being serialized again. |
| 2295 | typedef uint64_t hash_value_t; |
| 2296 | // clang-format off |
| 2297 | #ifdef FLATBUFFERS_CPP98_STL |
| 2298 | typedef void (*resolver_function_t)(void **pointer_adr, hash_value_t hash); |
| 2299 | typedef hash_value_t (*rehasher_function_t)(void *pointer); |
| 2300 | #else |
| 2301 | typedef std::function<void (void **pointer_adr, hash_value_t hash)> |
| 2302 | resolver_function_t; |
| 2303 | typedef std::function<hash_value_t (void *pointer)> rehasher_function_t; |
| 2304 | #endif |
| 2305 | // clang-format on |
| 2306 | |
| 2307 | // Helper function to test if a field is present, using any of the field |
| 2308 | // enums in the generated code. |
| 2309 | // `table` must be a generated table type. Since this is a template parameter, |
| 2310 | // this is not typechecked to be a subclass of Table, so beware! |
| 2311 | // Note: this function will return false for fields equal to the default |
| 2312 | // value, since they're not stored in the buffer (unless force_defaults was |
| 2313 | // used). |
| 2314 | template<typename T> bool IsFieldPresent(const T *table, voffset_t field) { |
| 2315 | // Cast, since Table is a private baseclass of any table types. |
| 2316 | return reinterpret_cast<const Table *>(table)->CheckField(field); |
| 2317 | } |
| 2318 | |
| 2319 | // Utility function for reverse lookups on the EnumNames*() functions |
| 2320 | // (in the generated C++ code) |
| 2321 | // names must be NULL terminated. |
| 2322 | inline int LookupEnum(const char **names, const char *name) { |
| 2323 | for (const char **p = names; *p; p++) |
| 2324 | if (!strcmp(*p, name)) return static_cast<int>(p - names); |
| 2325 | return -1; |
| 2326 | } |
| 2327 | |
| 2328 | // These macros allow us to layout a struct with a guarantee that they'll end |
| 2329 | // up looking the same on different compilers and platforms. |
| 2330 | // It does this by disallowing the compiler to do any padding, and then |
| 2331 | // does padding itself by inserting extra padding fields that make every |
| 2332 | // element aligned to its own size. |
| 2333 | // Additionally, it manually sets the alignment of the struct as a whole, |
| 2334 | // which is typically its largest element, or a custom size set in the schema |
| 2335 | // by the force_align attribute. |
| 2336 | // These are used in the generated code only. |
| 2337 | |
| 2338 | // clang-format off |
| 2339 | #if defined(_MSC_VER) |
| 2340 | #define FLATBUFFERS_MANUALLY_ALIGNED_STRUCT(alignment) \ |
| 2341 | __pragma(pack(1)); \ |
| 2342 | struct __declspec(align(alignment)) |
| 2343 | #define FLATBUFFERS_STRUCT_END(name, size) \ |
| 2344 | __pragma(pack()); \ |
| 2345 | static_assert(sizeof(name) == size, "compiler breaks packing rules") |
| 2346 | #elif defined(__GNUC__) || defined(__clang__) |
| 2347 | #define FLATBUFFERS_MANUALLY_ALIGNED_STRUCT(alignment) \ |
| 2348 | _Pragma("pack(1)") \ |
| 2349 | struct __attribute__((aligned(alignment))) |
| 2350 | #define FLATBUFFERS_STRUCT_END(name, size) \ |
| 2351 | _Pragma("pack()") \ |
| 2352 | static_assert(sizeof(name) == size, "compiler breaks packing rules") |
| 2353 | #else |
| 2354 | #error Unknown compiler, please define structure alignment macros |
| 2355 | #endif |
| 2356 | // clang-format on |
| 2357 | |
| 2358 | // Minimal reflection via code generation. |
| 2359 | // Besides full-fat reflection (see reflection.h) and parsing/printing by |
| 2360 | // loading schemas (see idl.h), we can also have code generation for mimimal |
| 2361 | // reflection data which allows pretty-printing and other uses without needing |
| 2362 | // a schema or a parser. |
| 2363 | // Generate code with --reflect-types (types only) or --reflect-names (names |
| 2364 | // also) to enable. |
| 2365 | // See minireflect.h for utilities using this functionality. |
| 2366 | |
| 2367 | // These types are organized slightly differently as the ones in idl.h. |
| 2368 | enum SequenceType { ST_TABLE, ST_STRUCT, ST_UNION, ST_ENUM }; |
| 2369 | |
| 2370 | // Scalars have the same order as in idl.h |
| 2371 | // clang-format off |
| 2372 | #define FLATBUFFERS_GEN_ELEMENTARY_TYPES(ET) \ |
| 2373 | ET(ET_UTYPE) \ |
| 2374 | ET(ET_BOOL) \ |
| 2375 | ET(ET_CHAR) \ |
| 2376 | ET(ET_UCHAR) \ |
| 2377 | ET(ET_SHORT) \ |
| 2378 | ET(ET_USHORT) \ |
| 2379 | ET(ET_INT) \ |
| 2380 | ET(ET_UINT) \ |
| 2381 | ET(ET_LONG) \ |
| 2382 | ET(ET_ULONG) \ |
| 2383 | ET(ET_FLOAT) \ |
| 2384 | ET(ET_DOUBLE) \ |
| 2385 | ET(ET_STRING) \ |
| 2386 | ET(ET_SEQUENCE) // See SequenceType. |
| 2387 | |
| 2388 | enum ElementaryType { |
| 2389 | #define FLATBUFFERS_ET(E) E, |
| 2390 | FLATBUFFERS_GEN_ELEMENTARY_TYPES(FLATBUFFERS_ET) |
| 2391 | #undef FLATBUFFERS_ET |
| 2392 | }; |
| 2393 | |
| 2394 | inline const char * const *ElementaryTypeNames() { |
| 2395 | static const char * const names[] = { |
| 2396 | #define FLATBUFFERS_ET(E) #E, |
| 2397 | FLATBUFFERS_GEN_ELEMENTARY_TYPES(FLATBUFFERS_ET) |
| 2398 | #undef FLATBUFFERS_ET |
| 2399 | }; |
| 2400 | return names; |
| 2401 | } |
| 2402 | // clang-format on |
| 2403 | |
| 2404 | // Basic type info cost just 16bits per field! |
| 2405 | struct TypeCode { |
| 2406 | uint16_t base_type : 4; // ElementaryType |
| 2407 | uint16_t is_vector : 1; |
| 2408 | int16_t sequence_ref : 11; // Index into type_refs below, or -1 for none. |
| 2409 | }; |
| 2410 | |
| 2411 | static_assert(sizeof(TypeCode) == 2, "TypeCode" ); |
| 2412 | |
| 2413 | struct TypeTable; |
| 2414 | |
| 2415 | // Signature of the static method present in each type. |
| 2416 | typedef const TypeTable *(*TypeFunction)(); |
| 2417 | |
| 2418 | struct TypeTable { |
| 2419 | SequenceType st; |
| 2420 | size_t num_elems; // of type_codes, values, names (but not type_refs). |
| 2421 | const TypeCode *type_codes; // num_elems count |
| 2422 | const TypeFunction *type_refs; // less than num_elems entries (see TypeCode). |
| 2423 | const int32_t *values; // Only set for non-consecutive enum/union or structs. |
| 2424 | const char * const *names; // Only set if compiled with --reflect-names. |
| 2425 | }; |
| 2426 | |
| 2427 | // String which identifies the current version of FlatBuffers. |
| 2428 | // flatbuffer_version_string is used by Google developers to identify which |
| 2429 | // applications uploaded to Google Play are using this library. This allows |
| 2430 | // the development team at Google to determine the popularity of the library. |
| 2431 | // How it works: Applications that are uploaded to the Google Play Store are |
| 2432 | // scanned for this version string. We track which applications are using it |
| 2433 | // to measure popularity. You are free to remove it (of course) but we would |
| 2434 | // appreciate if you left it in. |
| 2435 | |
| 2436 | // Weak linkage is culled by VS & doesn't work on cygwin. |
| 2437 | // clang-format off |
| 2438 | #if !defined(_WIN32) && !defined(__CYGWIN__) |
| 2439 | |
| 2440 | extern volatile __attribute__((weak)) const char *flatbuffer_version_string; |
| 2441 | volatile __attribute__((weak)) const char *flatbuffer_version_string = |
| 2442 | "FlatBuffers " |
| 2443 | FLATBUFFERS_STRING(FLATBUFFERS_VERSION_MAJOR) "." |
| 2444 | FLATBUFFERS_STRING(FLATBUFFERS_VERSION_MINOR) "." |
| 2445 | FLATBUFFERS_STRING(FLATBUFFERS_VERSION_REVISION); |
| 2446 | |
| 2447 | #endif // !defined(_WIN32) && !defined(__CYGWIN__) |
| 2448 | |
| 2449 | #define FLATBUFFERS_DEFINE_BITMASK_OPERATORS(E, T)\ |
| 2450 | inline E operator | (E lhs, E rhs){\ |
| 2451 | return E(T(lhs) | T(rhs));\ |
| 2452 | }\ |
| 2453 | inline E operator & (E lhs, E rhs){\ |
| 2454 | return E(T(lhs) & T(rhs));\ |
| 2455 | }\ |
| 2456 | inline E operator ^ (E lhs, E rhs){\ |
| 2457 | return E(T(lhs) ^ T(rhs));\ |
| 2458 | }\ |
| 2459 | inline E operator ~ (E lhs){\ |
| 2460 | return E(~T(lhs));\ |
| 2461 | }\ |
| 2462 | inline E operator |= (E &lhs, E rhs){\ |
| 2463 | lhs = lhs | rhs;\ |
| 2464 | return lhs;\ |
| 2465 | }\ |
| 2466 | inline E operator &= (E &lhs, E rhs){\ |
| 2467 | lhs = lhs & rhs;\ |
| 2468 | return lhs;\ |
| 2469 | }\ |
| 2470 | inline E operator ^= (E &lhs, E rhs){\ |
| 2471 | lhs = lhs ^ rhs;\ |
| 2472 | return lhs;\ |
| 2473 | }\ |
| 2474 | inline bool operator !(E rhs) \ |
| 2475 | {\ |
| 2476 | return !bool(T(rhs)); \ |
| 2477 | } |
| 2478 | /// @endcond |
| 2479 | } // namespace flatbuffers |
| 2480 | |
| 2481 | #if defined(_MSC_VER) |
| 2482 | #pragma warning(pop) |
| 2483 | #endif |
| 2484 | // clang-format on |
| 2485 | |
| 2486 | #endif // FLATBUFFERS_H_ |
| 2487 | |