FlatBuffers
An open source project by FPL.
flatbuffers.h
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++() {
134  return *this;
135  }
136 
137  VectorIterator operator++(int) {
138  VectorIterator temp(data_, 0);
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--() {
155  return *this;
156  }
157 
158  VectorIterator operator--(int) {
159  VectorIterator temp(data_, 0);
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:
185  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.
454  public:
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 
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.
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 
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  // No change in other.allocator_
585  // No change in other.initial_size_
586  // No change in other.buffer_minalign_
587  other.own_allocator_ = false;
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  // release_raw only relinquishes the buffer ownership.
643  // Does not deallocate or reset the allocator. Destructor will do that.
644  buf_ = nullptr;
645  clear();
646  return buf;
647  }
648 
649  // Relinquish the pointer to the caller.
650  DetachedBuffer release() {
651  // allocator ownership (if any) is transferred to DetachedBuffer.
652  DetachedBuffer fb(allocator_, own_allocator_, buf_, reserved_, cur_,
653  size());
654  if (own_allocator_) {
655  allocator_ = nullptr;
656  own_allocator_ = false;
657  }
658  buf_ = nullptr;
659  clear();
660  return fb;
661  }
662 
663  size_t ensure_space(size_t len) {
664  FLATBUFFERS_ASSERT(cur_ >= scratch_ && scratch_ >= buf_);
665  if (len > static_cast<size_t>(cur_ - scratch_)) { reallocate(len); }
666  // Beyond this, signed offsets may not have enough range:
667  // (FlatBuffers > 2GB not supported).
668  FLATBUFFERS_ASSERT(size() < FLATBUFFERS_MAX_BUFFER_SIZE);
669  return len;
670  }
671 
672  inline uint8_t *make_space(size_t len) {
673  size_t space = ensure_space(len);
674  cur_ -= space;
675  return cur_;
676  }
677 
678  // Returns nullptr if using the DefaultAllocator.
679  Allocator *get_custom_allocator() { return allocator_; }
680 
681  uoffset_t size() const {
682  return static_cast<uoffset_t>(reserved_ - (cur_ - buf_));
683  }
684 
685  uoffset_t scratch_size() const {
686  return static_cast<uoffset_t>(scratch_ - buf_);
687  }
688 
689  size_t capacity() const { return reserved_; }
690 
691  uint8_t *data() const {
692  FLATBUFFERS_ASSERT(cur_);
693  return cur_;
694  }
695 
696  uint8_t *scratch_data() const {
697  FLATBUFFERS_ASSERT(buf_);
698  return buf_;
699  }
700 
701  uint8_t *scratch_end() const {
702  FLATBUFFERS_ASSERT(scratch_);
703  return scratch_;
704  }
705 
706  uint8_t *data_at(size_t offset) const { return buf_ + reserved_ - offset; }
707 
708  void push(const uint8_t *bytes, size_t num) {
709  memcpy(make_space(num), bytes, num);
710  }
711 
712  // Specialized version of push() that avoids memcpy call for small data.
713  template<typename T> void push_small(const T &little_endian_t) {
714  make_space(sizeof(T));
715  *reinterpret_cast<T *>(cur_) = little_endian_t;
716  }
717 
718  template<typename T> void scratch_push_small(const T &t) {
719  ensure_space(sizeof(T));
720  *reinterpret_cast<T *>(scratch_) = t;
721  scratch_ += sizeof(T);
722  }
723 
724  // fill() is most frequently called with small byte counts (<= 4),
725  // which is why we're using loops rather than calling memset.
726  void fill(size_t zero_pad_bytes) {
727  make_space(zero_pad_bytes);
728  for (size_t i = 0; i < zero_pad_bytes; i++) cur_[i] = 0;
729  }
730 
731  // Version for when we know the size is larger.
732  void fill_big(size_t zero_pad_bytes) {
733  memset(make_space(zero_pad_bytes), 0, zero_pad_bytes);
734  }
735 
736  void pop(size_t bytes_to_remove) { cur_ += bytes_to_remove; }
737  void scratch_pop(size_t bytes_to_remove) { scratch_ -= bytes_to_remove; }
738 
739  void swap(vector_downward &other) {
740  using std::swap;
741  swap(allocator_, other.allocator_);
742  swap(own_allocator_, other.own_allocator_);
743  swap(initial_size_, other.initial_size_);
744  swap(buffer_minalign_, other.buffer_minalign_);
745  swap(reserved_, other.reserved_);
746  swap(buf_, other.buf_);
747  swap(cur_, other.cur_);
748  swap(scratch_, other.scratch_);
749  }
750 
751  void swap_allocator(vector_downward &other) {
752  using std::swap;
753  swap(allocator_, other.allocator_);
754  swap(own_allocator_, other.own_allocator_);
755  }
756 
757  private:
758  // You shouldn't really be copying instances of this class.
759  FLATBUFFERS_DELETE_FUNC(vector_downward(const vector_downward &))
760  FLATBUFFERS_DELETE_FUNC(vector_downward &operator=(const vector_downward &))
761 
762  Allocator *allocator_;
763  bool own_allocator_;
764  size_t initial_size_;
765  size_t buffer_minalign_;
766  size_t reserved_;
767  uint8_t *buf_;
768  uint8_t *cur_; // Points at location between empty (below) and used (above).
769  uint8_t *scratch_; // Points to the end of the scratchpad in use.
770 
771  void reallocate(size_t len) {
772  auto old_reserved = reserved_;
773  auto old_size = size();
774  auto old_scratch_size = scratch_size();
775  reserved_ += (std::max)(len,
776  old_reserved ? old_reserved / 2 : initial_size_);
777  reserved_ = (reserved_ + buffer_minalign_ - 1) & ~(buffer_minalign_ - 1);
778  if (buf_) {
779  buf_ = ReallocateDownward(allocator_, buf_, old_reserved, reserved_,
780  old_size, old_scratch_size);
781  } else {
782  buf_ = Allocate(allocator_, reserved_);
783  }
784  cur_ = buf_ + reserved_ - old_size;
785  scratch_ = buf_ + old_scratch_size;
786  }
787 };
788 
789 // Converts a Field ID to a virtual table offset.
790 inline voffset_t FieldIndexToOffset(voffset_t field_id) {
791  // Should correspond to what EndTable() below builds up.
792  const int fixed_fields = 2; // Vtable size and Object Size.
793  return static_cast<voffset_t>((field_id + fixed_fields) * sizeof(voffset_t));
794 }
795 
796 template<typename T, typename Alloc>
797 const T *data(const std::vector<T, Alloc> &v) {
798  return v.empty() ? nullptr : &v.front();
799 }
800 template<typename T, typename Alloc> T *data(std::vector<T, Alloc> &v) {
801  return v.empty() ? nullptr : &v.front();
802 }
803 
804 /// @endcond
805 
806 /// @addtogroup flatbuffers_cpp_api
807 /// @{
808 /// @class FlatBufferBuilder
809 /// @brief Helper class to hold data needed in creation of a FlatBuffer.
810 /// To serialize data, you typically call one of the `Create*()` functions in
811 /// the generated code, which in turn call a sequence of `StartTable`/
812 /// `PushElement`/`AddElement`/`EndTable`, or the builtin `CreateString`/
813 /// `CreateVector` functions. Do this is depth-first order to build up a tree to
814 /// the root. `Finish()` wraps up the buffer ready for transport.
816  public:
817  /// @brief Default constructor for FlatBufferBuilder.
818  /// @param[in] initial_size The initial size of the buffer, in bytes. Defaults
819  /// to `1024`.
820  /// @param[in] allocator An `Allocator` to use. If null will use
821  /// `DefaultAllocator`.
822  /// @param[in] own_allocator Whether the builder/vector should own the
823  /// allocator. Defaults to / `false`.
824  /// @param[in] buffer_minalign Force the buffer to be aligned to the given
825  /// minimum alignment upon reallocation. Only needed if you intend to store
826  /// types with custom alignment AND you wish to read the buffer in-place
827  /// directly after creation.
828  explicit FlatBufferBuilder(size_t initial_size = 1024,
829  Allocator *allocator = nullptr,
830  bool own_allocator = false,
831  size_t buffer_minalign =
832  AlignOf<largest_scalar_t>())
833  : buf_(initial_size, allocator, own_allocator, buffer_minalign),
834  num_field_loc(0),
835  max_voffset_(0),
836  nested(false),
837  finished(false),
838  minalign_(1),
839  force_defaults_(false),
840  dedup_vtables_(true),
841  string_pool(nullptr) {
842  EndianCheck();
843  }
844 
845  /// @brief Move constructor for FlatBufferBuilder.
847  : buf_(1024, nullptr, false, AlignOf<largest_scalar_t>()),
848  num_field_loc(0),
849  max_voffset_(0),
850  nested(false),
851  finished(false),
852  minalign_(1),
853  force_defaults_(false),
854  dedup_vtables_(true),
855  string_pool(nullptr) {
856  EndianCheck();
857  // Default construct and swap idiom.
858  // Lack of delegating constructors in vs2010 makes it more verbose than needed.
859  Swap(other);
860  }
861 
862  /// @brief Move assignment operator for FlatBufferBuilder.
864  // Move construct a temporary and swap idiom
865  FlatBufferBuilder temp(std::move(other));
866  Swap(temp);
867  return *this;
868  }
869 
870  void Swap(FlatBufferBuilder &other) {
871  using std::swap;
872  buf_.swap(other.buf_);
873  swap(num_field_loc, other.num_field_loc);
874  swap(max_voffset_, other.max_voffset_);
875  swap(nested, other.nested);
876  swap(finished, other.finished);
877  swap(minalign_, other.minalign_);
878  swap(force_defaults_, other.force_defaults_);
879  swap(dedup_vtables_, other.dedup_vtables_);
880  swap(string_pool, other.string_pool);
881  }
882 
883  ~FlatBufferBuilder() {
884  if (string_pool) delete string_pool;
885  }
886 
887  void Reset() {
888  Clear(); // clear builder state
889  buf_.reset(); // deallocate buffer
890  }
891 
892  /// @brief Reset all the state in this FlatBufferBuilder so it can be reused
893  /// to construct another buffer.
894  void Clear() {
895  ClearOffsets();
896  buf_.clear();
897  nested = false;
898  finished = false;
899  minalign_ = 1;
900  if (string_pool) string_pool->clear();
901  }
902 
903  /// @brief The current size of the serialized buffer, counting from the end.
904  /// @return Returns an `uoffset_t` with the current size of the buffer.
905  uoffset_t GetSize() const { return buf_.size(); }
906 
907  /// @brief Get the serialized buffer (after you call `Finish()`).
908  /// @return Returns an `uint8_t` pointer to the FlatBuffer data inside the
909  /// buffer.
910  uint8_t *GetBufferPointer() const {
911  Finished();
912  return buf_.data();
913  }
914 
915  /// @brief Get a pointer to an unfinished buffer.
916  /// @return Returns a `uint8_t` pointer to the unfinished buffer.
917  uint8_t *GetCurrentBufferPointer() const { return buf_.data(); }
918 
919  /// @brief Get the released pointer to the serialized buffer.
920  /// @warning Do NOT attempt to use this FlatBufferBuilder afterwards!
921  /// @return A `FlatBuffer` that owns the buffer and its allocator and
922  /// behaves similar to a `unique_ptr` with a deleter.
923  /// Deprecated: use Release() instead
925  Finished();
926  return buf_.release();
927  }
928 
929  /// @brief Get the released DetachedBuffer.
930  /// @return A `DetachedBuffer` that owns the buffer and its allocator.
932  Finished();
933  return buf_.release();
934  }
935 
936  /// @brief Get the released pointer to the serialized buffer.
937  /// @param The size of the memory block containing
938  /// the serialized `FlatBuffer`.
939  /// @param The offset from the released pointer where the finished
940  /// `FlatBuffer` starts.
941  /// @return A raw pointer to the start of the memory block containing
942  /// the serialized `FlatBuffer`.
943  /// @remark If the allocator is owned, it gets deleted during this call.
944  uint8_t *ReleaseRaw(size_t &size, size_t &offset) {
945  Finished();
946  return buf_.release_raw(size, offset);
947  }
948 
949  /// @brief get the minimum alignment this buffer needs to be accessed
950  /// properly. This is only known once all elements have been written (after
951  /// you call Finish()). You can use this information if you need to embed
952  /// a FlatBuffer in some other buffer, such that you can later read it
953  /// without first having to copy it into its own buffer.
955  Finished();
956  return minalign_;
957  }
958 
959  /// @cond FLATBUFFERS_INTERNAL
960  void Finished() const {
961  // If you get this assert, you're attempting to get access a buffer
962  // which hasn't been finished yet. Be sure to call
963  // FlatBufferBuilder::Finish with your root table.
964  // If you really need to access an unfinished buffer, call
965  // GetCurrentBufferPointer instead.
966  FLATBUFFERS_ASSERT(finished);
967  }
968  /// @endcond
969 
970  /// @brief In order to save space, fields that are set to their default value
971  /// don't get serialized into the buffer.
972  /// @param[in] bool fd When set to `true`, always serializes default values that are set.
973  /// Optional fields which are not set explicitly, will still not be serialized.
974  void ForceDefaults(bool fd) { force_defaults_ = fd; }
975 
976  /// @brief By default vtables are deduped in order to save space.
977  /// @param[in] bool dedup When set to `true`, dedup vtables.
978  void DedupVtables(bool dedup) { dedup_vtables_ = dedup; }
979 
980  /// @cond FLATBUFFERS_INTERNAL
981  void Pad(size_t num_bytes) { buf_.fill(num_bytes); }
982 
983  void TrackMinAlign(size_t elem_size) {
984  if (elem_size > minalign_) minalign_ = elem_size;
985  }
986 
987  void Align(size_t elem_size) {
988  TrackMinAlign(elem_size);
989  buf_.fill(PaddingBytes(buf_.size(), elem_size));
990  }
991 
992  void PushFlatBuffer(const uint8_t *bytes, size_t size) {
993  PushBytes(bytes, size);
994  finished = true;
995  }
996 
997  void PushBytes(const uint8_t *bytes, size_t size) { buf_.push(bytes, size); }
998 
999  void PopBytes(size_t amount) { buf_.pop(amount); }
1000 
1001  template<typename T> void AssertScalarT() {
1002  // The code assumes power of 2 sizes and endian-swap-ability.
1003  static_assert(flatbuffers::is_scalar<T>::value, "T must be a scalar type");
1004  }
1005 
1006  // Write a single aligned scalar to the buffer
1007  template<typename T> uoffset_t PushElement(T element) {
1008  AssertScalarT<T>();
1009  T litle_endian_element = EndianScalar(element);
1010  Align(sizeof(T));
1011  buf_.push_small(litle_endian_element);
1012  return GetSize();
1013  }
1014 
1015  template<typename T> uoffset_t PushElement(Offset<T> off) {
1016  // Special case for offsets: see ReferTo below.
1017  return PushElement(ReferTo(off.o));
1018  }
1019 
1020  // When writing fields, we track where they are, so we can create correct
1021  // vtables later.
1022  void TrackField(voffset_t field, uoffset_t off) {
1023  FieldLoc fl = { off, field };
1024  buf_.scratch_push_small(fl);
1025  num_field_loc++;
1026  max_voffset_ = (std::max)(max_voffset_, field);
1027  }
1028 
1029  // Like PushElement, but additionally tracks the field this represents.
1030  template<typename T> void AddElement(voffset_t field, T e, T def) {
1031  // We don't serialize values equal to the default.
1032  if (e == def && !force_defaults_) return;
1033  auto off = PushElement(e);
1034  TrackField(field, off);
1035  }
1036 
1037  template<typename T> void AddOffset(voffset_t field, Offset<T> off) {
1038  if (off.IsNull()) return; // Don't store.
1039  AddElement(field, ReferTo(off.o), static_cast<uoffset_t>(0));
1040  }
1041 
1042  template<typename T> void AddStruct(voffset_t field, const T *structptr) {
1043  if (!structptr) return; // Default, don't store.
1044  Align(AlignOf<T>());
1045  buf_.push_small(*structptr);
1046  TrackField(field, GetSize());
1047  }
1048 
1049  void AddStructOffset(voffset_t field, uoffset_t off) {
1050  TrackField(field, off);
1051  }
1052 
1053  // Offsets initially are relative to the end of the buffer (downwards).
1054  // This function converts them to be relative to the current location
1055  // in the buffer (when stored here), pointing upwards.
1056  uoffset_t ReferTo(uoffset_t off) {
1057  // Align to ensure GetSize() below is correct.
1058  Align(sizeof(uoffset_t));
1059  // Offset must refer to something already in buffer.
1060  FLATBUFFERS_ASSERT(off && off <= GetSize());
1061  return GetSize() - off + static_cast<uoffset_t>(sizeof(uoffset_t));
1062  }
1063 
1064  void NotNested() {
1065  // If you hit this, you're trying to construct a Table/Vector/String
1066  // during the construction of its parent table (between the MyTableBuilder
1067  // and table.Finish().
1068  // Move the creation of these sub-objects to above the MyTableBuilder to
1069  // not get this assert.
1070  // Ignoring this assert may appear to work in simple cases, but the reason
1071  // it is here is that storing objects in-line may cause vtable offsets
1072  // to not fit anymore. It also leads to vtable duplication.
1073  FLATBUFFERS_ASSERT(!nested);
1074  // If you hit this, fields were added outside the scope of a table.
1075  FLATBUFFERS_ASSERT(!num_field_loc);
1076  }
1077 
1078  // From generated code (or from the parser), we call StartTable/EndTable
1079  // with a sequence of AddElement calls in between.
1080  uoffset_t StartTable() {
1081  NotNested();
1082  nested = true;
1083  return GetSize();
1084  }
1085 
1086  // This finishes one serialized object by generating the vtable if it's a
1087  // table, comparing it against existing vtables, and writing the
1088  // resulting vtable offset.
1089  uoffset_t EndTable(uoffset_t start) {
1090  // If you get this assert, a corresponding StartTable wasn't called.
1091  FLATBUFFERS_ASSERT(nested);
1092  // Write the vtable offset, which is the start of any Table.
1093  // We fill it's value later.
1094  auto vtableoffsetloc = PushElement<soffset_t>(0);
1095  // Write a vtable, which consists entirely of voffset_t elements.
1096  // It starts with the number of offsets, followed by a type id, followed
1097  // by the offsets themselves. In reverse:
1098  // Include space for the last offset and ensure empty tables have a
1099  // minimum size.
1100  max_voffset_ =
1101  (std::max)(static_cast<voffset_t>(max_voffset_ + sizeof(voffset_t)),
1102  FieldIndexToOffset(0));
1103  buf_.fill_big(max_voffset_);
1104  auto table_object_size = vtableoffsetloc - start;
1105  // Vtable use 16bit offsets.
1106  FLATBUFFERS_ASSERT(table_object_size < 0x10000);
1107  WriteScalar<voffset_t>(buf_.data() + sizeof(voffset_t),
1108  static_cast<voffset_t>(table_object_size));
1109  WriteScalar<voffset_t>(buf_.data(), max_voffset_);
1110  // Write the offsets into the table
1111  for (auto it = buf_.scratch_end() - num_field_loc * sizeof(FieldLoc);
1112  it < buf_.scratch_end(); it += sizeof(FieldLoc)) {
1113  auto field_location = reinterpret_cast<FieldLoc *>(it);
1114  auto pos = static_cast<voffset_t>(vtableoffsetloc - field_location->off);
1115  // If this asserts, it means you've set a field twice.
1116  FLATBUFFERS_ASSERT(
1117  !ReadScalar<voffset_t>(buf_.data() + field_location->id));
1118  WriteScalar<voffset_t>(buf_.data() + field_location->id, pos);
1119  }
1120  ClearOffsets();
1121  auto vt1 = reinterpret_cast<voffset_t *>(buf_.data());
1122  auto vt1_size = ReadScalar<voffset_t>(vt1);
1123  auto vt_use = GetSize();
1124  // See if we already have generated a vtable with this exact same
1125  // layout before. If so, make it point to the old one, remove this one.
1126  if (dedup_vtables_) {
1127  for (auto it = buf_.scratch_data(); it < buf_.scratch_end();
1128  it += sizeof(uoffset_t)) {
1129  auto vt_offset_ptr = reinterpret_cast<uoffset_t *>(it);
1130  auto vt2 = reinterpret_cast<voffset_t *>(buf_.data_at(*vt_offset_ptr));
1131  auto vt2_size = *vt2;
1132  if (vt1_size != vt2_size || memcmp(vt2, vt1, vt1_size)) continue;
1133  vt_use = *vt_offset_ptr;
1134  buf_.pop(GetSize() - vtableoffsetloc);
1135  break;
1136  }
1137  }
1138  // If this is a new vtable, remember it.
1139  if (vt_use == GetSize()) { buf_.scratch_push_small(vt_use); }
1140  // Fill the vtable offset we created above.
1141  // The offset points from the beginning of the object to where the
1142  // vtable is stored.
1143  // Offsets default direction is downward in memory for future format
1144  // flexibility (storing all vtables at the start of the file).
1145  WriteScalar(buf_.data_at(vtableoffsetloc),
1146  static_cast<soffset_t>(vt_use) -
1147  static_cast<soffset_t>(vtableoffsetloc));
1148 
1149  nested = false;
1150  return vtableoffsetloc;
1151  }
1152 
1153  // DEPRECATED: call the version above instead.
1154  uoffset_t EndTable(uoffset_t start, voffset_t /*numfields*/) {
1155  return EndTable(start);
1156  }
1157 
1158  // This checks a required field has been set in a given table that has
1159  // just been constructed.
1160  template<typename T> void Required(Offset<T> table, voffset_t field);
1161 
1162  uoffset_t StartStruct(size_t alignment) {
1163  Align(alignment);
1164  return GetSize();
1165  }
1166 
1167  uoffset_t EndStruct() { return GetSize(); }
1168 
1169  void ClearOffsets() {
1170  buf_.scratch_pop(num_field_loc * sizeof(FieldLoc));
1171  num_field_loc = 0;
1172  max_voffset_ = 0;
1173  }
1174 
1175  // Aligns such that when "len" bytes are written, an object can be written
1176  // after it with "alignment" without padding.
1177  void PreAlign(size_t len, size_t alignment) {
1178  TrackMinAlign(alignment);
1179  buf_.fill(PaddingBytes(GetSize() + len, alignment));
1180  }
1181  template<typename T> void PreAlign(size_t len) {
1182  AssertScalarT<T>();
1183  PreAlign(len, sizeof(T));
1184  }
1185  /// @endcond
1186 
1187  /// @brief Store a string in the buffer, which can contain any binary data.
1188  /// @param[in] str A const char pointer to the data to be stored as a string.
1189  /// @param[in] len The number of bytes that should be stored from `str`.
1190  /// @return Returns the offset in the buffer where the string starts.
1191  Offset<String> CreateString(const char *str, size_t len) {
1192  NotNested();
1193  PreAlign<uoffset_t>(len + 1); // Always 0-terminated.
1194  buf_.fill(1);
1195  PushBytes(reinterpret_cast<const uint8_t *>(str), len);
1196  PushElement(static_cast<uoffset_t>(len));
1197  return Offset<String>(GetSize());
1198  }
1199 
1200  /// @brief Store a string in the buffer, which is null-terminated.
1201  /// @param[in] str A const char pointer to a C-string to add to the buffer.
1202  /// @return Returns the offset in the buffer where the string starts.
1203  Offset<String> CreateString(const char *str) {
1204  return CreateString(str, strlen(str));
1205  }
1206 
1207  /// @brief Store a string in the buffer, which is null-terminated.
1208  /// @param[in] str A char pointer to a C-string to add to the buffer.
1209  /// @return Returns the offset in the buffer where the string starts.
1211  return CreateString(str, strlen(str));
1212  }
1213 
1214  /// @brief Store a string in the buffer, which can contain any binary data.
1215  /// @param[in] str A const reference to a std::string to store in the buffer.
1216  /// @return Returns the offset in the buffer where the string starts.
1217  Offset<String> CreateString(const std::string &str) {
1218  return CreateString(str.c_str(), str.length());
1219  }
1220 
1221  // clang-format off
1222  #ifdef FLATBUFFERS_HAS_STRING_VIEW
1223  /// @brief Store a string in the buffer, which can contain any binary data.
1224  /// @param[in] str A const string_view to copy in to the buffer.
1225  /// @return Returns the offset in the buffer where the string starts.
1226  Offset<String> CreateString(flatbuffers::string_view str) {
1227  return CreateString(str.data(), str.size());
1228  }
1229  #endif // FLATBUFFERS_HAS_STRING_VIEW
1230  // clang-format on
1231 
1232  /// @brief Store a string in the buffer, which can contain any binary data.
1233  /// @param[in] str A const pointer to a `String` struct to add to the buffer.
1234  /// @return Returns the offset in the buffer where the string starts
1236  return str ? CreateString(str->c_str(), str->Length()) : 0;
1237  }
1238 
1239  /// @brief Store a string in the buffer, which can contain any binary data.
1240  /// @param[in] str A const reference to a std::string like type with support
1241  /// of T::c_str() and T::length() to store in the buffer.
1242  /// @return Returns the offset in the buffer where the string starts.
1243  template<typename T> Offset<String> CreateString(const T &str) {
1244  return CreateString(str.c_str(), str.length());
1245  }
1246 
1247  /// @brief Store a string in the buffer, which can contain any binary data.
1248  /// If a string with this exact contents has already been serialized before,
1249  /// instead simply returns the offset of the existing string.
1250  /// @param[in] str A const char pointer to the data to be stored as a string.
1251  /// @param[in] len The number of bytes that should be stored from `str`.
1252  /// @return Returns the offset in the buffer where the string starts.
1253  Offset<String> CreateSharedString(const char *str, size_t len) {
1254  if (!string_pool)
1255  string_pool = new StringOffsetMap(StringOffsetCompare(buf_));
1256  auto size_before_string = buf_.size();
1257  // Must first serialize the string, since the set is all offsets into
1258  // buffer.
1259  auto off = CreateString(str, len);
1260  auto it = string_pool->find(off);
1261  // If it exists we reuse existing serialized data!
1262  if (it != string_pool->end()) {
1263  // We can remove the string we serialized.
1264  buf_.pop(buf_.size() - size_before_string);
1265  return *it;
1266  }
1267  // Record this string for future use.
1268  string_pool->insert(off);
1269  return off;
1270  }
1271 
1272  /// @brief Store a string in the buffer, which null-terminated.
1273  /// If a string with this exact contents has already been serialized before,
1274  /// instead simply returns the offset of the existing string.
1275  /// @param[in] str A const char pointer to a C-string to add to the buffer.
1276  /// @return Returns the offset in the buffer where the string starts.
1278  return CreateSharedString(str, strlen(str));
1279  }
1280 
1281  /// @brief Store a string in the buffer, which can contain any binary data.
1282  /// If a string with this exact contents has already been serialized before,
1283  /// instead simply returns the offset of the existing string.
1284  /// @param[in] str A const reference to a std::string to store in the buffer.
1285  /// @return Returns the offset in the buffer where the string starts.
1286  Offset<String> CreateSharedString(const std::string &str) {
1287  return CreateSharedString(str.c_str(), str.length());
1288  }
1289 
1290  /// @brief Store a string in the buffer, which can contain any binary data.
1291  /// If a string with this exact contents has already been serialized before,
1292  /// instead simply returns the offset of the existing string.
1293  /// @param[in] str A const pointer to a `String` struct to add to the buffer.
1294  /// @return Returns the offset in the buffer where the string starts
1296  return CreateSharedString(str->c_str(), str->Length());
1297  }
1298 
1299  /// @cond FLATBUFFERS_INTERNAL
1300  uoffset_t EndVector(size_t len) {
1301  FLATBUFFERS_ASSERT(nested); // Hit if no corresponding StartVector.
1302  nested = false;
1303  return PushElement(static_cast<uoffset_t>(len));
1304  }
1305 
1306  void StartVector(size_t len, size_t elemsize) {
1307  NotNested();
1308  nested = true;
1309  PreAlign<uoffset_t>(len * elemsize);
1310  PreAlign(len * elemsize, elemsize); // Just in case elemsize > uoffset_t.
1311  }
1312 
1313  // Call this right before StartVector/CreateVector if you want to force the
1314  // alignment to be something different than what the element size would
1315  // normally dictate.
1316  // This is useful when storing a nested_flatbuffer in a vector of bytes,
1317  // or when storing SIMD floats, etc.
1318  void ForceVectorAlignment(size_t len, size_t elemsize, size_t alignment) {
1319  PreAlign(len * elemsize, alignment);
1320  }
1321 
1322  // Similar to ForceVectorAlignment but for String fields.
1323  void ForceStringAlignment(size_t len, size_t alignment) {
1324  PreAlign((len + 1) * sizeof(char), alignment);
1325  }
1326 
1327  /// @endcond
1328 
1329  /// @brief Serialize an array into a FlatBuffer `vector`.
1330  /// @tparam T The data type of the array elements.
1331  /// @param[in] v A pointer to the array of type `T` to serialize into the
1332  /// buffer as a `vector`.
1333  /// @param[in] len The number of elements to serialize.
1334  /// @return Returns a typed `Offset` into the serialized data indicating
1335  /// where the vector is stored.
1336  template<typename T> Offset<Vector<T>> CreateVector(const T *v, size_t len) {
1337  // If this assert hits, you're specifying a template argument that is
1338  // causing the wrong overload to be selected, remove it.
1339  AssertScalarT<T>();
1340  StartVector(len, sizeof(T));
1341  // clang-format off
1342  #if FLATBUFFERS_LITTLEENDIAN
1343  PushBytes(reinterpret_cast<const uint8_t *>(v), len * sizeof(T));
1344  #else
1345  if (sizeof(T) == 1) {
1346  PushBytes(reinterpret_cast<const uint8_t *>(v), len);
1347  } else {
1348  for (auto i = len; i > 0; ) {
1349  PushElement(v[--i]);
1350  }
1351  }
1352  #endif
1353  // clang-format on
1354  return Offset<Vector<T>>(EndVector(len));
1355  }
1356 
1357  template<typename T>
1358  Offset<Vector<Offset<T>>> CreateVector(const Offset<T> *v, size_t len) {
1359  StartVector(len, sizeof(Offset<T>));
1360  for (auto i = len; i > 0;) { PushElement(v[--i]); }
1361  return Offset<Vector<Offset<T>>>(EndVector(len));
1362  }
1363 
1364  /// @brief Serialize a `std::vector` into a FlatBuffer `vector`.
1365  /// @tparam T The data type of the `std::vector` elements.
1366  /// @param v A const reference to the `std::vector` to serialize into the
1367  /// buffer as a `vector`.
1368  /// @return Returns a typed `Offset` into the serialized data indicating
1369  /// where the vector is stored.
1370  template<typename T> Offset<Vector<T>> CreateVector(const std::vector<T> &v) {
1371  return CreateVector(data(v), v.size());
1372  }
1373 
1374  // vector<bool> may be implemented using a bit-set, so we can't access it as
1375  // an array. Instead, read elements manually.
1376  // Background: https://isocpp.org/blog/2012/11/on-vectorbool
1377  Offset<Vector<uint8_t>> CreateVector(const std::vector<bool> &v) {
1378  StartVector(v.size(), sizeof(uint8_t));
1379  for (auto i = v.size(); i > 0;) {
1380  PushElement(static_cast<uint8_t>(v[--i]));
1381  }
1382  return Offset<Vector<uint8_t>>(EndVector(v.size()));
1383  }
1384 
1385  // clang-format off
1386  #ifndef FLATBUFFERS_CPP98_STL
1387  /// @brief Serialize values returned by a function into a FlatBuffer `vector`.
1388  /// This is a convenience function that takes care of iteration for you.
1389  /// @tparam T The data type of the `std::vector` elements.
1390  /// @param f A function that takes the current iteration 0..vector_size-1 and
1391  /// returns any type that you can construct a FlatBuffers vector out of.
1392  /// @return Returns a typed `Offset` into the serialized data indicating
1393  /// where the vector is stored.
1394  template<typename T> Offset<Vector<T>> CreateVector(size_t vector_size,
1395  const std::function<T (size_t i)> &f) {
1396  std::vector<T> elems(vector_size);
1397  for (size_t i = 0; i < vector_size; i++) elems[i] = f(i);
1398  return CreateVector(elems);
1399  }
1400  #endif
1401  // clang-format on
1402 
1403  /// @brief Serialize values returned by a function into a FlatBuffer `vector`.
1404  /// This is a convenience function that takes care of iteration for you.
1405  /// @tparam T The data type of the `std::vector` elements.
1406  /// @param f A function that takes the current iteration 0..vector_size-1,
1407  /// and the state parameter returning any type that you can construct a
1408  /// FlatBuffers vector out of.
1409  /// @param state State passed to f.
1410  /// @return Returns a typed `Offset` into the serialized data indicating
1411  /// where the vector is stored.
1412  template<typename T, typename F, typename S>
1413  Offset<Vector<T>> CreateVector(size_t vector_size, F f, S *state) {
1414  std::vector<T> elems(vector_size);
1415  for (size_t i = 0; i < vector_size; i++) elems[i] = f(i, state);
1416  return CreateVector(elems);
1417  }
1418 
1419  /// @brief Serialize a `std::vector<std::string>` into a FlatBuffer `vector`.
1420  /// This is a convenience function for a common case.
1421  /// @param v A const reference to the `std::vector` to serialize into the
1422  /// buffer as a `vector`.
1423  /// @return Returns a typed `Offset` into the serialized data indicating
1424  /// where the vector is stored.
1426  const std::vector<std::string> &v) {
1427  std::vector<Offset<String>> offsets(v.size());
1428  for (size_t i = 0; i < v.size(); i++) offsets[i] = CreateString(v[i]);
1429  return CreateVector(offsets);
1430  }
1431 
1432  /// @brief Serialize an array of structs into a FlatBuffer `vector`.
1433  /// @tparam T The data type of the struct array elements.
1434  /// @param[in] v A pointer to the array of type `T` to serialize into the
1435  /// buffer as a `vector`.
1436  /// @param[in] len The number of elements to serialize.
1437  /// @return Returns a typed `Offset` into the serialized data indicating
1438  /// where the vector is stored.
1439  template<typename T>
1441  StartVector(len * sizeof(T) / AlignOf<T>(), AlignOf<T>());
1442  PushBytes(reinterpret_cast<const uint8_t *>(v), sizeof(T) * len);
1443  return Offset<Vector<const T *>>(EndVector(len));
1444  }
1445 
1446  /// @brief Serialize an array of native structs into a FlatBuffer `vector`.
1447  /// @tparam T The data type of the struct array elements.
1448  /// @tparam S The data type of the native struct array elements.
1449  /// @param[in] v A pointer to the array of type `S` to serialize into the
1450  /// buffer as a `vector`.
1451  /// @param[in] len The number of elements to serialize.
1452  /// @return Returns a typed `Offset` into the serialized data indicating
1453  /// where the vector is stored.
1454  template<typename T, typename S>
1456  size_t len) {
1457  extern T Pack(const S &);
1458  typedef T (*Pack_t)(const S &);
1459  std::vector<T> vv(len);
1460  std::transform(v, v + len, vv.begin(), *(Pack_t)&Pack);
1461  return CreateVectorOfStructs<T>(vv.data(), vv.size());
1462  }
1463 
1464  // clang-format off
1465  #ifndef FLATBUFFERS_CPP98_STL
1466  /// @brief Serialize an array of structs into a FlatBuffer `vector`.
1467  /// @tparam T The data type of the struct array elements.
1468  /// @param[in] f A function that takes the current iteration 0..vector_size-1
1469  /// and a pointer to the struct that must be filled.
1470  /// @return Returns a typed `Offset` into the serialized data indicating
1471  /// where the vector is stored.
1472  /// This is mostly useful when flatbuffers are generated with mutation
1473  /// accessors.
1475  size_t vector_size, const std::function<void(size_t i, T *)> &filler) {
1476  T* structs = StartVectorOfStructs<T>(vector_size);
1477  for (size_t i = 0; i < vector_size; i++) {
1478  filler(i, structs);
1479  structs++;
1480  }
1481  return EndVectorOfStructs<T>(vector_size);
1482  }
1483  #endif
1484  // clang-format on
1485 
1486  /// @brief Serialize an array of structs into a FlatBuffer `vector`.
1487  /// @tparam T The data type of the struct array elements.
1488  /// @param[in] f A function that takes the current iteration 0..vector_size-1,
1489  /// a pointer to the struct that must be filled and the state argument.
1490  /// @param[in] state Arbitrary state to pass to f.
1491  /// @return Returns a typed `Offset` into the serialized data indicating
1492  /// where the vector is stored.
1493  /// This is mostly useful when flatbuffers are generated with mutation
1494  /// accessors.
1495  template<typename T, typename F, typename S>
1497  S *state) {
1498  T *structs = StartVectorOfStructs<T>(vector_size);
1499  for (size_t i = 0; i < vector_size; i++) {
1500  f(i, structs, state);
1501  structs++;
1502  }
1503  return EndVectorOfStructs<T>(vector_size);
1504  }
1505 
1506  /// @brief Serialize a `std::vector` of structs into a FlatBuffer `vector`.
1507  /// @tparam T The data type of the `std::vector` struct elements.
1508  /// @param[in]] v A const reference to the `std::vector` of structs to
1509  /// serialize into the buffer as a `vector`.
1510  /// @return Returns a typed `Offset` into the serialized data indicating
1511  /// where the vector is stored.
1512  template<typename T, typename Alloc>
1514  const std::vector<T, Alloc> &v) {
1515  return CreateVectorOfStructs(data(v), v.size());
1516  }
1517 
1518  /// @brief Serialize a `std::vector` of native structs into a FlatBuffer
1519  /// `vector`.
1520  /// @tparam T The data type of the `std::vector` struct elements.
1521  /// @tparam S The data type of the `std::vector` native struct elements.
1522  /// @param[in]] v A const reference to the `std::vector` of structs to
1523  /// serialize into the buffer as a `vector`.
1524  /// @return Returns a typed `Offset` into the serialized data indicating
1525  /// where the vector is stored.
1526  template<typename T, typename S>
1528  const std::vector<S> &v) {
1529  return CreateVectorOfNativeStructs<T, S>(data(v), v.size());
1530  }
1531 
1532  /// @cond FLATBUFFERS_INTERNAL
1533  template<typename T> struct StructKeyComparator {
1534  bool operator()(const T &a, const T &b) const {
1535  return a.KeyCompareLessThan(&b);
1536  }
1537 
1538  private:
1539  StructKeyComparator &operator=(const StructKeyComparator &);
1540  };
1541  /// @endcond
1542 
1543  /// @brief Serialize a `std::vector` of structs into a FlatBuffer `vector`
1544  /// in sorted order.
1545  /// @tparam T The data type of the `std::vector` struct elements.
1546  /// @param[in]] v A const reference to the `std::vector` of structs to
1547  /// serialize into the buffer as a `vector`.
1548  /// @return Returns a typed `Offset` into the serialized data indicating
1549  /// where the vector is stored.
1550  template<typename T>
1552  return CreateVectorOfSortedStructs(data(*v), v->size());
1553  }
1554 
1555  /// @brief Serialize a `std::vector` of native structs into a FlatBuffer
1556  /// `vector` in sorted order.
1557  /// @tparam T The data type of the `std::vector` struct elements.
1558  /// @tparam S The data type of the `std::vector` native struct elements.
1559  /// @param[in]] v A const reference to the `std::vector` of structs to
1560  /// serialize into the buffer as a `vector`.
1561  /// @return Returns a typed `Offset` into the serialized data indicating
1562  /// where the vector is stored.
1563  template<typename T, typename S>
1565  std::vector<S> *v) {
1566  return CreateVectorOfSortedNativeStructs<T, S>(data(*v), v->size());
1567  }
1568 
1569  /// @brief Serialize an array of structs into a FlatBuffer `vector` in sorted
1570  /// order.
1571  /// @tparam T The data type of the struct array elements.
1572  /// @param[in] v A pointer to the array of type `T` to serialize into the
1573  /// buffer as a `vector`.
1574  /// @param[in] len The number of elements to serialize.
1575  /// @return Returns a typed `Offset` into the serialized data indicating
1576  /// where the vector is stored.
1577  template<typename T>
1579  std::sort(v, v + len, StructKeyComparator<T>());
1580  return CreateVectorOfStructs(v, len);
1581  }
1582 
1583  /// @brief Serialize an array of native structs into a FlatBuffer `vector` in
1584  /// sorted order.
1585  /// @tparam T The data type of the struct array elements.
1586  /// @tparam S The data type of the native struct array elements.
1587  /// @param[in] v A pointer to the array of type `S` to serialize into the
1588  /// buffer as a `vector`.
1589  /// @param[in] len The number of elements to serialize.
1590  /// @return Returns a typed `Offset` into the serialized data indicating
1591  /// where the vector is stored.
1592  template<typename T, typename S>
1594  size_t len) {
1595  extern T Pack(const S &);
1596  typedef T (*Pack_t)(const S &);
1597  std::vector<T> vv(len);
1598  std::transform(v, v + len, vv.begin(), *(Pack_t)&Pack);
1599  return CreateVectorOfSortedStructs<T>(vv, len);
1600  }
1601 
1602  /// @cond FLATBUFFERS_INTERNAL
1603  template<typename T> struct TableKeyComparator {
1604  TableKeyComparator(vector_downward &buf) : buf_(buf) {}
1605  bool operator()(const Offset<T> &a, const Offset<T> &b) const {
1606  auto table_a = reinterpret_cast<T *>(buf_.data_at(a.o));
1607  auto table_b = reinterpret_cast<T *>(buf_.data_at(b.o));
1608  return table_a->KeyCompareLessThan(table_b);
1609  }
1610  vector_downward &buf_;
1611 
1612  private:
1613  TableKeyComparator &operator=(const TableKeyComparator &);
1614  };
1615  /// @endcond
1616 
1617  /// @brief Serialize an array of `table` offsets as a `vector` in the buffer
1618  /// in sorted order.
1619  /// @tparam T The data type that the offset refers to.
1620  /// @param[in] v An array of type `Offset<T>` that contains the `table`
1621  /// offsets to store in the buffer in sorted order.
1622  /// @param[in] len The number of elements to store in the `vector`.
1623  /// @return Returns a typed `Offset` into the serialized data indicating
1624  /// where the vector is stored.
1625  template<typename T>
1627  size_t len) {
1628  std::sort(v, v + len, TableKeyComparator<T>(buf_));
1629  return CreateVector(v, len);
1630  }
1631 
1632  /// @brief Serialize an array of `table` offsets as a `vector` in the buffer
1633  /// in sorted order.
1634  /// @tparam T The data type that the offset refers to.
1635  /// @param[in] v An array of type `Offset<T>` that contains the `table`
1636  /// offsets to store in the buffer in sorted order.
1637  /// @return Returns a typed `Offset` into the serialized data indicating
1638  /// where the vector is stored.
1639  template<typename T>
1641  std::vector<Offset<T>> *v) {
1642  return CreateVectorOfSortedTables(data(*v), v->size());
1643  }
1644 
1645  /// @brief Specialized version of `CreateVector` for non-copying use cases.
1646  /// Write the data any time later to the returned buffer pointer `buf`.
1647  /// @param[in] len The number of elements to store in the `vector`.
1648  /// @param[in] elemsize The size of each element in the `vector`.
1649  /// @param[out] buf A pointer to a `uint8_t` pointer that can be
1650  /// written to at a later time to serialize the data into a `vector`
1651  /// in the buffer.
1652  uoffset_t CreateUninitializedVector(size_t len, size_t elemsize,
1653  uint8_t **buf) {
1654  NotNested();
1655  StartVector(len, elemsize);
1656  buf_.make_space(len * elemsize);
1657  auto vec_start = GetSize();
1658  auto vec_end = EndVector(len);
1659  *buf = buf_.data_at(vec_start);
1660  return vec_end;
1661  }
1662 
1663  /// @brief Specialized version of `CreateVector` for non-copying use cases.
1664  /// Write the data any time later to the returned buffer pointer `buf`.
1665  /// @tparam T The data type of the data that will be stored in the buffer
1666  /// as a `vector`.
1667  /// @param[in] len The number of elements to store in the `vector`.
1668  /// @param[out] buf A pointer to a pointer of type `T` that can be
1669  /// written to at a later time to serialize the data into a `vector`
1670  /// in the buffer.
1671  template<typename T>
1673  AssertScalarT<T>();
1674  return CreateUninitializedVector(len, sizeof(T),
1675  reinterpret_cast<uint8_t **>(buf));
1676  }
1677 
1678  template<typename T>
1679  Offset<Vector<const T*>> CreateUninitializedVectorOfStructs(size_t len, T **buf) {
1680  return CreateUninitializedVector(len, sizeof(T),
1681  reinterpret_cast<uint8_t **>(buf));
1682  }
1683 
1684  /// @brief Write a struct by itself, typically to be part of a union.
1685  template<typename T> Offset<const T *> CreateStruct(const T &structobj) {
1686  NotNested();
1687  Align(AlignOf<T>());
1688  buf_.push_small(structobj);
1689  return Offset<const T *>(GetSize());
1690  }
1691 
1692  /// @brief The length of a FlatBuffer file header.
1693  static const size_t kFileIdentifierLength = 4;
1694 
1695  /// @brief Finish serializing a buffer by writing the root offset.
1696  /// @param[in] file_identifier If a `file_identifier` is given, the buffer
1697  /// will be prefixed with a standard FlatBuffers file header.
1698  template<typename T>
1699  void Finish(Offset<T> root, const char *file_identifier = nullptr) {
1700  Finish(root.o, file_identifier, false);
1701  }
1702 
1703  /// @brief Finish a buffer with a 32 bit size field pre-fixed (size of the
1704  /// buffer following the size field). These buffers are NOT compatible
1705  /// with standard buffers created by Finish, i.e. you can't call GetRoot
1706  /// on them, you have to use GetSizePrefixedRoot instead.
1707  /// All >32 bit quantities in this buffer will be aligned when the whole
1708  /// size pre-fixed buffer is aligned.
1709  /// These kinds of buffers are useful for creating a stream of FlatBuffers.
1710  template<typename T>
1712  const char *file_identifier = nullptr) {
1713  Finish(root.o, file_identifier, true);
1714  }
1715 
1716  protected:
1717  // You shouldn't really be copying instances of this class.
1719  FlatBufferBuilder &operator=(const FlatBufferBuilder &);
1720 
1721  void Finish(uoffset_t root, const char *file_identifier, bool size_prefix) {
1722  NotNested();
1723  buf_.clear_scratch();
1724  // This will cause the whole buffer to be aligned.
1725  PreAlign((size_prefix ? sizeof(uoffset_t) : 0) + sizeof(uoffset_t) +
1726  (file_identifier ? kFileIdentifierLength : 0),
1727  minalign_);
1728  if (file_identifier) {
1729  FLATBUFFERS_ASSERT(strlen(file_identifier) == kFileIdentifierLength);
1730  PushBytes(reinterpret_cast<const uint8_t *>(file_identifier),
1731  kFileIdentifierLength);
1732  }
1733  PushElement(ReferTo(root)); // Location of root.
1734  if (size_prefix) { PushElement(GetSize()); }
1735  finished = true;
1736  }
1737 
1738  struct FieldLoc {
1739  uoffset_t off;
1740  voffset_t id;
1741  };
1742 
1743  vector_downward buf_;
1744 
1745  // Accumulating offsets of table members while it is being built.
1746  // We store these in the scratch pad of buf_, after the vtable offsets.
1747  uoffset_t num_field_loc;
1748  // Track how much of the vtable is in use, so we can output the most compact
1749  // possible vtable.
1750  voffset_t max_voffset_;
1751 
1752  // Ensure objects are not nested.
1753  bool nested;
1754 
1755  // Ensure the buffer is finished before it is being accessed.
1756  bool finished;
1757 
1758  size_t minalign_;
1759 
1760  bool force_defaults_; // Serialize values equal to their defaults anyway.
1761 
1762  bool dedup_vtables_;
1763 
1765  StringOffsetCompare(const vector_downward &buf) : buf_(&buf) {}
1766  bool operator()(const Offset<String> &a, const Offset<String> &b) const {
1767  auto stra = reinterpret_cast<const String *>(buf_->data_at(a.o));
1768  auto strb = reinterpret_cast<const String *>(buf_->data_at(b.o));
1769  return strncmp(stra->c_str(), strb->c_str(),
1770  (std::min)(stra->size(), strb->size()) + 1) < 0;
1771  }
1772  const vector_downward *buf_;
1773  };
1774 
1775  // For use with CreateSharedString. Instantiated on first use only.
1776  typedef std::set<Offset<String>, StringOffsetCompare> StringOffsetMap;
1777  StringOffsetMap *string_pool;
1778 
1779  private:
1780  // Allocates space for a vector of structures.
1781  // Must be completed with EndVectorOfStructs().
1782  template<typename T> T *StartVectorOfStructs(size_t vector_size) {
1783  StartVector(vector_size * sizeof(T) / AlignOf<T>(), AlignOf<T>());
1784  return reinterpret_cast<T *>(buf_.make_space(vector_size * sizeof(T)));
1785  }
1786 
1787  // End the vector of structues in the flatbuffers.
1788  // Vector should have previously be started with StartVectorOfStructs().
1789  template<typename T>
1790  Offset<Vector<const T *>> EndVectorOfStructs(size_t vector_size) {
1791  return Offset<Vector<const T *>>(EndVector(vector_size));
1792  }
1793 };
1794 /// @}
1795 
1796 /// @cond FLATBUFFERS_INTERNAL
1797 // Helpers to get a typed pointer to the root object contained in the buffer.
1798 template<typename T> T *GetMutableRoot(void *buf) {
1799  EndianCheck();
1800  return reinterpret_cast<T *>(
1801  reinterpret_cast<uint8_t *>(buf) +
1802  EndianScalar(*reinterpret_cast<uoffset_t *>(buf)));
1803 }
1804 
1805 template<typename T> const T *GetRoot(const void *buf) {
1806  return GetMutableRoot<T>(const_cast<void *>(buf));
1807 }
1808 
1809 template<typename T> const T *GetSizePrefixedRoot(const void *buf) {
1810  return GetRoot<T>(reinterpret_cast<const uint8_t *>(buf) + sizeof(uoffset_t));
1811 }
1812 
1813 /// Helpers to get a typed pointer to objects that are currently being built.
1814 /// @warning Creating new objects will lead to reallocations and invalidates
1815 /// the pointer!
1816 template<typename T>
1817 T *GetMutableTemporaryPointer(FlatBufferBuilder &fbb, Offset<T> offset) {
1818  return reinterpret_cast<T *>(fbb.GetCurrentBufferPointer() + fbb.GetSize() -
1819  offset.o);
1820 }
1821 
1822 template<typename T>
1823 const T *GetTemporaryPointer(FlatBufferBuilder &fbb, Offset<T> offset) {
1824  return GetMutableTemporaryPointer<T>(fbb, offset);
1825 }
1826 
1827 /// @brief Get a pointer to the the file_identifier section of the buffer.
1828 /// @return Returns a const char pointer to the start of the file_identifier
1829 /// characters in the buffer. The returned char * has length
1830 /// 'flatbuffers::FlatBufferBuilder::kFileIdentifierLength'.
1831 /// This function is UNDEFINED for FlatBuffers whose schema does not include
1832 /// a file_identifier (likely points at padding or the start of a the root
1833 /// vtable).
1834 inline const char *GetBufferIdentifier(const void *buf, bool size_prefixed = false) {
1835  return reinterpret_cast<const char *>(buf) +
1836  ((size_prefixed) ? 2 * sizeof(uoffset_t) : sizeof(uoffset_t));
1837 }
1838 
1839 // Helper to see if the identifier in a buffer has the expected value.
1840 inline bool BufferHasIdentifier(const void *buf, const char *identifier, bool size_prefixed = false) {
1841  return strncmp(GetBufferIdentifier(buf, size_prefixed), identifier,
1843 }
1844 
1845 // Helper class to verify the integrity of a FlatBuffer
1846 class Verifier FLATBUFFERS_FINAL_CLASS {
1847  public:
1848  Verifier(const uint8_t *buf, size_t buf_len, uoffset_t _max_depth = 64,
1849  uoffset_t _max_tables = 1000000)
1850  : buf_(buf),
1851  size_(buf_len),
1852  depth_(0),
1853  max_depth_(_max_depth),
1854  num_tables_(0),
1855  max_tables_(_max_tables)
1856  // clang-format off
1857  #ifdef FLATBUFFERS_TRACK_VERIFIER_BUFFER_SIZE
1858  , upper_bound_(0)
1859  #endif
1860  // clang-format on
1861  {
1862  assert(size_ < FLATBUFFERS_MAX_BUFFER_SIZE);
1863  }
1864 
1865  // Central location where any verification failures register.
1866  bool Check(bool ok) const {
1867  // clang-format off
1868  #ifdef FLATBUFFERS_DEBUG_VERIFICATION_FAILURE
1869  FLATBUFFERS_ASSERT(ok);
1870  #endif
1871  #ifdef FLATBUFFERS_TRACK_VERIFIER_BUFFER_SIZE
1872  if (!ok)
1873  upper_bound_ = 0;
1874  #endif
1875  // clang-format on
1876  return ok;
1877  }
1878 
1879  // Verify any range within the buffer.
1880  bool Verify(size_t elem, size_t elem_len) const {
1881  // clang-format off
1882  #ifdef FLATBUFFERS_TRACK_VERIFIER_BUFFER_SIZE
1883  auto upper_bound = elem + elem_len;
1884  if (upper_bound_ < upper_bound)
1885  upper_bound_ = upper_bound;
1886  #endif
1887  // clang-format on
1888  return Check(elem_len < size_ && elem <= size_ - elem_len);
1889  }
1890 
1891  template<typename T> bool VerifyAlignment(size_t elem) const {
1892  return (elem & (sizeof(T) - 1)) == 0;
1893  }
1894 
1895  // Verify a range indicated by sizeof(T).
1896  template<typename T> bool Verify(size_t elem) const {
1897  return VerifyAlignment<T>(elem) && Verify(elem, sizeof(T));
1898  }
1899 
1900  // Verify relative to a known-good base pointer.
1901  bool Verify(const uint8_t *base, voffset_t elem_off, size_t elem_len) const {
1902  return Verify(static_cast<size_t>(base - buf_) + elem_off, elem_len);
1903  }
1904 
1905  template<typename T> bool Verify(const uint8_t *base, voffset_t elem_off)
1906  const {
1907  return Verify(static_cast<size_t>(base - buf_) + elem_off, sizeof(T));
1908  }
1909 
1910  // Verify a pointer (may be NULL) of a table type.
1911  template<typename T> bool VerifyTable(const T *table) {
1912  return !table || table->Verify(*this);
1913  }
1914 
1915  // Verify a pointer (may be NULL) of any vector type.
1916  template<typename T> bool VerifyVector(const Vector<T> *vec) const {
1917  return !vec || VerifyVectorOrString(reinterpret_cast<const uint8_t *>(vec),
1918  sizeof(T));
1919  }
1920 
1921  // Verify a pointer (may be NULL) of a vector to struct.
1922  template<typename T> bool VerifyVector(const Vector<const T *> *vec) const {
1923  return VerifyVector(reinterpret_cast<const Vector<T> *>(vec));
1924  }
1925 
1926  // Verify a pointer (may be NULL) to string.
1927  bool VerifyString(const String *str) const {
1928  size_t end;
1929  return !str ||
1930  (VerifyVectorOrString(reinterpret_cast<const uint8_t *>(str),
1931  1, &end) &&
1932  Verify(end, 1) && // Must have terminator
1933  Check(buf_[end] == '\0')); // Terminating byte must be 0.
1934  }
1935 
1936  // Common code between vectors and strings.
1937  bool VerifyVectorOrString(const uint8_t *vec, size_t elem_size,
1938  size_t *end = nullptr) const {
1939  auto veco = static_cast<size_t>(vec - buf_);
1940  // Check we can read the size field.
1941  if (!Verify<uoffset_t>(veco)) return false;
1942  // Check the whole array. If this is a string, the byte past the array
1943  // must be 0.
1944  auto size = ReadScalar<uoffset_t>(vec);
1945  auto max_elems = FLATBUFFERS_MAX_BUFFER_SIZE / elem_size;
1946  if (!Check(size < max_elems))
1947  return false; // Protect against byte_size overflowing.
1948  auto byte_size = sizeof(size) + elem_size * size;
1949  if (end) *end = veco + byte_size;
1950  return Verify(veco, byte_size);
1951  }
1952 
1953  // Special case for string contents, after the above has been called.
1954  bool VerifyVectorOfStrings(const Vector<Offset<String>> *vec) const {
1955  if (vec) {
1956  for (uoffset_t i = 0; i < vec->size(); i++) {
1957  if (!VerifyString(vec->Get(i))) return false;
1958  }
1959  }
1960  return true;
1961  }
1962 
1963  // Special case for table contents, after the above has been called.
1964  template<typename T> bool VerifyVectorOfTables(const Vector<Offset<T>> *vec) {
1965  if (vec) {
1966  for (uoffset_t i = 0; i < vec->size(); i++) {
1967  if (!vec->Get(i)->Verify(*this)) return false;
1968  }
1969  }
1970  return true;
1971  }
1972 
1973  bool VerifyTableStart(const uint8_t *table) {
1974  // Check the vtable offset.
1975  auto tableo = static_cast<size_t>(table - buf_);
1976  if (!Verify<soffset_t>(tableo)) return false;
1977  // This offset may be signed, but doing the substraction unsigned always
1978  // gives the result we want.
1979  auto vtableo = tableo - static_cast<size_t>(ReadScalar<soffset_t>(table));
1980  // Check the vtable size field, then check vtable fits in its entirety.
1981  return VerifyComplexity() && Verify<voffset_t>(vtableo) &&
1982  VerifyAlignment<voffset_t>(ReadScalar<voffset_t>(buf_ + vtableo)) &&
1983  Verify(vtableo, ReadScalar<voffset_t>(buf_ + vtableo));
1984  }
1985 
1986  template<typename T>
1987  bool VerifyBufferFromStart(const char *identifier, size_t start) {
1988  if (identifier &&
1989  (size_ < 2 * sizeof(flatbuffers::uoffset_t) ||
1990  !BufferHasIdentifier(buf_ + start, identifier))) {
1991  return false;
1992  }
1993 
1994  // Call T::Verify, which must be in the generated code for this type.
1995  auto o = VerifyOffset(start);
1996  return o && reinterpret_cast<const T *>(buf_ + start + o)->Verify(*this)
1997  // clang-format off
1998  #ifdef FLATBUFFERS_TRACK_VERIFIER_BUFFER_SIZE
1999  && GetComputedSize()
2000  #endif
2001  ;
2002  // clang-format on
2003  }
2004 
2005  // Verify this whole buffer, starting with root type T.
2006  template<typename T> bool VerifyBuffer() { return VerifyBuffer<T>(nullptr); }
2007 
2008  template<typename T> bool VerifyBuffer(const char *identifier) {
2009  return VerifyBufferFromStart<T>(identifier, 0);
2010  }
2011 
2012  template<typename T> bool VerifySizePrefixedBuffer(const char *identifier) {
2013  return Verify<uoffset_t>(0U) &&
2014  ReadScalar<uoffset_t>(buf_) == size_ - sizeof(uoffset_t) &&
2015  VerifyBufferFromStart<T>(identifier, sizeof(uoffset_t));
2016  }
2017 
2018  uoffset_t VerifyOffset(size_t start) const {
2019  if (!Verify<uoffset_t>(start)) return 0;
2020  auto o = ReadScalar<uoffset_t>(buf_ + start);
2021  // May not point to itself.
2022  Check(o != 0);
2023  // Can't wrap around / buffers are max 2GB.
2024  if (!Check(static_cast<soffset_t>(o) >= 0)) return 0;
2025  // Must be inside the buffer to create a pointer from it (pointer outside
2026  // buffer is UB).
2027  if (!Verify(start + o, 1)) return 0;
2028  return o;
2029  }
2030 
2031  uoffset_t VerifyOffset(const uint8_t *base, voffset_t start) const {
2032  return VerifyOffset(static_cast<size_t>(base - buf_) + start);
2033  }
2034 
2035  // Called at the start of a table to increase counters measuring data
2036  // structure depth and amount, and possibly bails out with false if
2037  // limits set by the constructor have been hit. Needs to be balanced
2038  // with EndTable().
2039  bool VerifyComplexity() {
2040  depth_++;
2041  num_tables_++;
2042  return Check(depth_ <= max_depth_ && num_tables_ <= max_tables_);
2043  }
2044 
2045  // Called at the end of a table to pop the depth count.
2046  bool EndTable() {
2047  depth_--;
2048  return true;
2049  }
2050 
2051  // clang-format off
2052  #ifdef FLATBUFFERS_TRACK_VERIFIER_BUFFER_SIZE
2053  // Returns the message size in bytes
2054  size_t GetComputedSize() const {
2055  uintptr_t size = upper_bound_;
2056  // Align the size to uoffset_t
2057  size = (size - 1 + sizeof(uoffset_t)) & ~(sizeof(uoffset_t) - 1);
2058  return (size > size_) ? 0 : size;
2059  }
2060  #endif
2061  // clang-format on
2062 
2063  private:
2064  const uint8_t *buf_;
2065  size_t size_;
2066  uoffset_t depth_;
2067  uoffset_t max_depth_;
2068  uoffset_t num_tables_;
2069  uoffset_t max_tables_;
2070  // clang-format off
2071  #ifdef FLATBUFFERS_TRACK_VERIFIER_BUFFER_SIZE
2072  mutable size_t upper_bound_;
2073  #endif
2074  // clang-format on
2075 };
2076 
2077 // Convenient way to bundle a buffer and its length, to pass it around
2078 // typed by its root.
2079 // A BufferRef does not own its buffer.
2080 struct BufferRefBase {}; // for std::is_base_of
2081 template<typename T> struct BufferRef : BufferRefBase {
2082  BufferRef() : buf(nullptr), len(0), must_free(false) {}
2083  BufferRef(uint8_t *_buf, uoffset_t _len)
2084  : buf(_buf), len(_len), must_free(false) {}
2085 
2086  ~BufferRef() {
2087  if (must_free) free(buf);
2088  }
2089 
2090  const T *GetRoot() const { return flatbuffers::GetRoot<T>(buf); }
2091 
2092  bool Verify() {
2093  Verifier verifier(buf, len);
2094  return verifier.VerifyBuffer<T>(nullptr);
2095  }
2096 
2097  uint8_t *buf;
2098  uoffset_t len;
2099  bool must_free;
2100 };
2101 
2102 // "structs" are flat structures that do not have an offset table, thus
2103 // always have all members present and do not support forwards/backwards
2104 // compatible extensions.
2105 
2106 class Struct FLATBUFFERS_FINAL_CLASS {
2107  public:
2108  template<typename T> T GetField(uoffset_t o) const {
2109  return ReadScalar<T>(&data_[o]);
2110  }
2111 
2112  template<typename T> T GetStruct(uoffset_t o) const {
2113  return reinterpret_cast<T>(&data_[o]);
2114  }
2115 
2116  const uint8_t *GetAddressOf(uoffset_t o) const { return &data_[o]; }
2117  uint8_t *GetAddressOf(uoffset_t o) { return &data_[o]; }
2118 
2119  private:
2120  uint8_t data_[1];
2121 };
2122 
2123 // "tables" use an offset table (possibly shared) that allows fields to be
2124 // omitted and added at will, but uses an extra indirection to read.
2125 class Table {
2126  public:
2127  const uint8_t *GetVTable() const {
2128  return data_ - ReadScalar<soffset_t>(data_);
2129  }
2130 
2131  // This gets the field offset for any of the functions below it, or 0
2132  // if the field was not present.
2133  voffset_t GetOptionalFieldOffset(voffset_t field) const {
2134  // The vtable offset is always at the start.
2135  auto vtable = GetVTable();
2136  // The first element is the size of the vtable (fields + type id + itself).
2137  auto vtsize = ReadScalar<voffset_t>(vtable);
2138  // If the field we're accessing is outside the vtable, we're reading older
2139  // data, so it's the same as if the offset was 0 (not present).
2140  return field < vtsize ? ReadScalar<voffset_t>(vtable + field) : 0;
2141  }
2142 
2143  template<typename T> T GetField(voffset_t field, T defaultval) const {
2144  auto field_offset = GetOptionalFieldOffset(field);
2145  return field_offset ? ReadScalar<T>(data_ + field_offset) : defaultval;
2146  }
2147 
2148  template<typename P> P GetPointer(voffset_t field) {
2149  auto field_offset = GetOptionalFieldOffset(field);
2150  auto p = data_ + field_offset;
2151  return field_offset ? reinterpret_cast<P>(p + ReadScalar<uoffset_t>(p))
2152  : nullptr;
2153  }
2154  template<typename P> P GetPointer(voffset_t field) const {
2155  return const_cast<Table *>(this)->GetPointer<P>(field);
2156  }
2157 
2158  template<typename P> P GetStruct(voffset_t field) const {
2159  auto field_offset = GetOptionalFieldOffset(field);
2160  auto p = const_cast<uint8_t *>(data_ + field_offset);
2161  return field_offset ? reinterpret_cast<P>(p) : nullptr;
2162  }
2163 
2164  template<typename T> bool SetField(voffset_t field, T val, T def) {
2165  auto field_offset = GetOptionalFieldOffset(field);
2166  if (!field_offset) return val == def;
2167  WriteScalar(data_ + field_offset, val);
2168  return true;
2169  }
2170 
2171  bool SetPointer(voffset_t field, const uint8_t *val) {
2172  auto field_offset = GetOptionalFieldOffset(field);
2173  if (!field_offset) return false;
2174  WriteScalar(data_ + field_offset,
2175  static_cast<uoffset_t>(val - (data_ + field_offset)));
2176  return true;
2177  }
2178 
2179  uint8_t *GetAddressOf(voffset_t field) {
2180  auto field_offset = GetOptionalFieldOffset(field);
2181  return field_offset ? data_ + field_offset : nullptr;
2182  }
2183  const uint8_t *GetAddressOf(voffset_t field) const {
2184  return const_cast<Table *>(this)->GetAddressOf(field);
2185  }
2186 
2187  bool CheckField(voffset_t field) const {
2188  return GetOptionalFieldOffset(field) != 0;
2189  }
2190 
2191  // Verify the vtable of this table.
2192  // Call this once per table, followed by VerifyField once per field.
2193  bool VerifyTableStart(Verifier &verifier) const {
2194  return verifier.VerifyTableStart(data_);
2195  }
2196 
2197  // Verify a particular field.
2198  template<typename T>
2199  bool VerifyField(const Verifier &verifier, voffset_t field) const {
2200  // Calling GetOptionalFieldOffset should be safe now thanks to
2201  // VerifyTable().
2202  auto field_offset = GetOptionalFieldOffset(field);
2203  // Check the actual field.
2204  return !field_offset || verifier.Verify<T>(data_, field_offset);
2205  }
2206 
2207  // VerifyField for required fields.
2208  template<typename T>
2209  bool VerifyFieldRequired(const Verifier &verifier, voffset_t field) const {
2210  auto field_offset = GetOptionalFieldOffset(field);
2211  return verifier.Check(field_offset != 0) &&
2212  verifier.Verify<T>(data_, field_offset);
2213  }
2214 
2215  // Versions for offsets.
2216  bool VerifyOffset(const Verifier &verifier, voffset_t field) const {
2217  auto field_offset = GetOptionalFieldOffset(field);
2218  return !field_offset || verifier.VerifyOffset(data_, field_offset);
2219  }
2220 
2221  bool VerifyOffsetRequired(const Verifier &verifier, voffset_t field) const {
2222  auto field_offset = GetOptionalFieldOffset(field);
2223  return verifier.Check(field_offset != 0) &&
2224  verifier.VerifyOffset(data_, field_offset);
2225  }
2226 
2227  private:
2228  // private constructor & copy constructor: you obtain instances of this
2229  // class by pointing to existing data only
2230  Table();
2231  Table(const Table &other);
2232 
2233  uint8_t data_[1];
2234 };
2235 
2236 template<typename T> void FlatBufferBuilder::Required(Offset<T> table,
2237  voffset_t field) {
2238  auto table_ptr = reinterpret_cast<const Table *>(buf_.data_at(table.o));
2239  bool ok = table_ptr->GetOptionalFieldOffset(field) != 0;
2240  // If this fails, the caller will show what field needs to be set.
2241  FLATBUFFERS_ASSERT(ok);
2242  (void)ok;
2243 }
2244 
2245 /// @brief This can compute the start of a FlatBuffer from a root pointer, i.e.
2246 /// it is the opposite transformation of GetRoot().
2247 /// This may be useful if you want to pass on a root and have the recipient
2248 /// delete the buffer afterwards.
2249 inline const uint8_t *GetBufferStartFromRootPointer(const void *root) {
2250  auto table = reinterpret_cast<const Table *>(root);
2251  auto vtable = table->GetVTable();
2252  // Either the vtable is before the root or after the root.
2253  auto start = (std::min)(vtable, reinterpret_cast<const uint8_t *>(root));
2254  // Align to at least sizeof(uoffset_t).
2255  start = reinterpret_cast<const uint8_t *>(reinterpret_cast<uintptr_t>(start) &
2256  ~(sizeof(uoffset_t) - 1));
2257  // Additionally, there may be a file_identifier in the buffer, and the root
2258  // offset. The buffer may have been aligned to any size between
2259  // sizeof(uoffset_t) and FLATBUFFERS_MAX_ALIGNMENT (see "force_align").
2260  // Sadly, the exact alignment is only known when constructing the buffer,
2261  // since it depends on the presence of values with said alignment properties.
2262  // So instead, we simply look at the next uoffset_t values (root,
2263  // file_identifier, and alignment padding) to see which points to the root.
2264  // None of the other values can "impersonate" the root since they will either
2265  // be 0 or four ASCII characters.
2266  static_assert(FlatBufferBuilder::kFileIdentifierLength == sizeof(uoffset_t),
2267  "file_identifier is assumed to be the same size as uoffset_t");
2268  for (auto possible_roots = FLATBUFFERS_MAX_ALIGNMENT / sizeof(uoffset_t) + 1;
2269  possible_roots; possible_roots--) {
2270  start -= sizeof(uoffset_t);
2271  if (ReadScalar<uoffset_t>(start) + start ==
2272  reinterpret_cast<const uint8_t *>(root))
2273  return start;
2274  }
2275  // We didn't find the root, either the "root" passed isn't really a root,
2276  // or the buffer is corrupt.
2277  // Assert, because calling this function with bad data may cause reads
2278  // outside of buffer boundaries.
2279  FLATBUFFERS_ASSERT(false);
2280  return nullptr;
2281 }
2282 
2283 /// @brief This return the prefixed size of a FlatBuffer.
2284 inline uoffset_t GetPrefixedSize(const uint8_t* buf){ return ReadScalar<uoffset_t>(buf); }
2285 
2286 // Base class for native objects (FlatBuffer data de-serialized into native
2287 // C++ data structures).
2288 // Contains no functionality, purely documentative.
2289 struct NativeTable {};
2290 
2291 /// @brief Function types to be used with resolving hashes into objects and
2292 /// back again. The resolver gets a pointer to a field inside an object API
2293 /// object that is of the type specified in the schema using the attribute
2294 /// `cpp_type` (it is thus important whatever you write to this address
2295 /// matches that type). The value of this field is initially null, so you
2296 /// may choose to implement a delayed binding lookup using this function
2297 /// if you wish. The resolver does the opposite lookup, for when the object
2298 /// is being serialized again.
2299 typedef uint64_t hash_value_t;
2300 // clang-format off
2301 #ifdef FLATBUFFERS_CPP98_STL
2302  typedef void (*resolver_function_t)(void **pointer_adr, hash_value_t hash);
2303  typedef hash_value_t (*rehasher_function_t)(void *pointer);
2304 #else
2305  typedef std::function<void (void **pointer_adr, hash_value_t hash)>
2306  resolver_function_t;
2307  typedef std::function<hash_value_t (void *pointer)> rehasher_function_t;
2308 #endif
2309 // clang-format on
2310 
2311 // Helper function to test if a field is present, using any of the field
2312 // enums in the generated code.
2313 // `table` must be a generated table type. Since this is a template parameter,
2314 // this is not typechecked to be a subclass of Table, so beware!
2315 // Note: this function will return false for fields equal to the default
2316 // value, since they're not stored in the buffer (unless force_defaults was
2317 // used).
2318 template<typename T> bool IsFieldPresent(const T *table, voffset_t field) {
2319  // Cast, since Table is a private baseclass of any table types.
2320  return reinterpret_cast<const Table *>(table)->CheckField(field);
2321 }
2322 
2323 // Utility function for reverse lookups on the EnumNames*() functions
2324 // (in the generated C++ code)
2325 // names must be NULL terminated.
2326 inline int LookupEnum(const char **names, const char *name) {
2327  for (const char **p = names; *p; p++)
2328  if (!strcmp(*p, name)) return static_cast<int>(p - names);
2329  return -1;
2330 }
2331 
2332 // These macros allow us to layout a struct with a guarantee that they'll end
2333 // up looking the same on different compilers and platforms.
2334 // It does this by disallowing the compiler to do any padding, and then
2335 // does padding itself by inserting extra padding fields that make every
2336 // element aligned to its own size.
2337 // Additionally, it manually sets the alignment of the struct as a whole,
2338 // which is typically its largest element, or a custom size set in the schema
2339 // by the force_align attribute.
2340 // These are used in the generated code only.
2341 
2342 // clang-format off
2343 #if defined(_MSC_VER)
2344  #define FLATBUFFERS_MANUALLY_ALIGNED_STRUCT(alignment) \
2345  __pragma(pack(1)); \
2346  struct __declspec(align(alignment))
2347  #define FLATBUFFERS_STRUCT_END(name, size) \
2348  __pragma(pack()); \
2349  static_assert(sizeof(name) == size, "compiler breaks packing rules")
2350 #elif defined(__GNUC__) || defined(__clang__)
2351  #define FLATBUFFERS_MANUALLY_ALIGNED_STRUCT(alignment) \
2352  _Pragma("pack(1)") \
2353  struct __attribute__((aligned(alignment)))
2354  #define FLATBUFFERS_STRUCT_END(name, size) \
2355  _Pragma("pack()") \
2356  static_assert(sizeof(name) == size, "compiler breaks packing rules")
2357 #else
2358  #error Unknown compiler, please define structure alignment macros
2359 #endif
2360 // clang-format on
2361 
2362 // Minimal reflection via code generation.
2363 // Besides full-fat reflection (see reflection.h) and parsing/printing by
2364 // loading schemas (see idl.h), we can also have code generation for mimimal
2365 // reflection data which allows pretty-printing and other uses without needing
2366 // a schema or a parser.
2367 // Generate code with --reflect-types (types only) or --reflect-names (names
2368 // also) to enable.
2369 // See minireflect.h for utilities using this functionality.
2370 
2371 // These types are organized slightly differently as the ones in idl.h.
2372 enum SequenceType { ST_TABLE, ST_STRUCT, ST_UNION, ST_ENUM };
2373 
2374 // Scalars have the same order as in idl.h
2375 // clang-format off
2376 #define FLATBUFFERS_GEN_ELEMENTARY_TYPES(ET) \
2377  ET(ET_UTYPE) \
2378  ET(ET_BOOL) \
2379  ET(ET_CHAR) \
2380  ET(ET_UCHAR) \
2381  ET(ET_SHORT) \
2382  ET(ET_USHORT) \
2383  ET(ET_INT) \
2384  ET(ET_UINT) \
2385  ET(ET_LONG) \
2386  ET(ET_ULONG) \
2387  ET(ET_FLOAT) \
2388  ET(ET_DOUBLE) \
2389  ET(ET_STRING) \
2390  ET(ET_SEQUENCE) // See SequenceType.
2391 
2392 enum ElementaryType {
2393  #define FLATBUFFERS_ET(E) E,
2394  FLATBUFFERS_GEN_ELEMENTARY_TYPES(FLATBUFFERS_ET)
2395  #undef FLATBUFFERS_ET
2396 };
2397 
2398 inline const char * const *ElementaryTypeNames() {
2399  static const char * const names[] = {
2400  #define FLATBUFFERS_ET(E) #E,
2401  FLATBUFFERS_GEN_ELEMENTARY_TYPES(FLATBUFFERS_ET)
2402  #undef FLATBUFFERS_ET
2403  };
2404  return names;
2405 }
2406 // clang-format on
2407 
2408 // Basic type info cost just 16bits per field!
2409 struct TypeCode {
2410  uint16_t base_type : 4; // ElementaryType
2411  uint16_t is_vector : 1;
2412  int16_t sequence_ref : 11; // Index into type_refs below, or -1 for none.
2413 };
2414 
2415 static_assert(sizeof(TypeCode) == 2, "TypeCode");
2416 
2417 struct TypeTable;
2418 
2419 // Signature of the static method present in each type.
2420 typedef const TypeTable *(*TypeFunction)();
2421 
2422 struct TypeTable {
2423  SequenceType st;
2424  size_t num_elems; // of type_codes, values, names (but not type_refs).
2425  const TypeCode *type_codes; // num_elems count
2426  const TypeFunction *type_refs; // less than num_elems entries (see TypeCode).
2427  const int32_t *values; // Only set for non-consecutive enum/union or structs.
2428  const char * const *names; // Only set if compiled with --reflect-names.
2429 };
2430 
2431 // String which identifies the current version of FlatBuffers.
2432 // flatbuffer_version_string is used by Google developers to identify which
2433 // applications uploaded to Google Play are using this library. This allows
2434 // the development team at Google to determine the popularity of the library.
2435 // How it works: Applications that are uploaded to the Google Play Store are
2436 // scanned for this version string. We track which applications are using it
2437 // to measure popularity. You are free to remove it (of course) but we would
2438 // appreciate if you left it in.
2439 
2440 // Weak linkage is culled by VS & doesn't work on cygwin.
2441 // clang-format off
2442 #if !defined(_WIN32) && !defined(__CYGWIN__)
2443 
2444 extern volatile __attribute__((weak)) const char *flatbuffer_version_string;
2445 volatile __attribute__((weak)) const char *flatbuffer_version_string =
2446  "FlatBuffers "
2447  FLATBUFFERS_STRING(FLATBUFFERS_VERSION_MAJOR) "."
2448  FLATBUFFERS_STRING(FLATBUFFERS_VERSION_MINOR) "."
2449  FLATBUFFERS_STRING(FLATBUFFERS_VERSION_REVISION);
2450 
2451 #endif // !defined(_WIN32) && !defined(__CYGWIN__)
2452 
2453 #define FLATBUFFERS_DEFINE_BITMASK_OPERATORS(E, T)\
2454  inline E operator | (E lhs, E rhs){\
2455  return E(T(lhs) | T(rhs));\
2456  }\
2457  inline E operator & (E lhs, E rhs){\
2458  return E(T(lhs) & T(rhs));\
2459  }\
2460  inline E operator ^ (E lhs, E rhs){\
2461  return E(T(lhs) ^ T(rhs));\
2462  }\
2463  inline E operator ~ (E lhs){\
2464  return E(~T(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 E operator ^= (E &lhs, E rhs){\
2475  lhs = lhs ^ rhs;\
2476  return lhs;\
2477  }\
2478  inline bool operator !(E rhs) \
2479  {\
2480  return !bool(T(rhs)); \
2481  }
2482 /// @endcond
2483 } // namespace flatbuffers
2484 
2485 // clang-format on
2486 
2487 #endif // FLATBUFFERS_H_
Definition: flatbuffers.h:25
Offset< Vector< T > > CreateVector(size_t vector_size, const std::function< T(size_t i)> &f)
Serialize values returned by a function into a FlatBuffer vector.
Definition: flatbuffers.h:1394
uoffset_t CreateUninitializedVector(size_t len, size_t elemsize, uint8_t **buf)
Specialized version of CreateVector for non-copying use cases.
Definition: flatbuffers.h:1652
Offset< Vector< const T * > > CreateVectorOfStructs(size_t vector_size, const std::function< void(size_t i, T *)> &filler)
Serialize an array of structs into a FlatBuffer vector.
Definition: flatbuffers.h:1474
Offset< Vector< const T * > > CreateVectorOfSortedStructs(T *v, size_t len)
Serialize an array of structs into a FlatBuffer vector in sorted order.
Definition: flatbuffers.h:1578
Offset< Vector< const T * > > CreateVectorOfSortedNativeStructs(std::vector< S > *v)
Serialize a std::vector of native structs into a FlatBuffer vector in sorted order.
Definition: flatbuffers.h:1564
uoffset_t GetSize() const
The current size of the serialized buffer, counting from the end.
Definition: flatbuffers.h:905
Offset< Vector< Offset< T > > > CreateVectorOfSortedTables(std::vector< Offset< T >> *v)
Serialize an array of table offsets as a vector in the buffer in sorted order.
Definition: flatbuffers.h:1640
Definition: flatbuffers.h:91
Helper class to hold data needed in creation of a FlatBuffer.
Definition: flatbuffers.h:815
FlatBufferBuilder & operator=(FlatBufferBuilder &&other)
Move assignment operator for FlatBufferBuilder.
Definition: flatbuffers.h:863
Offset< String > CreateString(char *str)
Store a string in the buffer, which is null-terminated.
Definition: flatbuffers.h:1210
void Clear()
Reset all the state in this FlatBufferBuilder so it can be reused to construct another buffer...
Definition: flatbuffers.h:894
Offset< Vector< const T * > > CreateVectorOfStructs(size_t vector_size, F f, S *state)
Serialize an array of structs into a FlatBuffer vector.
Definition: flatbuffers.h:1496
Offset< Vector< const T * > > CreateVectorOfNativeStructs(const S *v, size_t len)
Serialize an array of native structs into a FlatBuffer vector.
Definition: flatbuffers.h:1455
Offset< const T * > CreateStruct(const T &structobj)
Write a struct by itself, typically to be part of a union.
Definition: flatbuffers.h:1685
Definition: flatbuffers.h:22
void FinishSizePrefixed(Offset< T > root, const char *file_identifier=nullptr)
Finish a buffer with a 32 bit size field pre-fixed (size of the buffer following the size field)...
Definition: flatbuffers.h:1711
Definition: flatbuffers.h:453
Offset< String > CreateSharedString(const char *str)
Store a string in the buffer, which null-terminated.
Definition: flatbuffers.h:1277
Definition: flatbuffers.h:305
FlatBufferBuilder(FlatBufferBuilder &&other)
Move constructor for FlatBufferBuilder.
Definition: flatbuffers.h:846
Definition: flatbuffers.h:63
Offset< String > CreateString(const char *str, size_t len)
Store a string in the buffer, which can contain any binary data.
Definition: flatbuffers.h:1191
void ForceDefaults(bool fd)
In order to save space, fields that are set to their default value don&#39;t get serialized into the buff...
Definition: flatbuffers.h:974
uint8_t * GetBufferPointer() const
Get the serialized buffer (after you call Finish()).
Definition: flatbuffers.h:910
Definition: flatbuffers.h:415
void DedupVtables(bool dedup)
By default vtables are deduped in order to save space.
Definition: flatbuffers.h:978
static const size_t kFileIdentifierLength
The length of a FlatBuffer file header.
Definition: flatbuffers.h:1693
FlatBufferBuilder(size_t initial_size=1024, Allocator *allocator=nullptr, bool own_allocator=false, size_t buffer_minalign=AlignOf< largest_scalar_t >())
Default constructor for FlatBufferBuilder.
Definition: flatbuffers.h:828
Offset< String > CreateString(const String *str)
Store a string in the buffer, which can contain any binary data.
Definition: flatbuffers.h:1235
Definition: flatbuffers.h:560
Offset< Vector< const T * > > CreateVectorOfSortedNativeStructs(S *v, size_t len)
Serialize an array of native structs into a FlatBuffer vector in sorted order.
Definition: flatbuffers.h:1593
Offset< String > CreateSharedString(const String *str)
Store a string in the buffer, which can contain any binary data.
Definition: flatbuffers.h:1295
uint8_t * GetCurrentBufferPointer() const
Get a pointer to an unfinished buffer.
Definition: flatbuffers.h:917
Offset< String > CreateString(const T &str)
Store a string in the buffer, which can contain any binary data.
Definition: flatbuffers.h:1243
Offset< Vector< const T * > > CreateVectorOfSortedStructs(std::vector< T > *v)
Serialize a std::vector of structs into a FlatBuffer vector in sorted order.
Definition: flatbuffers.h:1551
Offset< Vector< Offset< String > > > CreateVectorOfStrings(const std::vector< std::string > &v)
Serialize a std::vector<std::string> into a FlatBuffer vector.
Definition: flatbuffers.h:1425
Offset< Vector< T > > CreateVector(size_t vector_size, F f, S *state)
Serialize values returned by a function into a FlatBuffer vector.
Definition: flatbuffers.h:1413
size_t GetBufferMinAlignment()
get the minimum alignment this buffer needs to be accessed properly.
Definition: flatbuffers.h:954
Offset< Vector< const T * > > CreateVectorOfStructs(const std::vector< T, Alloc > &v)
Serialize a std::vector of structs into a FlatBuffer vector.
Definition: flatbuffers.h:1513
Offset< Vector< const T * > > CreateVectorOfStructs(const T *v, size_t len)
Serialize an array of structs into a FlatBuffer vector.
Definition: flatbuffers.h:1440
Offset< Vector< const T * > > CreateVectorOfNativeStructs(const std::vector< S > &v)
Serialize a std::vector of native structs into a FlatBuffer vector.
Definition: flatbuffers.h:1527
Offset< String > CreateString(const char *str)
Store a string in the buffer, which is null-terminated.
Definition: flatbuffers.h:1203
Definition: flatbuffers.h:374
Definition: flatbuffers.h:343
uint8_t * ReleaseRaw(size_t &size, size_t &offset)
Get the released pointer to the serialized buffer.
Definition: flatbuffers.h:944
Definition: flatbuffers.h:1738
Offset< String > CreateString(const std::string &str)
Store a string in the buffer, which can contain any binary data.
Definition: flatbuffers.h:1217
Offset< Vector< T > > CreateVector(const std::vector< T > &v)
Serialize a std::vector into a FlatBuffer vector.
Definition: flatbuffers.h:1370
Offset< Vector< T > > CreateUninitializedVector(size_t len, T **buf)
Specialized version of CreateVector for non-copying use cases.
Definition: flatbuffers.h:1672
Offset< String > CreateString(flatbuffers::string_view str)
Store a string in the buffer, which can contain any binary data.
Definition: flatbuffers.h:1226
Offset< Vector< T > > CreateVector(const T *v, size_t len)
Serialize an array into a FlatBuffer vector.
Definition: flatbuffers.h:1336
Offset< String > CreateSharedString(const std::string &str)
Store a string in the buffer, which can contain any binary data.
Definition: flatbuffers.h:1286
Offset< Vector< Offset< T > > > CreateVectorOfSortedTables(Offset< T > *v, size_t len)
Serialize an array of table offsets as a vector in the buffer in sorted order.
Definition: flatbuffers.h:1626
DetachedBuffer Release()
Get the released DetachedBuffer.
Definition: flatbuffers.h:931
Offset< String > CreateSharedString(const char *str, size_t len)
Store a string in the buffer, which can contain any binary data.
Definition: flatbuffers.h:1253
Definition: flatbuffers.h:182
DetachedBuffer ReleaseBufferPointer()
Get the released pointer to the serialized buffer.
Definition: flatbuffers.h:924
void Finish(Offset< T > root, const char *file_identifier=nullptr)
Finish serializing a buffer by writing the root offset.
Definition: flatbuffers.h:1699