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