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