builder.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858
  1. # Copyright 2014 Google Inc. All rights reserved.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. import warnings
  15. from . import compat
  16. from . import encode
  17. from . import number_types as N
  18. from . import packer
  19. from .compat import memoryview_type
  20. from .compat import NumpyRequiredForThisFeature, import_numpy
  21. from .compat import range_func
  22. from .number_types import (SOffsetTFlags, UOffsetTFlags, VOffsetTFlags)
  23. np = import_numpy()
  24. ## @file
  25. ## @addtogroup flatbuffers_python_api
  26. ## @{
  27. ## @cond FLATBUFFERS_INTERNAL
  28. class OffsetArithmeticError(RuntimeError):
  29. """Error caused by an Offset arithmetic error.
  30. Probably caused by bad writing of fields. This is considered an unreachable
  31. situation in normal circumstances.
  32. """
  33. pass
  34. class IsNotNestedError(RuntimeError):
  35. """Error caused by using a Builder to write Object data when not inside
  36. an Object.
  37. """
  38. pass
  39. class IsNestedError(RuntimeError):
  40. """Error caused by using a Builder to begin an Object when an Object is
  41. already being built.
  42. """
  43. pass
  44. class StructIsNotInlineError(RuntimeError):
  45. """Error caused by using a Builder to write a Struct at a location that
  46. is not the current Offset.
  47. """
  48. pass
  49. class BuilderSizeError(RuntimeError):
  50. """Error caused by causing a Builder to exceed the hardcoded limit of 2
  51. gigabytes.
  52. """
  53. pass
  54. class BuilderNotFinishedError(RuntimeError):
  55. """Error caused by not calling `Finish` before calling `Output`."""
  56. pass
  57. class EndVectorLengthMismatched(RuntimeError):
  58. """The number of elements passed to EndVector does not match the number
  59. specified in StartVector.
  60. """
  61. pass
  62. # VtableMetadataFields is the count of metadata fields in each vtable.
  63. VtableMetadataFields = 2
  64. ## @endcond
  65. class Builder(object):
  66. """A Builder is used to construct one or more FlatBuffers.
  67. Typically, Builder objects will be used from code generated by the `flatc`
  68. compiler.
  69. A Builder constructs byte buffers in a last-first manner for simplicity and
  70. performance during reading.
  71. Internally, a Builder is a state machine for creating FlatBuffer objects.
  72. It holds the following internal state:
  73. - Bytes: an array of bytes.
  74. - current_vtable: a list of integers.
  75. - vtables: a hash of vtable entries.
  76. Attributes:
  77. Bytes: The internal `bytearray` for the Builder.
  78. finished: A boolean determining if the Builder has been finalized.
  79. """
  80. ## @cond FLATBUFFERS_INTENRAL
  81. __slots__ = (
  82. "Bytes",
  83. "current_vtable",
  84. "head",
  85. "minalign",
  86. "objectEnd",
  87. "vtables",
  88. "nested",
  89. "forceDefaults",
  90. "finished",
  91. "vectorNumElems",
  92. "sharedStrings",
  93. )
  94. """Maximum buffer size constant, in bytes.
  95. Builder will never allow it's buffer grow over this size.
  96. Currently equals 2Gb.
  97. """
  98. MAX_BUFFER_SIZE = 2**31
  99. ## @endcond
  100. def __init__(self, initialSize=1024):
  101. """Initializes a Builder of size `initial_size`.
  102. The internal buffer is grown as needed.
  103. """
  104. if not (0 <= initialSize <= Builder.MAX_BUFFER_SIZE):
  105. msg = "flatbuffers: Cannot create Builder larger than 2 gigabytes."
  106. raise BuilderSizeError(msg)
  107. self.Bytes = bytearray(initialSize)
  108. ## @cond FLATBUFFERS_INTERNAL
  109. self.current_vtable = None
  110. self.head = UOffsetTFlags.py_type(initialSize)
  111. self.minalign = 1
  112. self.objectEnd = None
  113. self.vtables = {}
  114. self.nested = False
  115. self.forceDefaults = False
  116. self.sharedStrings = None
  117. ## @endcond
  118. self.finished = False
  119. def Clear(self):
  120. ## @cond FLATBUFFERS_INTERNAL
  121. self.current_vtable = None
  122. self.head = len(self.Bytes)
  123. self.minalign = 1
  124. self.objectEnd = None
  125. self.vtables = {}
  126. self.nested = False
  127. self.forceDefaults = False
  128. self.sharedStrings = None
  129. self.vectorNumElems = None
  130. ## @endcond
  131. self.finished = False
  132. def Output(self):
  133. """Return the portion of the buffer that has been used for writing data.
  134. This is the typical way to access the FlatBuffer data inside the
  135. builder. If you try to access `Builder.Bytes` directly, you would need
  136. to manually index it with `Head()`, since the buffer is constructed
  137. backwards.
  138. It raises BuilderNotFinishedError if the buffer has not been finished
  139. with `Finish`.
  140. """
  141. if not self.finished:
  142. raise BuilderNotFinishedError()
  143. return self.Bytes[self.head :]
  144. ## @cond FLATBUFFERS_INTERNAL
  145. def StartObject(self, numfields):
  146. """StartObject initializes bookkeeping for writing a new object."""
  147. self.assertNotNested()
  148. # use 32-bit offsets so that arithmetic doesn't overflow.
  149. self.current_vtable = [0] * numfields
  150. self.objectEnd = self.Offset()
  151. self.nested = True
  152. def WriteVtable(self):
  153. """WriteVtable serializes the vtable for the current object, if needed.
  154. Before writing out the vtable, this checks pre-existing vtables for
  155. equality to this one. If an equal vtable is found, point the object to
  156. the existing vtable and return.
  157. Because vtable values are sensitive to alignment of object data, not
  158. all logically-equal vtables will be deduplicated.
  159. A vtable has the following format:
  160. <VOffsetT: size of the vtable in bytes, including this value>
  161. <VOffsetT: size of the object in bytes, including the vtable offset>
  162. <VOffsetT: offset for a field> * N, where N is the number of fields
  163. in the schema for this type. Includes deprecated fields.
  164. Thus, a vtable is made of 2 + N elements, each VOffsetT bytes wide.
  165. An object has the following format:
  166. <SOffsetT: offset to this object's vtable (may be negative)>
  167. <byte: data>+
  168. """
  169. # Prepend a zero scalar to the object. Later in this function we'll
  170. # write an offset here that points to the object's vtable:
  171. self.PrependSOffsetTRelative(0)
  172. objectOffset = self.Offset()
  173. vtKey = []
  174. trim = True
  175. for elem in reversed(self.current_vtable):
  176. if elem == 0:
  177. if trim:
  178. continue
  179. else:
  180. elem = objectOffset - elem
  181. trim = False
  182. vtKey.append(elem)
  183. objectSize = UOffsetTFlags.py_type(objectOffset - self.objectEnd)
  184. vtKey.append(objectSize)
  185. vtKey = tuple(vtKey)
  186. # calculate the size of the object
  187. vt2Offset = self.vtables.get(vtKey)
  188. if vt2Offset is None:
  189. # Did not find a vtable, so write this one to the buffer.
  190. # Write out the current vtable in reverse , because
  191. # serialization occurs in last-first order:
  192. i = len(self.current_vtable) - 1
  193. trailing = 0
  194. trim = True
  195. while i >= 0:
  196. off = 0
  197. elem = self.current_vtable[i]
  198. i -= 1
  199. if elem == 0:
  200. if trim:
  201. trailing += 1
  202. continue
  203. else:
  204. # Forward reference to field;
  205. # use 32bit number to ensure no overflow:
  206. off = objectOffset - elem
  207. trim = False
  208. self.PrependVOffsetT(off)
  209. # The two metadata fields are written last.
  210. # First, store the object bytesize:
  211. self.PrependVOffsetT(VOffsetTFlags.py_type(objectSize))
  212. # Second, store the vtable bytesize:
  213. vBytes = len(self.current_vtable) - trailing + VtableMetadataFields
  214. vBytes *= N.VOffsetTFlags.bytewidth
  215. self.PrependVOffsetT(VOffsetTFlags.py_type(vBytes))
  216. # Next, write the offset to the new vtable in the
  217. # already-allocated SOffsetT at the beginning of this object:
  218. objectStart = SOffsetTFlags.py_type(len(self.Bytes) - objectOffset)
  219. encode.Write(
  220. packer.soffset,
  221. self.Bytes,
  222. objectStart,
  223. SOffsetTFlags.py_type(self.Offset() - objectOffset),
  224. )
  225. # Finally, store this vtable in memory for future
  226. # deduplication:
  227. self.vtables[vtKey] = self.Offset()
  228. else:
  229. # Found a duplicate vtable.
  230. objectStart = SOffsetTFlags.py_type(len(self.Bytes) - objectOffset)
  231. self.head = UOffsetTFlags.py_type(objectStart)
  232. # Write the offset to the found vtable in the
  233. # already-allocated SOffsetT at the beginning of this object:
  234. encode.Write(
  235. packer.soffset,
  236. self.Bytes,
  237. self.Head(),
  238. SOffsetTFlags.py_type(vt2Offset - objectOffset),
  239. )
  240. self.current_vtable = None
  241. return objectOffset
  242. def EndObject(self):
  243. """EndObject writes data necessary to finish object construction."""
  244. self.assertNested()
  245. self.nested = False
  246. return self.WriteVtable()
  247. def GrowByteBuffer(self):
  248. """Doubles the size of the byteslice, and copies the old data towards
  249. the end of the new buffer (since we build the buffer backwards).
  250. """
  251. if len(self.Bytes) == Builder.MAX_BUFFER_SIZE:
  252. msg = "flatbuffers: cannot grow buffer beyond 2 gigabytes"
  253. raise BuilderSizeError(msg)
  254. newSize = min(len(self.Bytes) * 2, Builder.MAX_BUFFER_SIZE)
  255. if newSize == 0:
  256. newSize = 1
  257. bytes2 = bytearray(newSize)
  258. bytes2[newSize - len(self.Bytes) :] = self.Bytes
  259. self.Bytes = bytes2
  260. ## @endcond
  261. def Head(self):
  262. """Get the start of useful data in the underlying byte buffer.
  263. Note: unlike other functions, this value is interpreted as from the
  264. left.
  265. """
  266. ## @cond FLATBUFFERS_INTERNAL
  267. return self.head
  268. ## @endcond
  269. ## @cond FLATBUFFERS_INTERNAL
  270. def Offset(self):
  271. """Offset relative to the end of the buffer."""
  272. return len(self.Bytes) - self.head
  273. def Pad(self, n):
  274. """Pad places zeros at the current offset."""
  275. if n <= 0:
  276. return
  277. new_head = self.head - n
  278. self.Bytes[new_head : self.head] = b"\x00" * n
  279. self.head = new_head
  280. def Prep(self, size, additionalBytes):
  281. """Prep prepares to write an element of `size` after `additional_bytes`
  282. have been written, e.g. if you write a string, you need to align
  283. such the int length field is aligned to SizeInt32, and the string
  284. data follows it directly.
  285. If all you need to do is align, `additionalBytes` will be 0.
  286. """
  287. # Track the biggest thing we've ever aligned to.
  288. if size > self.minalign:
  289. self.minalign = size
  290. # Find the amount of alignment needed such that `size` is properly
  291. # aligned after `additionalBytes`:
  292. head = self.head
  293. buf_len = len(self.Bytes)
  294. alignSize = (~(buf_len - head + additionalBytes)) + 1
  295. alignSize &= size - 1
  296. # Reallocate the buffer if needed:
  297. needed = alignSize + size + additionalBytes
  298. while head < needed:
  299. oldBufSize = buf_len
  300. self.GrowByteBuffer()
  301. buf_len = len(self.Bytes)
  302. head += buf_len - oldBufSize
  303. self.head = head
  304. self.Pad(alignSize)
  305. def PrependSOffsetTRelative(self, off):
  306. """PrependSOffsetTRelative prepends an SOffsetT, relative to where it
  307. will be written.
  308. """
  309. # Ensure alignment is already done:
  310. self.Prep(N.SOffsetTFlags.bytewidth, 0)
  311. if not (off <= self.Offset()):
  312. msg = "flatbuffers: Offset arithmetic error."
  313. raise OffsetArithmeticError(msg)
  314. off2 = self.Offset() - off + N.SOffsetTFlags.bytewidth
  315. self.PlaceSOffsetT(off2)
  316. ## @endcond
  317. def PrependUOffsetTRelative(self, off):
  318. """Prepends an unsigned offset into vector data, relative to where it
  319. will be written.
  320. """
  321. # Ensure alignment is already done:
  322. self.Prep(N.UOffsetTFlags.bytewidth, 0)
  323. if not (off <= self.Offset()):
  324. msg = "flatbuffers: Offset arithmetic error."
  325. raise OffsetArithmeticError(msg)
  326. off2 = self.Offset() - off + N.UOffsetTFlags.bytewidth
  327. self.PlaceUOffsetT(off2)
  328. ## @cond FLATBUFFERS_INTERNAL
  329. def StartVector(self, elemSize, numElems, alignment):
  330. """StartVector initializes bookkeeping for writing a new vector.
  331. A vector has the following format:
  332. - <UOffsetT: number of elements in this vector>
  333. - <T: data>+, where T is the type of elements of this vector.
  334. """
  335. self.assertNotNested()
  336. self.nested = True
  337. self.vectorNumElems = numElems
  338. self.Prep(N.Uint32Flags.bytewidth, elemSize * numElems)
  339. self.Prep(alignment, elemSize * numElems) # In case alignment > int.
  340. return self.Offset()
  341. ## @endcond
  342. def EndVector(self, numElems=None):
  343. """EndVector writes data necessary to finish vector construction."""
  344. self.assertNested()
  345. ## @cond FLATBUFFERS_INTERNAL
  346. self.nested = False
  347. ## @endcond
  348. if numElems:
  349. warnings.warn("numElems is deprecated.", DeprecationWarning, stacklevel=2)
  350. if numElems != self.vectorNumElems:
  351. raise EndVectorLengthMismatched()
  352. # we already made space for this, so write without PrependUint32
  353. self.PlaceUOffsetT(self.vectorNumElems)
  354. self.vectorNumElems = None
  355. return self.Offset()
  356. def CreateSharedString(self, s, encoding="utf-8", errors="strict"):
  357. """CreateSharedString checks if the string is already written to the buffer
  358. before calling CreateString.
  359. """
  360. if not self.sharedStrings:
  361. self.sharedStrings = {}
  362. elif s in self.sharedStrings:
  363. return self.sharedStrings[s]
  364. off = self.CreateString(s, encoding, errors)
  365. self.sharedStrings[s] = off
  366. return off
  367. def CreateString(self, s, encoding="utf-8", errors="strict"):
  368. """CreateString writes a null-terminated byte string as a vector."""
  369. self.assertNotNested()
  370. ## @cond FLATBUFFERS_INTERNAL
  371. self.nested = True
  372. ## @endcond
  373. if isinstance(s, compat.string_types):
  374. x = s.encode(encoding, errors)
  375. elif isinstance(s, compat.binary_types):
  376. x = s
  377. else:
  378. raise TypeError("non-string passed to CreateString")
  379. payload_len = len(x)
  380. self.Prep(N.UOffsetTFlags.bytewidth, (payload_len + 1) * N.Uint8Flags.bytewidth)
  381. self.Place(0, N.Uint8Flags)
  382. new_head = self.head - payload_len
  383. self.head = new_head
  384. self.Bytes[new_head : new_head + payload_len] = x
  385. self.vectorNumElems = payload_len
  386. return self.EndVector()
  387. def CreateByteVector(self, x):
  388. """CreateString writes a byte vector."""
  389. self.assertNotNested()
  390. ## @cond FLATBUFFERS_INTERNAL
  391. self.nested = True
  392. ## @endcond
  393. if not isinstance(x, compat.binary_types):
  394. raise TypeError("non-byte vector passed to CreateByteVector")
  395. data_len = len(x)
  396. self.Prep(N.UOffsetTFlags.bytewidth, data_len * N.Uint8Flags.bytewidth)
  397. new_head = self.head - data_len
  398. self.head = new_head
  399. self.Bytes[new_head : new_head + data_len] = x
  400. self.vectorNumElems = data_len
  401. return self.EndVector()
  402. def CreateNumpyVector(self, x):
  403. """CreateNumpyVector writes a numpy array into the buffer."""
  404. if np is None:
  405. # Numpy is required for this feature
  406. raise NumpyRequiredForThisFeature("Numpy was not found.")
  407. if not isinstance(x, np.ndarray):
  408. raise TypeError("non-numpy-ndarray passed to CreateNumpyVector")
  409. if x.dtype.kind not in ["b", "i", "u", "f"]:
  410. raise TypeError("numpy-ndarray holds elements of unsupported datatype")
  411. if x.ndim > 1:
  412. raise TypeError("multidimensional-ndarray passed to CreateNumpyVector")
  413. self.StartVector(x.itemsize, x.size, x.dtype.alignment)
  414. # Ensure little endian byte ordering
  415. if x.dtype.str[0] == "<":
  416. x_lend = x
  417. else:
  418. x_lend = x.byteswap(inplace=False)
  419. # tobytes ensures c_contiguous ordering
  420. payload = x_lend.tobytes(order="C")
  421. # Calculate total length
  422. payload_len = len(payload)
  423. new_head = self.head - payload_len
  424. self.head = new_head
  425. self.Bytes[new_head : new_head + payload_len] = payload
  426. self.vectorNumElems = x.size
  427. return self.EndVector()
  428. ## @cond FLATBUFFERS_INTERNAL
  429. def assertNested(self):
  430. """Check that we are in the process of building an object."""
  431. if not self.nested:
  432. raise IsNotNestedError()
  433. def assertNotNested(self):
  434. """Check that no other objects are being built while making this object.
  435. If not, raise an exception.
  436. """
  437. if self.nested:
  438. raise IsNestedError()
  439. def assertStructIsInline(self, obj):
  440. """Structs are always stored inline, so need to be created right
  441. where they are used. You'll get this error if you created it
  442. elsewhere.
  443. """
  444. N.enforce_number(obj, N.UOffsetTFlags)
  445. if obj != self.Offset():
  446. msg = (
  447. "flatbuffers: Tried to write a Struct at an Offset that "
  448. "is different from the current Offset of the Builder."
  449. )
  450. raise StructIsNotInlineError(msg)
  451. def Slot(self, slotnum):
  452. """Slot sets the vtable key `voffset` to the current location in the
  453. buffer.
  454. """
  455. self.assertNested()
  456. self.current_vtable[slotnum] = self.Offset()
  457. ## @endcond
  458. def __Finish(self, rootTable, sizePrefix, file_identifier=None):
  459. """Finish finalizes a buffer, pointing to the given `rootTable`."""
  460. N.enforce_number(rootTable, N.UOffsetTFlags)
  461. prepSize = N.UOffsetTFlags.bytewidth
  462. if file_identifier is not None:
  463. prepSize += N.Int32Flags.bytewidth
  464. if sizePrefix:
  465. prepSize += N.Int32Flags.bytewidth
  466. self.Prep(self.minalign, prepSize)
  467. if file_identifier is not None:
  468. self.Prep(N.UOffsetTFlags.bytewidth, encode.FILE_IDENTIFIER_LENGTH)
  469. # Convert bytes object file_identifier to an array of 4 8-bit integers,
  470. # and use big-endian to enforce size compliance.
  471. # https://docs.python.org/2/library/struct.html#format-characters
  472. file_identifier = N.struct.unpack(">BBBB", file_identifier)
  473. for i in range(encode.FILE_IDENTIFIER_LENGTH - 1, -1, -1):
  474. # Place the bytes of the file_identifer in reverse order:
  475. self.Place(file_identifier[i], N.Uint8Flags)
  476. self.PrependUOffsetTRelative(rootTable)
  477. if sizePrefix:
  478. size = len(self.Bytes) - self.head
  479. N.enforce_number(size, N.Int32Flags)
  480. self.PrependInt32(size)
  481. self.finished = True
  482. return self.head
  483. def Finish(self, rootTable, file_identifier=None):
  484. """Finish finalizes a buffer, pointing to the given `rootTable`."""
  485. return self.__Finish(rootTable, False, file_identifier=file_identifier)
  486. def FinishSizePrefixed(self, rootTable, file_identifier=None):
  487. """Finish finalizes a buffer, pointing to the given `rootTable`,
  488. with the size prefixed.
  489. """
  490. return self.__Finish(rootTable, True, file_identifier=file_identifier)
  491. ## @cond FLATBUFFERS_INTERNAL
  492. def Prepend(self, flags, off):
  493. self.Prep(flags.bytewidth, 0)
  494. self.Place(off, flags)
  495. def PrependSlot(self, flags, o, x, d):
  496. if x is not None:
  497. N.enforce_number(x, flags)
  498. if d is not None:
  499. N.enforce_number(d, flags)
  500. if x != d or (self.forceDefaults and d is not None):
  501. self.Prepend(flags, x)
  502. self.Slot(o)
  503. def PrependBoolSlot(self, *args):
  504. self.PrependSlot(N.BoolFlags, *args)
  505. def PrependByteSlot(self, *args):
  506. self.PrependSlot(N.Uint8Flags, *args)
  507. def PrependUint8Slot(self, *args):
  508. self.PrependSlot(N.Uint8Flags, *args)
  509. def PrependUint16Slot(self, *args):
  510. self.PrependSlot(N.Uint16Flags, *args)
  511. def PrependUint32Slot(self, *args):
  512. self.PrependSlot(N.Uint32Flags, *args)
  513. def PrependUint64Slot(self, *args):
  514. self.PrependSlot(N.Uint64Flags, *args)
  515. def PrependInt8Slot(self, *args):
  516. self.PrependSlot(N.Int8Flags, *args)
  517. def PrependInt16Slot(self, *args):
  518. self.PrependSlot(N.Int16Flags, *args)
  519. def PrependInt32Slot(self, *args):
  520. self.PrependSlot(N.Int32Flags, *args)
  521. def PrependInt64Slot(self, *args):
  522. self.PrependSlot(N.Int64Flags, *args)
  523. def PrependFloat32Slot(self, *args):
  524. self.PrependSlot(N.Float32Flags, *args)
  525. def PrependFloat64Slot(self, *args):
  526. self.PrependSlot(N.Float64Flags, *args)
  527. def PrependUOffsetTRelativeSlot(self, o, x, d):
  528. """PrependUOffsetTRelativeSlot prepends an UOffsetT onto the object at
  529. vtable slot `o`. If value `x` equals default `d`, then the slot will
  530. be set to zero and no other data will be written.
  531. """
  532. if x != d or self.forceDefaults:
  533. self.PrependUOffsetTRelative(x)
  534. self.Slot(o)
  535. def PrependStructSlot(self, v, x, d):
  536. """PrependStructSlot prepends a struct onto the object at vtable slot `o`.
  537. Structs are stored inline, so nothing additional is being added. In
  538. generated code, `d` is always 0.
  539. """
  540. N.enforce_number(d, N.UOffsetTFlags)
  541. if x != d:
  542. self.assertStructIsInline(x)
  543. self.Slot(v)
  544. ## @endcond
  545. def PrependBool(self, x):
  546. """Prepend a `bool` to the Builder buffer.
  547. Note: aligns and checks for space.
  548. """
  549. self.Prepend(N.BoolFlags, x)
  550. def PrependByte(self, x):
  551. """Prepend a `byte` to the Builder buffer.
  552. Note: aligns and checks for space.
  553. """
  554. self.Prepend(N.Uint8Flags, x)
  555. def PrependUint8(self, x):
  556. """Prepend an `uint8` to the Builder buffer.
  557. Note: aligns and checks for space.
  558. """
  559. self.Prepend(N.Uint8Flags, x)
  560. def PrependUint16(self, x):
  561. """Prepend an `uint16` to the Builder buffer.
  562. Note: aligns and checks for space.
  563. """
  564. self.Prepend(N.Uint16Flags, x)
  565. def PrependUint32(self, x):
  566. """Prepend an `uint32` to the Builder buffer.
  567. Note: aligns and checks for space.
  568. """
  569. self.Prepend(N.Uint32Flags, x)
  570. def PrependUint64(self, x):
  571. """Prepend an `uint64` to the Builder buffer.
  572. Note: aligns and checks for space.
  573. """
  574. self.Prepend(N.Uint64Flags, x)
  575. def PrependInt8(self, x):
  576. """Prepend an `int8` to the Builder buffer.
  577. Note: aligns and checks for space.
  578. """
  579. self.Prepend(N.Int8Flags, x)
  580. def PrependInt16(self, x):
  581. """Prepend an `int16` to the Builder buffer.
  582. Note: aligns and checks for space.
  583. """
  584. self.Prepend(N.Int16Flags, x)
  585. def PrependInt32(self, x):
  586. """Prepend an `int32` to the Builder buffer.
  587. Note: aligns and checks for space.
  588. """
  589. self.Prepend(N.Int32Flags, x)
  590. def PrependInt64(self, x):
  591. """Prepend an `int64` to the Builder buffer.
  592. Note: aligns and checks for space.
  593. """
  594. self.Prepend(N.Int64Flags, x)
  595. def PrependFloat32(self, x):
  596. """Prepend a `float32` to the Builder buffer.
  597. Note: aligns and checks for space.
  598. """
  599. self.Prepend(N.Float32Flags, x)
  600. def PrependFloat64(self, x):
  601. """Prepend a `float64` to the Builder buffer.
  602. Note: aligns and checks for space.
  603. """
  604. self.Prepend(N.Float64Flags, x)
  605. def ForceDefaults(self, forceDefaults):
  606. """In order to save space, fields that are set to their default value
  607. don't get serialized into the buffer. Forcing defaults provides a
  608. way to manually disable this optimization. When set to `True`, will
  609. always serialize default values.
  610. """
  611. self.forceDefaults = forceDefaults
  612. ##############################################################
  613. ## @cond FLATBUFFERS_INTERNAL
  614. def PrependVOffsetT(self, x):
  615. self.Prepend(N.VOffsetTFlags, x)
  616. def Place(self, x, flags):
  617. """Place prepends a value specified by `flags` to the Builder,
  618. without checking for available space.
  619. """
  620. N.enforce_number(x, flags)
  621. new_head = self.head - flags.bytewidth
  622. self.head = new_head
  623. encode.Write(flags.packer_type, self.Bytes, new_head, x)
  624. def PlaceVOffsetT(self, x):
  625. """PlaceVOffsetT prepends a VOffsetT to the Builder, without checking
  626. for space.
  627. """
  628. N.enforce_number(x, N.VOffsetTFlags)
  629. new_head = self.head - N.VOffsetTFlags.bytewidth
  630. self.head = new_head
  631. encode.Write(packer.voffset, self.Bytes, new_head, x)
  632. def PlaceSOffsetT(self, x):
  633. """PlaceSOffsetT prepends a SOffsetT to the Builder, without checking
  634. for space.
  635. """
  636. N.enforce_number(x, N.SOffsetTFlags)
  637. new_head = self.head - N.SOffsetTFlags.bytewidth
  638. self.head = new_head
  639. encode.Write(packer.soffset, self.Bytes, new_head, x)
  640. def PlaceUOffsetT(self, x):
  641. """PlaceUOffsetT prepends a UOffsetT to the Builder, without checking
  642. for space.
  643. """
  644. N.enforce_number(x, N.UOffsetTFlags)
  645. new_head = self.head - N.UOffsetTFlags.bytewidth
  646. self.head = new_head
  647. encode.Write(packer.uoffset, self.Bytes, new_head, x)
  648. ## @endcond
  649. ## @}