flexbuffers.h 54 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631
  1. /*
  2. * Copyright 2017 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_FLEXBUFFERS_H_
  17. #define FLATBUFFERS_FLEXBUFFERS_H_
  18. #include <map>
  19. // Used to select STL variant.
  20. #include "flatbuffers/base.h"
  21. // We use the basic binary writing functions from the regular FlatBuffers.
  22. #include "flatbuffers/util.h"
  23. #ifdef _MSC_VER
  24. # include <intrin.h>
  25. #endif
  26. #if defined(_MSC_VER)
  27. # pragma warning(push)
  28. # pragma warning(disable : 4127) // C4127: conditional expression is constant
  29. #endif
  30. namespace flexbuffers {
  31. class Reference;
  32. class Map;
  33. // These are used in the lower 2 bits of a type field to determine the size of
  34. // the elements (and or size field) of the item pointed to (e.g. vector).
  35. enum BitWidth {
  36. BIT_WIDTH_8 = 0,
  37. BIT_WIDTH_16 = 1,
  38. BIT_WIDTH_32 = 2,
  39. BIT_WIDTH_64 = 3,
  40. };
  41. // These are used as the upper 6 bits of a type field to indicate the actual
  42. // type.
  43. enum Type {
  44. FBT_NULL = 0,
  45. FBT_INT = 1,
  46. FBT_UINT = 2,
  47. FBT_FLOAT = 3,
  48. // Types above stored inline, types below store an offset.
  49. FBT_KEY = 4,
  50. FBT_STRING = 5,
  51. FBT_INDIRECT_INT = 6,
  52. FBT_INDIRECT_UINT = 7,
  53. FBT_INDIRECT_FLOAT = 8,
  54. FBT_MAP = 9,
  55. FBT_VECTOR = 10, // Untyped.
  56. FBT_VECTOR_INT = 11, // Typed any size (stores no type table).
  57. FBT_VECTOR_UINT = 12,
  58. FBT_VECTOR_FLOAT = 13,
  59. FBT_VECTOR_KEY = 14,
  60. // DEPRECATED, use FBT_VECTOR or FBT_VECTOR_KEY instead.
  61. // Read test.cpp/FlexBuffersDeprecatedTest() for details on why.
  62. FBT_VECTOR_STRING_DEPRECATED = 15,
  63. FBT_VECTOR_INT2 = 16, // Typed tuple (no type table, no size field).
  64. FBT_VECTOR_UINT2 = 17,
  65. FBT_VECTOR_FLOAT2 = 18,
  66. FBT_VECTOR_INT3 = 19, // Typed triple (no type table, no size field).
  67. FBT_VECTOR_UINT3 = 20,
  68. FBT_VECTOR_FLOAT3 = 21,
  69. FBT_VECTOR_INT4 = 22, // Typed quad (no type table, no size field).
  70. FBT_VECTOR_UINT4 = 23,
  71. FBT_VECTOR_FLOAT4 = 24,
  72. FBT_BLOB = 25,
  73. FBT_BOOL = 26,
  74. FBT_VECTOR_BOOL =
  75. 36, // To Allow the same type of conversion of type to vector type
  76. };
  77. inline bool IsInline(Type t) { return t <= FBT_FLOAT || t == FBT_BOOL; }
  78. inline bool IsTypedVectorElementType(Type t) {
  79. return (t >= FBT_INT && t <= FBT_STRING) || t == FBT_BOOL;
  80. }
  81. inline bool IsTypedVector(Type t) {
  82. return (t >= FBT_VECTOR_INT && t <= FBT_VECTOR_STRING_DEPRECATED) ||
  83. t == FBT_VECTOR_BOOL;
  84. }
  85. inline bool IsFixedTypedVector(Type t) {
  86. return t >= FBT_VECTOR_INT2 && t <= FBT_VECTOR_FLOAT4;
  87. }
  88. inline Type ToTypedVector(Type t, size_t fixed_len = 0) {
  89. FLATBUFFERS_ASSERT(IsTypedVectorElementType(t));
  90. switch (fixed_len) {
  91. case 0: return static_cast<Type>(t - FBT_INT + FBT_VECTOR_INT);
  92. case 2: return static_cast<Type>(t - FBT_INT + FBT_VECTOR_INT2);
  93. case 3: return static_cast<Type>(t - FBT_INT + FBT_VECTOR_INT3);
  94. case 4: return static_cast<Type>(t - FBT_INT + FBT_VECTOR_INT4);
  95. default: FLATBUFFERS_ASSERT(0); return FBT_NULL;
  96. }
  97. }
  98. inline Type ToTypedVectorElementType(Type t) {
  99. FLATBUFFERS_ASSERT(IsTypedVector(t));
  100. return static_cast<Type>(t - FBT_VECTOR_INT + FBT_INT);
  101. }
  102. inline Type ToFixedTypedVectorElementType(Type t, uint8_t *len) {
  103. FLATBUFFERS_ASSERT(IsFixedTypedVector(t));
  104. auto fixed_type = t - FBT_VECTOR_INT2;
  105. *len = static_cast<uint8_t>(fixed_type / 3 +
  106. 2); // 3 types each, starting from length 2.
  107. return static_cast<Type>(fixed_type % 3 + FBT_INT);
  108. }
  109. // TODO: implement proper support for 8/16bit floats, or decide not to
  110. // support them.
  111. typedef int16_t half;
  112. typedef int8_t quarter;
  113. // TODO: can we do this without conditionals using intrinsics or inline asm
  114. // on some platforms? Given branch prediction the method below should be
  115. // decently quick, but it is the most frequently executed function.
  116. // We could do an (unaligned) 64-bit read if we ifdef out the platforms for
  117. // which that doesn't work (or where we'd read into un-owned memory).
  118. template<typename R, typename T1, typename T2, typename T4, typename T8>
  119. R ReadSizedScalar(const uint8_t *data, uint8_t byte_width) {
  120. return byte_width < 4
  121. ? (byte_width < 2
  122. ? static_cast<R>(flatbuffers::ReadScalar<T1>(data))
  123. : static_cast<R>(flatbuffers::ReadScalar<T2>(data)))
  124. : (byte_width < 8
  125. ? static_cast<R>(flatbuffers::ReadScalar<T4>(data))
  126. : static_cast<R>(flatbuffers::ReadScalar<T8>(data)));
  127. }
  128. inline int64_t ReadInt64(const uint8_t *data, uint8_t byte_width) {
  129. return ReadSizedScalar<int64_t, int8_t, int16_t, int32_t, int64_t>(
  130. data, byte_width);
  131. }
  132. inline uint64_t ReadUInt64(const uint8_t *data, uint8_t byte_width) {
  133. // This is the "hottest" function (all offset lookups use this), so worth
  134. // optimizing if possible.
  135. // TODO: GCC apparently replaces memcpy by a rep movsb, but only if count is a
  136. // constant, which here it isn't. Test if memcpy is still faster than
  137. // the conditionals in ReadSizedScalar. Can also use inline asm.
  138. // clang-format off
  139. #if defined(_MSC_VER) && (defined(_M_X64) || defined _M_IX86)
  140. uint64_t u = 0;
  141. __movsb(reinterpret_cast<uint8_t *>(&u),
  142. reinterpret_cast<const uint8_t *>(data), byte_width);
  143. return flatbuffers::EndianScalar(u);
  144. #else
  145. return ReadSizedScalar<uint64_t, uint8_t, uint16_t, uint32_t, uint64_t>(
  146. data, byte_width);
  147. #endif
  148. // clang-format on
  149. }
  150. inline double ReadDouble(const uint8_t *data, uint8_t byte_width) {
  151. return ReadSizedScalar<double, quarter, half, float, double>(data,
  152. byte_width);
  153. }
  154. inline const uint8_t *Indirect(const uint8_t *offset, uint8_t byte_width) {
  155. return offset - ReadUInt64(offset, byte_width);
  156. }
  157. template<typename T> const uint8_t *Indirect(const uint8_t *offset) {
  158. return offset - flatbuffers::ReadScalar<T>(offset);
  159. }
  160. inline BitWidth WidthU(uint64_t u) {
  161. #define FLATBUFFERS_GET_FIELD_BIT_WIDTH(value, width) \
  162. { \
  163. if (!((u) & ~((1ULL << (width)) - 1ULL))) return BIT_WIDTH_##width; \
  164. }
  165. FLATBUFFERS_GET_FIELD_BIT_WIDTH(u, 8);
  166. FLATBUFFERS_GET_FIELD_BIT_WIDTH(u, 16);
  167. FLATBUFFERS_GET_FIELD_BIT_WIDTH(u, 32);
  168. #undef FLATBUFFERS_GET_FIELD_BIT_WIDTH
  169. return BIT_WIDTH_64;
  170. }
  171. inline BitWidth WidthI(int64_t i) {
  172. auto u = static_cast<uint64_t>(i) << 1;
  173. return WidthU(i >= 0 ? u : ~u);
  174. }
  175. inline BitWidth WidthF(double f) {
  176. return static_cast<double>(static_cast<float>(f)) == f ? BIT_WIDTH_32
  177. : BIT_WIDTH_64;
  178. }
  179. // Base class of all types below.
  180. // Points into the data buffer and allows access to one type.
  181. class Object {
  182. public:
  183. Object(const uint8_t *data, uint8_t byte_width)
  184. : data_(data), byte_width_(byte_width) {}
  185. protected:
  186. const uint8_t *data_;
  187. uint8_t byte_width_;
  188. };
  189. // Object that has a size, obtained either from size prefix, or elsewhere.
  190. class Sized : public Object {
  191. public:
  192. // Size prefix.
  193. Sized(const uint8_t *data, uint8_t byte_width)
  194. : Object(data, byte_width), size_(read_size()) {}
  195. // Manual size.
  196. Sized(const uint8_t *data, uint8_t byte_width, size_t sz)
  197. : Object(data, byte_width), size_(sz) {}
  198. size_t size() const { return size_; }
  199. // Access size stored in `byte_width_` bytes before data_ pointer.
  200. size_t read_size() const {
  201. return static_cast<size_t>(ReadUInt64(data_ - byte_width_, byte_width_));
  202. }
  203. protected:
  204. size_t size_;
  205. };
  206. class String : public Sized {
  207. public:
  208. // Size prefix.
  209. String(const uint8_t *data, uint8_t byte_width) : Sized(data, byte_width) {}
  210. // Manual size.
  211. String(const uint8_t *data, uint8_t byte_width, size_t sz)
  212. : Sized(data, byte_width, sz) {}
  213. size_t length() const { return size(); }
  214. const char *c_str() const { return reinterpret_cast<const char *>(data_); }
  215. std::string str() const { return std::string(c_str(), size()); }
  216. static String EmptyString() {
  217. static const char *empty_string = "";
  218. return String(reinterpret_cast<const uint8_t *>(empty_string), 1, 0);
  219. }
  220. bool IsTheEmptyString() const { return data_ == EmptyString().data_; }
  221. };
  222. class Blob : public Sized {
  223. public:
  224. Blob(const uint8_t *data_buf, uint8_t byte_width)
  225. : Sized(data_buf, byte_width) {}
  226. static Blob EmptyBlob() {
  227. static const uint8_t empty_blob[] = { 0 /*len*/ };
  228. return Blob(empty_blob + 1, 1);
  229. }
  230. bool IsTheEmptyBlob() const { return data_ == EmptyBlob().data_; }
  231. const uint8_t *data() const { return data_; }
  232. };
  233. class Vector : public Sized {
  234. public:
  235. Vector(const uint8_t *data, uint8_t byte_width) : Sized(data, byte_width) {}
  236. Reference operator[](size_t i) const;
  237. static Vector EmptyVector() {
  238. static const uint8_t empty_vector[] = { 0 /*len*/ };
  239. return Vector(empty_vector + 1, 1);
  240. }
  241. bool IsTheEmptyVector() const { return data_ == EmptyVector().data_; }
  242. };
  243. class TypedVector : public Sized {
  244. public:
  245. TypedVector(const uint8_t *data, uint8_t byte_width, Type element_type)
  246. : Sized(data, byte_width), type_(element_type) {}
  247. Reference operator[](size_t i) const;
  248. static TypedVector EmptyTypedVector() {
  249. static const uint8_t empty_typed_vector[] = { 0 /*len*/ };
  250. return TypedVector(empty_typed_vector + 1, 1, FBT_INT);
  251. }
  252. bool IsTheEmptyVector() const {
  253. return data_ == TypedVector::EmptyTypedVector().data_;
  254. }
  255. Type ElementType() { return type_; }
  256. friend Reference;
  257. private:
  258. Type type_;
  259. friend Map;
  260. };
  261. class FixedTypedVector : public Object {
  262. public:
  263. FixedTypedVector(const uint8_t *data, uint8_t byte_width, Type element_type,
  264. uint8_t len)
  265. : Object(data, byte_width), type_(element_type), len_(len) {}
  266. Reference operator[](size_t i) const;
  267. static FixedTypedVector EmptyFixedTypedVector() {
  268. static const uint8_t fixed_empty_vector[] = { 0 /* unused */ };
  269. return FixedTypedVector(fixed_empty_vector, 1, FBT_INT, 0);
  270. }
  271. bool IsTheEmptyFixedTypedVector() const {
  272. return data_ == FixedTypedVector::EmptyFixedTypedVector().data_;
  273. }
  274. Type ElementType() { return type_; }
  275. uint8_t size() { return len_; }
  276. private:
  277. Type type_;
  278. uint8_t len_;
  279. };
  280. class Map : public Vector {
  281. public:
  282. Map(const uint8_t *data, uint8_t byte_width) : Vector(data, byte_width) {}
  283. Reference operator[](const char *key) const;
  284. Reference operator[](const std::string &key) const;
  285. Vector Values() const { return Vector(data_, byte_width_); }
  286. TypedVector Keys() const {
  287. const size_t num_prefixed_fields = 3;
  288. auto keys_offset = data_ - byte_width_ * num_prefixed_fields;
  289. return TypedVector(Indirect(keys_offset, byte_width_),
  290. static_cast<uint8_t>(
  291. ReadUInt64(keys_offset + byte_width_, byte_width_)),
  292. FBT_KEY);
  293. }
  294. static Map EmptyMap() {
  295. static const uint8_t empty_map[] = {
  296. 0 /*keys_len*/, 0 /*keys_offset*/, 1 /*keys_width*/, 0 /*len*/
  297. };
  298. return Map(empty_map + 4, 1);
  299. }
  300. bool IsTheEmptyMap() const { return data_ == EmptyMap().data_; }
  301. };
  302. template<typename T>
  303. void AppendToString(std::string &s, T &&v, bool keys_quoted) {
  304. s += "[ ";
  305. for (size_t i = 0; i < v.size(); i++) {
  306. if (i) s += ", ";
  307. v[i].ToString(true, keys_quoted, s);
  308. }
  309. s += " ]";
  310. }
  311. class Reference {
  312. public:
  313. Reference()
  314. : data_(nullptr),
  315. parent_width_(0),
  316. byte_width_(BIT_WIDTH_8),
  317. type_(FBT_NULL) {}
  318. Reference(const uint8_t *data, uint8_t parent_width, uint8_t byte_width,
  319. Type type)
  320. : data_(data),
  321. parent_width_(parent_width),
  322. byte_width_(byte_width),
  323. type_(type) {}
  324. Reference(const uint8_t *data, uint8_t parent_width, uint8_t packed_type)
  325. : data_(data), parent_width_(parent_width) {
  326. byte_width_ = 1U << static_cast<BitWidth>(packed_type & 3);
  327. type_ = static_cast<Type>(packed_type >> 2);
  328. }
  329. Type GetType() const { return type_; }
  330. bool IsNull() const { return type_ == FBT_NULL; }
  331. bool IsBool() const { return type_ == FBT_BOOL; }
  332. bool IsInt() const { return type_ == FBT_INT || type_ == FBT_INDIRECT_INT; }
  333. bool IsUInt() const {
  334. return type_ == FBT_UINT || type_ == FBT_INDIRECT_UINT;
  335. }
  336. bool IsIntOrUint() const { return IsInt() || IsUInt(); }
  337. bool IsFloat() const {
  338. return type_ == FBT_FLOAT || type_ == FBT_INDIRECT_FLOAT;
  339. }
  340. bool IsNumeric() const { return IsIntOrUint() || IsFloat(); }
  341. bool IsString() const { return type_ == FBT_STRING; }
  342. bool IsKey() const { return type_ == FBT_KEY; }
  343. bool IsVector() const { return type_ == FBT_VECTOR || type_ == FBT_MAP; }
  344. bool IsUntypedVector() const { return type_ == FBT_VECTOR; }
  345. bool IsTypedVector() const { return flexbuffers::IsTypedVector(type_); }
  346. bool IsFixedTypedVector() const {
  347. return flexbuffers::IsFixedTypedVector(type_);
  348. }
  349. bool IsAnyVector() const {
  350. return (IsTypedVector() || IsFixedTypedVector() || IsVector());
  351. }
  352. bool IsMap() const { return type_ == FBT_MAP; }
  353. bool IsBlob() const { return type_ == FBT_BLOB; }
  354. bool AsBool() const {
  355. return (type_ == FBT_BOOL ? ReadUInt64(data_, parent_width_)
  356. : AsUInt64()) != 0;
  357. }
  358. // Reads any type as a int64_t. Never fails, does most sensible conversion.
  359. // Truncates floats, strings are attempted to be parsed for a number,
  360. // vectors/maps return their size. Returns 0 if all else fails.
  361. int64_t AsInt64() const {
  362. if (type_ == FBT_INT) {
  363. // A fast path for the common case.
  364. return ReadInt64(data_, parent_width_);
  365. } else
  366. switch (type_) {
  367. case FBT_INDIRECT_INT: return ReadInt64(Indirect(), byte_width_);
  368. case FBT_UINT: return ReadUInt64(data_, parent_width_);
  369. case FBT_INDIRECT_UINT: return ReadUInt64(Indirect(), byte_width_);
  370. case FBT_FLOAT:
  371. return static_cast<int64_t>(ReadDouble(data_, parent_width_));
  372. case FBT_INDIRECT_FLOAT:
  373. return static_cast<int64_t>(ReadDouble(Indirect(), byte_width_));
  374. case FBT_NULL: return 0;
  375. case FBT_STRING: return flatbuffers::StringToInt(AsString().c_str());
  376. case FBT_VECTOR: return static_cast<int64_t>(AsVector().size());
  377. case FBT_BOOL: return ReadInt64(data_, parent_width_);
  378. default:
  379. // Convert other things to int.
  380. return 0;
  381. }
  382. }
  383. // TODO: could specialize these to not use AsInt64() if that saves
  384. // extension ops in generated code, and use a faster op than ReadInt64.
  385. int32_t AsInt32() const { return static_cast<int32_t>(AsInt64()); }
  386. int16_t AsInt16() const { return static_cast<int16_t>(AsInt64()); }
  387. int8_t AsInt8() const { return static_cast<int8_t>(AsInt64()); }
  388. uint64_t AsUInt64() const {
  389. if (type_ == FBT_UINT) {
  390. // A fast path for the common case.
  391. return ReadUInt64(data_, parent_width_);
  392. } else
  393. switch (type_) {
  394. case FBT_INDIRECT_UINT: return ReadUInt64(Indirect(), byte_width_);
  395. case FBT_INT: return ReadInt64(data_, parent_width_);
  396. case FBT_INDIRECT_INT: return ReadInt64(Indirect(), byte_width_);
  397. case FBT_FLOAT:
  398. return static_cast<uint64_t>(ReadDouble(data_, parent_width_));
  399. case FBT_INDIRECT_FLOAT:
  400. return static_cast<uint64_t>(ReadDouble(Indirect(), byte_width_));
  401. case FBT_NULL: return 0;
  402. case FBT_STRING: return flatbuffers::StringToUInt(AsString().c_str());
  403. case FBT_VECTOR: return static_cast<uint64_t>(AsVector().size());
  404. case FBT_BOOL: return ReadUInt64(data_, parent_width_);
  405. default:
  406. // Convert other things to uint.
  407. return 0;
  408. }
  409. }
  410. uint32_t AsUInt32() const { return static_cast<uint32_t>(AsUInt64()); }
  411. uint16_t AsUInt16() const { return static_cast<uint16_t>(AsUInt64()); }
  412. uint8_t AsUInt8() const { return static_cast<uint8_t>(AsUInt64()); }
  413. double AsDouble() const {
  414. if (type_ == FBT_FLOAT) {
  415. // A fast path for the common case.
  416. return ReadDouble(data_, parent_width_);
  417. } else
  418. switch (type_) {
  419. case FBT_INDIRECT_FLOAT: return ReadDouble(Indirect(), byte_width_);
  420. case FBT_INT:
  421. return static_cast<double>(ReadInt64(data_, parent_width_));
  422. case FBT_UINT:
  423. return static_cast<double>(ReadUInt64(data_, parent_width_));
  424. case FBT_INDIRECT_INT:
  425. return static_cast<double>(ReadInt64(Indirect(), byte_width_));
  426. case FBT_INDIRECT_UINT:
  427. return static_cast<double>(ReadUInt64(Indirect(), byte_width_));
  428. case FBT_NULL: return 0.0;
  429. case FBT_STRING: {
  430. #if 1
  431. #pragma GCC diagnostic push
  432. #pragma GCC diagnostic ignored "-Wnull-dereference"
  433. // TODO(b/173239141): Patched via micro/tools/make/flexbuffers_download.sh
  434. // Introduce a segfault for an unsupported code path for TFLM.
  435. return *(static_cast<double*>(nullptr));
  436. #pragma GCC diagnostic pop
  437. #else
  438. // This is the original code
  439. double d;
  440. flatbuffers::StringToNumber(AsString().c_str(), &d);
  441. return d;
  442. #endif
  443. }
  444. case FBT_VECTOR: return static_cast<double>(AsVector().size());
  445. case FBT_BOOL:
  446. return static_cast<double>(ReadUInt64(data_, parent_width_));
  447. default:
  448. // Convert strings and other things to float.
  449. return 0;
  450. }
  451. }
  452. float AsFloat() const { return static_cast<float>(AsDouble()); }
  453. const char *AsKey() const {
  454. if (type_ == FBT_KEY || type_ == FBT_STRING) {
  455. return reinterpret_cast<const char *>(Indirect());
  456. } else {
  457. return "";
  458. }
  459. }
  460. // This function returns the empty string if you try to read something that
  461. // is not a string or key.
  462. String AsString() const {
  463. if (type_ == FBT_STRING) {
  464. return String(Indirect(), byte_width_);
  465. } else if (type_ == FBT_KEY) {
  466. auto key = Indirect();
  467. return String(key, byte_width_,
  468. strlen(reinterpret_cast<const char *>(key)));
  469. } else {
  470. return String::EmptyString();
  471. }
  472. }
  473. // Unlike AsString(), this will convert any type to a std::string.
  474. std::string ToString() const {
  475. std::string s;
  476. ToString(false, false, s);
  477. return s;
  478. }
  479. // Convert any type to a JSON-like string. strings_quoted determines if
  480. // string values at the top level receive "" quotes (inside other values
  481. // they always do). keys_quoted determines if keys are quoted, at any level.
  482. // TODO(wvo): add further options to have indentation/newlines.
  483. void ToString(bool strings_quoted, bool keys_quoted, std::string &s) const {
  484. if (type_ == FBT_STRING) {
  485. String str(Indirect(), byte_width_);
  486. if (strings_quoted) {
  487. flatbuffers::EscapeString(str.c_str(), str.length(), &s, true, false);
  488. } else {
  489. s.append(str.c_str(), str.length());
  490. }
  491. } else if (IsKey()) {
  492. auto str = AsKey();
  493. if (keys_quoted) {
  494. flatbuffers::EscapeString(str, strlen(str), &s, true, false);
  495. } else {
  496. s += str;
  497. }
  498. } else if (IsInt()) {
  499. s += flatbuffers::NumToString(AsInt64());
  500. } else if (IsUInt()) {
  501. s += flatbuffers::NumToString(AsUInt64());
  502. } else if (IsFloat()) {
  503. s += flatbuffers::NumToString(AsDouble());
  504. } else if (IsNull()) {
  505. s += "null";
  506. } else if (IsBool()) {
  507. s += AsBool() ? "true" : "false";
  508. } else if (IsMap()) {
  509. s += "{ ";
  510. auto m = AsMap();
  511. auto keys = m.Keys();
  512. auto vals = m.Values();
  513. for (size_t i = 0; i < keys.size(); i++) {
  514. keys[i].ToString(true, keys_quoted, s);
  515. s += ": ";
  516. vals[i].ToString(true, keys_quoted, s);
  517. if (i < keys.size() - 1) s += ", ";
  518. }
  519. s += " }";
  520. } else if (IsVector()) {
  521. AppendToString<Vector>(s, AsVector(), keys_quoted);
  522. } else if (IsTypedVector()) {
  523. AppendToString<TypedVector>(s, AsTypedVector(), keys_quoted);
  524. } else if (IsFixedTypedVector()) {
  525. AppendToString<FixedTypedVector>(s, AsFixedTypedVector(), keys_quoted);
  526. } else if (IsBlob()) {
  527. auto blob = AsBlob();
  528. flatbuffers::EscapeString(reinterpret_cast<const char *>(blob.data()),
  529. blob.size(), &s, true, false);
  530. } else {
  531. s += "(?)";
  532. }
  533. }
  534. // This function returns the empty blob if you try to read a not-blob.
  535. // Strings can be viewed as blobs too.
  536. Blob AsBlob() const {
  537. if (type_ == FBT_BLOB || type_ == FBT_STRING) {
  538. return Blob(Indirect(), byte_width_);
  539. } else {
  540. return Blob::EmptyBlob();
  541. }
  542. }
  543. // This function returns the empty vector if you try to read a not-vector.
  544. // Maps can be viewed as vectors too.
  545. Vector AsVector() const {
  546. if (type_ == FBT_VECTOR || type_ == FBT_MAP) {
  547. return Vector(Indirect(), byte_width_);
  548. } else {
  549. return Vector::EmptyVector();
  550. }
  551. }
  552. TypedVector AsTypedVector() const {
  553. if (IsTypedVector()) {
  554. auto tv =
  555. TypedVector(Indirect(), byte_width_, ToTypedVectorElementType(type_));
  556. if (tv.type_ == FBT_STRING) {
  557. // These can't be accessed as strings, since we don't know the bit-width
  558. // of the size field, see the declaration of
  559. // FBT_VECTOR_STRING_DEPRECATED above for details.
  560. // We change the type here to be keys, which are a subtype of strings,
  561. // and will ignore the size field. This will truncate strings with
  562. // embedded nulls.
  563. tv.type_ = FBT_KEY;
  564. }
  565. return tv;
  566. } else {
  567. return TypedVector::EmptyTypedVector();
  568. }
  569. }
  570. FixedTypedVector AsFixedTypedVector() const {
  571. if (IsFixedTypedVector()) {
  572. uint8_t len = 0;
  573. auto vtype = ToFixedTypedVectorElementType(type_, &len);
  574. return FixedTypedVector(Indirect(), byte_width_, vtype, len);
  575. } else {
  576. return FixedTypedVector::EmptyFixedTypedVector();
  577. }
  578. }
  579. Map AsMap() const {
  580. if (type_ == FBT_MAP) {
  581. return Map(Indirect(), byte_width_);
  582. } else {
  583. return Map::EmptyMap();
  584. }
  585. }
  586. template<typename T> T As() const;
  587. // Experimental: Mutation functions.
  588. // These allow scalars in an already created buffer to be updated in-place.
  589. // Since by default scalars are stored in the smallest possible space,
  590. // the new value may not fit, in which case these functions return false.
  591. // To avoid this, you can construct the values you intend to mutate using
  592. // Builder::ForceMinimumBitWidth.
  593. bool MutateInt(int64_t i) {
  594. if (type_ == FBT_INT) {
  595. return Mutate(data_, i, parent_width_, WidthI(i));
  596. } else if (type_ == FBT_INDIRECT_INT) {
  597. return Mutate(Indirect(), i, byte_width_, WidthI(i));
  598. } else if (type_ == FBT_UINT) {
  599. auto u = static_cast<uint64_t>(i);
  600. return Mutate(data_, u, parent_width_, WidthU(u));
  601. } else if (type_ == FBT_INDIRECT_UINT) {
  602. auto u = static_cast<uint64_t>(i);
  603. return Mutate(Indirect(), u, byte_width_, WidthU(u));
  604. } else {
  605. return false;
  606. }
  607. }
  608. bool MutateBool(bool b) {
  609. return type_ == FBT_BOOL && Mutate(data_, b, parent_width_, BIT_WIDTH_8);
  610. }
  611. bool MutateUInt(uint64_t u) {
  612. if (type_ == FBT_UINT) {
  613. return Mutate(data_, u, parent_width_, WidthU(u));
  614. } else if (type_ == FBT_INDIRECT_UINT) {
  615. return Mutate(Indirect(), u, byte_width_, WidthU(u));
  616. } else if (type_ == FBT_INT) {
  617. auto i = static_cast<int64_t>(u);
  618. return Mutate(data_, i, parent_width_, WidthI(i));
  619. } else if (type_ == FBT_INDIRECT_INT) {
  620. auto i = static_cast<int64_t>(u);
  621. return Mutate(Indirect(), i, byte_width_, WidthI(i));
  622. } else {
  623. return false;
  624. }
  625. }
  626. bool MutateFloat(float f) {
  627. if (type_ == FBT_FLOAT) {
  628. return MutateF(data_, f, parent_width_, BIT_WIDTH_32);
  629. } else if (type_ == FBT_INDIRECT_FLOAT) {
  630. return MutateF(Indirect(), f, byte_width_, BIT_WIDTH_32);
  631. } else {
  632. return false;
  633. }
  634. }
  635. bool MutateFloat(double d) {
  636. if (type_ == FBT_FLOAT) {
  637. return MutateF(data_, d, parent_width_, WidthF(d));
  638. } else if (type_ == FBT_INDIRECT_FLOAT) {
  639. return MutateF(Indirect(), d, byte_width_, WidthF(d));
  640. } else {
  641. return false;
  642. }
  643. }
  644. bool MutateString(const char *str, size_t len) {
  645. auto s = AsString();
  646. if (s.IsTheEmptyString()) return false;
  647. // This is very strict, could allow shorter strings, but that creates
  648. // garbage.
  649. if (s.length() != len) return false;
  650. memcpy(const_cast<char *>(s.c_str()), str, len);
  651. return true;
  652. }
  653. bool MutateString(const char *str) { return MutateString(str, strlen(str)); }
  654. bool MutateString(const std::string &str) {
  655. return MutateString(str.data(), str.length());
  656. }
  657. private:
  658. const uint8_t *Indirect() const {
  659. return flexbuffers::Indirect(data_, parent_width_);
  660. }
  661. template<typename T>
  662. bool Mutate(const uint8_t *dest, T t, size_t byte_width,
  663. BitWidth value_width) {
  664. auto fits = static_cast<size_t>(static_cast<size_t>(1U) << value_width) <=
  665. byte_width;
  666. if (fits) {
  667. t = flatbuffers::EndianScalar(t);
  668. memcpy(const_cast<uint8_t *>(dest), &t, byte_width);
  669. }
  670. return fits;
  671. }
  672. template<typename T>
  673. bool MutateF(const uint8_t *dest, T t, size_t byte_width,
  674. BitWidth value_width) {
  675. if (byte_width == sizeof(double))
  676. return Mutate(dest, static_cast<double>(t), byte_width, value_width);
  677. if (byte_width == sizeof(float))
  678. return Mutate(dest, static_cast<float>(t), byte_width, value_width);
  679. FLATBUFFERS_ASSERT(false);
  680. return false;
  681. }
  682. const uint8_t *data_;
  683. uint8_t parent_width_;
  684. uint8_t byte_width_;
  685. Type type_;
  686. };
  687. // Template specialization for As().
  688. template<> inline bool Reference::As<bool>() const { return AsBool(); }
  689. template<> inline int8_t Reference::As<int8_t>() const { return AsInt8(); }
  690. template<> inline int16_t Reference::As<int16_t>() const { return AsInt16(); }
  691. template<> inline int32_t Reference::As<int32_t>() const { return AsInt32(); }
  692. template<> inline int64_t Reference::As<int64_t>() const { return AsInt64(); }
  693. template<> inline uint8_t Reference::As<uint8_t>() const { return AsUInt8(); }
  694. template<> inline uint16_t Reference::As<uint16_t>() const {
  695. return AsUInt16();
  696. }
  697. template<> inline uint32_t Reference::As<uint32_t>() const {
  698. return AsUInt32();
  699. }
  700. template<> inline uint64_t Reference::As<uint64_t>() const {
  701. return AsUInt64();
  702. }
  703. template<> inline double Reference::As<double>() const { return AsDouble(); }
  704. template<> inline float Reference::As<float>() const { return AsFloat(); }
  705. template<> inline String Reference::As<String>() const { return AsString(); }
  706. template<> inline std::string Reference::As<std::string>() const {
  707. return AsString().str();
  708. }
  709. template<> inline Blob Reference::As<Blob>() const { return AsBlob(); }
  710. template<> inline Vector Reference::As<Vector>() const { return AsVector(); }
  711. template<> inline TypedVector Reference::As<TypedVector>() const {
  712. return AsTypedVector();
  713. }
  714. template<> inline FixedTypedVector Reference::As<FixedTypedVector>() const {
  715. return AsFixedTypedVector();
  716. }
  717. template<> inline Map Reference::As<Map>() const { return AsMap(); }
  718. inline uint8_t PackedType(BitWidth bit_width, Type type) {
  719. return static_cast<uint8_t>(bit_width | (type << 2));
  720. }
  721. inline uint8_t NullPackedType() { return PackedType(BIT_WIDTH_8, FBT_NULL); }
  722. // Vector accessors.
  723. // Note: if you try to access outside of bounds, you get a Null value back
  724. // instead. Normally this would be an assert, but since this is "dynamically
  725. // typed" data, you may not want that (someone sends you a 2d vector and you
  726. // wanted 3d).
  727. // The Null converts seamlessly into a default value for any other type.
  728. // TODO(wvo): Could introduce an #ifdef that makes this into an assert?
  729. inline Reference Vector::operator[](size_t i) const {
  730. auto len = size();
  731. if (i >= len) return Reference(nullptr, 1, NullPackedType());
  732. auto packed_type = (data_ + len * byte_width_)[i];
  733. auto elem = data_ + i * byte_width_;
  734. return Reference(elem, byte_width_, packed_type);
  735. }
  736. inline Reference TypedVector::operator[](size_t i) const {
  737. auto len = size();
  738. if (i >= len) return Reference(nullptr, 1, NullPackedType());
  739. auto elem = data_ + i * byte_width_;
  740. return Reference(elem, byte_width_, 1, type_);
  741. }
  742. inline Reference FixedTypedVector::operator[](size_t i) const {
  743. if (i >= len_) return Reference(nullptr, 1, NullPackedType());
  744. auto elem = data_ + i * byte_width_;
  745. return Reference(elem, byte_width_, 1, type_);
  746. }
  747. template<typename T> int KeyCompare(const void *key, const void *elem) {
  748. auto str_elem = reinterpret_cast<const char *>(
  749. Indirect<T>(reinterpret_cast<const uint8_t *>(elem)));
  750. auto skey = reinterpret_cast<const char *>(key);
  751. return strcmp(skey, str_elem);
  752. }
  753. inline Reference Map::operator[](const char *key) const {
  754. auto keys = Keys();
  755. // We can't pass keys.byte_width_ to the comparison function, so we have
  756. // to pick the right one ahead of time.
  757. int (*comp)(const void *, const void *) = nullptr;
  758. switch (keys.byte_width_) {
  759. case 1: comp = KeyCompare<uint8_t>; break;
  760. case 2: comp = KeyCompare<uint16_t>; break;
  761. case 4: comp = KeyCompare<uint32_t>; break;
  762. case 8: comp = KeyCompare<uint64_t>; break;
  763. }
  764. auto res = std::bsearch(key, keys.data_, keys.size(), keys.byte_width_, comp);
  765. if (!res) return Reference(nullptr, 1, NullPackedType());
  766. auto i = (reinterpret_cast<uint8_t *>(res) - keys.data_) / keys.byte_width_;
  767. return (*static_cast<const Vector *>(this))[i];
  768. }
  769. inline Reference Map::operator[](const std::string &key) const {
  770. return (*this)[key.c_str()];
  771. }
  772. inline Reference GetRoot(const uint8_t *buffer, size_t size) {
  773. // See Finish() below for the serialization counterpart of this.
  774. // The root starts at the end of the buffer, so we parse backwards from there.
  775. auto end = buffer + size;
  776. auto byte_width = *--end;
  777. auto packed_type = *--end;
  778. end -= byte_width; // The root data item.
  779. return Reference(end, byte_width, packed_type);
  780. }
  781. inline Reference GetRoot(const std::vector<uint8_t> &buffer) {
  782. return GetRoot(flatbuffers::vector_data(buffer), buffer.size());
  783. }
  784. // Flags that configure how the Builder behaves.
  785. // The "Share" flags determine if the Builder automatically tries to pool
  786. // this type. Pooling can reduce the size of serialized data if there are
  787. // multiple maps of the same kind, at the expense of slightly slower
  788. // serialization (the cost of lookups) and more memory use (std::set).
  789. // By default this is on for keys, but off for strings.
  790. // Turn keys off if you have e.g. only one map.
  791. // Turn strings on if you expect many non-unique string values.
  792. // Additionally, sharing key vectors can save space if you have maps with
  793. // identical field populations.
  794. enum BuilderFlag {
  795. BUILDER_FLAG_NONE = 0,
  796. BUILDER_FLAG_SHARE_KEYS = 1,
  797. BUILDER_FLAG_SHARE_STRINGS = 2,
  798. BUILDER_FLAG_SHARE_KEYS_AND_STRINGS = 3,
  799. BUILDER_FLAG_SHARE_KEY_VECTORS = 4,
  800. BUILDER_FLAG_SHARE_ALL = 7,
  801. };
  802. class Builder FLATBUFFERS_FINAL_CLASS {
  803. public:
  804. Builder(size_t initial_size = 256,
  805. BuilderFlag flags = BUILDER_FLAG_SHARE_KEYS)
  806. : buf_(initial_size),
  807. finished_(false),
  808. flags_(flags),
  809. force_min_bit_width_(BIT_WIDTH_8),
  810. key_pool(KeyOffsetCompare(buf_)),
  811. string_pool(StringOffsetCompare(buf_)) {
  812. buf_.clear();
  813. }
  814. /// @brief Get the serialized buffer (after you call `Finish()`).
  815. /// @return Returns a vector owned by this class.
  816. const std::vector<uint8_t> &GetBuffer() const {
  817. Finished();
  818. return buf_;
  819. }
  820. // Size of the buffer. Does not include unfinished values.
  821. size_t GetSize() const { return buf_.size(); }
  822. // Reset all state so we can re-use the buffer.
  823. void Clear() {
  824. buf_.clear();
  825. stack_.clear();
  826. finished_ = false;
  827. // flags_ remains as-is;
  828. force_min_bit_width_ = BIT_WIDTH_8;
  829. key_pool.clear();
  830. string_pool.clear();
  831. }
  832. // All value constructing functions below have two versions: one that
  833. // takes a key (for placement inside a map) and one that doesn't (for inside
  834. // vectors and elsewhere).
  835. void Null() { stack_.push_back(Value()); }
  836. void Null(const char *key) {
  837. Key(key);
  838. Null();
  839. }
  840. void Int(int64_t i) { stack_.push_back(Value(i, FBT_INT, WidthI(i))); }
  841. void Int(const char *key, int64_t i) {
  842. Key(key);
  843. Int(i);
  844. }
  845. void UInt(uint64_t u) { stack_.push_back(Value(u, FBT_UINT, WidthU(u))); }
  846. void UInt(const char *key, uint64_t u) {
  847. Key(key);
  848. UInt(u);
  849. }
  850. void Float(float f) { stack_.push_back(Value(f)); }
  851. void Float(const char *key, float f) {
  852. Key(key);
  853. Float(f);
  854. }
  855. void Double(double f) { stack_.push_back(Value(f)); }
  856. void Double(const char *key, double d) {
  857. Key(key);
  858. Double(d);
  859. }
  860. void Bool(bool b) { stack_.push_back(Value(b)); }
  861. void Bool(const char *key, bool b) {
  862. Key(key);
  863. Bool(b);
  864. }
  865. void IndirectInt(int64_t i) { PushIndirect(i, FBT_INDIRECT_INT, WidthI(i)); }
  866. void IndirectInt(const char *key, int64_t i) {
  867. Key(key);
  868. IndirectInt(i);
  869. }
  870. void IndirectUInt(uint64_t u) {
  871. PushIndirect(u, FBT_INDIRECT_UINT, WidthU(u));
  872. }
  873. void IndirectUInt(const char *key, uint64_t u) {
  874. Key(key);
  875. IndirectUInt(u);
  876. }
  877. void IndirectFloat(float f) {
  878. PushIndirect(f, FBT_INDIRECT_FLOAT, BIT_WIDTH_32);
  879. }
  880. void IndirectFloat(const char *key, float f) {
  881. Key(key);
  882. IndirectFloat(f);
  883. }
  884. void IndirectDouble(double f) {
  885. PushIndirect(f, FBT_INDIRECT_FLOAT, WidthF(f));
  886. }
  887. void IndirectDouble(const char *key, double d) {
  888. Key(key);
  889. IndirectDouble(d);
  890. }
  891. size_t Key(const char *str, size_t len) {
  892. auto sloc = buf_.size();
  893. WriteBytes(str, len + 1);
  894. if (flags_ & BUILDER_FLAG_SHARE_KEYS) {
  895. auto it = key_pool.find(sloc);
  896. if (it != key_pool.end()) {
  897. // Already in the buffer. Remove key we just serialized, and use
  898. // existing offset instead.
  899. buf_.resize(sloc);
  900. sloc = *it;
  901. } else {
  902. key_pool.insert(sloc);
  903. }
  904. }
  905. stack_.push_back(Value(static_cast<uint64_t>(sloc), FBT_KEY, BIT_WIDTH_8));
  906. return sloc;
  907. }
  908. size_t Key(const char *str) { return Key(str, strlen(str)); }
  909. size_t Key(const std::string &str) { return Key(str.c_str(), str.size()); }
  910. size_t String(const char *str, size_t len) {
  911. auto reset_to = buf_.size();
  912. auto sloc = CreateBlob(str, len, 1, FBT_STRING);
  913. if (flags_ & BUILDER_FLAG_SHARE_STRINGS) {
  914. StringOffset so(sloc, len);
  915. auto it = string_pool.find(so);
  916. if (it != string_pool.end()) {
  917. // Already in the buffer. Remove string we just serialized, and use
  918. // existing offset instead.
  919. buf_.resize(reset_to);
  920. sloc = it->first;
  921. stack_.back().u_ = sloc;
  922. } else {
  923. string_pool.insert(so);
  924. }
  925. }
  926. return sloc;
  927. }
  928. size_t String(const char *str) { return String(str, strlen(str)); }
  929. size_t String(const std::string &str) {
  930. return String(str.c_str(), str.size());
  931. }
  932. void String(const flexbuffers::String &str) {
  933. String(str.c_str(), str.length());
  934. }
  935. void String(const char *key, const char *str) {
  936. Key(key);
  937. String(str);
  938. }
  939. void String(const char *key, const std::string &str) {
  940. Key(key);
  941. String(str);
  942. }
  943. void String(const char *key, const flexbuffers::String &str) {
  944. Key(key);
  945. String(str);
  946. }
  947. size_t Blob(const void *data, size_t len) {
  948. return CreateBlob(data, len, 0, FBT_BLOB);
  949. }
  950. size_t Blob(const std::vector<uint8_t> &v) {
  951. return CreateBlob(flatbuffers::vector_data(v), v.size(), 0, FBT_BLOB);
  952. }
  953. // TODO(wvo): support all the FlexBuffer types (like flexbuffers::String),
  954. // e.g. Vector etc. Also in overloaded versions.
  955. // Also some FlatBuffers types?
  956. size_t StartVector() { return stack_.size(); }
  957. size_t StartVector(const char *key) {
  958. Key(key);
  959. return stack_.size();
  960. }
  961. size_t StartMap() { return stack_.size(); }
  962. size_t StartMap(const char *key) {
  963. Key(key);
  964. return stack_.size();
  965. }
  966. // TODO(wvo): allow this to specify an aligment greater than the natural
  967. // alignment.
  968. size_t EndVector(size_t start, bool typed, bool fixed) {
  969. auto vec = CreateVector(start, stack_.size() - start, 1, typed, fixed);
  970. // Remove temp elements and return vector.
  971. stack_.resize(start);
  972. stack_.push_back(vec);
  973. return static_cast<size_t>(vec.u_);
  974. }
  975. size_t EndMap(size_t start) {
  976. // We should have interleaved keys and values on the stack.
  977. // Make sure it is an even number:
  978. auto len = stack_.size() - start;
  979. FLATBUFFERS_ASSERT(!(len & 1));
  980. len /= 2;
  981. // Make sure keys are all strings:
  982. for (auto key = start; key < stack_.size(); key += 2) {
  983. FLATBUFFERS_ASSERT(stack_[key].type_ == FBT_KEY);
  984. }
  985. // Now sort values, so later we can do a binary search lookup.
  986. // We want to sort 2 array elements at a time.
  987. struct TwoValue {
  988. Value key;
  989. Value val;
  990. };
  991. // TODO(wvo): strict aliasing?
  992. // TODO(wvo): allow the caller to indicate the data is already sorted
  993. // for maximum efficiency? With an assert to check sortedness to make sure
  994. // we're not breaking binary search.
  995. // Or, we can track if the map is sorted as keys are added which would be
  996. // be quite cheap (cheaper than checking it here), so we can skip this
  997. // step automatically when appliccable, and encourage people to write in
  998. // sorted fashion.
  999. // std::sort is typically already a lot faster on sorted data though.
  1000. auto dict =
  1001. reinterpret_cast<TwoValue *>(flatbuffers::vector_data(stack_) + start);
  1002. std::sort(dict, dict + len,
  1003. [&](const TwoValue &a, const TwoValue &b) -> bool {
  1004. auto as = reinterpret_cast<const char *>(
  1005. flatbuffers::vector_data(buf_) + a.key.u_);
  1006. auto bs = reinterpret_cast<const char *>(
  1007. flatbuffers::vector_data(buf_) + b.key.u_);
  1008. auto comp = strcmp(as, bs);
  1009. // If this assertion hits, you've added two keys with the same
  1010. // value to this map.
  1011. // TODO: Have to check for pointer equality, as some sort
  1012. // implementation apparently call this function with the same
  1013. // element?? Why?
  1014. FLATBUFFERS_ASSERT(comp || &a == &b);
  1015. return comp < 0;
  1016. });
  1017. // First create a vector out of all keys.
  1018. // TODO(wvo): if kBuilderFlagShareKeyVectors is true, see if we can share
  1019. // the first vector.
  1020. auto keys = CreateVector(start, len, 2, true, false);
  1021. auto vec = CreateVector(start + 1, len, 2, false, false, &keys);
  1022. // Remove temp elements and return map.
  1023. stack_.resize(start);
  1024. stack_.push_back(vec);
  1025. return static_cast<size_t>(vec.u_);
  1026. }
  1027. template<typename F> size_t Vector(F f) {
  1028. auto start = StartVector();
  1029. f();
  1030. return EndVector(start, false, false);
  1031. }
  1032. template<typename F, typename T> size_t Vector(F f, T &state) {
  1033. auto start = StartVector();
  1034. f(state);
  1035. return EndVector(start, false, false);
  1036. }
  1037. template<typename F> size_t Vector(const char *key, F f) {
  1038. auto start = StartVector(key);
  1039. f();
  1040. return EndVector(start, false, false);
  1041. }
  1042. template<typename F, typename T>
  1043. size_t Vector(const char *key, F f, T &state) {
  1044. auto start = StartVector(key);
  1045. f(state);
  1046. return EndVector(start, false, false);
  1047. }
  1048. template<typename T> void Vector(const T *elems, size_t len) {
  1049. if (flatbuffers::is_scalar<T>::value) {
  1050. // This path should be a lot quicker and use less space.
  1051. ScalarVector(elems, len, false);
  1052. } else {
  1053. auto start = StartVector();
  1054. for (size_t i = 0; i < len; i++) Add(elems[i]);
  1055. EndVector(start, false, false);
  1056. }
  1057. }
  1058. template<typename T>
  1059. void Vector(const char *key, const T *elems, size_t len) {
  1060. Key(key);
  1061. Vector(elems, len);
  1062. }
  1063. template<typename T> void Vector(const std::vector<T> &vec) {
  1064. Vector(flatbuffers::vector_data(vec), vec.size());
  1065. }
  1066. template<typename F> size_t TypedVector(F f) {
  1067. auto start = StartVector();
  1068. f();
  1069. return EndVector(start, true, false);
  1070. }
  1071. template<typename F, typename T> size_t TypedVector(F f, T &state) {
  1072. auto start = StartVector();
  1073. f(state);
  1074. return EndVector(start, true, false);
  1075. }
  1076. template<typename F> size_t TypedVector(const char *key, F f) {
  1077. auto start = StartVector(key);
  1078. f();
  1079. return EndVector(start, true, false);
  1080. }
  1081. template<typename F, typename T>
  1082. size_t TypedVector(const char *key, F f, T &state) {
  1083. auto start = StartVector(key);
  1084. f(state);
  1085. return EndVector(start, true, false);
  1086. }
  1087. template<typename T> size_t FixedTypedVector(const T *elems, size_t len) {
  1088. // We only support a few fixed vector lengths. Anything bigger use a
  1089. // regular typed vector.
  1090. FLATBUFFERS_ASSERT(len >= 2 && len <= 4);
  1091. // And only scalar values.
  1092. static_assert(flatbuffers::is_scalar<T>::value, "Unrelated types");
  1093. return ScalarVector(elems, len, true);
  1094. }
  1095. template<typename T>
  1096. size_t FixedTypedVector(const char *key, const T *elems, size_t len) {
  1097. Key(key);
  1098. return FixedTypedVector(elems, len);
  1099. }
  1100. template<typename F> size_t Map(F f) {
  1101. auto start = StartMap();
  1102. f();
  1103. return EndMap(start);
  1104. }
  1105. template<typename F, typename T> size_t Map(F f, T &state) {
  1106. auto start = StartMap();
  1107. f(state);
  1108. return EndMap(start);
  1109. }
  1110. template<typename F> size_t Map(const char *key, F f) {
  1111. auto start = StartMap(key);
  1112. f();
  1113. return EndMap(start);
  1114. }
  1115. template<typename F, typename T> size_t Map(const char *key, F f, T &state) {
  1116. auto start = StartMap(key);
  1117. f(state);
  1118. return EndMap(start);
  1119. }
  1120. template<typename T> void Map(const std::map<std::string, T> &map) {
  1121. auto start = StartMap();
  1122. for (auto it = map.begin(); it != map.end(); ++it)
  1123. Add(it->first.c_str(), it->second);
  1124. EndMap(start);
  1125. }
  1126. // If you wish to share a value explicitly (a value not shared automatically
  1127. // through one of the BUILDER_FLAG_SHARE_* flags) you can do so with these
  1128. // functions. Or if you wish to turn those flags off for performance reasons
  1129. // and still do some explicit sharing. For example:
  1130. // builder.IndirectDouble(M_PI);
  1131. // auto id = builder.LastValue(); // Remember where we stored it.
  1132. // .. more code goes here ..
  1133. // builder.ReuseValue(id); // Refers to same double by offset.
  1134. // LastValue works regardless of whether the value has a key or not.
  1135. // Works on any data type.
  1136. struct Value;
  1137. Value LastValue() { return stack_.back(); }
  1138. void ReuseValue(Value v) { stack_.push_back(v); }
  1139. void ReuseValue(const char *key, Value v) {
  1140. Key(key);
  1141. ReuseValue(v);
  1142. }
  1143. // Overloaded Add that tries to call the correct function above.
  1144. void Add(int8_t i) { Int(i); }
  1145. void Add(int16_t i) { Int(i); }
  1146. void Add(int32_t i) { Int(i); }
  1147. void Add(int64_t i) { Int(i); }
  1148. void Add(uint8_t u) { UInt(u); }
  1149. void Add(uint16_t u) { UInt(u); }
  1150. void Add(uint32_t u) { UInt(u); }
  1151. void Add(uint64_t u) { UInt(u); }
  1152. void Add(float f) { Float(f); }
  1153. void Add(double d) { Double(d); }
  1154. void Add(bool b) { Bool(b); }
  1155. void Add(const char *str) { String(str); }
  1156. void Add(const std::string &str) { String(str); }
  1157. void Add(const flexbuffers::String &str) { String(str); }
  1158. template<typename T> void Add(const std::vector<T> &vec) { Vector(vec); }
  1159. template<typename T> void Add(const char *key, const T &t) {
  1160. Key(key);
  1161. Add(t);
  1162. }
  1163. template<typename T> void Add(const std::map<std::string, T> &map) {
  1164. Map(map);
  1165. }
  1166. template<typename T> void operator+=(const T &t) { Add(t); }
  1167. // This function is useful in combination with the Mutate* functions above.
  1168. // It forces elements of vectors and maps to have a minimum size, such that
  1169. // they can later be updated without failing.
  1170. // Call with no arguments to reset.
  1171. void ForceMinimumBitWidth(BitWidth bw = BIT_WIDTH_8) {
  1172. force_min_bit_width_ = bw;
  1173. }
  1174. void Finish() {
  1175. // If you hit this assert, you likely have objects that were never included
  1176. // in a parent. You need to have exactly one root to finish a buffer.
  1177. // Check your Start/End calls are matched, and all objects are inside
  1178. // some other object.
  1179. FLATBUFFERS_ASSERT(stack_.size() == 1);
  1180. // Write root value.
  1181. auto byte_width = Align(stack_[0].ElemWidth(buf_.size(), 0));
  1182. WriteAny(stack_[0], byte_width);
  1183. // Write root type.
  1184. Write(stack_[0].StoredPackedType(), 1);
  1185. // Write root size. Normally determined by parent, but root has no parent :)
  1186. Write(byte_width, 1);
  1187. finished_ = true;
  1188. }
  1189. private:
  1190. void Finished() const {
  1191. // If you get this assert, you're attempting to get access a buffer
  1192. // which hasn't been finished yet. Be sure to call
  1193. // Builder::Finish with your root object.
  1194. FLATBUFFERS_ASSERT(finished_);
  1195. }
  1196. // Align to prepare for writing a scalar with a certain size.
  1197. uint8_t Align(BitWidth alignment) {
  1198. auto byte_width = 1U << alignment;
  1199. buf_.insert(buf_.end(), flatbuffers::PaddingBytes(buf_.size(), byte_width),
  1200. 0);
  1201. return static_cast<uint8_t>(byte_width);
  1202. }
  1203. void WriteBytes(const void *val, size_t size) {
  1204. buf_.insert(buf_.end(), reinterpret_cast<const uint8_t *>(val),
  1205. reinterpret_cast<const uint8_t *>(val) + size);
  1206. }
  1207. template<typename T> void Write(T val, size_t byte_width) {
  1208. FLATBUFFERS_ASSERT(sizeof(T) >= byte_width);
  1209. val = flatbuffers::EndianScalar(val);
  1210. WriteBytes(&val, byte_width);
  1211. }
  1212. void WriteDouble(double f, uint8_t byte_width) {
  1213. switch (byte_width) {
  1214. case 8: Write(f, byte_width); break;
  1215. case 4: Write(static_cast<float>(f), byte_width); break;
  1216. // case 2: Write(static_cast<half>(f), byte_width); break;
  1217. // case 1: Write(static_cast<quarter>(f), byte_width); break;
  1218. default: FLATBUFFERS_ASSERT(0);
  1219. }
  1220. }
  1221. void WriteOffset(uint64_t o, uint8_t byte_width) {
  1222. auto reloff = buf_.size() - o;
  1223. FLATBUFFERS_ASSERT(byte_width == 8 || reloff < 1ULL << (byte_width * 8));
  1224. Write(reloff, byte_width);
  1225. }
  1226. template<typename T> void PushIndirect(T val, Type type, BitWidth bit_width) {
  1227. auto byte_width = Align(bit_width);
  1228. auto iloc = buf_.size();
  1229. Write(val, byte_width);
  1230. stack_.push_back(Value(static_cast<uint64_t>(iloc), type, bit_width));
  1231. }
  1232. static BitWidth WidthB(size_t byte_width) {
  1233. switch (byte_width) {
  1234. case 1: return BIT_WIDTH_8;
  1235. case 2: return BIT_WIDTH_16;
  1236. case 4: return BIT_WIDTH_32;
  1237. case 8: return BIT_WIDTH_64;
  1238. default: FLATBUFFERS_ASSERT(false); return BIT_WIDTH_64;
  1239. }
  1240. }
  1241. template<typename T> static Type GetScalarType() {
  1242. static_assert(flatbuffers::is_scalar<T>::value, "Unrelated types");
  1243. return flatbuffers::is_floating_point<T>::value
  1244. ? FBT_FLOAT
  1245. : flatbuffers::is_same<T, bool>::value
  1246. ? FBT_BOOL
  1247. : (flatbuffers::is_unsigned<T>::value ? FBT_UINT
  1248. : FBT_INT);
  1249. }
  1250. public:
  1251. // This was really intended to be private, except for LastValue/ReuseValue.
  1252. struct Value {
  1253. union {
  1254. int64_t i_;
  1255. uint64_t u_;
  1256. double f_;
  1257. };
  1258. Type type_;
  1259. // For scalars: of itself, for vector: of its elements, for string: length.
  1260. BitWidth min_bit_width_;
  1261. Value() : i_(0), type_(FBT_NULL), min_bit_width_(BIT_WIDTH_8) {}
  1262. Value(bool b)
  1263. : u_(static_cast<uint64_t>(b)),
  1264. type_(FBT_BOOL),
  1265. min_bit_width_(BIT_WIDTH_8) {}
  1266. Value(int64_t i, Type t, BitWidth bw)
  1267. : i_(i), type_(t), min_bit_width_(bw) {}
  1268. Value(uint64_t u, Type t, BitWidth bw)
  1269. : u_(u), type_(t), min_bit_width_(bw) {}
  1270. Value(float f)
  1271. : f_(static_cast<double>(f)),
  1272. type_(FBT_FLOAT),
  1273. min_bit_width_(BIT_WIDTH_32) {}
  1274. Value(double f) : f_(f), type_(FBT_FLOAT), min_bit_width_(WidthF(f)) {}
  1275. uint8_t StoredPackedType(BitWidth parent_bit_width_ = BIT_WIDTH_8) const {
  1276. return PackedType(StoredWidth(parent_bit_width_), type_);
  1277. }
  1278. BitWidth ElemWidth(size_t buf_size, size_t elem_index) const {
  1279. if (IsInline(type_)) {
  1280. return min_bit_width_;
  1281. } else {
  1282. // We have an absolute offset, but want to store a relative offset
  1283. // elem_index elements beyond the current buffer end. Since whether
  1284. // the relative offset fits in a certain byte_width depends on
  1285. // the size of the elements before it (and their alignment), we have
  1286. // to test for each size in turn.
  1287. for (size_t byte_width = 1;
  1288. byte_width <= sizeof(flatbuffers::largest_scalar_t);
  1289. byte_width *= 2) {
  1290. // Where are we going to write this offset?
  1291. auto offset_loc = buf_size +
  1292. flatbuffers::PaddingBytes(buf_size, byte_width) +
  1293. elem_index * byte_width;
  1294. // Compute relative offset.
  1295. auto offset = offset_loc - u_;
  1296. // Does it fit?
  1297. auto bit_width = WidthU(offset);
  1298. if (static_cast<size_t>(static_cast<size_t>(1U) << bit_width) ==
  1299. byte_width)
  1300. return bit_width;
  1301. }
  1302. FLATBUFFERS_ASSERT(false); // Must match one of the sizes above.
  1303. return BIT_WIDTH_64;
  1304. }
  1305. }
  1306. BitWidth StoredWidth(BitWidth parent_bit_width_ = BIT_WIDTH_8) const {
  1307. if (IsInline(type_)) {
  1308. return (std::max)(min_bit_width_, parent_bit_width_);
  1309. } else {
  1310. return min_bit_width_;
  1311. }
  1312. }
  1313. };
  1314. private:
  1315. void WriteAny(const Value &val, uint8_t byte_width) {
  1316. switch (val.type_) {
  1317. case FBT_NULL:
  1318. case FBT_INT: Write(val.i_, byte_width); break;
  1319. case FBT_BOOL:
  1320. case FBT_UINT: Write(val.u_, byte_width); break;
  1321. case FBT_FLOAT: WriteDouble(val.f_, byte_width); break;
  1322. default: WriteOffset(val.u_, byte_width); break;
  1323. }
  1324. }
  1325. size_t CreateBlob(const void *data, size_t len, size_t trailing, Type type) {
  1326. auto bit_width = WidthU(len);
  1327. auto byte_width = Align(bit_width);
  1328. Write<uint64_t>(len, byte_width);
  1329. auto sloc = buf_.size();
  1330. WriteBytes(data, len + trailing);
  1331. stack_.push_back(Value(static_cast<uint64_t>(sloc), type, bit_width));
  1332. return sloc;
  1333. }
  1334. template<typename T>
  1335. size_t ScalarVector(const T *elems, size_t len, bool fixed) {
  1336. auto vector_type = GetScalarType<T>();
  1337. auto byte_width = sizeof(T);
  1338. auto bit_width = WidthB(byte_width);
  1339. // If you get this assert, you're trying to write a vector with a size
  1340. // field that is bigger than the scalars you're trying to write (e.g. a
  1341. // byte vector > 255 elements). For such types, write a "blob" instead.
  1342. // TODO: instead of asserting, could write vector with larger elements
  1343. // instead, though that would be wasteful.
  1344. FLATBUFFERS_ASSERT(WidthU(len) <= bit_width);
  1345. Align(bit_width);
  1346. if (!fixed) Write<uint64_t>(len, byte_width);
  1347. auto vloc = buf_.size();
  1348. for (size_t i = 0; i < len; i++) Write(elems[i], byte_width);
  1349. stack_.push_back(Value(static_cast<uint64_t>(vloc),
  1350. ToTypedVector(vector_type, fixed ? len : 0),
  1351. bit_width));
  1352. return vloc;
  1353. }
  1354. Value CreateVector(size_t start, size_t vec_len, size_t step, bool typed,
  1355. bool fixed, const Value *keys = nullptr) {
  1356. FLATBUFFERS_ASSERT(
  1357. !fixed ||
  1358. typed); // typed=false, fixed=true combination is not supported.
  1359. // Figure out smallest bit width we can store this vector with.
  1360. auto bit_width = (std::max)(force_min_bit_width_, WidthU(vec_len));
  1361. auto prefix_elems = 1;
  1362. if (keys) {
  1363. // If this vector is part of a map, we will pre-fix an offset to the keys
  1364. // to this vector.
  1365. bit_width = (std::max)(bit_width, keys->ElemWidth(buf_.size(), 0));
  1366. prefix_elems += 2;
  1367. }
  1368. Type vector_type = FBT_KEY;
  1369. // Check bit widths and types for all elements.
  1370. for (size_t i = start; i < stack_.size(); i += step) {
  1371. auto elem_width =
  1372. stack_[i].ElemWidth(buf_.size(), i - start + prefix_elems);
  1373. bit_width = (std::max)(bit_width, elem_width);
  1374. if (typed) {
  1375. if (i == start) {
  1376. vector_type = stack_[i].type_;
  1377. } else {
  1378. // If you get this assert, you are writing a typed vector with
  1379. // elements that are not all the same type.
  1380. FLATBUFFERS_ASSERT(vector_type == stack_[i].type_);
  1381. }
  1382. }
  1383. }
  1384. // If you get this assert, your fixed types are not one of:
  1385. // Int / UInt / Float / Key.
  1386. FLATBUFFERS_ASSERT(!fixed || IsTypedVectorElementType(vector_type));
  1387. auto byte_width = Align(bit_width);
  1388. // Write vector. First the keys width/offset if available, and size.
  1389. if (keys) {
  1390. WriteOffset(keys->u_, byte_width);
  1391. Write<uint64_t>(1ULL << keys->min_bit_width_, byte_width);
  1392. }
  1393. if (!fixed) Write<uint64_t>(vec_len, byte_width);
  1394. // Then the actual data.
  1395. auto vloc = buf_.size();
  1396. for (size_t i = start; i < stack_.size(); i += step) {
  1397. WriteAny(stack_[i], byte_width);
  1398. }
  1399. // Then the types.
  1400. if (!typed) {
  1401. for (size_t i = start; i < stack_.size(); i += step) {
  1402. buf_.push_back(stack_[i].StoredPackedType(bit_width));
  1403. }
  1404. }
  1405. return Value(static_cast<uint64_t>(vloc),
  1406. keys ? FBT_MAP
  1407. : (typed ? ToTypedVector(vector_type, fixed ? vec_len : 0)
  1408. : FBT_VECTOR),
  1409. bit_width);
  1410. }
  1411. // You shouldn't really be copying instances of this class.
  1412. Builder(const Builder &);
  1413. Builder &operator=(const Builder &);
  1414. std::vector<uint8_t> buf_;
  1415. std::vector<Value> stack_;
  1416. bool finished_;
  1417. BuilderFlag flags_;
  1418. BitWidth force_min_bit_width_;
  1419. struct KeyOffsetCompare {
  1420. explicit KeyOffsetCompare(const std::vector<uint8_t> &buf) : buf_(&buf) {}
  1421. bool operator()(size_t a, size_t b) const {
  1422. auto stra =
  1423. reinterpret_cast<const char *>(flatbuffers::vector_data(*buf_) + a);
  1424. auto strb =
  1425. reinterpret_cast<const char *>(flatbuffers::vector_data(*buf_) + b);
  1426. return strcmp(stra, strb) < 0;
  1427. }
  1428. const std::vector<uint8_t> *buf_;
  1429. };
  1430. typedef std::pair<size_t, size_t> StringOffset;
  1431. struct StringOffsetCompare {
  1432. explicit StringOffsetCompare(const std::vector<uint8_t> &buf)
  1433. : buf_(&buf) {}
  1434. bool operator()(const StringOffset &a, const StringOffset &b) const {
  1435. auto stra = reinterpret_cast<const char *>(
  1436. flatbuffers::vector_data(*buf_) + a.first);
  1437. auto strb = reinterpret_cast<const char *>(
  1438. flatbuffers::vector_data(*buf_) + b.first);
  1439. return strncmp(stra, strb, (std::min)(a.second, b.second) + 1) < 0;
  1440. }
  1441. const std::vector<uint8_t> *buf_;
  1442. };
  1443. typedef std::set<size_t, KeyOffsetCompare> KeyOffsetMap;
  1444. typedef std::set<StringOffset, StringOffsetCompare> StringOffsetMap;
  1445. KeyOffsetMap key_pool;
  1446. StringOffsetMap string_pool;
  1447. };
  1448. } // namespace flexbuffers
  1449. #if defined(_MSC_VER)
  1450. # pragma warning(pop)
  1451. #endif
  1452. #endif // FLATBUFFERS_FLEXBUFFERS_H_