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