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