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