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