m2m模型翻译
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

824 lines
27 KiB

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