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