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