flatbuffers.h 101 KB

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