FlatBuffers
An open source project by FPL.
 All Classes Namespaces Files Functions Variables Properties Groups Pages
flatbuffers.h
Go to the documentation of this file.
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 <assert.h>
21 
22 #include <cstdint>
23 #include <cstddef>
24 #include <cstdlib>
25 #include <cstring>
26 #include <string>
27 #include <utility>
28 #include <type_traits>
29 #include <vector>
30 #include <set>
31 #include <algorithm>
32 #include <memory>
33 
34 #ifdef _STLPORT_VERSION
35  #define FLATBUFFERS_CPP98_STL
36 #endif
37 #ifndef FLATBUFFERS_CPP98_STL
38  #include <functional>
39 #endif
40 
41 /// @cond FLATBUFFERS_INTERNAL
42 #if __cplusplus <= 199711L && \
43  (!defined(_MSC_VER) || _MSC_VER < 1600) && \
44  (!defined(__GNUC__) || \
45  (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__ < 40400))
46  #error A C++11 compatible compiler with support for the auto typing is \
47  required for FlatBuffers.
48  #error __cplusplus _MSC_VER __GNUC__ __GNUC_MINOR__ __GNUC_PATCHLEVEL__
49 #endif
50 
51 #if !defined(__clang__) && \
52  defined(__GNUC__) && \
53  (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__ < 40600)
54  // Backwards compatability for g++ 4.4, and 4.5 which don't have the nullptr
55  // and constexpr keywords. Note the __clang__ check is needed, because clang
56  // presents itself as an older GNUC compiler.
57  #ifndef nullptr_t
58  const class nullptr_t {
59  public:
60  template<class T> inline operator T*() const { return 0; }
61  private:
62  void operator&() const;
63  } nullptr = {};
64  #endif
65  #ifndef constexpr
66  #define constexpr const
67  #endif
68 #endif
69 
70 // The wire format uses a little endian encoding (since that's efficient for
71 // the common platforms).
72 #if !defined(FLATBUFFERS_LITTLEENDIAN)
73  #if defined(__GNUC__) || defined(__clang__)
74  #ifdef __BIG_ENDIAN__
75  #define FLATBUFFERS_LITTLEENDIAN 0
76  #else
77  #define FLATBUFFERS_LITTLEENDIAN 1
78  #endif // __BIG_ENDIAN__
79  #elif defined(_MSC_VER)
80  #if defined(_M_PPC)
81  #define FLATBUFFERS_LITTLEENDIAN 0
82  #else
83  #define FLATBUFFERS_LITTLEENDIAN 1
84  #endif
85  #else
86  #error Unable to determine endianness, define FLATBUFFERS_LITTLEENDIAN.
87  #endif
88 #endif // !defined(FLATBUFFERS_LITTLEENDIAN)
89 
90 #define FLATBUFFERS_VERSION_MAJOR 1
91 #define FLATBUFFERS_VERSION_MINOR 5
92 #define FLATBUFFERS_VERSION_REVISION 0
93 #define FLATBUFFERS_STRING_EXPAND(X) #X
94 #define FLATBUFFERS_STRING(X) FLATBUFFERS_STRING_EXPAND(X)
95 
96 #if (!defined(_MSC_VER) || _MSC_VER > 1600) && \
97  (!defined(__GNUC__) || (__GNUC__ * 100 + __GNUC_MINOR__ >= 407))
98  #define FLATBUFFERS_FINAL_CLASS final
99 #else
100  #define FLATBUFFERS_FINAL_CLASS
101 #endif
102 
103 #if (!defined(_MSC_VER) || _MSC_VER >= 1900) && \
104  (!defined(__GNUC__) || (__GNUC__ * 100 + __GNUC_MINOR__ >= 406))
105  #define FLATBUFFERS_CONSTEXPR constexpr
106 #else
107  #define FLATBUFFERS_CONSTEXPR
108 #endif
109 
110 /// @endcond
111 
112 /// @file
113 namespace flatbuffers {
114 
115 /// @cond FLATBUFFERS_INTERNAL
116 // Our default offset / size type, 32bit on purpose on 64bit systems.
117 // Also, using a consistent offset type maintains compatibility of serialized
118 // offset values between 32bit and 64bit systems.
119 typedef uint32_t uoffset_t;
120 
121 // Signed offsets for references that can go in both directions.
122 typedef int32_t soffset_t;
123 
124 // Offset/index used in v-tables, can be changed to uint8_t in
125 // format forks to save a bit of space if desired.
126 typedef uint16_t voffset_t;
127 
128 typedef uintmax_t largest_scalar_t;
129 
130 // In 32bits, this evaluates to 2GB - 1
131 #define FLATBUFFERS_MAX_BUFFER_SIZE ((1ULL << (sizeof(soffset_t) * 8 - 1)) - 1)
132 
133 // We support aligning the contents of buffers up to this size.
134 #define FLATBUFFERS_MAX_ALIGNMENT 16
135 
136 #ifndef FLATBUFFERS_CPP98_STL
137 // Pointer to relinquished memory.
138 typedef std::unique_ptr<uint8_t, std::function<void(uint8_t * /* unused */)>>
139  unique_ptr_t;
140 #endif
141 
142 // Wrapper for uoffset_t to allow safe template specialization.
143 template<typename T> struct Offset {
144  uoffset_t o;
145  Offset() : o(0) {}
146  Offset(uoffset_t _o) : o(_o) {}
147  Offset<void> Union() const { return Offset<void>(o); }
148 };
149 
150 inline void EndianCheck() {
151  int endiantest = 1;
152  // If this fails, see FLATBUFFERS_LITTLEENDIAN above.
153  assert(*reinterpret_cast<char *>(&endiantest) == FLATBUFFERS_LITTLEENDIAN);
154  (void)endiantest;
155 }
156 
157 template<typename T> T EndianSwap(T t) {
158  #if defined(_MSC_VER)
159  #define FLATBUFFERS_BYTESWAP16 _byteswap_ushort
160  #define FLATBUFFERS_BYTESWAP32 _byteswap_ulong
161  #define FLATBUFFERS_BYTESWAP64 _byteswap_uint64
162  #else
163  #if defined(__GNUC__) && __GNUC__ * 100 + __GNUC_MINOR__ < 408
164  // __builtin_bswap16 was missing prior to GCC 4.8.
165  #define FLATBUFFERS_BYTESWAP16(x) \
166  static_cast<uint16_t>(__builtin_bswap32(static_cast<uint32_t>(x) << 16))
167  #else
168  #define FLATBUFFERS_BYTESWAP16 __builtin_bswap16
169  #endif
170  #define FLATBUFFERS_BYTESWAP32 __builtin_bswap32
171  #define FLATBUFFERS_BYTESWAP64 __builtin_bswap64
172  #endif
173  if (sizeof(T) == 1) { // Compile-time if-then's.
174  return t;
175  } else if (sizeof(T) == 2) {
176  auto r = FLATBUFFERS_BYTESWAP16(*reinterpret_cast<uint16_t *>(&t));
177  return *reinterpret_cast<T *>(&r);
178  } else if (sizeof(T) == 4) {
179  auto r = FLATBUFFERS_BYTESWAP32(*reinterpret_cast<uint32_t *>(&t));
180  return *reinterpret_cast<T *>(&r);
181  } else if (sizeof(T) == 8) {
182  auto r = FLATBUFFERS_BYTESWAP64(*reinterpret_cast<uint64_t *>(&t));
183  return *reinterpret_cast<T *>(&r);
184  } else {
185  assert(0);
186  }
187 }
188 
189 template<typename T> T EndianScalar(T t) {
190  #if FLATBUFFERS_LITTLEENDIAN
191  return t;
192  #else
193  return EndianSwap(t);
194  #endif
195 }
196 
197 template<typename T> T ReadScalar(const void *p) {
198  return EndianScalar(*reinterpret_cast<const T *>(p));
199 }
200 
201 template<typename T> void WriteScalar(void *p, T t) {
202  *reinterpret_cast<T *>(p) = EndianScalar(t);
203 }
204 
205 template<typename T> size_t AlignOf() {
206  #ifdef _MSC_VER
207  return __alignof(T);
208  #else
209  #ifndef alignof
210  return __alignof__(T);
211  #else
212  return alignof(T);
213  #endif
214  #endif
215 }
216 
217 // When we read serialized data from memory, in the case of most scalars,
218 // we want to just read T, but in the case of Offset, we want to actually
219 // perform the indirection and return a pointer.
220 // The template specialization below does just that.
221 // It is wrapped in a struct since function templates can't overload on the
222 // return type like this.
223 // The typedef is for the convenience of callers of this function
224 // (avoiding the need for a trailing return decltype)
225 template<typename T> struct IndirectHelper {
226  typedef T return_type;
227  typedef T mutable_return_type;
228  static const size_t element_stride = sizeof(T);
229  static return_type Read(const uint8_t *p, uoffset_t i) {
230  return EndianScalar((reinterpret_cast<const T *>(p))[i]);
231  }
232 };
233 template<typename T> struct IndirectHelper<Offset<T>> {
234  typedef const T *return_type;
235  typedef T *mutable_return_type;
236  static const size_t element_stride = sizeof(uoffset_t);
237  static return_type Read(const uint8_t *p, uoffset_t i) {
238  p += i * sizeof(uoffset_t);
239  return reinterpret_cast<return_type>(p + ReadScalar<uoffset_t>(p));
240  }
241 };
242 template<typename T> struct IndirectHelper<const T *> {
243  typedef const T *return_type;
244  typedef T *mutable_return_type;
245  static const size_t element_stride = sizeof(T);
246  static return_type Read(const uint8_t *p, uoffset_t i) {
247  return reinterpret_cast<const T *>(p + i * sizeof(T));
248  }
249 };
250 
251 // An STL compatible iterator implementation for Vector below, effectively
252 // calling Get() for every element.
253 template<typename T, typename IT>
254 struct VectorIterator
255  : public std::iterator<std::random_access_iterator_tag, IT, uoffset_t> {
256 
257  typedef std::iterator<std::random_access_iterator_tag, IT, uoffset_t> super_type;
258 
259 public:
260  VectorIterator(const uint8_t *data, uoffset_t i) :
261  data_(data + IndirectHelper<T>::element_stride * i) {}
262  VectorIterator(const VectorIterator &other) : data_(other.data_) {}
263  #ifndef FLATBUFFERS_CPP98_STL
264  VectorIterator(VectorIterator &&other) : data_(std::move(other.data_)) {}
265  #endif
266 
267  VectorIterator &operator=(const VectorIterator &other) {
268  data_ = other.data_;
269  return *this;
270  }
271 
272  VectorIterator &operator=(VectorIterator &&other) {
273  data_ = other.data_;
274  return *this;
275  }
276 
277  bool operator==(const VectorIterator &other) const {
278  return data_ == other.data_;
279  }
280 
281  bool operator!=(const VectorIterator &other) const {
282  return data_ != other.data_;
283  }
284 
285  ptrdiff_t operator-(const VectorIterator &other) const {
286  return (data_ - other.data_) / IndirectHelper<T>::element_stride;
287  }
288 
289  typename super_type::value_type operator *() const {
290  return IndirectHelper<T>::Read(data_, 0);
291  }
292 
293  typename super_type::value_type operator->() const {
294  return IndirectHelper<T>::Read(data_, 0);
295  }
296 
297  VectorIterator &operator++() {
298  data_ += IndirectHelper<T>::element_stride;
299  return *this;
300  }
301 
302  VectorIterator operator++(int) {
303  VectorIterator temp(data_, 0);
304  data_ += IndirectHelper<T>::element_stride;
305  return temp;
306  }
307 
308  VectorIterator operator+(const uoffset_t &offset) {
309  return VectorIterator(data_ + offset * IndirectHelper<T>::element_stride, 0);
310  }
311 
312  VectorIterator& operator+=(const uoffset_t &offset) {
313  data_ += offset * IndirectHelper<T>::element_stride;
314  return *this;
315  }
316 
317  VectorIterator &operator--() {
318  data_ -= IndirectHelper<T>::element_stride;
319  return *this;
320  }
321 
322  VectorIterator operator--(int) {
323  VectorIterator temp(data_, 0);
324  data_ -= IndirectHelper<T>::element_stride;
325  return temp;
326  }
327 
328  VectorIterator operator-(const uoffset_t &offset) {
329  return VectorIterator(data_ - offset * IndirectHelper<T>::element_stride, 0);
330  }
331 
332  VectorIterator& operator-=(const uoffset_t &offset) {
333  data_ -= offset * IndirectHelper<T>::element_stride;
334  return *this;
335  }
336 
337 private:
338  const uint8_t *data_;
339 };
340 
341 // This is used as a helper type for accessing vectors.
342 // Vector::data() assumes the vector elements start after the length field.
343 template<typename T> class Vector {
344 public:
345  typedef VectorIterator<T, typename IndirectHelper<T>::mutable_return_type>
346  iterator;
347  typedef VectorIterator<T, typename IndirectHelper<T>::return_type>
348  const_iterator;
349 
350  uoffset_t size() const { return EndianScalar(length_); }
351 
352  // Deprecated: use size(). Here for backwards compatibility.
353  uoffset_t Length() const { return size(); }
354 
355  typedef typename IndirectHelper<T>::return_type return_type;
356  typedef typename IndirectHelper<T>::mutable_return_type mutable_return_type;
357 
358  return_type Get(uoffset_t i) const {
359  assert(i < size());
360  return IndirectHelper<T>::Read(Data(), i);
361  }
362 
363  return_type operator[](uoffset_t i) const { return Get(i); }
364 
365  // If this is a Vector of enums, T will be its storage type, not the enum
366  // type. This function makes it convenient to retrieve value with enum
367  // type E.
368  template<typename E> E GetEnum(uoffset_t i) const {
369  return static_cast<E>(Get(i));
370  }
371 
372  const void *GetStructFromOffset(size_t o) const {
373  return reinterpret_cast<const void *>(Data() + o);
374  }
375 
376  iterator begin() { return iterator(Data(), 0); }
377  const_iterator begin() const { return const_iterator(Data(), 0); }
378 
379  iterator end() { return iterator(Data(), size()); }
380  const_iterator end() const { return const_iterator(Data(), size()); }
381 
382  // Change elements if you have a non-const pointer to this object.
383  // Scalars only. See reflection.h, and the documentation.
384  void Mutate(uoffset_t i, const T& val) {
385  assert(i < size());
386  WriteScalar(data() + i, val);
387  }
388 
389  // Change an element of a vector of tables (or strings).
390  // "val" points to the new table/string, as you can obtain from
391  // e.g. reflection::AddFlatBuffer().
392  void MutateOffset(uoffset_t i, const uint8_t *val) {
393  assert(i < size());
394  assert(sizeof(T) == sizeof(uoffset_t));
395  WriteScalar(data() + i,
396  static_cast<uoffset_t>(val - (Data() + i * sizeof(uoffset_t))));
397  }
398 
399  // Get a mutable pointer to tables/strings inside this vector.
400  mutable_return_type GetMutableObject(uoffset_t i) const {
401  assert(i < size());
402  return const_cast<mutable_return_type>(IndirectHelper<T>::Read(Data(), i));
403  }
404 
405  // The raw data in little endian format. Use with care.
406  const uint8_t *Data() const {
407  return reinterpret_cast<const uint8_t *>(&length_ + 1);
408  }
409 
410  uint8_t *Data() {
411  return reinterpret_cast<uint8_t *>(&length_ + 1);
412  }
413 
414  // Similarly, but typed, much like std::vector::data
415  const T *data() const { return reinterpret_cast<const T *>(Data()); }
416  T *data() { return reinterpret_cast<T *>(Data()); }
417 
418  template<typename K> return_type LookupByKey(K key) const {
419  void *search_result = std::bsearch(&key, Data(), size(),
420  IndirectHelper<T>::element_stride, KeyCompare<K>);
421 
422  if (!search_result) {
423  return nullptr; // Key not found.
424  }
425 
426  const uint8_t *element = reinterpret_cast<const uint8_t *>(search_result);
427 
428  return IndirectHelper<T>::Read(element, 0);
429  }
430 
431 protected:
432  // This class is only used to access pre-existing data. Don't ever
433  // try to construct these manually.
434  Vector();
435 
436  uoffset_t length_;
437 
438 private:
439  template<typename K> static int KeyCompare(const void *ap, const void *bp) {
440  const K *key = reinterpret_cast<const K *>(ap);
441  const uint8_t *data = reinterpret_cast<const uint8_t *>(bp);
442  auto table = IndirectHelper<T>::Read(data, 0);
443 
444  // std::bsearch compares with the operands transposed, so we negate the
445  // result here.
446  return -table->KeyCompareWithValue(*key);
447  }
448 };
449 
450 // Represent a vector much like the template above, but in this case we
451 // don't know what the element types are (used with reflection.h).
452 class VectorOfAny {
453 public:
454  uoffset_t size() const { return EndianScalar(length_); }
455 
456  const uint8_t *Data() const {
457  return reinterpret_cast<const uint8_t *>(&length_ + 1);
458  }
459  uint8_t *Data() {
460  return reinterpret_cast<uint8_t *>(&length_ + 1);
461  }
462 protected:
463  VectorOfAny();
464 
465  uoffset_t length_;
466 };
467 
468 // Convenient helper function to get the length of any vector, regardless
469 // of wether it is null or not (the field is not set).
470 template<typename T> static inline size_t VectorLength(const Vector<T> *v) {
471  return v ? v->Length() : 0;
472 }
473 
474 struct String : public Vector<char> {
475  const char *c_str() const { return reinterpret_cast<const char *>(Data()); }
476  std::string str() const { return std::string(c_str(), Length()); }
477 
478  bool operator <(const String &o) const {
479  return strcmp(c_str(), o.c_str()) < 0;
480  }
481 };
482 
483 // Simple indirection for buffer allocation, to allow this to be overridden
484 // with custom allocation (see the FlatBufferBuilder constructor).
485 class simple_allocator {
486  public:
487  virtual ~simple_allocator() {}
488  virtual uint8_t *allocate(size_t size) const { return new uint8_t[size]; }
489  virtual void deallocate(uint8_t *p) const { delete[] p; }
490 };
491 
492 // This is a minimal replication of std::vector<uint8_t> functionality,
493 // except growing from higher to lower addresses. i.e push_back() inserts data
494 // in the lowest address in the vector.
495 class vector_downward {
496  public:
497  explicit vector_downward(size_t initial_size,
498  const simple_allocator &allocator)
499  : reserved_(initial_size),
500  buf_(allocator.allocate(reserved_)),
501  cur_(buf_ + reserved_),
502  allocator_(allocator) {
503  assert((initial_size & (sizeof(largest_scalar_t) - 1)) == 0);
504  }
505 
506  ~vector_downward() {
507  if (buf_)
508  allocator_.deallocate(buf_);
509  }
510 
511  void clear() {
512  if (buf_ == nullptr)
513  buf_ = allocator_.allocate(reserved_);
514 
515  cur_ = buf_ + reserved_;
516  }
517 
518  #ifndef FLATBUFFERS_CPP98_STL
519  // Relinquish the pointer to the caller.
520  unique_ptr_t release() {
521  // Actually deallocate from the start of the allocated memory.
522  std::function<void(uint8_t *)> deleter(
523  std::bind(&simple_allocator::deallocate, allocator_, buf_));
524 
525  // Point to the desired offset.
526  unique_ptr_t retval(data(), deleter);
527 
528  // Don't deallocate when this instance is destroyed.
529  buf_ = nullptr;
530  cur_ = nullptr;
531 
532  return retval;
533  }
534  #endif
535 
536  size_t growth_policy(size_t bytes) {
537  return (bytes / 2) & ~(sizeof(largest_scalar_t) - 1);
538  }
539 
540  uint8_t *make_space(size_t len) {
541  if (len > static_cast<size_t>(cur_ - buf_)) {
542  auto old_size = size();
543  auto largest_align = AlignOf<largest_scalar_t>();
544  reserved_ += (std::max)(len, growth_policy(reserved_));
545  // Round up to avoid undefined behavior from unaligned loads and stores.
546  reserved_ = (reserved_ + (largest_align - 1)) & ~(largest_align - 1);
547  auto new_buf = allocator_.allocate(reserved_);
548  auto new_cur = new_buf + reserved_ - old_size;
549  memcpy(new_cur, cur_, old_size);
550  cur_ = new_cur;
551  allocator_.deallocate(buf_);
552  buf_ = new_buf;
553  }
554  cur_ -= len;
555  // Beyond this, signed offsets may not have enough range:
556  // (FlatBuffers > 2GB not supported).
557  assert(size() < FLATBUFFERS_MAX_BUFFER_SIZE);
558  return cur_;
559  }
560 
561  uoffset_t size() const {
562  assert(cur_ != nullptr && buf_ != nullptr);
563  return static_cast<uoffset_t>(reserved_ - (cur_ - buf_));
564  }
565 
566  uint8_t *data() const {
567  assert(cur_ != nullptr);
568  return cur_;
569  }
570 
571  uint8_t *data_at(size_t offset) const { return buf_ + reserved_ - offset; }
572 
573  // push() & fill() are most frequently called with small byte counts (<= 4),
574  // which is why we're using loops rather than calling memcpy/memset.
575  void push(const uint8_t *bytes, size_t num) {
576  auto dest = make_space(num);
577  for (size_t i = 0; i < num; i++) dest[i] = bytes[i];
578  }
579 
580  void fill(size_t zero_pad_bytes) {
581  auto dest = make_space(zero_pad_bytes);
582  for (size_t i = 0; i < zero_pad_bytes; i++) dest[i] = 0;
583  }
584 
585  void pop(size_t bytes_to_remove) { cur_ += bytes_to_remove; }
586 
587  private:
588  // You shouldn't really be copying instances of this class.
589  vector_downward(const vector_downward &);
590  vector_downward &operator=(const vector_downward &);
591 
592  size_t reserved_;
593  uint8_t *buf_;
594  uint8_t *cur_; // Points at location between empty (below) and used (above).
595  const simple_allocator &allocator_;
596 };
597 
598 // Converts a Field ID to a virtual table offset.
599 inline voffset_t FieldIndexToOffset(voffset_t field_id) {
600  // Should correspond to what EndTable() below builds up.
601  const int fixed_fields = 2; // Vtable size and Object Size.
602  return static_cast<voffset_t>((field_id + fixed_fields) * sizeof(voffset_t));
603 }
604 
605 // Computes how many bytes you'd have to pad to be able to write an
606 // "scalar_size" scalar if the buffer had grown to "buf_size" (downwards in
607 // memory).
608 inline size_t PaddingBytes(size_t buf_size, size_t scalar_size) {
609  return ((~buf_size) + 1) & (scalar_size - 1);
610 }
611 
612 template <typename T> const T* data(const std::vector<T> &v) {
613  return v.empty() ? nullptr : &v.front();
614 }
615 template <typename T> T* data(std::vector<T> &v) {
616  return v.empty() ? nullptr : &v.front();
617 }
618 
619 /// @endcond
620 
621 /// @addtogroup flatbuffers_cpp_api
622 /// @{
623 /// @class FlatBufferBuilder
624 /// @brief Helper class to hold data needed in creation of a FlatBuffer.
625 /// To serialize data, you typically call one of the `Create*()` functions in
626 /// the generated code, which in turn call a sequence of `StartTable`/
627 /// `PushElement`/`AddElement`/`EndTable`, or the builtin `CreateString`/
628 /// `CreateVector` functions. Do this is depth-first order to build up a tree to
629 /// the root. `Finish()` wraps up the buffer ready for transport.
631 /// @cond FLATBUFFERS_INTERNAL
632 FLATBUFFERS_FINAL_CLASS
633 /// @endcond
634 {
635  public:
636  /// @brief Default constructor for FlatBufferBuilder.
637  /// @param[in] initial_size The initial size of the buffer, in bytes. Defaults
638  /// to`1024`.
639  /// @param[in] allocator A pointer to the `simple_allocator` that should be
640  /// used. Defaults to `nullptr`, which means the `default_allocator` will be
641  /// be used.
642  explicit FlatBufferBuilder(uoffset_t initial_size = 1024,
643  const simple_allocator *allocator = nullptr)
644  : buf_(initial_size, allocator ? *allocator : default_allocator),
645  nested(false), finished(false), minalign_(1), force_defaults_(false),
646  string_pool(nullptr) {
647  offsetbuf_.reserve(16); // Avoid first few reallocs.
648  vtables_.reserve(16);
649  EndianCheck();
650  }
651 
652  ~FlatBufferBuilder() {
653  if (string_pool) delete string_pool;
654  }
655 
656  /// @brief Reset all the state in this FlatBufferBuilder so it can be reused
657  /// to construct another buffer.
658  void Clear() {
659  buf_.clear();
660  offsetbuf_.clear();
661  nested = false;
662  finished = false;
663  vtables_.clear();
664  minalign_ = 1;
665  if (string_pool) string_pool->clear();
666  }
667 
668  /// @brief The current size of the serialized buffer, counting from the end.
669  /// @return Returns an `uoffset_t` with the current size of the buffer.
670  uoffset_t GetSize() const { return buf_.size(); }
671 
672  /// @brief Get the serialized buffer (after you call `Finish()`).
673  /// @return Returns an `uint8_t` pointer to the FlatBuffer data inside the
674  /// buffer.
675  uint8_t *GetBufferPointer() const {
676  Finished();
677  return buf_.data();
678  }
679 
680  /// @brief Get a pointer to an unfinished buffer.
681  /// @return Returns a `uint8_t` pointer to the unfinished buffer.
682  uint8_t *GetCurrentBufferPointer() const { return buf_.data(); }
683 
684  #ifndef FLATBUFFERS_CPP98_STL
685  /// @brief Get the released pointer to the serialized buffer.
686  /// @warning Do NOT attempt to use this FlatBufferBuilder afterwards!
687  /// @return The `unique_ptr` returned has a special allocator that knows how
688  /// to deallocate this pointer (since it points to the middle of an
689  /// allocation). Thus, do not mix this pointer with other `unique_ptr`'s, or
690  /// call `release()`/`reset()` on it.
691  unique_ptr_t ReleaseBufferPointer() {
692  Finished();
693  return buf_.release();
694  }
695  #endif
696 
697  /// @brief get the minimum alignment this buffer needs to be accessed
698  /// properly. This is only known once all elements have been written (after
699  /// you call Finish()). You can use this information if you need to embed
700  /// a FlatBuffer in some other buffer, such that you can later read it
701  /// without first having to copy it into its own buffer.
703  Finished();
704  return minalign_;
705  }
706 
707  /// @cond FLATBUFFERS_INTERNAL
708  void Finished() const {
709  // If you get this assert, you're attempting to get access a buffer
710  // which hasn't been finished yet. Be sure to call
711  // FlatBufferBuilder::Finish with your root table.
712  // If you really need to access an unfinished buffer, call
713  // GetCurrentBufferPointer instead.
714  assert(finished);
715  }
716  /// @endcond
717 
718  /// @brief In order to save space, fields that are set to their default value
719  /// don't get serialized into the buffer.
720  /// @param[in] bool fd When set to `true`, always serializes default values.
721  void ForceDefaults(bool fd) { force_defaults_ = fd; }
722 
723  /// @cond FLATBUFFERS_INTERNAL
724  void Pad(size_t num_bytes) { buf_.fill(num_bytes); }
725 
726  void Align(size_t elem_size) {
727  if (elem_size > minalign_) minalign_ = elem_size;
728  buf_.fill(PaddingBytes(buf_.size(), elem_size));
729  }
730 
731  void PushFlatBuffer(const uint8_t *bytes, size_t size) {
732  PushBytes(bytes, size);
733  finished = true;
734  }
735 
736  void PushBytes(const uint8_t *bytes, size_t size) {
737  buf_.push(bytes, size);
738  }
739 
740  void PopBytes(size_t amount) { buf_.pop(amount); }
741 
742  template<typename T> void AssertScalarT() {
743  #ifndef FLATBUFFERS_CPP98_STL
744  // The code assumes power of 2 sizes and endian-swap-ability.
745  static_assert(std::is_scalar<T>::value
746  // The Offset<T> type is essentially a scalar but fails is_scalar.
747  || sizeof(T) == sizeof(Offset<void>),
748  "T must be a scalar type");
749  #endif
750  }
751 
752  // Write a single aligned scalar to the buffer
753  template<typename T> uoffset_t PushElement(T element) {
754  AssertScalarT<T>();
755  T litle_endian_element = EndianScalar(element);
756  Align(sizeof(T));
757  PushBytes(reinterpret_cast<uint8_t *>(&litle_endian_element), sizeof(T));
758  return GetSize();
759  }
760 
761  template<typename T> uoffset_t PushElement(Offset<T> off) {
762  // Special case for offsets: see ReferTo below.
763  return PushElement(ReferTo(off.o));
764  }
765 
766  // When writing fields, we track where they are, so we can create correct
767  // vtables later.
768  void TrackField(voffset_t field, uoffset_t off) {
769  FieldLoc fl = { off, field };
770  offsetbuf_.push_back(fl);
771  }
772 
773  // Like PushElement, but additionally tracks the field this represents.
774  template<typename T> void AddElement(voffset_t field, T e, T def) {
775  // We don't serialize values equal to the default.
776  if (e == def && !force_defaults_) return;
777  auto off = PushElement(e);
778  TrackField(field, off);
779  }
780 
781  template<typename T> void AddOffset(voffset_t field, Offset<T> off) {
782  if (!off.o) return; // An offset of 0 means NULL, don't store.
783  AddElement(field, ReferTo(off.o), static_cast<uoffset_t>(0));
784  }
785 
786  template<typename T> void AddStruct(voffset_t field, const T *structptr) {
787  if (!structptr) return; // Default, don't store.
788  Align(AlignOf<T>());
789  PushBytes(reinterpret_cast<const uint8_t *>(structptr), sizeof(T));
790  TrackField(field, GetSize());
791  }
792 
793  void AddStructOffset(voffset_t field, uoffset_t off) {
794  TrackField(field, off);
795  }
796 
797  // Offsets initially are relative to the end of the buffer (downwards).
798  // This function converts them to be relative to the current location
799  // in the buffer (when stored here), pointing upwards.
800  uoffset_t ReferTo(uoffset_t off) {
801  // Align to ensure GetSize() below is correct.
802  Align(sizeof(uoffset_t));
803  // Offset must refer to something already in buffer.
804  assert(off && off <= GetSize());
805  return GetSize() - off + static_cast<uoffset_t>(sizeof(uoffset_t));
806  }
807 
808  void NotNested() {
809  // If you hit this, you're trying to construct a Table/Vector/String
810  // during the construction of its parent table (between the MyTableBuilder
811  // and table.Finish().
812  // Move the creation of these sub-objects to above the MyTableBuilder to
813  // not get this assert.
814  // Ignoring this assert may appear to work in simple cases, but the reason
815  // it is here is that storing objects in-line may cause vtable offsets
816  // to not fit anymore. It also leads to vtable duplication.
817  assert(!nested);
818  }
819 
820  // From generated code (or from the parser), we call StartTable/EndTable
821  // with a sequence of AddElement calls in between.
822  uoffset_t StartTable() {
823  NotNested();
824  nested = true;
825  return GetSize();
826  }
827 
828  // This finishes one serialized object by generating the vtable if it's a
829  // table, comparing it against existing vtables, and writing the
830  // resulting vtable offset.
831  uoffset_t EndTable(uoffset_t start, voffset_t numfields) {
832  // If you get this assert, a corresponding StartTable wasn't called.
833  assert(nested);
834  // Write the vtable offset, which is the start of any Table.
835  // We fill it's value later.
836  auto vtableoffsetloc = PushElement<soffset_t>(0);
837  // Write a vtable, which consists entirely of voffset_t elements.
838  // It starts with the number of offsets, followed by a type id, followed
839  // by the offsets themselves. In reverse:
840  buf_.fill(numfields * sizeof(voffset_t));
841  auto table_object_size = vtableoffsetloc - start;
842  assert(table_object_size < 0x10000); // Vtable use 16bit offsets.
843  PushElement<voffset_t>(static_cast<voffset_t>(table_object_size));
844  PushElement<voffset_t>(FieldIndexToOffset(numfields));
845  // Write the offsets into the table
846  for (auto field_location = offsetbuf_.begin();
847  field_location != offsetbuf_.end();
848  ++field_location) {
849  auto pos = static_cast<voffset_t>(vtableoffsetloc - field_location->off);
850  // If this asserts, it means you've set a field twice.
851  assert(!ReadScalar<voffset_t>(buf_.data() + field_location->id));
852  WriteScalar<voffset_t>(buf_.data() + field_location->id, pos);
853  }
854  offsetbuf_.clear();
855  auto vt1 = reinterpret_cast<voffset_t *>(buf_.data());
856  auto vt1_size = ReadScalar<voffset_t>(vt1);
857  auto vt_use = GetSize();
858  // See if we already have generated a vtable with this exact same
859  // layout before. If so, make it point to the old one, remove this one.
860  for (auto it = vtables_.begin(); it != vtables_.end(); ++it) {
861  auto vt2 = reinterpret_cast<voffset_t *>(buf_.data_at(*it));
862  auto vt2_size = *vt2;
863  if (vt1_size != vt2_size || memcmp(vt2, vt1, vt1_size)) continue;
864  vt_use = *it;
865  buf_.pop(GetSize() - vtableoffsetloc);
866  break;
867  }
868  // If this is a new vtable, remember it.
869  if (vt_use == GetSize()) {
870  vtables_.push_back(vt_use);
871  }
872  // Fill the vtable offset we created above.
873  // The offset points from the beginning of the object to where the
874  // vtable is stored.
875  // Offsets default direction is downward in memory for future format
876  // flexibility (storing all vtables at the start of the file).
877  WriteScalar(buf_.data_at(vtableoffsetloc),
878  static_cast<soffset_t>(vt_use) -
879  static_cast<soffset_t>(vtableoffsetloc));
880 
881  nested = false;
882  return vtableoffsetloc;
883  }
884 
885  // This checks a required field has been set in a given table that has
886  // just been constructed.
887  template<typename T> void Required(Offset<T> table, voffset_t field) {
888  auto table_ptr = buf_.data_at(table.o);
889  auto vtable_ptr = table_ptr - ReadScalar<soffset_t>(table_ptr);
890  bool ok = ReadScalar<voffset_t>(vtable_ptr + field) != 0;
891  // If this fails, the caller will show what field needs to be set.
892  assert(ok);
893  (void)ok;
894  }
895 
896  uoffset_t StartStruct(size_t alignment) {
897  Align(alignment);
898  return GetSize();
899  }
900 
901  uoffset_t EndStruct() { return GetSize(); }
902 
903  void ClearOffsets() { offsetbuf_.clear(); }
904 
905  // Aligns such that when "len" bytes are written, an object can be written
906  // after it with "alignment" without padding.
907  void PreAlign(size_t len, size_t alignment) {
908  buf_.fill(PaddingBytes(GetSize() + len, alignment));
909  }
910  template<typename T> void PreAlign(size_t len) {
911  AssertScalarT<T>();
912  PreAlign(len, sizeof(T));
913  }
914  /// @endcond
915 
916  /// @brief Store a string in the buffer, which can contain any binary data.
917  /// @param[in] str A const char pointer to the data to be stored as a string.
918  /// @param[in] len The number of bytes that should be stored from `str`.
919  /// @return Returns the offset in the buffer where the string starts.
920  Offset<String> CreateString(const char *str, size_t len) {
921  NotNested();
922  PreAlign<uoffset_t>(len + 1); // Always 0-terminated.
923  buf_.fill(1);
924  PushBytes(reinterpret_cast<const uint8_t *>(str), len);
925  PushElement(static_cast<uoffset_t>(len));
926  return Offset<String>(GetSize());
927  }
928 
929  /// @brief Store a string in the buffer, which is null-terminated.
930  /// @param[in] str A const char pointer to a C-string to add to the buffer.
931  /// @return Returns the offset in the buffer where the string starts.
932  Offset<String> CreateString(const char *str) {
933  return CreateString(str, strlen(str));
934  }
935 
936  /// @brief Store a string in the buffer, which can contain any binary data.
937  /// @param[in] str A const reference to a std::string to store in the buffer.
938  /// @return Returns the offset in the buffer where the string starts.
939  Offset<String> CreateString(const std::string &str) {
940  return CreateString(str.c_str(), str.length());
941  }
942 
943  /// @brief Store a string in the buffer, which can contain any binary data.
944  /// @param[in] str A const pointer to a `String` struct to add to the buffer.
945  /// @return Returns the offset in the buffer where the string starts
946  Offset<String> CreateString(const String *str) {
947  return str ? CreateString(str->c_str(), str->Length()) : 0;
948  }
949 
950  /// @brief Store a string in the buffer, which can contain any binary data.
951  /// If a string with this exact contents has already been serialized before,
952  /// instead simply returns the offset of the existing string.
953  /// @param[in] str A const char pointer to the data to be stored as a string.
954  /// @param[in] len The number of bytes that should be stored from `str`.
955  /// @return Returns the offset in the buffer where the string starts.
956  Offset<String> CreateSharedString(const char *str, size_t len) {
957  if (!string_pool)
958  string_pool = new StringOffsetMap(StringOffsetCompare(buf_));
959  auto size_before_string = buf_.size();
960  // Must first serialize the string, since the set is all offsets into
961  // buffer.
962  auto off = CreateString(str, len);
963  auto it = string_pool->find(off);
964  // If it exists we reuse existing serialized data!
965  if (it != string_pool->end()) {
966  // We can remove the string we serialized.
967  buf_.pop(buf_.size() - size_before_string);
968  return *it;
969  }
970  // Record this string for future use.
971  string_pool->insert(off);
972  return off;
973  }
974 
975  /// @brief Store a string in the buffer, which null-terminated.
976  /// If a string with this exact contents has already been serialized before,
977  /// instead simply returns the offset of the existing string.
978  /// @param[in] str A const char pointer to a C-string to add to the buffer.
979  /// @return Returns the offset in the buffer where the string starts.
980  Offset<String> CreateSharedString(const char *str) {
981  return CreateSharedString(str, strlen(str));
982  }
983 
984  /// @brief Store a string in the buffer, which can contain any binary data.
985  /// If a string with this exact contents has already been serialized before,
986  /// instead simply returns the offset of the existing string.
987  /// @param[in] str A const reference to a std::string to store in the buffer.
988  /// @return Returns the offset in the buffer where the string starts.
989  Offset<String> CreateSharedString(const std::string &str) {
990  return CreateSharedString(str.c_str(), str.length());
991  }
992 
993  /// @brief Store a string in the buffer, which can contain any binary data.
994  /// If a string with this exact contents has already been serialized before,
995  /// instead simply returns the offset of the existing string.
996  /// @param[in] str A const pointer to a `String` struct to add to the buffer.
997  /// @return Returns the offset in the buffer where the string starts
998  Offset<String> CreateSharedString(const String *str) {
999  return CreateSharedString(str->c_str(), str->Length());
1000  }
1001 
1002  /// @cond FLATBUFFERS_INTERNAL
1003  uoffset_t EndVector(size_t len) {
1004  assert(nested); // Hit if no corresponding StartVector.
1005  nested = false;
1006  return PushElement(static_cast<uoffset_t>(len));
1007  }
1008 
1009  void StartVector(size_t len, size_t elemsize) {
1010  NotNested();
1011  nested = true;
1012  PreAlign<uoffset_t>(len * elemsize);
1013  PreAlign(len * elemsize, elemsize); // Just in case elemsize > uoffset_t.
1014  }
1015 
1016  // Call this right before StartVector/CreateVector if you want to force the
1017  // alignment to be something different than what the element size would
1018  // normally dictate.
1019  // This is useful when storing a nested_flatbuffer in a vector of bytes,
1020  // or when storing SIMD floats, etc.
1021  void ForceVectorAlignment(size_t len, size_t elemsize, size_t alignment) {
1022  PreAlign(len * elemsize, alignment);
1023  }
1024 
1025  uint8_t *ReserveElements(size_t len, size_t elemsize) {
1026  return buf_.make_space(len * elemsize);
1027  }
1028  /// @endcond
1029 
1030  /// @brief Serialize an array into a FlatBuffer `vector`.
1031  /// @tparam T The data type of the array elements.
1032  /// @param[in] v A pointer to the array of type `T` to serialize into the
1033  /// buffer as a `vector`.
1034  /// @param[in] len The number of elements to serialize.
1035  /// @return Returns a typed `Offset` into the serialized data indicating
1036  /// where the vector is stored.
1037  template<typename T> Offset<Vector<T>> CreateVector(const T *v, size_t len) {
1038  StartVector(len, sizeof(T));
1039  for (auto i = len; i > 0; ) {
1040  PushElement(v[--i]);
1041  }
1042  return Offset<Vector<T>>(EndVector(len));
1043  }
1044 
1045  /// @brief Serialize a `std::vector` into a FlatBuffer `vector`.
1046  /// @tparam T The data type of the `std::vector` elements.
1047  /// @param v A const reference to the `std::vector` to serialize into the
1048  /// buffer as a `vector`.
1049  /// @return Returns a typed `Offset` into the serialized data indicating
1050  /// where the vector is stored.
1051  template<typename T> Offset<Vector<T>> CreateVector(const std::vector<T> &v) {
1052  return CreateVector(data(v), v.size());
1053  }
1054 
1055  // vector<bool> may be implemented using a bit-set, so we can't access it as
1056  // an array. Instead, read elements manually.
1057  // Background: https://isocpp.org/blog/2012/11/on-vectorbool
1058  Offset<Vector<uint8_t>> CreateVector(const std::vector<bool> &v) {
1059  StartVector(v.size(), sizeof(uint8_t));
1060  for (auto i = v.size(); i > 0; ) {
1061  PushElement(static_cast<uint8_t>(v[--i]));
1062  }
1063  return Offset<Vector<uint8_t>>(EndVector(v.size()));
1064  }
1065 
1066  #ifndef FLATBUFFERS_CPP98_STL
1067  /// @brief Serialize values returned by a function into a FlatBuffer `vector`.
1068  /// This is a convenience function that takes care of iteration for you.
1069  /// @tparam T The data type of the `std::vector` elements.
1070  /// @param f A function that takes the current iteration 0..vector_size-1 and
1071  /// returns any type that you can construct a FlatBuffers vector out of.
1072  /// @return Returns a typed `Offset` into the serialized data indicating
1073  /// where the vector is stored.
1074  template<typename T> Offset<Vector<T>> CreateVector(size_t vector_size,
1075  const std::function<T (size_t i)> &f) {
1076  std::vector<T> elems(vector_size);
1077  for (size_t i = 0; i < vector_size; i++) elems[i] = f(i);
1078  return CreateVector(elems);
1079  }
1080  #endif
1081 
1082  /// @brief Serialize a `std::vector<std::string>` into a FlatBuffer `vector`.
1083  /// This is a convenience function for a common case.
1084  /// @param v A const reference to the `std::vector` to serialize into the
1085  /// buffer as a `vector`.
1086  /// @return Returns a typed `Offset` into the serialized data indicating
1087  /// where the vector is stored.
1088  Offset<Vector<Offset<String>>> CreateVectorOfStrings(
1089  const std::vector<std::string> &v) {
1090  std::vector<Offset<String>> offsets(v.size());
1091  for (size_t i = 0; i < v.size(); i++) offsets[i] = CreateString(v[i]);
1092  return CreateVector(offsets);
1093  }
1094 
1095  /// @brief Serialize an array of structs into a FlatBuffer `vector`.
1096  /// @tparam T The data type of the struct array elements.
1097  /// @param[in] v A pointer to the array of type `T` to serialize into the
1098  /// buffer as a `vector`.
1099  /// @param[in] len The number of elements to serialize.
1100  /// @return Returns a typed `Offset` into the serialized data indicating
1101  /// where the vector is stored.
1102  template<typename T> Offset<Vector<const T *>> CreateVectorOfStructs(
1103  const T *v, size_t len) {
1104  StartVector(len * sizeof(T) / AlignOf<T>(), AlignOf<T>());
1105  PushBytes(reinterpret_cast<const uint8_t *>(v), sizeof(T) * len);
1106  return Offset<Vector<const T *>>(EndVector(len));
1107  }
1108 
1109  /// @brief Serialize a `std::vector` of structs into a FlatBuffer `vector`.
1110  /// @tparam T The data type of the `std::vector` struct elements.
1111  /// @param[in]] v A const reference to the `std::vector` of structs to
1112  /// serialize into the buffer as a `vector`.
1113  /// @return Returns a typed `Offset` into the serialized data indicating
1114  /// where the vector is stored.
1115  template<typename T> Offset<Vector<const T *>> CreateVectorOfStructs(
1116  const std::vector<T> &v) {
1117  return CreateVectorOfStructs(data(v), v.size());
1118  }
1119 
1120  /// @cond FLATBUFFERS_INTERNAL
1121  template<typename T>
1122  struct TableKeyComparator {
1123  TableKeyComparator(vector_downward& buf) : buf_(buf) {}
1124  bool operator()(const Offset<T> &a, const Offset<T> &b) const {
1125  auto table_a = reinterpret_cast<T *>(buf_.data_at(a.o));
1126  auto table_b = reinterpret_cast<T *>(buf_.data_at(b.o));
1127  return table_a->KeyCompareLessThan(table_b);
1128  }
1129  vector_downward& buf_;
1130 
1131  private:
1132  TableKeyComparator& operator= (const TableKeyComparator&);
1133  };
1134  /// @endcond
1135 
1136  /// @brief Serialize an array of `table` offsets as a `vector` in the buffer
1137  /// in sorted order.
1138  /// @tparam T The data type that the offset refers to.
1139  /// @param[in] v An array of type `Offset<T>` that contains the `table`
1140  /// offsets to store in the buffer in sorted order.
1141  /// @param[in] len The number of elements to store in the `vector`.
1142  /// @return Returns a typed `Offset` into the serialized data indicating
1143  /// where the vector is stored.
1144  template<typename T> Offset<Vector<Offset<T>>> CreateVectorOfSortedTables(
1145  Offset<T> *v, size_t len) {
1146  std::sort(v, v + len, TableKeyComparator<T>(buf_));
1147  return CreateVector(v, len);
1148  }
1149 
1150  /// @brief Serialize an array of `table` offsets as a `vector` in the buffer
1151  /// in sorted order.
1152  /// @tparam T The data type that the offset refers to.
1153  /// @param[in] v An array of type `Offset<T>` that contains the `table`
1154  /// offsets to store in the buffer in sorted order.
1155  /// @return Returns a typed `Offset` into the serialized data indicating
1156  /// where the vector is stored.
1157  template<typename T> Offset<Vector<Offset<T>>> CreateVectorOfSortedTables(
1158  std::vector<Offset<T>> *v) {
1159  return CreateVectorOfSortedTables(data(*v), v->size());
1160  }
1161 
1162  /// @brief Specialized version of `CreateVector` for non-copying use cases.
1163  /// Write the data any time later to the returned buffer pointer `buf`.
1164  /// @param[in] len The number of elements to store in the `vector`.
1165  /// @param[in] elemsize The size of each element in the `vector`.
1166  /// @param[out] buf A pointer to a `uint8_t` pointer that can be
1167  /// written to at a later time to serialize the data into a `vector`
1168  /// in the buffer.
1169  uoffset_t CreateUninitializedVector(size_t len, size_t elemsize,
1170  uint8_t **buf) {
1171  NotNested();
1172  StartVector(len, elemsize);
1173  buf_.make_space(len * elemsize);
1174  auto vec_start = GetSize();
1175  auto vec_end = EndVector(len);
1176  *buf = buf_.data_at(vec_start);
1177  return vec_end;
1178  }
1179 
1180  /// @brief Specialized version of `CreateVector` for non-copying use cases.
1181  /// Write the data any time later to the returned buffer pointer `buf`.
1182  /// @tparam T The data type of the data that will be stored in the buffer
1183  /// as a `vector`.
1184  /// @param[in] len The number of elements to store in the `vector`.
1185  /// @param[out] buf A pointer to a pointer of type `T` that can be
1186  /// written to at a later time to serialize the data into a `vector`
1187  /// in the buffer.
1188  template<typename T> Offset<Vector<T>> CreateUninitializedVector(
1189  size_t len, T **buf) {
1190  return CreateUninitializedVector(len, sizeof(T),
1191  reinterpret_cast<uint8_t **>(buf));
1192  }
1193 
1194  /// @brief The length of a FlatBuffer file header.
1195  static const size_t kFileIdentifierLength = 4;
1196 
1197  /// @brief Finish serializing a buffer by writing the root offset.
1198  /// @param[in] file_identifier If a `file_identifier` is given, the buffer
1199  /// will be prefixed with a standard FlatBuffers file header.
1200  template<typename T> void Finish(Offset<T> root,
1201  const char *file_identifier = nullptr) {
1202 
1203  Finish(root.o, file_identifier, false);
1204  }
1205 
1206  /// @brief Finish a buffer with a 32 bit size field pre-fixed (size of the
1207  /// buffer following the size field). These buffers are NOT compatible
1208  /// with standard buffers created by Finish, i.e. you can't call GetRoot
1209  /// on them, you have to use GetSizePrefixedRoot instead.
1210  /// All >32 bit quantities in this buffer will be aligned when the whole
1211  /// size pre-fixed buffer is aligned.
1212  /// These kinds of buffers are useful for creating a stream of FlatBuffers.
1213  template<typename T> void FinishSizePrefixed(Offset<T> root,
1214  const char *file_identifier = nullptr) {
1215  Finish(root.o, file_identifier, true);
1216  }
1217 
1218  private:
1219  // You shouldn't really be copying instances of this class.
1221  FlatBufferBuilder &operator=(const FlatBufferBuilder &);
1222 
1223  void Finish(uoffset_t root, const char *file_identifier, bool size_prefix) {
1224  NotNested();
1225  // This will cause the whole buffer to be aligned.
1226  PreAlign((size_prefix ? sizeof(uoffset_t) : 0) +
1227  sizeof(uoffset_t) +
1228  (file_identifier ? kFileIdentifierLength : 0),
1229  minalign_);
1230  if (file_identifier) {
1231  assert(strlen(file_identifier) == kFileIdentifierLength);
1232  buf_.push(reinterpret_cast<const uint8_t *>(file_identifier),
1234  }
1235  PushElement(ReferTo(root)); // Location of root.
1236  if (size_prefix) {
1237  PushElement(GetSize());
1238  }
1239  finished = true;
1240  }
1241 
1242  struct FieldLoc {
1243  uoffset_t off;
1244  voffset_t id;
1245  };
1246 
1247  simple_allocator default_allocator;
1248 
1249  vector_downward buf_;
1250 
1251  // Accumulating offsets of table members while it is being built.
1252  std::vector<FieldLoc> offsetbuf_;
1253 
1254  // Ensure objects are not nested.
1255  bool nested;
1256 
1257  // Ensure the buffer is finished before it is being accessed.
1258  bool finished;
1259 
1260  std::vector<uoffset_t> vtables_; // todo: Could make this into a map?
1261 
1262  size_t minalign_;
1263 
1264  bool force_defaults_; // Serialize values equal to their defaults anyway.
1265 
1266  struct StringOffsetCompare {
1267  StringOffsetCompare(const vector_downward &buf) : buf_(&buf) {}
1268  bool operator() (const Offset<String> &a, const Offset<String> &b) const {
1269  auto stra = reinterpret_cast<const String *>(buf_->data_at(a.o));
1270  auto strb = reinterpret_cast<const String *>(buf_->data_at(b.o));
1271  return strncmp(stra->c_str(), strb->c_str(),
1272  std::min(stra->size(), strb->size()) + 1) < 0;
1273  }
1274  const vector_downward *buf_;
1275  };
1276 
1277  // For use with CreateSharedString. Instantiated on first use only.
1278  typedef std::set<Offset<String>, StringOffsetCompare> StringOffsetMap;
1279  StringOffsetMap *string_pool;
1280 };
1281 /// @}
1282 
1283 /// @cond FLATBUFFERS_INTERNAL
1284 // Helpers to get a typed pointer to the root object contained in the buffer.
1285 template<typename T> T *GetMutableRoot(void *buf) {
1286  EndianCheck();
1287  return reinterpret_cast<T *>(reinterpret_cast<uint8_t *>(buf) +
1288  EndianScalar(*reinterpret_cast<uoffset_t *>(buf)));
1289 }
1290 
1291 template<typename T> const T *GetRoot(const void *buf) {
1292  return GetMutableRoot<T>(const_cast<void *>(buf));
1293 }
1294 
1295 template<typename T> const T *GetSizePrefixedRoot(const void *buf) {
1296  return GetRoot<T>(reinterpret_cast<const uint8_t *>(buf) + sizeof(uoffset_t));
1297 }
1298 
1299 /// Helpers to get a typed pointer to objects that are currently being built.
1300 /// @warning Creating new objects will lead to reallocations and invalidates
1301 /// the pointer!
1302 template<typename T> T *GetMutableTemporaryPointer(FlatBufferBuilder &fbb,
1303  Offset<T> offset) {
1304  return reinterpret_cast<T *>(fbb.GetCurrentBufferPointer() +
1305  fbb.GetSize() - offset.o);
1306 }
1307 
1308 template<typename T> const T *GetTemporaryPointer(FlatBufferBuilder &fbb,
1309  Offset<T> offset) {
1310  return GetMutableTemporaryPointer<T>(fbb, offset);
1311 }
1312 
1313 // Helper to see if the identifier in a buffer has the expected value.
1314 inline bool BufferHasIdentifier(const void *buf, const char *identifier) {
1315  return strncmp(reinterpret_cast<const char *>(buf) + sizeof(uoffset_t),
1316  identifier, FlatBufferBuilder::kFileIdentifierLength) == 0;
1317 }
1318 
1319 // Helper class to verify the integrity of a FlatBuffer
1320 class Verifier FLATBUFFERS_FINAL_CLASS {
1321  public:
1322  Verifier(const uint8_t *buf, size_t buf_len, size_t _max_depth = 64,
1323  size_t _max_tables = 1000000)
1324  : buf_(buf), end_(buf + buf_len), depth_(0), max_depth_(_max_depth),
1325  num_tables_(0), max_tables_(_max_tables)
1326  #ifdef FLATBUFFERS_TRACK_VERIFIER_BUFFER_SIZE
1327  , upper_bound_(buf)
1328  #endif
1329  {}
1330 
1331  // Central location where any verification failures register.
1332  bool Check(bool ok) const {
1333  #ifdef FLATBUFFERS_DEBUG_VERIFICATION_FAILURE
1334  assert(ok);
1335  #endif
1336  #ifdef FLATBUFFERS_TRACK_VERIFIER_BUFFER_SIZE
1337  if (!ok)
1338  upper_bound_ = buf_;
1339  #endif
1340  return ok;
1341  }
1342 
1343  // Verify any range within the buffer.
1344  bool Verify(const void *elem, size_t elem_len) const {
1345  #ifdef FLATBUFFERS_TRACK_VERIFIER_BUFFER_SIZE
1346  auto upper_bound = reinterpret_cast<const uint8_t *>(elem) + elem_len;
1347  if (upper_bound_ < upper_bound)
1348  upper_bound_ = upper_bound;
1349  #endif
1350  return Check(elem_len <= (size_t) (end_ - buf_) &&
1351  elem >= buf_ &&
1352  elem <= end_ - elem_len);
1353  }
1354 
1355  // Verify a range indicated by sizeof(T).
1356  template<typename T> bool Verify(const void *elem) const {
1357  return Verify(elem, sizeof(T));
1358  }
1359 
1360  // Verify a pointer (may be NULL) of a table type.
1361  template<typename T> bool VerifyTable(const T *table) {
1362  return !table || table->Verify(*this);
1363  }
1364 
1365  // Verify a pointer (may be NULL) of any vector type.
1366  template<typename T> bool Verify(const Vector<T> *vec) const {
1367  const uint8_t *end;
1368  return !vec ||
1369  VerifyVector(reinterpret_cast<const uint8_t *>(vec), sizeof(T),
1370  &end);
1371  }
1372 
1373  // Verify a pointer (may be NULL) of a vector to struct.
1374  template<typename T> bool Verify(const Vector<const T *> *vec) const {
1375  return Verify(reinterpret_cast<const Vector<T> *>(vec));
1376  }
1377 
1378  // Verify a pointer (may be NULL) to string.
1379  bool Verify(const String *str) const {
1380  const uint8_t *end;
1381  return !str ||
1382  (VerifyVector(reinterpret_cast<const uint8_t *>(str), 1, &end) &&
1383  Verify(end, 1) && // Must have terminator
1384  Check(*end == '\0')); // Terminating byte must be 0.
1385  }
1386 
1387  // Common code between vectors and strings.
1388  bool VerifyVector(const uint8_t *vec, size_t elem_size,
1389  const uint8_t **end) const {
1390  // Check we can read the size field.
1391  if (!Verify<uoffset_t>(vec)) return false;
1392  // Check the whole array. If this is a string, the byte past the array
1393  // must be 0.
1394  auto size = ReadScalar<uoffset_t>(vec);
1395  auto max_elems = FLATBUFFERS_MAX_BUFFER_SIZE / elem_size;
1396  if (!Check(size < max_elems))
1397  return false; // Protect against byte_size overflowing.
1398  auto byte_size = sizeof(size) + elem_size * size;
1399  *end = vec + byte_size;
1400  return Verify(vec, byte_size);
1401  }
1402 
1403  // Special case for string contents, after the above has been called.
1404  bool VerifyVectorOfStrings(const Vector<Offset<String>> *vec) const {
1405  if (vec) {
1406  for (uoffset_t i = 0; i < vec->size(); i++) {
1407  if (!Verify(vec->Get(i))) return false;
1408  }
1409  }
1410  return true;
1411  }
1412 
1413  // Special case for table contents, after the above has been called.
1414  template<typename T> bool VerifyVectorOfTables(const Vector<Offset<T>> *vec) {
1415  if (vec) {
1416  for (uoffset_t i = 0; i < vec->size(); i++) {
1417  if (!vec->Get(i)->Verify(*this)) return false;
1418  }
1419  }
1420  return true;
1421  }
1422 
1423  template<typename T> bool VerifyBufferFromStart(const char *identifier,
1424  const uint8_t *start) {
1425  if (identifier &&
1426  (size_t(end_ - start) < 2 * sizeof(flatbuffers::uoffset_t) ||
1427  !BufferHasIdentifier(start, identifier))) {
1428  return false;
1429  }
1430 
1431  // Call T::Verify, which must be in the generated code for this type.
1432  return Verify<uoffset_t>(start) &&
1433  reinterpret_cast<const T *>(start + ReadScalar<uoffset_t>(start))->
1434  Verify(*this)
1435  #ifdef FLATBUFFERS_TRACK_VERIFIER_BUFFER_SIZE
1436  && GetComputedSize()
1437  #endif
1438  ;
1439  }
1440 
1441  // Verify this whole buffer, starting with root type T.
1442  template<typename T> bool VerifyBuffer(const char *identifier) {
1443  return VerifyBufferFromStart<T>(identifier, buf_);
1444  }
1445 
1446  template<typename T> bool VerifySizePrefixedBuffer(const char *identifier) {
1447  return Verify<uoffset_t>(buf_) &&
1448  ReadScalar<uoffset_t>(buf_) == end_ - buf_ - sizeof(uoffset_t) &&
1449  VerifyBufferFromStart<T>(identifier, buf_ + sizeof(uoffset_t));
1450  }
1451 
1452  // Called at the start of a table to increase counters measuring data
1453  // structure depth and amount, and possibly bails out with false if
1454  // limits set by the constructor have been hit. Needs to be balanced
1455  // with EndTable().
1456  bool VerifyComplexity() {
1457  depth_++;
1458  num_tables_++;
1459  return Check(depth_ <= max_depth_ && num_tables_ <= max_tables_);
1460  }
1461 
1462  // Called at the end of a table to pop the depth count.
1463  bool EndTable() {
1464  depth_--;
1465  return true;
1466  }
1467 
1468  #ifdef FLATBUFFERS_TRACK_VERIFIER_BUFFER_SIZE
1469  // Returns the message size in bytes
1470  size_t GetComputedSize() const {
1471  uintptr_t size = upper_bound_ - buf_;
1472  // Align the size to uoffset_t
1473  size = (size - 1 + sizeof(uoffset_t)) & ~(sizeof(uoffset_t) - 1);
1474  return (buf_ + size > end_) ? 0 : size;
1475  }
1476  #endif
1477 
1478  private:
1479  const uint8_t *buf_;
1480  const uint8_t *end_;
1481  size_t depth_;
1482  size_t max_depth_;
1483  size_t num_tables_;
1484  size_t max_tables_;
1485 #ifdef FLATBUFFERS_TRACK_VERIFIER_BUFFER_SIZE
1486  mutable const uint8_t *upper_bound_;
1487 #endif
1488 };
1489 
1490 // Convenient way to bundle a buffer and its length, to pass it around
1491 // typed by its root.
1492 // A BufferRef does not own its buffer.
1493 struct BufferRefBase {}; // for std::is_base_of
1494 template<typename T> struct BufferRef : BufferRefBase {
1495  BufferRef() : buf(nullptr), len(0), must_free(false) {}
1496  BufferRef(uint8_t *_buf, uoffset_t _len)
1497  : buf(_buf), len(_len), must_free(false) {}
1498 
1499  ~BufferRef() { if (must_free) free(buf); }
1500 
1501  const T *GetRoot() const { return flatbuffers::GetRoot<T>(buf); }
1502 
1503  bool Verify() {
1504  Verifier verifier(buf, len);
1505  return verifier.VerifyBuffer<T>(nullptr);
1506  }
1507 
1508  uint8_t *buf;
1509  uoffset_t len;
1510  bool must_free;
1511 };
1512 
1513 // "structs" are flat structures that do not have an offset table, thus
1514 // always have all members present and do not support forwards/backwards
1515 // compatible extensions.
1516 
1517 class Struct FLATBUFFERS_FINAL_CLASS {
1518  public:
1519  template<typename T> T GetField(uoffset_t o) const {
1520  return ReadScalar<T>(&data_[o]);
1521  }
1522 
1523  template<typename T> T GetStruct(uoffset_t o) const {
1524  return reinterpret_cast<T>(&data_[o]);
1525  }
1526 
1527  const uint8_t *GetAddressOf(uoffset_t o) const { return &data_[o]; }
1528  uint8_t *GetAddressOf(uoffset_t o) { return &data_[o]; }
1529 
1530  private:
1531  uint8_t data_[1];
1532 };
1533 
1534 // "tables" use an offset table (possibly shared) that allows fields to be
1535 // omitted and added at will, but uses an extra indirection to read.
1536 class Table {
1537  public:
1538  const uint8_t *GetVTable() const {
1539  return data_ - ReadScalar<soffset_t>(data_);
1540  }
1541 
1542  // This gets the field offset for any of the functions below it, or 0
1543  // if the field was not present.
1544  voffset_t GetOptionalFieldOffset(voffset_t field) const {
1545  // The vtable offset is always at the start.
1546  auto vtable = GetVTable();
1547  // The first element is the size of the vtable (fields + type id + itself).
1548  auto vtsize = ReadScalar<voffset_t>(vtable);
1549  // If the field we're accessing is outside the vtable, we're reading older
1550  // data, so it's the same as if the offset was 0 (not present).
1551  return field < vtsize ? ReadScalar<voffset_t>(vtable + field) : 0;
1552  }
1553 
1554  template<typename T> T GetField(voffset_t field, T defaultval) const {
1555  auto field_offset = GetOptionalFieldOffset(field);
1556  return field_offset ? ReadScalar<T>(data_ + field_offset) : defaultval;
1557  }
1558 
1559  template<typename P> P GetPointer(voffset_t field) {
1560  auto field_offset = GetOptionalFieldOffset(field);
1561  auto p = data_ + field_offset;
1562  return field_offset
1563  ? reinterpret_cast<P>(p + ReadScalar<uoffset_t>(p))
1564  : nullptr;
1565  }
1566  template<typename P> P GetPointer(voffset_t field) const {
1567  return const_cast<Table *>(this)->GetPointer<P>(field);
1568  }
1569 
1570  template<typename P> P GetStruct(voffset_t field) const {
1571  auto field_offset = GetOptionalFieldOffset(field);
1572  auto p = const_cast<uint8_t *>(data_ + field_offset);
1573  return field_offset ? reinterpret_cast<P>(p) : nullptr;
1574  }
1575 
1576  template<typename T> bool SetField(voffset_t field, T val) {
1577  auto field_offset = GetOptionalFieldOffset(field);
1578  if (!field_offset) return false;
1579  WriteScalar(data_ + field_offset, val);
1580  return true;
1581  }
1582 
1583  bool SetPointer(voffset_t field, const uint8_t *val) {
1584  auto field_offset = GetOptionalFieldOffset(field);
1585  if (!field_offset) return false;
1586  WriteScalar(data_ + field_offset,
1587  static_cast<uoffset_t>(val - (data_ + field_offset)));
1588  return true;
1589  }
1590 
1591  uint8_t *GetAddressOf(voffset_t field) {
1592  auto field_offset = GetOptionalFieldOffset(field);
1593  return field_offset ? data_ + field_offset : nullptr;
1594  }
1595  const uint8_t *GetAddressOf(voffset_t field) const {
1596  return const_cast<Table *>(this)->GetAddressOf(field);
1597  }
1598 
1599  bool CheckField(voffset_t field) const {
1600  return GetOptionalFieldOffset(field) != 0;
1601  }
1602 
1603  // Verify the vtable of this table.
1604  // Call this once per table, followed by VerifyField once per field.
1605  bool VerifyTableStart(Verifier &verifier) const {
1606  // Check the vtable offset.
1607  if (!verifier.Verify<soffset_t>(data_)) return false;
1608  auto vtable = GetVTable();
1609  // Check the vtable size field, then check vtable fits in its entirety.
1610  return verifier.VerifyComplexity() &&
1611  verifier.Verify<voffset_t>(vtable) &&
1612  (ReadScalar<voffset_t>(vtable) & (sizeof(voffset_t) - 1)) == 0 &&
1613  verifier.Verify(vtable, ReadScalar<voffset_t>(vtable));
1614  }
1615 
1616  // Verify a particular field.
1617  template<typename T> bool VerifyField(const Verifier &verifier,
1618  voffset_t field) const {
1619  // Calling GetOptionalFieldOffset should be safe now thanks to
1620  // VerifyTable().
1621  auto field_offset = GetOptionalFieldOffset(field);
1622  // Check the actual field.
1623  return !field_offset || verifier.Verify<T>(data_ + field_offset);
1624  }
1625 
1626  // VerifyField for required fields.
1627  template<typename T> bool VerifyFieldRequired(const Verifier &verifier,
1628  voffset_t field) const {
1629  auto field_offset = GetOptionalFieldOffset(field);
1630  return verifier.Check(field_offset != 0) &&
1631  verifier.Verify<T>(data_ + field_offset);
1632  }
1633 
1634  private:
1635  // private constructor & copy constructor: you obtain instances of this
1636  // class by pointing to existing data only
1637  Table();
1638  Table(const Table &other);
1639 
1640  uint8_t data_[1];
1641 };
1642 
1643 /// @brief This can compute the start of a FlatBuffer from a root pointer, i.e.
1644 /// it is the opposite transformation of GetRoot().
1645 /// This may be useful if you want to pass on a root and have the recipient
1646 /// delete the buffer afterwards.
1647 inline const uint8_t *GetBufferStartFromRootPointer(const void *root) {
1648  auto table = reinterpret_cast<const Table *>(root);
1649  auto vtable = table->GetVTable();
1650  // Either the vtable is before the root or after the root.
1651  auto start = std::min(vtable, reinterpret_cast<const uint8_t *>(root));
1652  // Align to at least sizeof(uoffset_t).
1653  start = reinterpret_cast<const uint8_t *>(
1654  reinterpret_cast<uintptr_t>(start) & ~(sizeof(uoffset_t) - 1));
1655  // Additionally, there may be a file_identifier in the buffer, and the root
1656  // offset. The buffer may have been aligned to any size between
1657  // sizeof(uoffset_t) and FLATBUFFERS_MAX_ALIGNMENT (see "force_align").
1658  // Sadly, the exact alignment is only known when constructing the buffer,
1659  // since it depends on the presence of values with said alignment properties.
1660  // So instead, we simply look at the next uoffset_t values (root,
1661  // file_identifier, and alignment padding) to see which points to the root.
1662  // None of the other values can "impersonate" the root since they will either
1663  // be 0 or four ASCII characters.
1664  static_assert(FlatBufferBuilder::kFileIdentifierLength == sizeof(uoffset_t),
1665  "file_identifier is assumed to be the same size as uoffset_t");
1666  for (auto possible_roots = FLATBUFFERS_MAX_ALIGNMENT / sizeof(uoffset_t) + 1;
1667  possible_roots;
1668  possible_roots--) {
1669  start -= sizeof(uoffset_t);
1670  if (ReadScalar<uoffset_t>(start) + start ==
1671  reinterpret_cast<const uint8_t *>(root)) return start;
1672  }
1673  // We didn't find the root, either the "root" passed isn't really a root,
1674  // or the buffer is corrupt.
1675  // Assert, because calling this function with bad data may cause reads
1676  // outside of buffer boundaries.
1677  assert(false);
1678  return nullptr;
1679 }
1680 
1681 // Base class for native objects (FlatBuffer data de-serialized into native
1682 // C++ data structures).
1683 // Contains no functionality, purely documentative.
1684 struct NativeTable {
1685 };
1686 
1687 /// @brief Function types to be used with resolving hashes into objects and
1688 /// back again. The resolver gets a pointer to a field inside an object API
1689 /// object that is of the type specified in the schema using the attribute
1690 /// `cpp_type` (it is thus important whatever you write to this address
1691 /// matches that type). The value of this field is initially null, so you
1692 /// may choose to implement a delayed binding lookup using this function
1693 /// if you wish. The resolver does the opposite lookup, for when the object
1694 /// is being serialized again.
1695 typedef uint64_t hash_value_t;
1696 #ifdef FLATBUFFERS_CPP98_STL
1697  typedef void (*resolver_function_t)(void **pointer_adr, hash_value_t hash);
1698  typedef hash_value_t (*rehasher_function_t)(void *pointer);
1699 #else
1700  typedef std::function<void (void **pointer_adr, hash_value_t hash)>
1701  resolver_function_t;
1702  typedef std::function<hash_value_t (void *pointer)> rehasher_function_t;
1703 #endif
1704 
1705 // Helper function to test if a field is present, using any of the field
1706 // enums in the generated code.
1707 // `table` must be a generated table type. Since this is a template parameter,
1708 // this is not typechecked to be a subclass of Table, so beware!
1709 // Note: this function will return false for fields equal to the default
1710 // value, since they're not stored in the buffer (unless force_defaults was
1711 // used).
1712 template<typename T> bool IsFieldPresent(const T *table, voffset_t field) {
1713  // Cast, since Table is a private baseclass of any table types.
1714  return reinterpret_cast<const Table *>(table)->CheckField(field);
1715 }
1716 
1717 // Utility function for reverse lookups on the EnumNames*() functions
1718 // (in the generated C++ code)
1719 // names must be NULL terminated.
1720 inline int LookupEnum(const char **names, const char *name) {
1721  for (const char **p = names; *p; p++)
1722  if (!strcmp(*p, name))
1723  return static_cast<int>(p - names);
1724  return -1;
1725 }
1726 
1727 // These macros allow us to layout a struct with a guarantee that they'll end
1728 // up looking the same on different compilers and platforms.
1729 // It does this by disallowing the compiler to do any padding, and then
1730 // does padding itself by inserting extra padding fields that make every
1731 // element aligned to its own size.
1732 // Additionally, it manually sets the alignment of the struct as a whole,
1733 // which is typically its largest element, or a custom size set in the schema
1734 // by the force_align attribute.
1735 // These are used in the generated code only.
1736 
1737 #if defined(_MSC_VER)
1738  #define MANUALLY_ALIGNED_STRUCT(alignment) \
1739  __pragma(pack(1)); \
1740  struct __declspec(align(alignment))
1741  #define STRUCT_END(name, size) \
1742  __pragma(pack()); \
1743  static_assert(sizeof(name) == size, "compiler breaks packing rules")
1744 #elif defined(__GNUC__) || defined(__clang__)
1745  #define MANUALLY_ALIGNED_STRUCT(alignment) \
1746  _Pragma("pack(1)") \
1747  struct __attribute__((aligned(alignment)))
1748  #define STRUCT_END(name, size) \
1749  _Pragma("pack()") \
1750  static_assert(sizeof(name) == size, "compiler breaks packing rules")
1751 #else
1752  #error Unknown compiler, please define structure alignment macros
1753 #endif
1754 
1755 // String which identifies the current version of FlatBuffers.
1756 // flatbuffer_version_string is used by Google developers to identify which
1757 // applications uploaded to Google Play are using this library. This allows
1758 // the development team at Google to determine the popularity of the library.
1759 // How it works: Applications that are uploaded to the Google Play Store are
1760 // scanned for this version string. We track which applications are using it
1761 // to measure popularity. You are free to remove it (of course) but we would
1762 // appreciate if you left it in.
1763 
1764 // Weak linkage is culled by VS & doesn't work on cygwin.
1765 #if !defined(_WIN32) && !defined(__CYGWIN__)
1766 
1767 extern volatile __attribute__((weak)) const char *flatbuffer_version_string;
1768 volatile __attribute__((weak)) const char *flatbuffer_version_string =
1769  "FlatBuffers "
1770  FLATBUFFERS_STRING(FLATBUFFERS_VERSION_MAJOR) "."
1771  FLATBUFFERS_STRING(FLATBUFFERS_VERSION_MINOR) "."
1772  FLATBUFFERS_STRING(FLATBUFFERS_VERSION_REVISION);
1773 
1774 #endif // !defined(_WIN32) && !defined(__CYGWIN__)
1775 
1776 #define DEFINE_BITMASK_OPERATORS(E, T)\
1777  inline E operator | (E lhs, E rhs){\
1778  return E(T(lhs) | T(rhs));\
1779  }\
1780  inline E operator & (E lhs, E rhs){\
1781  return E(T(lhs) & T(rhs));\
1782  }\
1783  inline E operator ^ (E lhs, E rhs){\
1784  return E(T(lhs) ^ T(rhs));\
1785  }\
1786  inline E operator ~ (E lhs){\
1787  return E(~T(lhs));\
1788  }\
1789  inline E operator |= (E &lhs, E rhs){\
1790  lhs = lhs | rhs;\
1791  return lhs;\
1792  }\
1793  inline E operator &= (E &lhs, E rhs){\
1794  lhs = lhs & rhs;\
1795  return lhs;\
1796  }\
1797  inline E operator ^= (E &lhs, E rhs){\
1798  lhs = lhs ^ rhs;\
1799  return lhs;\
1800  }\
1801  inline bool operator !(E rhs) \
1802  {\
1803  return !bool(T(rhs)); \
1804  }
1805 /// @endcond
1806 } // namespace flatbuffers
1807 
1808 #endif // FLATBUFFERS_H_
Offset< Vector< T > > CreateVector(size_t vector_size, const std::function< T(size_t i)> &f)
Serialize values returned by a function into a FlatBuffer vector.
Definition: flatbuffers.h:1074
uoffset_t CreateUninitializedVector(size_t len, size_t elemsize, uint8_t **buf)
Specialized version of CreateVector for non-copying use cases.
Definition: flatbuffers.h:1169
Offset< Vector< Offset< T > > > CreateVectorOfSortedTables(std::vector< Offset< T >> *v)
Serialize an array of table offsets as a vector in the buffer in sorted order.
Definition: flatbuffers.h:1157
Helper class to hold data needed in creation of a FlatBuffer.
Definition: flatbuffers.h:630
uoffset_t GetSize() const
The current size of the serialized buffer, counting from the end.
Definition: flatbuffers.h:670
FlatBufferBuilder(uoffset_t initial_size=1024, const simple_allocator *allocator=nullptr)
Default constructor for FlatBufferBuilder.
Definition: flatbuffers.h:642
void Clear()
Reset all the state in this FlatBufferBuilder so it can be reused to construct another buffer...
Definition: flatbuffers.h:658
unique_ptr_t ReleaseBufferPointer()
Get the released pointer to the serialized buffer.
Definition: flatbuffers.h:691
void FinishSizePrefixed(Offset< T > root, const char *file_identifier=nullptr)
Finish a buffer with a 32 bit size field pre-fixed (size of the buffer following the size field)...
Definition: flatbuffers.h:1213
Offset< String > CreateSharedString(const char *str)
Store a string in the buffer, which null-terminated.
Definition: flatbuffers.h:980
Offset< String > CreateString(const char *str, size_t len)
Store a string in the buffer, which can contain any binary data.
Definition: flatbuffers.h:920
void ForceDefaults(bool fd)
In order to save space, fields that are set to their default value don't get serialized into the buff...
Definition: flatbuffers.h:721
static const size_t kFileIdentifierLength
The length of a FlatBuffer file header.
Definition: flatbuffers.h:1195
Offset< String > CreateString(const String *str)
Store a string in the buffer, which can contain any binary data.
Definition: flatbuffers.h:946
Offset< String > CreateSharedString(const String *str)
Store a string in the buffer, which can contain any binary data.
Definition: flatbuffers.h:998
Offset< Vector< Offset< String > > > CreateVectorOfStrings(const std::vector< std::string > &v)
Serialize a std::vector into a FlatBuffer vector.
Definition: flatbuffers.h:1088
size_t GetBufferMinAlignment()
get the minimum alignment this buffer needs to be accessed properly.
Definition: flatbuffers.h:702
Offset< Vector< const T * > > CreateVectorOfStructs(const T *v, size_t len)
Serialize an array of structs into a FlatBuffer vector.
Definition: flatbuffers.h:1102
Offset< String > CreateString(const char *str)
Store a string in the buffer, which is null-terminated.
Definition: flatbuffers.h:932
Offset< String > CreateString(const std::string &str)
Store a string in the buffer, which can contain any binary data.
Definition: flatbuffers.h:939
Offset< Vector< T > > CreateVector(const std::vector< T > &v)
Serialize a std::vector into a FlatBuffer vector.
Definition: flatbuffers.h:1051
Offset< Vector< T > > CreateUninitializedVector(size_t len, T **buf)
Specialized version of CreateVector for non-copying use cases.
Definition: flatbuffers.h:1188
uint8_t * GetCurrentBufferPointer() const
Get a pointer to an unfinished buffer.
Definition: flatbuffers.h:682
Offset< Vector< T > > CreateVector(const T *v, size_t len)
Serialize an array into a FlatBuffer vector.
Definition: flatbuffers.h:1037
Offset< String > CreateSharedString(const std::string &str)
Store a string in the buffer, which can contain any binary data.
Definition: flatbuffers.h:989
Offset< Vector< Offset< T > > > CreateVectorOfSortedTables(Offset< T > *v, size_t len)
Serialize an array of table offsets as a vector in the buffer in sorted order.
Definition: flatbuffers.h:1144
Offset< String > CreateSharedString(const char *str, size_t len)
Store a string in the buffer, which can contain any binary data.
Definition: flatbuffers.h:956
Offset< Vector< const T * > > CreateVectorOfStructs(const std::vector< T > &v)
Serialize a std::vector of structs into a FlatBuffer vector.
Definition: flatbuffers.h:1115
void Finish(Offset< T > root, const char *file_identifier=nullptr)
Finish serializing a buffer by writing the root offset.
Definition: flatbuffers.h:1200
uint8_t * GetBufferPointer() const
Get the serialized buffer (after you call Finish()).
Definition: flatbuffers.h:675