2 * Copyright 2014 Google Inc. All rights reserved.
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
17 #ifndef FLATBUFFERS_H_
18 #define FLATBUFFERS_H_
20 #include "flatbuffers/base.h"
22 #if defined(FLATBUFFERS_NAN_DEFAULTS)
26 namespace flatbuffers {
27 // Generic 'operator==' with conditional specialisations.
28 template<typename T> inline bool IsTheSameAs(T e, T def) { return e == def; }
30 #if defined(FLATBUFFERS_NAN_DEFAULTS) && \
31 (!defined(_MSC_VER) || _MSC_VER >= 1800)
32 // Like `operator==(e, def)` with weak NaN if T=(float|double).
33 template<> inline bool IsTheSameAs<float>(float e, float def) {
34 return (e == def) || (std::isnan(def) && std::isnan(e));
36 template<> inline bool IsTheSameAs<double>(double e, double def) {
37 return (e == def) || (std::isnan(def) && std::isnan(e));
41 // Wrapper for uoffset_t to allow safe template specialization.
42 // Value is allowed to be 0 to indicate a null object (see e.g. AddOffset).
43 template<typename T> struct Offset {
46 Offset(uoffset_t _o) : o(_o) {}
47 Offset<void> Union() const { return Offset<void>(o); }
48 bool IsNull() const { return !o; }
51 inline void EndianCheck() {
53 // If this fails, see FLATBUFFERS_LITTLEENDIAN above.
54 FLATBUFFERS_ASSERT(*reinterpret_cast<char *>(&endiantest) ==
55 FLATBUFFERS_LITTLEENDIAN);
59 template<typename T> FLATBUFFERS_CONSTEXPR size_t AlignOf() {
65 return __alignof__(T);
73 // When we read serialized data from memory, in the case of most scalars,
74 // we want to just read T, but in the case of Offset, we want to actually
75 // perform the indirection and return a pointer.
76 // The template specialization below does just that.
77 // It is wrapped in a struct since function templates can't overload on the
78 // return type like this.
79 // The typedef is for the convenience of callers of this function
80 // (avoiding the need for a trailing return decltype)
81 template<typename T> struct IndirectHelper {
82 typedef T return_type;
83 typedef T mutable_return_type;
84 static const size_t element_stride = sizeof(T);
85 static return_type Read(const uint8_t *p, uoffset_t i) {
86 return EndianScalar((reinterpret_cast<const T *>(p))[i]);
89 template<typename T> struct IndirectHelper<Offset<T>> {
90 typedef const T *return_type;
91 typedef T *mutable_return_type;
92 static const size_t element_stride = sizeof(uoffset_t);
93 static return_type Read(const uint8_t *p, uoffset_t i) {
94 p += i * sizeof(uoffset_t);
95 return reinterpret_cast<return_type>(p + ReadScalar<uoffset_t>(p));
98 template<typename T> struct IndirectHelper<const T *> {
99 typedef const T *return_type;
100 typedef T *mutable_return_type;
101 static const size_t element_stride = sizeof(T);
102 static return_type Read(const uint8_t *p, uoffset_t i) {
103 return reinterpret_cast<const T *>(p + i * sizeof(T));
107 // An STL compatible iterator implementation for Vector below, effectively
108 // calling Get() for every element.
109 template<typename T, typename IT> struct VectorIterator {
110 typedef std::random_access_iterator_tag iterator_category;
111 typedef IT value_type;
112 typedef ptrdiff_t difference_type;
114 typedef IT &reference;
116 VectorIterator(const uint8_t *data, uoffset_t i)
117 : data_(data + IndirectHelper<T>::element_stride * i) {}
118 VectorIterator(const VectorIterator &other) : data_(other.data_) {}
119 VectorIterator() : data_(nullptr) {}
121 VectorIterator &operator=(const VectorIterator &other) {
127 #if !defined(FLATBUFFERS_CPP98_STL)
128 VectorIterator &operator=(VectorIterator &&other) {
132 #endif // !defined(FLATBUFFERS_CPP98_STL)
135 bool operator==(const VectorIterator &other) const {
136 return data_ == other.data_;
139 bool operator<(const VectorIterator &other) const {
140 return data_ < other.data_;
143 bool operator!=(const VectorIterator &other) const {
144 return data_ != other.data_;
147 difference_type operator-(const VectorIterator &other) const {
148 return (data_ - other.data_) / IndirectHelper<T>::element_stride;
151 IT operator*() const { return IndirectHelper<T>::Read(data_, 0); }
153 IT operator->() const { return IndirectHelper<T>::Read(data_, 0); }
155 VectorIterator &operator++() {
156 data_ += IndirectHelper<T>::element_stride;
160 VectorIterator operator++(int) {
161 VectorIterator temp(data_, 0);
162 data_ += IndirectHelper<T>::element_stride;
166 VectorIterator operator+(const uoffset_t &offset) const {
167 return VectorIterator(data_ + offset * IndirectHelper<T>::element_stride,
171 VectorIterator &operator+=(const uoffset_t &offset) {
172 data_ += offset * IndirectHelper<T>::element_stride;
176 VectorIterator &operator--() {
177 data_ -= IndirectHelper<T>::element_stride;
181 VectorIterator operator--(int) {
182 VectorIterator temp(data_, 0);
183 data_ -= IndirectHelper<T>::element_stride;
187 VectorIterator operator-(const uoffset_t &offset) const {
188 return VectorIterator(data_ - offset * IndirectHelper<T>::element_stride,
192 VectorIterator &operator-=(const uoffset_t &offset) {
193 data_ -= offset * IndirectHelper<T>::element_stride;
198 const uint8_t *data_;
201 template<typename Iterator> struct VectorReverseIterator :
202 public std::reverse_iterator<Iterator> {
204 explicit VectorReverseIterator(Iterator iter) :
205 std::reverse_iterator<Iterator>(iter) {}
207 typename Iterator::value_type operator*() const {
208 return *(std::reverse_iterator<Iterator>::current);
211 typename Iterator::value_type operator->() const {
212 return *(std::reverse_iterator<Iterator>::current);
218 // This is used as a helper type for accessing vectors.
219 // Vector::data() assumes the vector elements start after the length field.
220 template<typename T> class Vector {
222 typedef VectorIterator<T, typename IndirectHelper<T>::mutable_return_type>
224 typedef VectorIterator<T, typename IndirectHelper<T>::return_type>
226 typedef VectorReverseIterator<iterator> reverse_iterator;
227 typedef VectorReverseIterator<const_iterator> const_reverse_iterator;
229 uoffset_t size() const { return EndianScalar(length_); }
231 // Deprecated: use size(). Here for backwards compatibility.
232 FLATBUFFERS_ATTRIBUTE(deprecated("use size() instead"))
233 uoffset_t Length() const { return size(); }
235 typedef typename IndirectHelper<T>::return_type return_type;
236 typedef typename IndirectHelper<T>::mutable_return_type mutable_return_type;
238 return_type Get(uoffset_t i) const {
239 FLATBUFFERS_ASSERT(i < size());
240 return IndirectHelper<T>::Read(Data(), i);
243 return_type operator[](uoffset_t i) const { return Get(i); }
245 // If this is a Vector of enums, T will be its storage type, not the enum
246 // type. This function makes it convenient to retrieve value with enum
248 template<typename E> E GetEnum(uoffset_t i) const {
249 return static_cast<E>(Get(i));
252 // If this a vector of unions, this does the cast for you. There's no check
253 // to make sure this is the right type!
254 template<typename U> const U *GetAs(uoffset_t i) const {
255 return reinterpret_cast<const U *>(Get(i));
258 // If this a vector of unions, this does the cast for you. There's no check
259 // to make sure this is actually a string!
260 const String *GetAsString(uoffset_t i) const {
261 return reinterpret_cast<const String *>(Get(i));
264 const void *GetStructFromOffset(size_t o) const {
265 return reinterpret_cast<const void *>(Data() + o);
268 iterator begin() { return iterator(Data(), 0); }
269 const_iterator begin() const { return const_iterator(Data(), 0); }
271 iterator end() { return iterator(Data(), size()); }
272 const_iterator end() const { return const_iterator(Data(), size()); }
274 reverse_iterator rbegin() { return reverse_iterator(end() - 1); }
275 const_reverse_iterator rbegin() const { return const_reverse_iterator(end() - 1); }
277 reverse_iterator rend() { return reverse_iterator(begin() - 1); }
278 const_reverse_iterator rend() const { return const_reverse_iterator(begin() - 1); }
280 const_iterator cbegin() const { return begin(); }
282 const_iterator cend() const { return end(); }
284 const_reverse_iterator crbegin() const { return rbegin(); }
286 const_reverse_iterator crend() const { return rend(); }
288 // Change elements if you have a non-const pointer to this object.
289 // Scalars only. See reflection.h, and the documentation.
290 void Mutate(uoffset_t i, const T &val) {
291 FLATBUFFERS_ASSERT(i < size());
292 WriteScalar(data() + i, val);
295 // Change an element of a vector of tables (or strings).
296 // "val" points to the new table/string, as you can obtain from
297 // e.g. reflection::AddFlatBuffer().
298 void MutateOffset(uoffset_t i, const uint8_t *val) {
299 FLATBUFFERS_ASSERT(i < size());
300 static_assert(sizeof(T) == sizeof(uoffset_t), "Unrelated types");
301 WriteScalar(data() + i,
302 static_cast<uoffset_t>(val - (Data() + i * sizeof(uoffset_t))));
305 // Get a mutable pointer to tables/strings inside this vector.
306 mutable_return_type GetMutableObject(uoffset_t i) const {
307 FLATBUFFERS_ASSERT(i < size());
308 return const_cast<mutable_return_type>(IndirectHelper<T>::Read(Data(), i));
311 // The raw data in little endian format. Use with care.
312 const uint8_t *Data() const {
313 return reinterpret_cast<const uint8_t *>(&length_ + 1);
316 uint8_t *Data() { return reinterpret_cast<uint8_t *>(&length_ + 1); }
318 // Similarly, but typed, much like std::vector::data
319 const T *data() const { return reinterpret_cast<const T *>(Data()); }
320 T *data() { return reinterpret_cast<T *>(Data()); }
322 template<typename K> return_type LookupByKey(K key) const {
323 void *search_result = std::bsearch(
324 &key, Data(), size(), IndirectHelper<T>::element_stride, KeyCompare<K>);
326 if (!search_result) {
327 return nullptr; // Key not found.
330 const uint8_t *element = reinterpret_cast<const uint8_t *>(search_result);
332 return IndirectHelper<T>::Read(element, 0);
336 // This class is only used to access pre-existing data. Don't ever
337 // try to construct these manually.
343 // This class is a pointer. Copying will therefore create an invalid object.
344 // Private and unimplemented copy constructor.
345 Vector(const Vector &);
347 template<typename K> static int KeyCompare(const void *ap, const void *bp) {
348 const K *key = reinterpret_cast<const K *>(ap);
349 const uint8_t *data = reinterpret_cast<const uint8_t *>(bp);
350 auto table = IndirectHelper<T>::Read(data, 0);
352 // std::bsearch compares with the operands transposed, so we negate the
354 return -table->KeyCompareWithValue(*key);
358 // Represent a vector much like the template above, but in this case we
359 // don't know what the element types are (used with reflection.h).
362 uoffset_t size() const { return EndianScalar(length_); }
364 const uint8_t *Data() const {
365 return reinterpret_cast<const uint8_t *>(&length_ + 1);
367 uint8_t *Data() { return reinterpret_cast<uint8_t *>(&length_ + 1); }
375 VectorOfAny(const VectorOfAny &);
378 #ifndef FLATBUFFERS_CPP98_STL
379 template<typename T, typename U>
380 Vector<Offset<T>> *VectorCast(Vector<Offset<U>> *ptr) {
381 static_assert(std::is_base_of<T, U>::value, "Unrelated types");
382 return reinterpret_cast<Vector<Offset<T>> *>(ptr);
385 template<typename T, typename U>
386 const Vector<Offset<T>> *VectorCast(const Vector<Offset<U>> *ptr) {
387 static_assert(std::is_base_of<T, U>::value, "Unrelated types");
388 return reinterpret_cast<const Vector<Offset<T>> *>(ptr);
392 // Convenient helper function to get the length of any vector, regardless
393 // of whether it is null or not (the field is not set).
394 template<typename T> static inline size_t VectorLength(const Vector<T> *v) {
395 return v ? v->size() : 0;
398 // Lexicographically compare two strings (possibly containing nulls), and
399 // return true if the first is less than the second.
400 static inline bool StringLessThan(const char *a_data, uoffset_t a_size,
401 const char *b_data, uoffset_t b_size) {
402 const auto cmp = memcmp(a_data, b_data, (std::min)(a_size, b_size));
403 return cmp == 0 ? a_size < b_size : cmp < 0;
406 struct String : public Vector<char> {
407 const char *c_str() const { return reinterpret_cast<const char *>(Data()); }
408 std::string str() const { return std::string(c_str(), size()); }
411 #ifdef FLATBUFFERS_HAS_STRING_VIEW
412 flatbuffers::string_view string_view() const {
413 return flatbuffers::string_view(c_str(), size());
415 #endif // FLATBUFFERS_HAS_STRING_VIEW
418 bool operator<(const String &o) const {
419 return StringLessThan(this->data(), this->size(), o.data(), o.size());
423 // Convenience function to get std::string from a String returning an empty
424 // string on null pointer.
425 static inline std::string GetString(const String * str) {
426 return str ? str->str() : "";
429 // Convenience function to get char* from a String returning an empty string on
431 static inline const char * GetCstring(const String * str) {
432 return str ? str->c_str() : "";
435 // Allocator interface. This is flatbuffers-specific and meant only for
436 // `vector_downward` usage.
439 virtual ~Allocator() {}
441 // Allocate `size` bytes of memory.
442 virtual uint8_t *allocate(size_t size) = 0;
444 // Deallocate `size` bytes of memory at `p` allocated by this allocator.
445 virtual void deallocate(uint8_t *p, size_t size) = 0;
447 // Reallocate `new_size` bytes of memory, replacing the old region of size
448 // `old_size` at `p`. In contrast to a normal realloc, this grows downwards,
449 // and is intended specifcally for `vector_downward` use.
450 // `in_use_back` and `in_use_front` indicate how much of `old_size` is
451 // actually in use at each end, and needs to be copied.
452 virtual uint8_t *reallocate_downward(uint8_t *old_p, size_t old_size,
453 size_t new_size, size_t in_use_back,
454 size_t in_use_front) {
455 FLATBUFFERS_ASSERT(new_size > old_size); // vector_downward only grows
456 uint8_t *new_p = allocate(new_size);
457 memcpy_downward(old_p, old_size, new_p, new_size, in_use_back,
459 deallocate(old_p, old_size);
464 // Called by `reallocate_downward` to copy memory from `old_p` of `old_size`
465 // to `new_p` of `new_size`. Only memory of size `in_use_front` and
466 // `in_use_back` will be copied from the front and back of the old memory
468 void memcpy_downward(uint8_t *old_p, size_t old_size,
469 uint8_t *new_p, size_t new_size,
470 size_t in_use_back, size_t in_use_front) {
471 memcpy(new_p + new_size - in_use_back, old_p + old_size - in_use_back,
473 memcpy(new_p, old_p, in_use_front);
477 // DefaultAllocator uses new/delete to allocate memory regions
478 class DefaultAllocator : public Allocator {
480 uint8_t *allocate(size_t size) FLATBUFFERS_OVERRIDE {
481 return new uint8_t[size];
484 void deallocate(uint8_t *p, size_t) FLATBUFFERS_OVERRIDE {
488 static void dealloc(void *p, size_t) {
489 delete[] static_cast<uint8_t *>(p);
493 // These functions allow for a null allocator to mean use the default allocator,
494 // as used by DetachedBuffer and vector_downward below.
495 // This is to avoid having a statically or dynamically allocated default
496 // allocator, or having to move it between the classes that may own it.
497 inline uint8_t *Allocate(Allocator *allocator, size_t size) {
498 return allocator ? allocator->allocate(size)
499 : DefaultAllocator().allocate(size);
502 inline void Deallocate(Allocator *allocator, uint8_t *p, size_t size) {
503 if (allocator) allocator->deallocate(p, size);
504 else DefaultAllocator().deallocate(p, size);
507 inline uint8_t *ReallocateDownward(Allocator *allocator, uint8_t *old_p,
508 size_t old_size, size_t new_size,
509 size_t in_use_back, size_t in_use_front) {
511 ? allocator->reallocate_downward(old_p, old_size, new_size,
512 in_use_back, in_use_front)
513 : DefaultAllocator().reallocate_downward(old_p, old_size, new_size,
514 in_use_back, in_use_front);
517 // DetachedBuffer is a finished flatbuffer memory region, detached from its
518 // builder. The original memory region and allocator are also stored so that
519 // the DetachedBuffer can manage the memory lifetime.
520 class DetachedBuffer {
523 : allocator_(nullptr),
524 own_allocator_(false),
530 DetachedBuffer(Allocator *allocator, bool own_allocator, uint8_t *buf,
531 size_t reserved, uint8_t *cur, size_t sz)
532 : allocator_(allocator),
533 own_allocator_(own_allocator),
540 #if !defined(FLATBUFFERS_CPP98_STL)
542 DetachedBuffer(DetachedBuffer &&other)
543 : allocator_(other.allocator_),
544 own_allocator_(other.own_allocator_),
546 reserved_(other.reserved_),
552 #endif // !defined(FLATBUFFERS_CPP98_STL)
556 #if !defined(FLATBUFFERS_CPP98_STL)
558 DetachedBuffer &operator=(DetachedBuffer &&other) {
561 allocator_ = other.allocator_;
562 own_allocator_ = other.own_allocator_;
564 reserved_ = other.reserved_;
573 #endif // !defined(FLATBUFFERS_CPP98_STL)
576 ~DetachedBuffer() { destroy(); }
578 const uint8_t *data() const { return cur_; }
580 uint8_t *data() { return cur_; }
582 size_t size() const { return size_; }
585 #if 0 // disabled for now due to the ordering of classes in this header
587 bool Verify() const {
588 Verifier verifier(data(), size());
589 return verifier.Verify<T>(nullptr);
593 const T* GetRoot() const {
594 return flatbuffers::GetRoot<T>(data());
599 return flatbuffers::GetRoot<T>(data());
605 #if !defined(FLATBUFFERS_CPP98_STL)
607 // These may change access mode, leave these at end of public section
608 FLATBUFFERS_DELETE_FUNC(DetachedBuffer(const DetachedBuffer &other))
609 FLATBUFFERS_DELETE_FUNC(
610 DetachedBuffer &operator=(const DetachedBuffer &other))
612 #endif // !defined(FLATBUFFERS_CPP98_STL)
616 Allocator *allocator_;
623 inline void destroy() {
624 if (buf_) Deallocate(allocator_, buf_, reserved_);
625 if (own_allocator_ && allocator_) { delete allocator_; }
629 inline void reset() {
630 allocator_ = nullptr;
631 own_allocator_ = false;
639 // This is a minimal replication of std::vector<uint8_t> functionality,
640 // except growing from higher to lower addresses. i.e push_back() inserts data
641 // in the lowest address in the vector.
642 // Since this vector leaves the lower part unused, we support a "scratch-pad"
643 // that can be stored there for temporary data, to share the allocated space.
644 // Essentially, this supports 2 std::vectors in a single buffer.
645 class vector_downward {
647 explicit vector_downward(size_t initial_size,
648 Allocator *allocator,
650 size_t buffer_minalign)
651 : allocator_(allocator),
652 own_allocator_(own_allocator),
653 initial_size_(initial_size),
654 buffer_minalign_(buffer_minalign),
661 #if !defined(FLATBUFFERS_CPP98_STL)
662 vector_downward(vector_downward &&other)
664 vector_downward(vector_downward &other)
665 #endif // defined(FLATBUFFERS_CPP98_STL)
667 : allocator_(other.allocator_),
668 own_allocator_(other.own_allocator_),
669 initial_size_(other.initial_size_),
670 buffer_minalign_(other.buffer_minalign_),
671 reserved_(other.reserved_),
674 scratch_(other.scratch_) {
675 // No change in other.allocator_
676 // No change in other.initial_size_
677 // No change in other.buffer_minalign_
678 other.own_allocator_ = false;
680 other.buf_ = nullptr;
681 other.cur_ = nullptr;
682 other.scratch_ = nullptr;
686 #if !defined(FLATBUFFERS_CPP98_STL)
688 vector_downward &operator=(vector_downward &&other) {
689 // Move construct a temporary and swap idiom
690 vector_downward temp(std::move(other));
695 #endif // defined(FLATBUFFERS_CPP98_STL)
710 cur_ = buf_ + reserved_;
718 void clear_scratch() {
722 void clear_allocator() {
723 if (own_allocator_ && allocator_) { delete allocator_; }
724 allocator_ = nullptr;
725 own_allocator_ = false;
728 void clear_buffer() {
729 if (buf_) Deallocate(allocator_, buf_, reserved_);
733 // Relinquish the pointer to the caller.
734 uint8_t *release_raw(size_t &allocated_bytes, size_t &offset) {
736 allocated_bytes = reserved_;
737 offset = static_cast<size_t>(cur_ - buf_);
739 // release_raw only relinquishes the buffer ownership.
740 // Does not deallocate or reset the allocator. Destructor will do that.
746 // Relinquish the pointer to the caller.
747 DetachedBuffer release() {
748 // allocator ownership (if any) is transferred to DetachedBuffer.
749 DetachedBuffer fb(allocator_, own_allocator_, buf_, reserved_, cur_,
751 if (own_allocator_) {
752 allocator_ = nullptr;
753 own_allocator_ = false;
760 size_t ensure_space(size_t len) {
761 FLATBUFFERS_ASSERT(cur_ >= scratch_ && scratch_ >= buf_);
762 if (len > static_cast<size_t>(cur_ - scratch_)) { reallocate(len); }
763 // Beyond this, signed offsets may not have enough range:
764 // (FlatBuffers > 2GB not supported).
765 FLATBUFFERS_ASSERT(size() < FLATBUFFERS_MAX_BUFFER_SIZE);
769 inline uint8_t *make_space(size_t len) {
770 size_t space = ensure_space(len);
775 // Returns nullptr if using the DefaultAllocator.
776 Allocator *get_custom_allocator() { return allocator_; }
778 uoffset_t size() const {
779 return static_cast<uoffset_t>(reserved_ - (cur_ - buf_));
782 uoffset_t scratch_size() const {
783 return static_cast<uoffset_t>(scratch_ - buf_);
786 size_t capacity() const { return reserved_; }
788 uint8_t *data() const {
789 FLATBUFFERS_ASSERT(cur_);
793 uint8_t *scratch_data() const {
794 FLATBUFFERS_ASSERT(buf_);
798 uint8_t *scratch_end() const {
799 FLATBUFFERS_ASSERT(scratch_);
803 uint8_t *data_at(size_t offset) const { return buf_ + reserved_ - offset; }
805 void push(const uint8_t *bytes, size_t num) {
806 memcpy(make_space(num), bytes, num);
809 // Specialized version of push() that avoids memcpy call for small data.
810 template<typename T> void push_small(const T &little_endian_t) {
811 make_space(sizeof(T));
812 *reinterpret_cast<T *>(cur_) = little_endian_t;
815 template<typename T> void scratch_push_small(const T &t) {
816 ensure_space(sizeof(T));
817 *reinterpret_cast<T *>(scratch_) = t;
818 scratch_ += sizeof(T);
821 // fill() is most frequently called with small byte counts (<= 4),
822 // which is why we're using loops rather than calling memset.
823 void fill(size_t zero_pad_bytes) {
824 make_space(zero_pad_bytes);
825 for (size_t i = 0; i < zero_pad_bytes; i++) cur_[i] = 0;
828 // Version for when we know the size is larger.
829 void fill_big(size_t zero_pad_bytes) {
830 memset(make_space(zero_pad_bytes), 0, zero_pad_bytes);
833 void pop(size_t bytes_to_remove) { cur_ += bytes_to_remove; }
834 void scratch_pop(size_t bytes_to_remove) { scratch_ -= bytes_to_remove; }
836 void swap(vector_downward &other) {
838 swap(allocator_, other.allocator_);
839 swap(own_allocator_, other.own_allocator_);
840 swap(initial_size_, other.initial_size_);
841 swap(buffer_minalign_, other.buffer_minalign_);
842 swap(reserved_, other.reserved_);
843 swap(buf_, other.buf_);
844 swap(cur_, other.cur_);
845 swap(scratch_, other.scratch_);
848 void swap_allocator(vector_downward &other) {
850 swap(allocator_, other.allocator_);
851 swap(own_allocator_, other.own_allocator_);
855 // You shouldn't really be copying instances of this class.
856 FLATBUFFERS_DELETE_FUNC(vector_downward(const vector_downward &))
857 FLATBUFFERS_DELETE_FUNC(vector_downward &operator=(const vector_downward &))
859 Allocator *allocator_;
861 size_t initial_size_;
862 size_t buffer_minalign_;
865 uint8_t *cur_; // Points at location between empty (below) and used (above).
866 uint8_t *scratch_; // Points to the end of the scratchpad in use.
868 void reallocate(size_t len) {
869 auto old_reserved = reserved_;
870 auto old_size = size();
871 auto old_scratch_size = scratch_size();
872 reserved_ += (std::max)(len,
873 old_reserved ? old_reserved / 2 : initial_size_);
874 reserved_ = (reserved_ + buffer_minalign_ - 1) & ~(buffer_minalign_ - 1);
876 buf_ = ReallocateDownward(allocator_, buf_, old_reserved, reserved_,
877 old_size, old_scratch_size);
879 buf_ = Allocate(allocator_, reserved_);
881 cur_ = buf_ + reserved_ - old_size;
882 scratch_ = buf_ + old_scratch_size;
886 // Converts a Field ID to a virtual table offset.
887 inline voffset_t FieldIndexToOffset(voffset_t field_id) {
888 // Should correspond to what EndTable() below builds up.
889 const int fixed_fields = 2; // Vtable size and Object Size.
890 return static_cast<voffset_t>((field_id + fixed_fields) * sizeof(voffset_t));
893 template<typename T, typename Alloc>
894 const T *data(const std::vector<T, Alloc> &v) {
895 return v.empty() ? nullptr : &v.front();
897 template<typename T, typename Alloc> T *data(std::vector<T, Alloc> &v) {
898 return v.empty() ? nullptr : &v.front();
903 /// @addtogroup flatbuffers_cpp_api
905 /// @class FlatBufferBuilder
906 /// @brief Helper class to hold data needed in creation of a FlatBuffer.
907 /// To serialize data, you typically call one of the `Create*()` functions in
908 /// the generated code, which in turn call a sequence of `StartTable`/
909 /// `PushElement`/`AddElement`/`EndTable`, or the builtin `CreateString`/
910 /// `CreateVector` functions. Do this is depth-first order to build up a tree to
911 /// the root. `Finish()` wraps up the buffer ready for transport.
912 class FlatBufferBuilder {
914 /// @brief Default constructor for FlatBufferBuilder.
915 /// @param[in] initial_size The initial size of the buffer, in bytes. Defaults
917 /// @param[in] allocator An `Allocator` to use. If null will use
918 /// `DefaultAllocator`.
919 /// @param[in] own_allocator Whether the builder/vector should own the
920 /// allocator. Defaults to / `false`.
921 /// @param[in] buffer_minalign Force the buffer to be aligned to the given
922 /// minimum alignment upon reallocation. Only needed if you intend to store
923 /// types with custom alignment AND you wish to read the buffer in-place
924 /// directly after creation.
925 explicit FlatBufferBuilder(size_t initial_size = 1024,
926 Allocator *allocator = nullptr,
927 bool own_allocator = false,
928 size_t buffer_minalign =
929 AlignOf<largest_scalar_t>())
930 : buf_(initial_size, allocator, own_allocator, buffer_minalign),
936 force_defaults_(false),
937 dedup_vtables_(true),
938 string_pool(nullptr) {
943 /// @brief Move constructor for FlatBufferBuilder.
944 #if !defined(FLATBUFFERS_CPP98_STL)
945 FlatBufferBuilder(FlatBufferBuilder &&other)
947 FlatBufferBuilder(FlatBufferBuilder &other)
948 #endif // #if !defined(FLATBUFFERS_CPP98_STL)
949 : buf_(1024, nullptr, false, AlignOf<largest_scalar_t>()),
955 force_defaults_(false),
956 dedup_vtables_(true),
957 string_pool(nullptr) {
959 // Default construct and swap idiom.
960 // Lack of delegating constructors in vs2010 makes it more verbose than needed.
966 #if !defined(FLATBUFFERS_CPP98_STL)
968 /// @brief Move assignment operator for FlatBufferBuilder.
969 FlatBufferBuilder &operator=(FlatBufferBuilder &&other) {
970 // Move construct a temporary and swap idiom
971 FlatBufferBuilder temp(std::move(other));
976 #endif // defined(FLATBUFFERS_CPP98_STL)
979 void Swap(FlatBufferBuilder &other) {
981 buf_.swap(other.buf_);
982 swap(num_field_loc, other.num_field_loc);
983 swap(max_voffset_, other.max_voffset_);
984 swap(nested, other.nested);
985 swap(finished, other.finished);
986 swap(minalign_, other.minalign_);
987 swap(force_defaults_, other.force_defaults_);
988 swap(dedup_vtables_, other.dedup_vtables_);
989 swap(string_pool, other.string_pool);
992 ~FlatBufferBuilder() {
993 if (string_pool) delete string_pool;
997 Clear(); // clear builder state
998 buf_.reset(); // deallocate buffer
1001 /// @brief Reset all the state in this FlatBufferBuilder so it can be reused
1002 /// to construct another buffer.
1009 if (string_pool) string_pool->clear();
1012 /// @brief The current size of the serialized buffer, counting from the end.
1013 /// @return Returns an `uoffset_t` with the current size of the buffer.
1014 uoffset_t GetSize() const { return buf_.size(); }
1016 /// @brief Get the serialized buffer (after you call `Finish()`).
1017 /// @return Returns an `uint8_t` pointer to the FlatBuffer data inside the
1019 uint8_t *GetBufferPointer() const {
1024 /// @brief Get a pointer to an unfinished buffer.
1025 /// @return Returns a `uint8_t` pointer to the unfinished buffer.
1026 uint8_t *GetCurrentBufferPointer() const { return buf_.data(); }
1028 /// @brief Get the released pointer to the serialized buffer.
1029 /// @warning Do NOT attempt to use this FlatBufferBuilder afterwards!
1030 /// @return A `FlatBuffer` that owns the buffer and its allocator and
1031 /// behaves similar to a `unique_ptr` with a deleter.
1032 FLATBUFFERS_ATTRIBUTE(deprecated("use Release() instead")) DetachedBuffer
1033 ReleaseBufferPointer() {
1035 return buf_.release();
1038 /// @brief Get the released DetachedBuffer.
1039 /// @return A `DetachedBuffer` that owns the buffer and its allocator.
1040 DetachedBuffer Release() {
1042 return buf_.release();
1045 /// @brief Get the released pointer to the serialized buffer.
1046 /// @param The size of the memory block containing
1047 /// the serialized `FlatBuffer`.
1048 /// @param The offset from the released pointer where the finished
1049 /// `FlatBuffer` starts.
1050 /// @return A raw pointer to the start of the memory block containing
1051 /// the serialized `FlatBuffer`.
1052 /// @remark If the allocator is owned, it gets deleted when the destructor is called..
1053 uint8_t *ReleaseRaw(size_t &size, size_t &offset) {
1055 return buf_.release_raw(size, offset);
1058 /// @brief get the minimum alignment this buffer needs to be accessed
1059 /// properly. This is only known once all elements have been written (after
1060 /// you call Finish()). You can use this information if you need to embed
1061 /// a FlatBuffer in some other buffer, such that you can later read it
1062 /// without first having to copy it into its own buffer.
1063 size_t GetBufferMinAlignment() {
1068 /// @cond FLATBUFFERS_INTERNAL
1069 void Finished() const {
1070 // If you get this assert, you're attempting to get access a buffer
1071 // which hasn't been finished yet. Be sure to call
1072 // FlatBufferBuilder::Finish with your root table.
1073 // If you really need to access an unfinished buffer, call
1074 // GetCurrentBufferPointer instead.
1075 FLATBUFFERS_ASSERT(finished);
1079 /// @brief In order to save space, fields that are set to their default value
1080 /// don't get serialized into the buffer.
1081 /// @param[in] bool fd When set to `true`, always serializes default values that are set.
1082 /// Optional fields which are not set explicitly, will still not be serialized.
1083 void ForceDefaults(bool fd) { force_defaults_ = fd; }
1085 /// @brief By default vtables are deduped in order to save space.
1086 /// @param[in] bool dedup When set to `true`, dedup vtables.
1087 void DedupVtables(bool dedup) { dedup_vtables_ = dedup; }
1089 /// @cond FLATBUFFERS_INTERNAL
1090 void Pad(size_t num_bytes) { buf_.fill(num_bytes); }
1092 void TrackMinAlign(size_t elem_size) {
1093 if (elem_size > minalign_) minalign_ = elem_size;
1096 void Align(size_t elem_size) {
1097 TrackMinAlign(elem_size);
1098 buf_.fill(PaddingBytes(buf_.size(), elem_size));
1101 void PushFlatBuffer(const uint8_t *bytes, size_t size) {
1102 PushBytes(bytes, size);
1106 void PushBytes(const uint8_t *bytes, size_t size) { buf_.push(bytes, size); }
1108 void PopBytes(size_t amount) { buf_.pop(amount); }
1110 template<typename T> void AssertScalarT() {
1111 // The code assumes power of 2 sizes and endian-swap-ability.
1112 static_assert(flatbuffers::is_scalar<T>::value, "T must be a scalar type");
1115 // Write a single aligned scalar to the buffer
1116 template<typename T> uoffset_t PushElement(T element) {
1118 T litle_endian_element = EndianScalar(element);
1120 buf_.push_small(litle_endian_element);
1124 template<typename T> uoffset_t PushElement(Offset<T> off) {
1125 // Special case for offsets: see ReferTo below.
1126 return PushElement(ReferTo(off.o));
1129 // When writing fields, we track where they are, so we can create correct
1131 void TrackField(voffset_t field, uoffset_t off) {
1132 FieldLoc fl = { off, field };
1133 buf_.scratch_push_small(fl);
1135 max_voffset_ = (std::max)(max_voffset_, field);
1138 // Like PushElement, but additionally tracks the field this represents.
1139 template<typename T> void AddElement(voffset_t field, T e, T def) {
1140 // We don't serialize values equal to the default.
1141 if (IsTheSameAs(e, def) && !force_defaults_) return;
1142 auto off = PushElement(e);
1143 TrackField(field, off);
1146 template<typename T> void AddOffset(voffset_t field, Offset<T> off) {
1147 if (off.IsNull()) return; // Don't store.
1148 AddElement(field, ReferTo(off.o), static_cast<uoffset_t>(0));
1151 template<typename T> void AddStruct(voffset_t field, const T *structptr) {
1152 if (!structptr) return; // Default, don't store.
1153 Align(AlignOf<T>());
1154 buf_.push_small(*structptr);
1155 TrackField(field, GetSize());
1158 void AddStructOffset(voffset_t field, uoffset_t off) {
1159 TrackField(field, off);
1162 // Offsets initially are relative to the end of the buffer (downwards).
1163 // This function converts them to be relative to the current location
1164 // in the buffer (when stored here), pointing upwards.
1165 uoffset_t ReferTo(uoffset_t off) {
1166 // Align to ensure GetSize() below is correct.
1167 Align(sizeof(uoffset_t));
1168 // Offset must refer to something already in buffer.
1169 FLATBUFFERS_ASSERT(off && off <= GetSize());
1170 return GetSize() - off + static_cast<uoffset_t>(sizeof(uoffset_t));
1174 // If you hit this, you're trying to construct a Table/Vector/String
1175 // during the construction of its parent table (between the MyTableBuilder
1176 // and table.Finish().
1177 // Move the creation of these sub-objects to above the MyTableBuilder to
1178 // not get this assert.
1179 // Ignoring this assert may appear to work in simple cases, but the reason
1180 // it is here is that storing objects in-line may cause vtable offsets
1181 // to not fit anymore. It also leads to vtable duplication.
1182 FLATBUFFERS_ASSERT(!nested);
1183 // If you hit this, fields were added outside the scope of a table.
1184 FLATBUFFERS_ASSERT(!num_field_loc);
1187 // From generated code (or from the parser), we call StartTable/EndTable
1188 // with a sequence of AddElement calls in between.
1189 uoffset_t StartTable() {
1195 // This finishes one serialized object by generating the vtable if it's a
1196 // table, comparing it against existing vtables, and writing the
1197 // resulting vtable offset.
1198 uoffset_t EndTable(uoffset_t start) {
1199 // If you get this assert, a corresponding StartTable wasn't called.
1200 FLATBUFFERS_ASSERT(nested);
1201 // Write the vtable offset, which is the start of any Table.
1202 // We fill it's value later.
1203 auto vtableoffsetloc = PushElement<soffset_t>(0);
1204 // Write a vtable, which consists entirely of voffset_t elements.
1205 // It starts with the number of offsets, followed by a type id, followed
1206 // by the offsets themselves. In reverse:
1207 // Include space for the last offset and ensure empty tables have a
1210 (std::max)(static_cast<voffset_t>(max_voffset_ + sizeof(voffset_t)),
1211 FieldIndexToOffset(0));
1212 buf_.fill_big(max_voffset_);
1213 auto table_object_size = vtableoffsetloc - start;
1214 // Vtable use 16bit offsets.
1215 FLATBUFFERS_ASSERT(table_object_size < 0x10000);
1216 WriteScalar<voffset_t>(buf_.data() + sizeof(voffset_t),
1217 static_cast<voffset_t>(table_object_size));
1218 WriteScalar<voffset_t>(buf_.data(), max_voffset_);
1219 // Write the offsets into the table
1220 for (auto it = buf_.scratch_end() - num_field_loc * sizeof(FieldLoc);
1221 it < buf_.scratch_end(); it += sizeof(FieldLoc)) {
1222 auto field_location = reinterpret_cast<FieldLoc *>(it);
1223 auto pos = static_cast<voffset_t>(vtableoffsetloc - field_location->off);
1224 // If this asserts, it means you've set a field twice.
1226 !ReadScalar<voffset_t>(buf_.data() + field_location->id));
1227 WriteScalar<voffset_t>(buf_.data() + field_location->id, pos);
1230 auto vt1 = reinterpret_cast<voffset_t *>(buf_.data());
1231 auto vt1_size = ReadScalar<voffset_t>(vt1);
1232 auto vt_use = GetSize();
1233 // See if we already have generated a vtable with this exact same
1234 // layout before. If so, make it point to the old one, remove this one.
1235 if (dedup_vtables_) {
1236 for (auto it = buf_.scratch_data(); it < buf_.scratch_end();
1237 it += sizeof(uoffset_t)) {
1238 auto vt_offset_ptr = reinterpret_cast<uoffset_t *>(it);
1239 auto vt2 = reinterpret_cast<voffset_t *>(buf_.data_at(*vt_offset_ptr));
1240 auto vt2_size = *vt2;
1241 if (vt1_size != vt2_size || 0 != memcmp(vt2, vt1, vt1_size)) continue;
1242 vt_use = *vt_offset_ptr;
1243 buf_.pop(GetSize() - vtableoffsetloc);
1247 // If this is a new vtable, remember it.
1248 if (vt_use == GetSize()) { buf_.scratch_push_small(vt_use); }
1249 // Fill the vtable offset we created above.
1250 // The offset points from the beginning of the object to where the
1251 // vtable is stored.
1252 // Offsets default direction is downward in memory for future format
1253 // flexibility (storing all vtables at the start of the file).
1254 WriteScalar(buf_.data_at(vtableoffsetloc),
1255 static_cast<soffset_t>(vt_use) -
1256 static_cast<soffset_t>(vtableoffsetloc));
1259 return vtableoffsetloc;
1262 FLATBUFFERS_ATTRIBUTE(deprecated("call the version above instead"))
1263 uoffset_t EndTable(uoffset_t start, voffset_t /*numfields*/) {
1264 return EndTable(start);
1267 // This checks a required field has been set in a given table that has
1268 // just been constructed.
1269 template<typename T> void Required(Offset<T> table, voffset_t field);
1271 uoffset_t StartStruct(size_t alignment) {
1276 uoffset_t EndStruct() { return GetSize(); }
1278 void ClearOffsets() {
1279 buf_.scratch_pop(num_field_loc * sizeof(FieldLoc));
1284 // Aligns such that when "len" bytes are written, an object can be written
1285 // after it with "alignment" without padding.
1286 void PreAlign(size_t len, size_t alignment) {
1287 TrackMinAlign(alignment);
1288 buf_.fill(PaddingBytes(GetSize() + len, alignment));
1290 template<typename T> void PreAlign(size_t len) {
1292 PreAlign(len, sizeof(T));
1296 /// @brief Store a string in the buffer, which can contain any binary data.
1297 /// @param[in] str A const char pointer to the data to be stored as a string.
1298 /// @param[in] len The number of bytes that should be stored from `str`.
1299 /// @return Returns the offset in the buffer where the string starts.
1300 Offset<String> CreateString(const char *str, size_t len) {
1302 PreAlign<uoffset_t>(len + 1); // Always 0-terminated.
1304 PushBytes(reinterpret_cast<const uint8_t *>(str), len);
1305 PushElement(static_cast<uoffset_t>(len));
1306 return Offset<String>(GetSize());
1309 /// @brief Store a string in the buffer, which is null-terminated.
1310 /// @param[in] str A const char pointer to a C-string to add to the buffer.
1311 /// @return Returns the offset in the buffer where the string starts.
1312 Offset<String> CreateString(const char *str) {
1313 return CreateString(str, strlen(str));
1316 /// @brief Store a string in the buffer, which is null-terminated.
1317 /// @param[in] str A char pointer to a C-string to add to the buffer.
1318 /// @return Returns the offset in the buffer where the string starts.
1319 Offset<String> CreateString(char *str) {
1320 return CreateString(str, strlen(str));
1323 /// @brief Store a string in the buffer, which can contain any binary data.
1324 /// @param[in] str A const reference to a std::string to store in the buffer.
1325 /// @return Returns the offset in the buffer where the string starts.
1326 Offset<String> CreateString(const std::string &str) {
1327 return CreateString(str.c_str(), str.length());
1331 #ifdef FLATBUFFERS_HAS_STRING_VIEW
1332 /// @brief Store a string in the buffer, which can contain any binary data.
1333 /// @param[in] str A const string_view to copy in to the buffer.
1334 /// @return Returns the offset in the buffer where the string starts.
1335 Offset<String> CreateString(flatbuffers::string_view str) {
1336 return CreateString(str.data(), str.size());
1338 #endif // FLATBUFFERS_HAS_STRING_VIEW
1341 /// @brief Store a string in the buffer, which can contain any binary data.
1342 /// @param[in] str A const pointer to a `String` struct to add to the buffer.
1343 /// @return Returns the offset in the buffer where the string starts
1344 Offset<String> CreateString(const String *str) {
1345 return str ? CreateString(str->c_str(), str->size()) : 0;
1348 /// @brief Store a string in the buffer, which can contain any binary data.
1349 /// @param[in] str A const reference to a std::string like type with support
1350 /// of T::c_str() and T::length() to store in the buffer.
1351 /// @return Returns the offset in the buffer where the string starts.
1352 template<typename T> Offset<String> CreateString(const T &str) {
1353 return CreateString(str.c_str(), str.length());
1356 /// @brief Store a string in the buffer, which can contain any binary data.
1357 /// If a string with this exact contents has already been serialized before,
1358 /// instead simply returns the offset of the existing string.
1359 /// @param[in] str A const char pointer to the data to be stored as a string.
1360 /// @param[in] len The number of bytes that should be stored from `str`.
1361 /// @return Returns the offset in the buffer where the string starts.
1362 Offset<String> CreateSharedString(const char *str, size_t len) {
1364 string_pool = new StringOffsetMap(StringOffsetCompare(buf_));
1365 auto size_before_string = buf_.size();
1366 // Must first serialize the string, since the set is all offsets into
1368 auto off = CreateString(str, len);
1369 auto it = string_pool->find(off);
1370 // If it exists we reuse existing serialized data!
1371 if (it != string_pool->end()) {
1372 // We can remove the string we serialized.
1373 buf_.pop(buf_.size() - size_before_string);
1376 // Record this string for future use.
1377 string_pool->insert(off);
1381 /// @brief Store a string in the buffer, which null-terminated.
1382 /// If a string with this exact contents has already been serialized before,
1383 /// instead simply returns the offset of the existing string.
1384 /// @param[in] str A const char pointer to a C-string to add to the buffer.
1385 /// @return Returns the offset in the buffer where the string starts.
1386 Offset<String> CreateSharedString(const char *str) {
1387 return CreateSharedString(str, strlen(str));
1390 /// @brief Store a string in the buffer, which can contain any binary data.
1391 /// If a string with this exact contents has already been serialized before,
1392 /// instead simply returns the offset of the existing string.
1393 /// @param[in] str A const reference to a std::string to store in the buffer.
1394 /// @return Returns the offset in the buffer where the string starts.
1395 Offset<String> CreateSharedString(const std::string &str) {
1396 return CreateSharedString(str.c_str(), str.length());
1399 /// @brief Store a string in the buffer, which can contain any binary data.
1400 /// If a string with this exact contents has already been serialized before,
1401 /// instead simply returns the offset of the existing string.
1402 /// @param[in] str A const pointer to a `String` struct to add to the buffer.
1403 /// @return Returns the offset in the buffer where the string starts
1404 Offset<String> CreateSharedString(const String *str) {
1405 return CreateSharedString(str->c_str(), str->size());
1408 /// @cond FLATBUFFERS_INTERNAL
1409 uoffset_t EndVector(size_t len) {
1410 FLATBUFFERS_ASSERT(nested); // Hit if no corresponding StartVector.
1412 return PushElement(static_cast<uoffset_t>(len));
1415 void StartVector(size_t len, size_t elemsize) {
1418 PreAlign<uoffset_t>(len * elemsize);
1419 PreAlign(len * elemsize, elemsize); // Just in case elemsize > uoffset_t.
1422 // Call this right before StartVector/CreateVector if you want to force the
1423 // alignment to be something different than what the element size would
1424 // normally dictate.
1425 // This is useful when storing a nested_flatbuffer in a vector of bytes,
1426 // or when storing SIMD floats, etc.
1427 void ForceVectorAlignment(size_t len, size_t elemsize, size_t alignment) {
1428 PreAlign(len * elemsize, alignment);
1431 // Similar to ForceVectorAlignment but for String fields.
1432 void ForceStringAlignment(size_t len, size_t alignment) {
1433 PreAlign((len + 1) * sizeof(char), alignment);
1438 /// @brief Serialize an array into a FlatBuffer `vector`.
1439 /// @tparam T The data type of the array elements.
1440 /// @param[in] v A pointer to the array of type `T` to serialize into the
1441 /// buffer as a `vector`.
1442 /// @param[in] len The number of elements to serialize.
1443 /// @return Returns a typed `Offset` into the serialized data indicating
1444 /// where the vector is stored.
1445 template<typename T> Offset<Vector<T>> CreateVector(const T *v, size_t len) {
1446 // If this assert hits, you're specifying a template argument that is
1447 // causing the wrong overload to be selected, remove it.
1449 StartVector(len, sizeof(T));
1451 #if FLATBUFFERS_LITTLEENDIAN
1452 PushBytes(reinterpret_cast<const uint8_t *>(v), len * sizeof(T));
1454 if (sizeof(T) == 1) {
1455 PushBytes(reinterpret_cast<const uint8_t *>(v), len);
1457 for (auto i = len; i > 0; ) {
1458 PushElement(v[--i]);
1463 return Offset<Vector<T>>(EndVector(len));
1466 template<typename T>
1467 Offset<Vector<Offset<T>>> CreateVector(const Offset<T> *v, size_t len) {
1468 StartVector(len, sizeof(Offset<T>));
1469 for (auto i = len; i > 0;) { PushElement(v[--i]); }
1470 return Offset<Vector<Offset<T>>>(EndVector(len));
1473 /// @brief Serialize a `std::vector` into a FlatBuffer `vector`.
1474 /// @tparam T The data type of the `std::vector` elements.
1475 /// @param v A const reference to the `std::vector` to serialize into the
1476 /// buffer as a `vector`.
1477 /// @return Returns a typed `Offset` into the serialized data indicating
1478 /// where the vector is stored.
1479 template<typename T> Offset<Vector<T>> CreateVector(const std::vector<T> &v) {
1480 return CreateVector(data(v), v.size());
1483 // vector<bool> may be implemented using a bit-set, so we can't access it as
1484 // an array. Instead, read elements manually.
1485 // Background: https://isocpp.org/blog/2012/11/on-vectorbool
1486 Offset<Vector<uint8_t>> CreateVector(const std::vector<bool> &v) {
1487 StartVector(v.size(), sizeof(uint8_t));
1488 for (auto i = v.size(); i > 0;) {
1489 PushElement(static_cast<uint8_t>(v[--i]));
1491 return Offset<Vector<uint8_t>>(EndVector(v.size()));
1495 #ifndef FLATBUFFERS_CPP98_STL
1496 /// @brief Serialize values returned by a function into a FlatBuffer `vector`.
1497 /// This is a convenience function that takes care of iteration for you.
1498 /// @tparam T The data type of the `std::vector` elements.
1499 /// @param f A function that takes the current iteration 0..vector_size-1 and
1500 /// returns any type that you can construct a FlatBuffers vector out of.
1501 /// @return Returns a typed `Offset` into the serialized data indicating
1502 /// where the vector is stored.
1503 template<typename T> Offset<Vector<T>> CreateVector(size_t vector_size,
1504 const std::function<T (size_t i)> &f) {
1505 std::vector<T> elems(vector_size);
1506 for (size_t i = 0; i < vector_size; i++) elems[i] = f(i);
1507 return CreateVector(elems);
1512 /// @brief Serialize values returned by a function into a FlatBuffer `vector`.
1513 /// This is a convenience function that takes care of iteration for you.
1514 /// @tparam T The data type of the `std::vector` elements.
1515 /// @param f A function that takes the current iteration 0..vector_size-1,
1516 /// and the state parameter returning any type that you can construct a
1517 /// FlatBuffers vector out of.
1518 /// @param state State passed to f.
1519 /// @return Returns a typed `Offset` into the serialized data indicating
1520 /// where the vector is stored.
1521 template<typename T, typename F, typename S>
1522 Offset<Vector<T>> CreateVector(size_t vector_size, F f, S *state) {
1523 std::vector<T> elems(vector_size);
1524 for (size_t i = 0; i < vector_size; i++) elems[i] = f(i, state);
1525 return CreateVector(elems);
1528 /// @brief Serialize a `std::vector<std::string>` into a FlatBuffer `vector`.
1529 /// This is a convenience function for a common case.
1530 /// @param v A const reference to the `std::vector` to serialize into the
1531 /// buffer as a `vector`.
1532 /// @return Returns a typed `Offset` into the serialized data indicating
1533 /// where the vector is stored.
1534 Offset<Vector<Offset<String>>> CreateVectorOfStrings(
1535 const std::vector<std::string> &v) {
1536 std::vector<Offset<String>> offsets(v.size());
1537 for (size_t i = 0; i < v.size(); i++) offsets[i] = CreateString(v[i]);
1538 return CreateVector(offsets);
1541 /// @brief Serialize an array of structs into a FlatBuffer `vector`.
1542 /// @tparam T The data type of the struct array elements.
1543 /// @param[in] v A pointer to the array of type `T` to serialize into the
1544 /// buffer as a `vector`.
1545 /// @param[in] len The number of elements to serialize.
1546 /// @return Returns a typed `Offset` into the serialized data indicating
1547 /// where the vector is stored.
1548 template<typename T>
1549 Offset<Vector<const T *>> CreateVectorOfStructs(const T *v, size_t len) {
1550 StartVector(len * sizeof(T) / AlignOf<T>(), AlignOf<T>());
1551 PushBytes(reinterpret_cast<const uint8_t *>(v), sizeof(T) * len);
1552 return Offset<Vector<const T *>>(EndVector(len));
1555 /// @brief Serialize an array of native structs into a FlatBuffer `vector`.
1556 /// @tparam T The data type of the struct array elements.
1557 /// @tparam S The data type of the native struct array elements.
1558 /// @param[in] v A pointer to the array of type `S` to serialize into the
1559 /// buffer as a `vector`.
1560 /// @param[in] len The number of elements to serialize.
1561 /// @return Returns a typed `Offset` into the serialized data indicating
1562 /// where the vector is stored.
1563 template<typename T, typename S>
1564 Offset<Vector<const T *>> CreateVectorOfNativeStructs(const S *v,
1566 extern T Pack(const S &);
1567 typedef T (*Pack_t)(const S &);
1568 std::vector<T> vv(len);
1569 std::transform(v, v + len, vv.begin(), static_cast<Pack_t&>(Pack));
1570 return CreateVectorOfStructs<T>(vv.data(), vv.size());
1574 #ifndef FLATBUFFERS_CPP98_STL
1575 /// @brief Serialize an array of structs into a FlatBuffer `vector`.
1576 /// @tparam T The data type of the struct array elements.
1577 /// @param[in] f A function that takes the current iteration 0..vector_size-1
1578 /// and a pointer to the struct that must be filled.
1579 /// @return Returns a typed `Offset` into the serialized data indicating
1580 /// where the vector is stored.
1581 /// This is mostly useful when flatbuffers are generated with mutation
1583 template<typename T> Offset<Vector<const T *>> CreateVectorOfStructs(
1584 size_t vector_size, const std::function<void(size_t i, T *)> &filler) {
1585 T* structs = StartVectorOfStructs<T>(vector_size);
1586 for (size_t i = 0; i < vector_size; i++) {
1590 return EndVectorOfStructs<T>(vector_size);
1595 /// @brief Serialize an array of structs into a FlatBuffer `vector`.
1596 /// @tparam T The data type of the struct array elements.
1597 /// @param[in] f A function that takes the current iteration 0..vector_size-1,
1598 /// a pointer to the struct that must be filled and the state argument.
1599 /// @param[in] state Arbitrary state to pass to f.
1600 /// @return Returns a typed `Offset` into the serialized data indicating
1601 /// where the vector is stored.
1602 /// This is mostly useful when flatbuffers are generated with mutation
1604 template<typename T, typename F, typename S>
1605 Offset<Vector<const T *>> CreateVectorOfStructs(size_t vector_size, F f,
1607 T *structs = StartVectorOfStructs<T>(vector_size);
1608 for (size_t i = 0; i < vector_size; i++) {
1609 f(i, structs, state);
1612 return EndVectorOfStructs<T>(vector_size);
1615 /// @brief Serialize a `std::vector` of structs into a FlatBuffer `vector`.
1616 /// @tparam T The data type of the `std::vector` struct elements.
1617 /// @param[in]] v A const reference to the `std::vector` of structs to
1618 /// serialize into the buffer as a `vector`.
1619 /// @return Returns a typed `Offset` into the serialized data indicating
1620 /// where the vector is stored.
1621 template<typename T, typename Alloc>
1622 Offset<Vector<const T *>> CreateVectorOfStructs(
1623 const std::vector<T, Alloc> &v) {
1624 return CreateVectorOfStructs(data(v), v.size());
1627 /// @brief Serialize a `std::vector` of native structs into a FlatBuffer
1629 /// @tparam T The data type of the `std::vector` struct elements.
1630 /// @tparam S The data type of the `std::vector` native struct elements.
1631 /// @param[in]] v A const reference to the `std::vector` of structs to
1632 /// serialize into the buffer as a `vector`.
1633 /// @return Returns a typed `Offset` into the serialized data indicating
1634 /// where the vector is stored.
1635 template<typename T, typename S>
1636 Offset<Vector<const T *>> CreateVectorOfNativeStructs(
1637 const std::vector<S> &v) {
1638 return CreateVectorOfNativeStructs<T, S>(data(v), v.size());
1641 /// @cond FLATBUFFERS_INTERNAL
1642 template<typename T> struct StructKeyComparator {
1643 bool operator()(const T &a, const T &b) const {
1644 return a.KeyCompareLessThan(&b);
1648 StructKeyComparator &operator=(const StructKeyComparator &);
1652 /// @brief Serialize a `std::vector` of structs into a FlatBuffer `vector`
1653 /// in sorted order.
1654 /// @tparam T The data type of the `std::vector` struct elements.
1655 /// @param[in]] v A const reference to the `std::vector` of structs to
1656 /// serialize into the buffer as a `vector`.
1657 /// @return Returns a typed `Offset` into the serialized data indicating
1658 /// where the vector is stored.
1659 template<typename T>
1660 Offset<Vector<const T *>> CreateVectorOfSortedStructs(std::vector<T> *v) {
1661 return CreateVectorOfSortedStructs(data(*v), v->size());
1664 /// @brief Serialize a `std::vector` of native structs into a FlatBuffer
1665 /// `vector` in sorted order.
1666 /// @tparam T The data type of the `std::vector` struct elements.
1667 /// @tparam S The data type of the `std::vector` native struct elements.
1668 /// @param[in]] v A const reference to the `std::vector` of structs to
1669 /// serialize into the buffer as a `vector`.
1670 /// @return Returns a typed `Offset` into the serialized data indicating
1671 /// where the vector is stored.
1672 template<typename T, typename S>
1673 Offset<Vector<const T *>> CreateVectorOfSortedNativeStructs(
1674 std::vector<S> *v) {
1675 return CreateVectorOfSortedNativeStructs<T, S>(data(*v), v->size());
1678 /// @brief Serialize an array of structs into a FlatBuffer `vector` in sorted
1680 /// @tparam T The data type of the struct array elements.
1681 /// @param[in] v A pointer to the array of type `T` to serialize into the
1682 /// buffer as a `vector`.
1683 /// @param[in] len The number of elements to serialize.
1684 /// @return Returns a typed `Offset` into the serialized data indicating
1685 /// where the vector is stored.
1686 template<typename T>
1687 Offset<Vector<const T *>> CreateVectorOfSortedStructs(T *v, size_t len) {
1688 std::sort(v, v + len, StructKeyComparator<T>());
1689 return CreateVectorOfStructs(v, len);
1692 /// @brief Serialize an array of native structs into a FlatBuffer `vector` in
1694 /// @tparam T The data type of the struct array elements.
1695 /// @tparam S The data type of the native struct array elements.
1696 /// @param[in] v A pointer to the array of type `S` to serialize into the
1697 /// buffer as a `vector`.
1698 /// @param[in] len The number of elements to serialize.
1699 /// @return Returns a typed `Offset` into the serialized data indicating
1700 /// where the vector is stored.
1701 template<typename T, typename S>
1702 Offset<Vector<const T *>> CreateVectorOfSortedNativeStructs(S *v,
1704 extern T Pack(const S &);
1705 typedef T (*Pack_t)(const S &);
1706 std::vector<T> vv(len);
1707 std::transform(v, v + len, vv.begin(), static_cast<Pack_t&>(Pack));
1708 return CreateVectorOfSortedStructs<T>(vv, len);
1711 /// @cond FLATBUFFERS_INTERNAL
1712 template<typename T> struct TableKeyComparator {
1713 TableKeyComparator(vector_downward &buf) : buf_(buf) {}
1714 bool operator()(const Offset<T> &a, const Offset<T> &b) const {
1715 auto table_a = reinterpret_cast<T *>(buf_.data_at(a.o));
1716 auto table_b = reinterpret_cast<T *>(buf_.data_at(b.o));
1717 return table_a->KeyCompareLessThan(table_b);
1719 vector_downward &buf_;
1722 TableKeyComparator &operator=(const TableKeyComparator &);
1726 /// @brief Serialize an array of `table` offsets as a `vector` in the buffer
1727 /// in sorted order.
1728 /// @tparam T The data type that the offset refers to.
1729 /// @param[in] v An array of type `Offset<T>` that contains the `table`
1730 /// offsets to store in the buffer in sorted order.
1731 /// @param[in] len The number of elements to store in the `vector`.
1732 /// @return Returns a typed `Offset` into the serialized data indicating
1733 /// where the vector is stored.
1734 template<typename T>
1735 Offset<Vector<Offset<T>>> CreateVectorOfSortedTables(Offset<T> *v,
1737 std::sort(v, v + len, TableKeyComparator<T>(buf_));
1738 return CreateVector(v, len);
1741 /// @brief Serialize an array of `table` offsets as a `vector` in the buffer
1742 /// in sorted order.
1743 /// @tparam T The data type that the offset refers to.
1744 /// @param[in] v An array of type `Offset<T>` that contains the `table`
1745 /// offsets to store in the buffer in sorted order.
1746 /// @return Returns a typed `Offset` into the serialized data indicating
1747 /// where the vector is stored.
1748 template<typename T>
1749 Offset<Vector<Offset<T>>> CreateVectorOfSortedTables(
1750 std::vector<Offset<T>> *v) {
1751 return CreateVectorOfSortedTables(data(*v), v->size());
1754 /// @brief Specialized version of `CreateVector` for non-copying use cases.
1755 /// Write the data any time later to the returned buffer pointer `buf`.
1756 /// @param[in] len The number of elements to store in the `vector`.
1757 /// @param[in] elemsize The size of each element in the `vector`.
1758 /// @param[out] buf A pointer to a `uint8_t` pointer that can be
1759 /// written to at a later time to serialize the data into a `vector`
1761 uoffset_t CreateUninitializedVector(size_t len, size_t elemsize,
1764 StartVector(len, elemsize);
1765 buf_.make_space(len * elemsize);
1766 auto vec_start = GetSize();
1767 auto vec_end = EndVector(len);
1768 *buf = buf_.data_at(vec_start);
1772 /// @brief Specialized version of `CreateVector` for non-copying use cases.
1773 /// Write the data any time later to the returned buffer pointer `buf`.
1774 /// @tparam T The data type of the data that will be stored in the buffer
1776 /// @param[in] len The number of elements to store in the `vector`.
1777 /// @param[out] buf A pointer to a pointer of type `T` that can be
1778 /// written to at a later time to serialize the data into a `vector`
1780 template<typename T>
1781 Offset<Vector<T>> CreateUninitializedVector(size_t len, T **buf) {
1783 return CreateUninitializedVector(len, sizeof(T),
1784 reinterpret_cast<uint8_t **>(buf));
1787 template<typename T>
1788 Offset<Vector<const T*>> CreateUninitializedVectorOfStructs(size_t len, T **buf) {
1789 return CreateUninitializedVector(len, sizeof(T),
1790 reinterpret_cast<uint8_t **>(buf));
1794 // @brief Create a vector of scalar type T given as input a vector of scalar
1795 // type U, useful with e.g. pre "enum class" enums, or any existing scalar
1796 // data of the wrong type.
1797 template<typename T, typename U>
1798 Offset<Vector<T>> CreateVectorScalarCast(const U *v, size_t len) {
1801 StartVector(len, sizeof(T));
1802 for (auto i = len; i > 0;) { PushElement(static_cast<T>(v[--i])); }
1803 return Offset<Vector<T>>(EndVector(len));
1806 /// @brief Write a struct by itself, typically to be part of a union.
1807 template<typename T> Offset<const T *> CreateStruct(const T &structobj) {
1809 Align(AlignOf<T>());
1810 buf_.push_small(structobj);
1811 return Offset<const T *>(GetSize());
1814 /// @brief The length of a FlatBuffer file header.
1815 static const size_t kFileIdentifierLength = 4;
1817 /// @brief Finish serializing a buffer by writing the root offset.
1818 /// @param[in] file_identifier If a `file_identifier` is given, the buffer
1819 /// will be prefixed with a standard FlatBuffers file header.
1820 template<typename T>
1821 void Finish(Offset<T> root, const char *file_identifier = nullptr) {
1822 Finish(root.o, file_identifier, false);
1825 /// @brief Finish a buffer with a 32 bit size field pre-fixed (size of the
1826 /// buffer following the size field). These buffers are NOT compatible
1827 /// with standard buffers created by Finish, i.e. you can't call GetRoot
1828 /// on them, you have to use GetSizePrefixedRoot instead.
1829 /// All >32 bit quantities in this buffer will be aligned when the whole
1830 /// size pre-fixed buffer is aligned.
1831 /// These kinds of buffers are useful for creating a stream of FlatBuffers.
1832 template<typename T>
1833 void FinishSizePrefixed(Offset<T> root,
1834 const char *file_identifier = nullptr) {
1835 Finish(root.o, file_identifier, true);
1838 void SwapBufAllocator(FlatBufferBuilder &other) {
1839 buf_.swap_allocator(other.buf_);
1844 // You shouldn't really be copying instances of this class.
1845 FlatBufferBuilder(const FlatBufferBuilder &);
1846 FlatBufferBuilder &operator=(const FlatBufferBuilder &);
1848 void Finish(uoffset_t root, const char *file_identifier, bool size_prefix) {
1850 buf_.clear_scratch();
1851 // This will cause the whole buffer to be aligned.
1852 PreAlign((size_prefix ? sizeof(uoffset_t) : 0) + sizeof(uoffset_t) +
1853 (file_identifier ? kFileIdentifierLength : 0),
1855 if (file_identifier) {
1856 FLATBUFFERS_ASSERT(strlen(file_identifier) == kFileIdentifierLength);
1857 PushBytes(reinterpret_cast<const uint8_t *>(file_identifier),
1858 kFileIdentifierLength);
1860 PushElement(ReferTo(root)); // Location of root.
1861 if (size_prefix) { PushElement(GetSize()); }
1870 vector_downward buf_;
1872 // Accumulating offsets of table members while it is being built.
1873 // We store these in the scratch pad of buf_, after the vtable offsets.
1874 uoffset_t num_field_loc;
1875 // Track how much of the vtable is in use, so we can output the most compact
1877 voffset_t max_voffset_;
1879 // Ensure objects are not nested.
1882 // Ensure the buffer is finished before it is being accessed.
1887 bool force_defaults_; // Serialize values equal to their defaults anyway.
1889 bool dedup_vtables_;
1891 struct StringOffsetCompare {
1892 StringOffsetCompare(const vector_downward &buf) : buf_(&buf) {}
1893 bool operator()(const Offset<String> &a, const Offset<String> &b) const {
1894 auto stra = reinterpret_cast<const String *>(buf_->data_at(a.o));
1895 auto strb = reinterpret_cast<const String *>(buf_->data_at(b.o));
1896 return StringLessThan(stra->data(), stra->size(),
1897 strb->data(), strb->size());
1899 const vector_downward *buf_;
1902 // For use with CreateSharedString. Instantiated on first use only.
1903 typedef std::set<Offset<String>, StringOffsetCompare> StringOffsetMap;
1904 StringOffsetMap *string_pool;
1907 // Allocates space for a vector of structures.
1908 // Must be completed with EndVectorOfStructs().
1909 template<typename T> T *StartVectorOfStructs(size_t vector_size) {
1910 StartVector(vector_size * sizeof(T) / AlignOf<T>(), AlignOf<T>());
1911 return reinterpret_cast<T *>(buf_.make_space(vector_size * sizeof(T)));
1914 // End the vector of structues in the flatbuffers.
1915 // Vector should have previously be started with StartVectorOfStructs().
1916 template<typename T>
1917 Offset<Vector<const T *>> EndVectorOfStructs(size_t vector_size) {
1918 return Offset<Vector<const T *>>(EndVector(vector_size));
1923 /// @cond FLATBUFFERS_INTERNAL
1924 // Helpers to get a typed pointer to the root object contained in the buffer.
1925 template<typename T> T *GetMutableRoot(void *buf) {
1927 return reinterpret_cast<T *>(
1928 reinterpret_cast<uint8_t *>(buf) +
1929 EndianScalar(*reinterpret_cast<uoffset_t *>(buf)));
1932 template<typename T> const T *GetRoot(const void *buf) {
1933 return GetMutableRoot<T>(const_cast<void *>(buf));
1936 template<typename T> const T *GetSizePrefixedRoot(const void *buf) {
1937 return GetRoot<T>(reinterpret_cast<const uint8_t *>(buf) + sizeof(uoffset_t));
1940 /// Helpers to get a typed pointer to objects that are currently being built.
1941 /// @warning Creating new objects will lead to reallocations and invalidates
1943 template<typename T>
1944 T *GetMutableTemporaryPointer(FlatBufferBuilder &fbb, Offset<T> offset) {
1945 return reinterpret_cast<T *>(fbb.GetCurrentBufferPointer() + fbb.GetSize() -
1949 template<typename T>
1950 const T *GetTemporaryPointer(FlatBufferBuilder &fbb, Offset<T> offset) {
1951 return GetMutableTemporaryPointer<T>(fbb, offset);
1954 /// @brief Get a pointer to the the file_identifier section of the buffer.
1955 /// @return Returns a const char pointer to the start of the file_identifier
1956 /// characters in the buffer. The returned char * has length
1957 /// 'flatbuffers::FlatBufferBuilder::kFileIdentifierLength'.
1958 /// This function is UNDEFINED for FlatBuffers whose schema does not include
1959 /// a file_identifier (likely points at padding or the start of a the root
1961 inline const char *GetBufferIdentifier(const void *buf, bool size_prefixed = false) {
1962 return reinterpret_cast<const char *>(buf) +
1963 ((size_prefixed) ? 2 * sizeof(uoffset_t) : sizeof(uoffset_t));
1966 // Helper to see if the identifier in a buffer has the expected value.
1967 inline bool BufferHasIdentifier(const void *buf, const char *identifier, bool size_prefixed = false) {
1968 return strncmp(GetBufferIdentifier(buf, size_prefixed), identifier,
1969 FlatBufferBuilder::kFileIdentifierLength) == 0;
1972 // Helper class to verify the integrity of a FlatBuffer
1973 class Verifier FLATBUFFERS_FINAL_CLASS {
1975 Verifier(const uint8_t *buf, size_t buf_len, uoffset_t _max_depth = 64,
1976 uoffset_t _max_tables = 1000000, bool _check_alignment = true)
1980 max_depth_(_max_depth),
1982 max_tables_(_max_tables),
1984 check_alignment_(_check_alignment)
1986 FLATBUFFERS_ASSERT(size_ < FLATBUFFERS_MAX_BUFFER_SIZE);
1989 // Central location where any verification failures register.
1990 bool Check(bool ok) const {
1992 #ifdef FLATBUFFERS_DEBUG_VERIFICATION_FAILURE
1993 FLATBUFFERS_ASSERT(ok);
1995 #ifdef FLATBUFFERS_TRACK_VERIFIER_BUFFER_SIZE
2003 // Verify any range within the buffer.
2004 bool Verify(size_t elem, size_t elem_len) const {
2006 #ifdef FLATBUFFERS_TRACK_VERIFIER_BUFFER_SIZE
2007 auto upper_bound = elem + elem_len;
2008 if (upper_bound_ < upper_bound)
2009 upper_bound_ = upper_bound;
2012 return Check(elem_len < size_ && elem <= size_ - elem_len);
2015 template<typename T> bool VerifyAlignment(size_t elem) const {
2016 return (elem & (sizeof(T) - 1)) == 0 || !check_alignment_;
2019 // Verify a range indicated by sizeof(T).
2020 template<typename T> bool Verify(size_t elem) const {
2021 return VerifyAlignment<T>(elem) && Verify(elem, sizeof(T));
2024 // Verify relative to a known-good base pointer.
2025 bool Verify(const uint8_t *base, voffset_t elem_off, size_t elem_len) const {
2026 return Verify(static_cast<size_t>(base - buf_) + elem_off, elem_len);
2029 template<typename T> bool Verify(const uint8_t *base, voffset_t elem_off)
2031 return Verify(static_cast<size_t>(base - buf_) + elem_off, sizeof(T));
2034 // Verify a pointer (may be NULL) of a table type.
2035 template<typename T> bool VerifyTable(const T *table) {
2036 return !table || table->Verify(*this);
2039 // Verify a pointer (may be NULL) of any vector type.
2040 template<typename T> bool VerifyVector(const Vector<T> *vec) const {
2041 return !vec || VerifyVectorOrString(reinterpret_cast<const uint8_t *>(vec),
2045 // Verify a pointer (may be NULL) of a vector to struct.
2046 template<typename T> bool VerifyVector(const Vector<const T *> *vec) const {
2047 return VerifyVector(reinterpret_cast<const Vector<T> *>(vec));
2050 // Verify a pointer (may be NULL) to string.
2051 bool VerifyString(const String *str) const {
2054 (VerifyVectorOrString(reinterpret_cast<const uint8_t *>(str),
2056 Verify(end, 1) && // Must have terminator
2057 Check(buf_[end] == '\0')); // Terminating byte must be 0.
2060 // Common code between vectors and strings.
2061 bool VerifyVectorOrString(const uint8_t *vec, size_t elem_size,
2062 size_t *end = nullptr) const {
2063 auto veco = static_cast<size_t>(vec - buf_);
2064 // Check we can read the size field.
2065 if (!Verify<uoffset_t>(veco)) return false;
2066 // Check the whole array. If this is a string, the byte past the array
2068 auto size = ReadScalar<uoffset_t>(vec);
2069 auto max_elems = FLATBUFFERS_MAX_BUFFER_SIZE / elem_size;
2070 if (!Check(size < max_elems))
2071 return false; // Protect against byte_size overflowing.
2072 auto byte_size = sizeof(size) + elem_size * size;
2073 if (end) *end = veco + byte_size;
2074 return Verify(veco, byte_size);
2077 // Special case for string contents, after the above has been called.
2078 bool VerifyVectorOfStrings(const Vector<Offset<String>> *vec) const {
2080 for (uoffset_t i = 0; i < vec->size(); i++) {
2081 if (!VerifyString(vec->Get(i))) return false;
2087 // Special case for table contents, after the above has been called.
2088 template<typename T> bool VerifyVectorOfTables(const Vector<Offset<T>> *vec) {
2090 for (uoffset_t i = 0; i < vec->size(); i++) {
2091 if (!vec->Get(i)->Verify(*this)) return false;
2097 bool VerifyTableStart(const uint8_t *table) {
2098 // Check the vtable offset.
2099 auto tableo = static_cast<size_t>(table - buf_);
2100 if (!Verify<soffset_t>(tableo)) return false;
2101 // This offset may be signed, but doing the substraction unsigned always
2102 // gives the result we want.
2103 auto vtableo = tableo - static_cast<size_t>(ReadScalar<soffset_t>(table));
2104 // Check the vtable size field, then check vtable fits in its entirety.
2105 return VerifyComplexity() && Verify<voffset_t>(vtableo) &&
2106 VerifyAlignment<voffset_t>(ReadScalar<voffset_t>(buf_ + vtableo)) &&
2107 Verify(vtableo, ReadScalar<voffset_t>(buf_ + vtableo));
2110 template<typename T>
2111 bool VerifyBufferFromStart(const char *identifier, size_t start) {
2113 (size_ < 2 * sizeof(flatbuffers::uoffset_t) ||
2114 !BufferHasIdentifier(buf_ + start, identifier))) {
2118 // Call T::Verify, which must be in the generated code for this type.
2119 auto o = VerifyOffset(start);
2120 return o && reinterpret_cast<const T *>(buf_ + start + o)->Verify(*this)
2122 #ifdef FLATBUFFERS_TRACK_VERIFIER_BUFFER_SIZE
2123 && GetComputedSize()
2129 // Verify this whole buffer, starting with root type T.
2130 template<typename T> bool VerifyBuffer() { return VerifyBuffer<T>(nullptr); }
2132 template<typename T> bool VerifyBuffer(const char *identifier) {
2133 return VerifyBufferFromStart<T>(identifier, 0);
2136 template<typename T> bool VerifySizePrefixedBuffer(const char *identifier) {
2137 return Verify<uoffset_t>(0U) &&
2138 ReadScalar<uoffset_t>(buf_) == size_ - sizeof(uoffset_t) &&
2139 VerifyBufferFromStart<T>(identifier, sizeof(uoffset_t));
2142 uoffset_t VerifyOffset(size_t start) const {
2143 if (!Verify<uoffset_t>(start)) return 0;
2144 auto o = ReadScalar<uoffset_t>(buf_ + start);
2145 // May not point to itself.
2146 if (!Check(o != 0)) return 0;
2147 // Can't wrap around / buffers are max 2GB.
2148 if (!Check(static_cast<soffset_t>(o) >= 0)) return 0;
2149 // Must be inside the buffer to create a pointer from it (pointer outside
2151 if (!Verify(start + o, 1)) return 0;
2155 uoffset_t VerifyOffset(const uint8_t *base, voffset_t start) const {
2156 return VerifyOffset(static_cast<size_t>(base - buf_) + start);
2159 // Called at the start of a table to increase counters measuring data
2160 // structure depth and amount, and possibly bails out with false if
2161 // limits set by the constructor have been hit. Needs to be balanced
2163 bool VerifyComplexity() {
2166 return Check(depth_ <= max_depth_ && num_tables_ <= max_tables_);
2169 // Called at the end of a table to pop the depth count.
2175 // Returns the message size in bytes
2176 size_t GetComputedSize() const {
2178 #ifdef FLATBUFFERS_TRACK_VERIFIER_BUFFER_SIZE
2179 uintptr_t size = upper_bound_;
2180 // Align the size to uoffset_t
2181 size = (size - 1 + sizeof(uoffset_t)) & ~(sizeof(uoffset_t) - 1);
2182 return (size > size_) ? 0 : size;
2184 // Must turn on FLATBUFFERS_TRACK_VERIFIER_BUFFER_SIZE for this to work.
2186 FLATBUFFERS_ASSERT(false);
2193 const uint8_t *buf_;
2196 uoffset_t max_depth_;
2197 uoffset_t num_tables_;
2198 uoffset_t max_tables_;
2199 mutable size_t upper_bound_;
2200 bool check_alignment_;
2203 // Convenient way to bundle a buffer and its length, to pass it around
2204 // typed by its root.
2205 // A BufferRef does not own its buffer.
2206 struct BufferRefBase {}; // for std::is_base_of
2207 template<typename T> struct BufferRef : BufferRefBase {
2208 BufferRef() : buf(nullptr), len(0), must_free(false) {}
2209 BufferRef(uint8_t *_buf, uoffset_t _len)
2210 : buf(_buf), len(_len), must_free(false) {}
2213 if (must_free) free(buf);
2216 const T *GetRoot() const { return flatbuffers::GetRoot<T>(buf); }
2219 Verifier verifier(buf, len);
2220 return verifier.VerifyBuffer<T>(nullptr);
2228 // "structs" are flat structures that do not have an offset table, thus
2229 // always have all members present and do not support forwards/backwards
2230 // compatible extensions.
2232 class Struct FLATBUFFERS_FINAL_CLASS {
2234 template<typename T> T GetField(uoffset_t o) const {
2235 return ReadScalar<T>(&data_[o]);
2238 template<typename T> T GetStruct(uoffset_t o) const {
2239 return reinterpret_cast<T>(&data_[o]);
2242 const uint8_t *GetAddressOf(uoffset_t o) const { return &data_[o]; }
2243 uint8_t *GetAddressOf(uoffset_t o) { return &data_[o]; }
2249 // "tables" use an offset table (possibly shared) that allows fields to be
2250 // omitted and added at will, but uses an extra indirection to read.
2253 const uint8_t *GetVTable() const {
2254 return data_ - ReadScalar<soffset_t>(data_);
2257 // This gets the field offset for any of the functions below it, or 0
2258 // if the field was not present.
2259 voffset_t GetOptionalFieldOffset(voffset_t field) const {
2260 // The vtable offset is always at the start.
2261 auto vtable = GetVTable();
2262 // The first element is the size of the vtable (fields + type id + itself).
2263 auto vtsize = ReadScalar<voffset_t>(vtable);
2264 // If the field we're accessing is outside the vtable, we're reading older
2265 // data, so it's the same as if the offset was 0 (not present).
2266 return field < vtsize ? ReadScalar<voffset_t>(vtable + field) : 0;
2269 template<typename T> T GetField(voffset_t field, T defaultval) const {
2270 auto field_offset = GetOptionalFieldOffset(field);
2271 return field_offset ? ReadScalar<T>(data_ + field_offset) : defaultval;
2274 template<typename P> P GetPointer(voffset_t field) {
2275 auto field_offset = GetOptionalFieldOffset(field);
2276 auto p = data_ + field_offset;
2277 return field_offset ? reinterpret_cast<P>(p + ReadScalar<uoffset_t>(p))
2280 template<typename P> P GetPointer(voffset_t field) const {
2281 return const_cast<Table *>(this)->GetPointer<P>(field);
2284 template<typename P> P GetStruct(voffset_t field) const {
2285 auto field_offset = GetOptionalFieldOffset(field);
2286 auto p = const_cast<uint8_t *>(data_ + field_offset);
2287 return field_offset ? reinterpret_cast<P>(p) : nullptr;
2290 template<typename T> bool SetField(voffset_t field, T val, T def) {
2291 auto field_offset = GetOptionalFieldOffset(field);
2292 if (!field_offset) return IsTheSameAs(val, def);
2293 WriteScalar(data_ + field_offset, val);
2297 bool SetPointer(voffset_t field, const uint8_t *val) {
2298 auto field_offset = GetOptionalFieldOffset(field);
2299 if (!field_offset) return false;
2300 WriteScalar(data_ + field_offset,
2301 static_cast<uoffset_t>(val - (data_ + field_offset)));
2305 uint8_t *GetAddressOf(voffset_t field) {
2306 auto field_offset = GetOptionalFieldOffset(field);
2307 return field_offset ? data_ + field_offset : nullptr;
2309 const uint8_t *GetAddressOf(voffset_t field) const {
2310 return const_cast<Table *>(this)->GetAddressOf(field);
2313 bool CheckField(voffset_t field) const {
2314 return GetOptionalFieldOffset(field) != 0;
2317 // Verify the vtable of this table.
2318 // Call this once per table, followed by VerifyField once per field.
2319 bool VerifyTableStart(Verifier &verifier) const {
2320 return verifier.VerifyTableStart(data_);
2323 // Verify a particular field.
2324 template<typename T>
2325 bool VerifyField(const Verifier &verifier, voffset_t field) const {
2326 // Calling GetOptionalFieldOffset should be safe now thanks to
2328 auto field_offset = GetOptionalFieldOffset(field);
2329 // Check the actual field.
2330 return !field_offset || verifier.Verify<T>(data_, field_offset);
2333 // VerifyField for required fields.
2334 template<typename T>
2335 bool VerifyFieldRequired(const Verifier &verifier, voffset_t field) const {
2336 auto field_offset = GetOptionalFieldOffset(field);
2337 return verifier.Check(field_offset != 0) &&
2338 verifier.Verify<T>(data_, field_offset);
2341 // Versions for offsets.
2342 bool VerifyOffset(const Verifier &verifier, voffset_t field) const {
2343 auto field_offset = GetOptionalFieldOffset(field);
2344 return !field_offset || verifier.VerifyOffset(data_, field_offset);
2347 bool VerifyOffsetRequired(const Verifier &verifier, voffset_t field) const {
2348 auto field_offset = GetOptionalFieldOffset(field);
2349 return verifier.Check(field_offset != 0) &&
2350 verifier.VerifyOffset(data_, field_offset);
2354 // private constructor & copy constructor: you obtain instances of this
2355 // class by pointing to existing data only
2357 Table(const Table &other);
2362 template<typename T> void FlatBufferBuilder::Required(Offset<T> table,
2364 auto table_ptr = reinterpret_cast<const Table *>(buf_.data_at(table.o));
2365 bool ok = table_ptr->GetOptionalFieldOffset(field) != 0;
2366 // If this fails, the caller will show what field needs to be set.
2367 FLATBUFFERS_ASSERT(ok);
2371 /// @brief This can compute the start of a FlatBuffer from a root pointer, i.e.
2372 /// it is the opposite transformation of GetRoot().
2373 /// This may be useful if you want to pass on a root and have the recipient
2374 /// delete the buffer afterwards.
2375 inline const uint8_t *GetBufferStartFromRootPointer(const void *root) {
2376 auto table = reinterpret_cast<const Table *>(root);
2377 auto vtable = table->GetVTable();
2378 // Either the vtable is before the root or after the root.
2379 auto start = (std::min)(vtable, reinterpret_cast<const uint8_t *>(root));
2380 // Align to at least sizeof(uoffset_t).
2381 start = reinterpret_cast<const uint8_t *>(reinterpret_cast<uintptr_t>(start) &
2382 ~(sizeof(uoffset_t) - 1));
2383 // Additionally, there may be a file_identifier in the buffer, and the root
2384 // offset. The buffer may have been aligned to any size between
2385 // sizeof(uoffset_t) and FLATBUFFERS_MAX_ALIGNMENT (see "force_align").
2386 // Sadly, the exact alignment is only known when constructing the buffer,
2387 // since it depends on the presence of values with said alignment properties.
2388 // So instead, we simply look at the next uoffset_t values (root,
2389 // file_identifier, and alignment padding) to see which points to the root.
2390 // None of the other values can "impersonate" the root since they will either
2391 // be 0 or four ASCII characters.
2392 static_assert(FlatBufferBuilder::kFileIdentifierLength == sizeof(uoffset_t),
2393 "file_identifier is assumed to be the same size as uoffset_t");
2394 for (auto possible_roots = FLATBUFFERS_MAX_ALIGNMENT / sizeof(uoffset_t) + 1;
2395 possible_roots; possible_roots--) {
2396 start -= sizeof(uoffset_t);
2397 if (ReadScalar<uoffset_t>(start) + start ==
2398 reinterpret_cast<const uint8_t *>(root))
2401 // We didn't find the root, either the "root" passed isn't really a root,
2402 // or the buffer is corrupt.
2403 // Assert, because calling this function with bad data may cause reads
2404 // outside of buffer boundaries.
2405 FLATBUFFERS_ASSERT(false);
2409 /// @brief This return the prefixed size of a FlatBuffer.
2410 inline uoffset_t GetPrefixedSize(const uint8_t* buf){ return ReadScalar<uoffset_t>(buf); }
2412 // Base class for native objects (FlatBuffer data de-serialized into native
2413 // C++ data structures).
2414 // Contains no functionality, purely documentative.
2415 struct NativeTable {};
2417 /// @brief Function types to be used with resolving hashes into objects and
2418 /// back again. The resolver gets a pointer to a field inside an object API
2419 /// object that is of the type specified in the schema using the attribute
2420 /// `cpp_type` (it is thus important whatever you write to this address
2421 /// matches that type). The value of this field is initially null, so you
2422 /// may choose to implement a delayed binding lookup using this function
2423 /// if you wish. The resolver does the opposite lookup, for when the object
2424 /// is being serialized again.
2425 typedef uint64_t hash_value_t;
2427 #ifdef FLATBUFFERS_CPP98_STL
2428 typedef void (*resolver_function_t)(void **pointer_adr, hash_value_t hash);
2429 typedef hash_value_t (*rehasher_function_t)(void *pointer);
2431 typedef std::function<void (void **pointer_adr, hash_value_t hash)>
2432 resolver_function_t;
2433 typedef std::function<hash_value_t (void *pointer)> rehasher_function_t;
2437 // Helper function to test if a field is present, using any of the field
2438 // enums in the generated code.
2439 // `table` must be a generated table type. Since this is a template parameter,
2440 // this is not typechecked to be a subclass of Table, so beware!
2441 // Note: this function will return false for fields equal to the default
2442 // value, since they're not stored in the buffer (unless force_defaults was
2444 template<typename T>
2445 bool IsFieldPresent(const T *table, typename T::FlatBuffersVTableOffset field) {
2446 // Cast, since Table is a private baseclass of any table types.
2447 return reinterpret_cast<const Table *>(table)->CheckField(
2448 static_cast<voffset_t>(field));
2451 // Utility function for reverse lookups on the EnumNames*() functions
2452 // (in the generated C++ code)
2453 // names must be NULL terminated.
2454 inline int LookupEnum(const char **names, const char *name) {
2455 for (const char **p = names; *p; p++)
2456 if (!strcmp(*p, name)) return static_cast<int>(p - names);
2460 // These macros allow us to layout a struct with a guarantee that they'll end
2461 // up looking the same on different compilers and platforms.
2462 // It does this by disallowing the compiler to do any padding, and then
2463 // does padding itself by inserting extra padding fields that make every
2464 // element aligned to its own size.
2465 // Additionally, it manually sets the alignment of the struct as a whole,
2466 // which is typically its largest element, or a custom size set in the schema
2467 // by the force_align attribute.
2468 // These are used in the generated code only.
2471 #if defined(_MSC_VER)
2472 #define FLATBUFFERS_MANUALLY_ALIGNED_STRUCT(alignment) \
2474 struct __declspec(align(alignment))
2475 #define FLATBUFFERS_STRUCT_END(name, size) \
2477 static_assert(sizeof(name) == size, "compiler breaks packing rules")
2478 #elif defined(__GNUC__) || defined(__clang__)
2479 #define FLATBUFFERS_MANUALLY_ALIGNED_STRUCT(alignment) \
2480 _Pragma("pack(1)") \
2481 struct __attribute__((aligned(alignment)))
2482 #define FLATBUFFERS_STRUCT_END(name, size) \
2484 static_assert(sizeof(name) == size, "compiler breaks packing rules")
2486 #error Unknown compiler, please define structure alignment macros
2490 // Minimal reflection via code generation.
2491 // Besides full-fat reflection (see reflection.h) and parsing/printing by
2492 // loading schemas (see idl.h), we can also have code generation for mimimal
2493 // reflection data which allows pretty-printing and other uses without needing
2494 // a schema or a parser.
2495 // Generate code with --reflect-types (types only) or --reflect-names (names
2497 // See minireflect.h for utilities using this functionality.
2499 // These types are organized slightly differently as the ones in idl.h.
2500 enum SequenceType { ST_TABLE, ST_STRUCT, ST_UNION, ST_ENUM };
2502 // Scalars have the same order as in idl.h
2504 #define FLATBUFFERS_GEN_ELEMENTARY_TYPES(ET) \
2518 ET(ET_SEQUENCE) // See SequenceType.
2520 enum ElementaryType {
2521 #define FLATBUFFERS_ET(E) E,
2522 FLATBUFFERS_GEN_ELEMENTARY_TYPES(FLATBUFFERS_ET)
2523 #undef FLATBUFFERS_ET
2526 inline const char * const *ElementaryTypeNames() {
2527 static const char * const names[] = {
2528 #define FLATBUFFERS_ET(E) #E,
2529 FLATBUFFERS_GEN_ELEMENTARY_TYPES(FLATBUFFERS_ET)
2530 #undef FLATBUFFERS_ET
2536 // Basic type info cost just 16bits per field!
2538 uint16_t base_type : 4; // ElementaryType
2539 uint16_t is_vector : 1;
2540 int16_t sequence_ref : 11; // Index into type_refs below, or -1 for none.
2543 static_assert(sizeof(TypeCode) == 2, "TypeCode");
2547 // Signature of the static method present in each type.
2548 typedef const TypeTable *(*TypeFunction)();
2552 size_t num_elems; // of type_codes, values, names (but not type_refs).
2553 const TypeCode *type_codes; // num_elems count
2554 const TypeFunction *type_refs; // less than num_elems entries (see TypeCode).
2555 const int64_t *values; // Only set for non-consecutive enum/union or structs.
2556 const char * const *names; // Only set if compiled with --reflect-names.
2559 // String which identifies the current version of FlatBuffers.
2560 // flatbuffer_version_string is used by Google developers to identify which
2561 // applications uploaded to Google Play are using this library. This allows
2562 // the development team at Google to determine the popularity of the library.
2563 // How it works: Applications that are uploaded to the Google Play Store are
2564 // scanned for this version string. We track which applications are using it
2565 // to measure popularity. You are free to remove it (of course) but we would
2566 // appreciate if you left it in.
2568 // Weak linkage is culled by VS & doesn't work on cygwin.
2570 #if !defined(_WIN32) && !defined(__CYGWIN__)
2572 extern volatile __attribute__((weak)) const char *flatbuffer_version_string;
2573 volatile __attribute__((weak)) const char *flatbuffer_version_string =
2575 FLATBUFFERS_STRING(FLATBUFFERS_VERSION_MAJOR) "."
2576 FLATBUFFERS_STRING(FLATBUFFERS_VERSION_MINOR) "."
2577 FLATBUFFERS_STRING(FLATBUFFERS_VERSION_REVISION);
2579 #endif // !defined(_WIN32) && !defined(__CYGWIN__)
2581 #define FLATBUFFERS_DEFINE_BITMASK_OPERATORS(E, T)\
2582 inline E operator | (E lhs, E rhs){\
2583 return E(T(lhs) | T(rhs));\
2585 inline E operator & (E lhs, E rhs){\
2586 return E(T(lhs) & T(rhs));\
2588 inline E operator ^ (E lhs, E rhs){\
2589 return E(T(lhs) ^ T(rhs));\
2591 inline E operator ~ (E lhs){\
2594 inline E operator |= (E &lhs, E rhs){\
2598 inline E operator &= (E &lhs, E rhs){\
2602 inline E operator ^= (E &lhs, E rhs){\
2606 inline bool operator !(E rhs) \
2608 return !bool(T(rhs)); \
2611 } // namespace flatbuffers
2615 #endif // FLATBUFFERS_H_