flatbuffers.h 100 KB

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