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