flatbuffers.h 99 KB

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