builder.go 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856
  1. package flatbuffers
  2. import "sort"
  3. // Builder is a state machine for creating FlatBuffer objects.
  4. // Use a Builder to construct object(s) starting from leaf nodes.
  5. //
  6. // A Builder constructs byte buffers in a last-first manner for simplicity and
  7. // performance.
  8. type Builder struct {
  9. // `Bytes` gives raw access to the buffer. Most users will want to use
  10. // FinishedBytes() instead.
  11. Bytes []byte
  12. minalign int
  13. vtable []UOffsetT
  14. objectEnd UOffsetT
  15. vtables []UOffsetT
  16. head UOffsetT
  17. nested bool
  18. finished bool
  19. sharedStrings map[string]UOffsetT
  20. }
  21. const fileIdentifierLength = 4
  22. const sizePrefixLength = 4
  23. // NewBuilder initializes a Builder of size `initial_size`.
  24. // The internal buffer is grown as needed.
  25. func NewBuilder(initialSize int) *Builder {
  26. if initialSize <= 0 {
  27. initialSize = 0
  28. }
  29. b := &Builder{}
  30. b.Bytes = make([]byte, initialSize)
  31. b.head = UOffsetT(initialSize)
  32. b.minalign = 1
  33. b.vtables = make([]UOffsetT, 0, 16) // sensible default capacity
  34. return b
  35. }
  36. // Reset truncates the underlying Builder buffer, facilitating alloc-free
  37. // reuse of a Builder. It also resets bookkeeping data.
  38. func (b *Builder) Reset() {
  39. if b.Bytes != nil {
  40. b.Bytes = b.Bytes[:cap(b.Bytes)]
  41. }
  42. if b.vtables != nil {
  43. b.vtables = b.vtables[:0]
  44. }
  45. if b.vtable != nil {
  46. b.vtable = b.vtable[:0]
  47. }
  48. if b.sharedStrings != nil {
  49. for key := range b.sharedStrings {
  50. delete(b.sharedStrings, key)
  51. }
  52. }
  53. b.head = UOffsetT(len(b.Bytes))
  54. b.minalign = 1
  55. b.nested = false
  56. b.finished = false
  57. }
  58. // FinishedBytes returns a pointer to the written data in the byte buffer.
  59. // Panics if the builder is not in a finished state (which is caused by calling
  60. // `Finish()`).
  61. func (b *Builder) FinishedBytes() []byte {
  62. b.assertFinished()
  63. return b.Bytes[b.Head():]
  64. }
  65. // StartObject initializes bookkeeping for writing a new object.
  66. func (b *Builder) StartObject(numfields int) {
  67. b.assertNotNested()
  68. b.nested = true
  69. // use 32-bit offsets so that arithmetic doesn't overflow.
  70. if cap(b.vtable) < numfields || b.vtable == nil {
  71. b.vtable = make([]UOffsetT, numfields)
  72. } else {
  73. b.vtable = b.vtable[:numfields]
  74. for i := 0; i < len(b.vtable); i++ {
  75. b.vtable[i] = 0
  76. }
  77. }
  78. b.objectEnd = b.Offset()
  79. }
  80. // WriteVtable serializes the vtable for the current object, if applicable.
  81. //
  82. // Before writing out the vtable, this checks pre-existing vtables for equality
  83. // to this one. If an equal vtable is found, point the object to the existing
  84. // vtable and return.
  85. //
  86. // Because vtable values are sensitive to alignment of object data, not all
  87. // logically-equal vtables will be deduplicated.
  88. //
  89. // A vtable has the following format:
  90. // <VOffsetT: size of the vtable in bytes, including this value>
  91. // <VOffsetT: size of the object in bytes, including the vtable offset>
  92. // <VOffsetT: offset for a field> * N, where N is the number of fields in
  93. // the schema for this type. Includes deprecated fields.
  94. // Thus, a vtable is made of 2 + N elements, each SizeVOffsetT bytes wide.
  95. //
  96. // An object has the following format:
  97. // <SOffsetT: offset to this object's vtable (may be negative)>
  98. // <byte: data>+
  99. func (b *Builder) WriteVtable() (n UOffsetT) {
  100. // Prepend a zero scalar to the object. Later in this function we'll
  101. // write an offset here that points to the object's vtable:
  102. b.PrependSOffsetT(0)
  103. objectOffset := b.Offset()
  104. existingVtable := UOffsetT(0)
  105. // Trim vtable of trailing zeroes.
  106. i := len(b.vtable) - 1
  107. for ; i >= 0 && b.vtable[i] == 0; i-- {
  108. }
  109. b.vtable = b.vtable[:i+1]
  110. // Search backwards through existing vtables, because similar vtables
  111. // are likely to have been recently appended. See
  112. // BenchmarkVtableDeduplication for a case in which this heuristic
  113. // saves about 30% of the time used in writing objects with duplicate
  114. // tables.
  115. for i := len(b.vtables) - 1; i >= 0; i-- {
  116. // Find the other vtable, which is associated with `i`:
  117. vt2Offset := b.vtables[i]
  118. vt2Start := len(b.Bytes) - int(vt2Offset)
  119. vt2Len := GetVOffsetT(b.Bytes[vt2Start:])
  120. metadata := VtableMetadataFields * SizeVOffsetT
  121. vt2End := vt2Start + int(vt2Len)
  122. vt2 := b.Bytes[vt2Start+metadata : vt2End]
  123. // Compare the other vtable to the one under consideration.
  124. // If they are equal, store the offset and break:
  125. if vtableEqual(b.vtable, objectOffset, vt2) {
  126. existingVtable = vt2Offset
  127. break
  128. }
  129. }
  130. if existingVtable == 0 {
  131. // Did not find a vtable, so write this one to the buffer.
  132. // Write out the current vtable in reverse , because
  133. // serialization occurs in last-first order:
  134. for i := len(b.vtable) - 1; i >= 0; i-- {
  135. var off UOffsetT
  136. if b.vtable[i] != 0 {
  137. // Forward reference to field;
  138. // use 32bit number to assert no overflow:
  139. off = objectOffset - b.vtable[i]
  140. }
  141. b.PrependVOffsetT(VOffsetT(off))
  142. }
  143. // The two metadata fields are written last.
  144. // First, store the object bytesize:
  145. objectSize := objectOffset - b.objectEnd
  146. b.PrependVOffsetT(VOffsetT(objectSize))
  147. // Second, store the vtable bytesize:
  148. vBytes := (len(b.vtable) + VtableMetadataFields) * SizeVOffsetT
  149. b.PrependVOffsetT(VOffsetT(vBytes))
  150. // Next, write the offset to the new vtable in the
  151. // already-allocated SOffsetT at the beginning of this object:
  152. objectStart := SOffsetT(len(b.Bytes)) - SOffsetT(objectOffset)
  153. WriteSOffsetT(b.Bytes[objectStart:],
  154. SOffsetT(b.Offset())-SOffsetT(objectOffset))
  155. // Finally, store this vtable in memory for future
  156. // deduplication:
  157. b.vtables = append(b.vtables, b.Offset())
  158. } else {
  159. // Found a duplicate vtable.
  160. objectStart := SOffsetT(len(b.Bytes)) - SOffsetT(objectOffset)
  161. b.head = UOffsetT(objectStart)
  162. // Write the offset to the found vtable in the
  163. // already-allocated SOffsetT at the beginning of this object:
  164. WriteSOffsetT(b.Bytes[b.head:],
  165. SOffsetT(existingVtable)-SOffsetT(objectOffset))
  166. }
  167. b.vtable = b.vtable[:0]
  168. return objectOffset
  169. }
  170. // EndObject writes data necessary to finish object construction.
  171. func (b *Builder) EndObject() UOffsetT {
  172. b.assertNested()
  173. n := b.WriteVtable()
  174. b.nested = false
  175. return n
  176. }
  177. // Doubles the size of the byteslice, and copies the old data towards the
  178. // end of the new byteslice (since we build the buffer backwards).
  179. func (b *Builder) growByteBuffer() {
  180. if (int64(len(b.Bytes)) & int64(0xC0000000)) != 0 {
  181. panic("cannot grow buffer beyond 2 gigabytes")
  182. }
  183. newLen := len(b.Bytes) * 2
  184. if newLen == 0 {
  185. newLen = 1
  186. }
  187. if cap(b.Bytes) >= newLen {
  188. b.Bytes = b.Bytes[:newLen]
  189. } else {
  190. extension := make([]byte, newLen-len(b.Bytes))
  191. b.Bytes = append(b.Bytes, extension...)
  192. }
  193. middle := newLen / 2
  194. copy(b.Bytes[middle:], b.Bytes[:middle])
  195. }
  196. // Head gives the start of useful data in the underlying byte buffer.
  197. // Note: unlike other functions, this value is interpreted as from the left.
  198. func (b *Builder) Head() UOffsetT {
  199. return b.head
  200. }
  201. // Offset relative to the end of the buffer.
  202. func (b *Builder) Offset() UOffsetT {
  203. return UOffsetT(len(b.Bytes)) - b.head
  204. }
  205. // Pad places zeros at the current offset.
  206. func (b *Builder) Pad(n int) {
  207. for i := 0; i < n; i++ {
  208. b.PlaceByte(0)
  209. }
  210. }
  211. // Prep prepares to write an element of `size` after `additional_bytes`
  212. // have been written, e.g. if you write a string, you need to align such
  213. // the int length field is aligned to SizeInt32, and the string data follows it
  214. // directly.
  215. // If all you need to do is align, `additionalBytes` will be 0.
  216. func (b *Builder) Prep(size, additionalBytes int) {
  217. // Track the biggest thing we've ever aligned to.
  218. if size > b.minalign {
  219. b.minalign = size
  220. }
  221. // Find the amount of alignment needed such that `size` is properly
  222. // aligned after `additionalBytes`:
  223. alignSize := (^(len(b.Bytes) - int(b.Head()) + additionalBytes)) + 1
  224. alignSize &= (size - 1)
  225. // Reallocate the buffer if needed:
  226. for int(b.head) <= alignSize+size+additionalBytes {
  227. oldBufSize := len(b.Bytes)
  228. b.growByteBuffer()
  229. b.head += UOffsetT(len(b.Bytes) - oldBufSize)
  230. }
  231. b.Pad(alignSize)
  232. }
  233. // PrependSOffsetT prepends an SOffsetT, relative to where it will be written.
  234. func (b *Builder) PrependSOffsetT(off SOffsetT) {
  235. b.Prep(SizeSOffsetT, 0) // Ensure alignment is already done.
  236. if !(UOffsetT(off) <= b.Offset()) {
  237. panic("unreachable: off <= b.Offset()")
  238. }
  239. off2 := SOffsetT(b.Offset()) - off + SOffsetT(SizeSOffsetT)
  240. b.PlaceSOffsetT(off2)
  241. }
  242. // PrependUOffsetT prepends an UOffsetT, relative to where it will be written.
  243. func (b *Builder) PrependUOffsetT(off UOffsetT) {
  244. b.Prep(SizeUOffsetT, 0) // Ensure alignment is already done.
  245. if !(off <= b.Offset()) {
  246. panic("unreachable: off <= b.Offset()")
  247. }
  248. off2 := b.Offset() - off + UOffsetT(SizeUOffsetT)
  249. b.PlaceUOffsetT(off2)
  250. }
  251. // StartVector initializes bookkeeping for writing a new vector.
  252. //
  253. // A vector has the following format:
  254. // <UOffsetT: number of elements in this vector>
  255. // <T: data>+, where T is the type of elements of this vector.
  256. func (b *Builder) StartVector(elemSize, numElems, alignment int) UOffsetT {
  257. b.assertNotNested()
  258. b.nested = true
  259. b.Prep(SizeUint32, elemSize*numElems)
  260. b.Prep(alignment, elemSize*numElems) // Just in case alignment > int.
  261. return b.Offset()
  262. }
  263. // EndVector writes data necessary to finish vector construction.
  264. func (b *Builder) EndVector(vectorNumElems int) UOffsetT {
  265. b.assertNested()
  266. // we already made space for this, so write without PrependUint32
  267. b.PlaceUOffsetT(UOffsetT(vectorNumElems))
  268. b.nested = false
  269. return b.Offset()
  270. }
  271. // CreateVectorOfTables serializes slice of table offsets into a vector.
  272. func (b *Builder) CreateVectorOfTables(offsets []UOffsetT) UOffsetT {
  273. b.assertNotNested()
  274. b.StartVector(4, len(offsets), 4)
  275. for i := len(offsets) - 1; i >= 0; i-- {
  276. b.PrependUOffsetT(offsets[i])
  277. }
  278. return b.EndVector(len(offsets))
  279. }
  280. type KeyCompare func(o1, o2 UOffsetT, buf []byte) bool
  281. func (b *Builder) CreateVectorOfSortedTables(offsets []UOffsetT, keyCompare KeyCompare) UOffsetT {
  282. sort.Slice(offsets, func(i, j int) bool {
  283. return keyCompare(offsets[i], offsets[j], b.Bytes)
  284. })
  285. return b.CreateVectorOfTables(offsets)
  286. }
  287. // CreateSharedString Checks if the string is already written
  288. // to the buffer before calling CreateString
  289. func (b *Builder) CreateSharedString(s string) UOffsetT {
  290. if b.sharedStrings == nil {
  291. b.sharedStrings = make(map[string]UOffsetT)
  292. }
  293. if v, ok := b.sharedStrings[s]; ok {
  294. return v
  295. }
  296. off := b.CreateString(s)
  297. b.sharedStrings[s] = off
  298. return off
  299. }
  300. // CreateString writes a null-terminated string as a vector.
  301. func (b *Builder) CreateString(s string) UOffsetT {
  302. b.assertNotNested()
  303. b.nested = true
  304. b.Prep(int(SizeUOffsetT), (len(s)+1)*SizeByte)
  305. b.PlaceByte(0)
  306. l := UOffsetT(len(s))
  307. b.head -= l
  308. copy(b.Bytes[b.head:b.head+l], s)
  309. return b.EndVector(len(s))
  310. }
  311. // CreateByteString writes a byte slice as a string (null-terminated).
  312. func (b *Builder) CreateByteString(s []byte) UOffsetT {
  313. b.assertNotNested()
  314. b.nested = true
  315. b.Prep(int(SizeUOffsetT), (len(s)+1)*SizeByte)
  316. b.PlaceByte(0)
  317. l := UOffsetT(len(s))
  318. b.head -= l
  319. copy(b.Bytes[b.head:b.head+l], s)
  320. return b.EndVector(len(s))
  321. }
  322. // CreateByteVector writes a ubyte vector
  323. func (b *Builder) CreateByteVector(v []byte) UOffsetT {
  324. b.assertNotNested()
  325. b.nested = true
  326. b.Prep(int(SizeUOffsetT), len(v)*SizeByte)
  327. l := UOffsetT(len(v))
  328. b.head -= l
  329. copy(b.Bytes[b.head:b.head+l], v)
  330. return b.EndVector(len(v))
  331. }
  332. func (b *Builder) assertNested() {
  333. // If you get this assert, you're in an object while trying to write
  334. // data that belongs outside of an object.
  335. // To fix this, write non-inline data (like vectors) before creating
  336. // objects.
  337. if !b.nested {
  338. panic("Incorrect creation order: must be inside object.")
  339. }
  340. }
  341. func (b *Builder) assertNotNested() {
  342. // If you hit this, you're trying to construct a Table/Vector/String
  343. // during the construction of its parent table (between the MyTableBuilder
  344. // and builder.Finish()).
  345. // Move the creation of these sub-objects to above the MyTableBuilder to
  346. // not get this assert.
  347. // Ignoring this assert may appear to work in simple cases, but the reason
  348. // it is here is that storing objects in-line may cause vtable offsets
  349. // to not fit anymore. It also leads to vtable duplication.
  350. if b.nested {
  351. panic("Incorrect creation order: object must not be nested.")
  352. }
  353. }
  354. func (b *Builder) assertFinished() {
  355. // If you get this assert, you're attempting to get access a buffer
  356. // which hasn't been finished yet. Be sure to call builder.Finish()
  357. // with your root table.
  358. // If you really need to access an unfinished buffer, use the Bytes
  359. // buffer directly.
  360. if !b.finished {
  361. panic("Incorrect use of FinishedBytes(): must call 'Finish' first.")
  362. }
  363. }
  364. // PrependBoolSlot prepends a bool onto the object at vtable slot `o`.
  365. // If value `x` equals default `d`, then the slot will be set to zero and no
  366. // other data will be written.
  367. func (b *Builder) PrependBoolSlot(o int, x, d bool) {
  368. val := byte(0)
  369. if x {
  370. val = 1
  371. }
  372. def := byte(0)
  373. if d {
  374. def = 1
  375. }
  376. b.PrependByteSlot(o, val, def)
  377. }
  378. // PrependByteSlot prepends a byte onto the object at vtable slot `o`.
  379. // If value `x` equals default `d`, then the slot will be set to zero and no
  380. // other data will be written.
  381. func (b *Builder) PrependByteSlot(o int, x, d byte) {
  382. if x != d {
  383. b.PrependByte(x)
  384. b.Slot(o)
  385. }
  386. }
  387. // PrependUint8Slot prepends a uint8 onto the object at vtable slot `o`.
  388. // If value `x` equals default `d`, then the slot will be set to zero and no
  389. // other data will be written.
  390. func (b *Builder) PrependUint8Slot(o int, x, d uint8) {
  391. if x != d {
  392. b.PrependUint8(x)
  393. b.Slot(o)
  394. }
  395. }
  396. // PrependUint16Slot prepends a uint16 onto the object at vtable slot `o`.
  397. // If value `x` equals default `d`, then the slot will be set to zero and no
  398. // other data will be written.
  399. func (b *Builder) PrependUint16Slot(o int, x, d uint16) {
  400. if x != d {
  401. b.PrependUint16(x)
  402. b.Slot(o)
  403. }
  404. }
  405. // PrependUint32Slot prepends a uint32 onto the object at vtable slot `o`.
  406. // If value `x` equals default `d`, then the slot will be set to zero and no
  407. // other data will be written.
  408. func (b *Builder) PrependUint32Slot(o int, x, d uint32) {
  409. if x != d {
  410. b.PrependUint32(x)
  411. b.Slot(o)
  412. }
  413. }
  414. // PrependUint64Slot prepends a uint64 onto the object at vtable slot `o`.
  415. // If value `x` equals default `d`, then the slot will be set to zero and no
  416. // other data will be written.
  417. func (b *Builder) PrependUint64Slot(o int, x, d uint64) {
  418. if x != d {
  419. b.PrependUint64(x)
  420. b.Slot(o)
  421. }
  422. }
  423. // PrependInt8Slot prepends a int8 onto the object at vtable slot `o`.
  424. // If value `x` equals default `d`, then the slot will be set to zero and no
  425. // other data will be written.
  426. func (b *Builder) PrependInt8Slot(o int, x, d int8) {
  427. if x != d {
  428. b.PrependInt8(x)
  429. b.Slot(o)
  430. }
  431. }
  432. // PrependInt16Slot prepends a int16 onto the object at vtable slot `o`.
  433. // If value `x` equals default `d`, then the slot will be set to zero and no
  434. // other data will be written.
  435. func (b *Builder) PrependInt16Slot(o int, x, d int16) {
  436. if x != d {
  437. b.PrependInt16(x)
  438. b.Slot(o)
  439. }
  440. }
  441. // PrependInt32Slot prepends a int32 onto the object at vtable slot `o`.
  442. // If value `x` equals default `d`, then the slot will be set to zero and no
  443. // other data will be written.
  444. func (b *Builder) PrependInt32Slot(o int, x, d int32) {
  445. if x != d {
  446. b.PrependInt32(x)
  447. b.Slot(o)
  448. }
  449. }
  450. // PrependInt64Slot prepends a int64 onto the object at vtable slot `o`.
  451. // If value `x` equals default `d`, then the slot will be set to zero and no
  452. // other data will be written.
  453. func (b *Builder) PrependInt64Slot(o int, x, d int64) {
  454. if x != d {
  455. b.PrependInt64(x)
  456. b.Slot(o)
  457. }
  458. }
  459. // PrependFloat32Slot prepends a float32 onto the object at vtable slot `o`.
  460. // If value `x` equals default `d`, then the slot will be set to zero and no
  461. // other data will be written.
  462. func (b *Builder) PrependFloat32Slot(o int, x, d float32) {
  463. if x != d {
  464. b.PrependFloat32(x)
  465. b.Slot(o)
  466. }
  467. }
  468. // PrependFloat64Slot prepends a float64 onto the object at vtable slot `o`.
  469. // If value `x` equals default `d`, then the slot will be set to zero and no
  470. // other data will be written.
  471. func (b *Builder) PrependFloat64Slot(o int, x, d float64) {
  472. if x != d {
  473. b.PrependFloat64(x)
  474. b.Slot(o)
  475. }
  476. }
  477. // PrependUOffsetTSlot prepends an UOffsetT onto the object at vtable slot `o`.
  478. // If value `x` equals default `d`, then the slot will be set to zero and no
  479. // other data will be written.
  480. func (b *Builder) PrependUOffsetTSlot(o int, x, d UOffsetT) {
  481. if x != d {
  482. b.PrependUOffsetT(x)
  483. b.Slot(o)
  484. }
  485. }
  486. // PrependStructSlot prepends a struct onto the object at vtable slot `o`.
  487. // Structs are stored inline, so nothing additional is being added.
  488. // In generated code, `d` is always 0.
  489. func (b *Builder) PrependStructSlot(voffset int, x, d UOffsetT) {
  490. if x != d {
  491. b.assertNested()
  492. if x != b.Offset() {
  493. panic("inline data write outside of object")
  494. }
  495. b.Slot(voffset)
  496. }
  497. }
  498. // Slot sets the vtable key `voffset` to the current location in the buffer.
  499. func (b *Builder) Slot(slotnum int) {
  500. b.vtable[slotnum] = UOffsetT(b.Offset())
  501. }
  502. // FinishWithFileIdentifier finalizes a buffer, pointing to the given `rootTable`.
  503. // as well as applys a file identifier
  504. func (b *Builder) FinishWithFileIdentifier(rootTable UOffsetT, fid []byte) {
  505. if fid == nil || len(fid) != fileIdentifierLength {
  506. panic("incorrect file identifier length")
  507. }
  508. // In order to add a file identifier to the flatbuffer message, we need
  509. // to prepare an alignment and file identifier length
  510. b.Prep(b.minalign, SizeInt32+fileIdentifierLength)
  511. for i := fileIdentifierLength - 1; i >= 0; i-- {
  512. // place the file identifier
  513. b.PlaceByte(fid[i])
  514. }
  515. // finish
  516. b.Finish(rootTable)
  517. }
  518. // FinishSizePrefixed finalizes a buffer, pointing to the given `rootTable`.
  519. // The buffer is prefixed with the size of the buffer, excluding the size
  520. // of the prefix itself.
  521. func (b *Builder) FinishSizePrefixed(rootTable UOffsetT) {
  522. b.finish(rootTable, true)
  523. }
  524. // FinishSizePrefixedWithFileIdentifier finalizes a buffer, pointing to the given `rootTable`
  525. // and applies a file identifier. The buffer is prefixed with the size of the buffer,
  526. // excluding the size of the prefix itself.
  527. func (b *Builder) FinishSizePrefixedWithFileIdentifier(rootTable UOffsetT, fid []byte) {
  528. if fid == nil || len(fid) != fileIdentifierLength {
  529. panic("incorrect file identifier length")
  530. }
  531. // In order to add a file identifier and size prefix to the flatbuffer message,
  532. // we need to prepare an alignment, a size prefix length, and file identifier length
  533. b.Prep(b.minalign, SizeInt32+fileIdentifierLength+sizePrefixLength)
  534. for i := fileIdentifierLength - 1; i >= 0; i-- {
  535. // place the file identifier
  536. b.PlaceByte(fid[i])
  537. }
  538. // finish
  539. b.finish(rootTable, true)
  540. }
  541. // Finish finalizes a buffer, pointing to the given `rootTable`.
  542. func (b *Builder) Finish(rootTable UOffsetT) {
  543. b.finish(rootTable, false)
  544. }
  545. // finish finalizes a buffer, pointing to the given `rootTable`
  546. // with an optional size prefix.
  547. func (b *Builder) finish(rootTable UOffsetT, sizePrefix bool) {
  548. b.assertNotNested()
  549. if sizePrefix {
  550. b.Prep(b.minalign, SizeUOffsetT+sizePrefixLength)
  551. } else {
  552. b.Prep(b.minalign, SizeUOffsetT)
  553. }
  554. b.PrependUOffsetT(rootTable)
  555. if sizePrefix {
  556. b.PlaceUint32(uint32(b.Offset()))
  557. }
  558. b.finished = true
  559. }
  560. // vtableEqual compares an unwritten vtable to a written vtable.
  561. func vtableEqual(a []UOffsetT, objectStart UOffsetT, b []byte) bool {
  562. if len(a)*SizeVOffsetT != len(b) {
  563. return false
  564. }
  565. for i := 0; i < len(a); i++ {
  566. x := GetVOffsetT(b[i*SizeVOffsetT : (i+1)*SizeVOffsetT])
  567. // Skip vtable entries that indicate a default value.
  568. if x == 0 && a[i] == 0 {
  569. continue
  570. }
  571. y := SOffsetT(objectStart) - SOffsetT(a[i])
  572. if SOffsetT(x) != y {
  573. return false
  574. }
  575. }
  576. return true
  577. }
  578. // PrependBool prepends a bool to the Builder buffer.
  579. // Aligns and checks for space.
  580. func (b *Builder) PrependBool(x bool) {
  581. b.Prep(SizeBool, 0)
  582. b.PlaceBool(x)
  583. }
  584. // PrependUint8 prepends a uint8 to the Builder buffer.
  585. // Aligns and checks for space.
  586. func (b *Builder) PrependUint8(x uint8) {
  587. b.Prep(SizeUint8, 0)
  588. b.PlaceUint8(x)
  589. }
  590. // PrependUint16 prepends a uint16 to the Builder buffer.
  591. // Aligns and checks for space.
  592. func (b *Builder) PrependUint16(x uint16) {
  593. b.Prep(SizeUint16, 0)
  594. b.PlaceUint16(x)
  595. }
  596. // PrependUint32 prepends a uint32 to the Builder buffer.
  597. // Aligns and checks for space.
  598. func (b *Builder) PrependUint32(x uint32) {
  599. b.Prep(SizeUint32, 0)
  600. b.PlaceUint32(x)
  601. }
  602. // PrependUint64 prepends a uint64 to the Builder buffer.
  603. // Aligns and checks for space.
  604. func (b *Builder) PrependUint64(x uint64) {
  605. b.Prep(SizeUint64, 0)
  606. b.PlaceUint64(x)
  607. }
  608. // PrependInt8 prepends a int8 to the Builder buffer.
  609. // Aligns and checks for space.
  610. func (b *Builder) PrependInt8(x int8) {
  611. b.Prep(SizeInt8, 0)
  612. b.PlaceInt8(x)
  613. }
  614. // PrependInt16 prepends a int16 to the Builder buffer.
  615. // Aligns and checks for space.
  616. func (b *Builder) PrependInt16(x int16) {
  617. b.Prep(SizeInt16, 0)
  618. b.PlaceInt16(x)
  619. }
  620. // PrependInt32 prepends a int32 to the Builder buffer.
  621. // Aligns and checks for space.
  622. func (b *Builder) PrependInt32(x int32) {
  623. b.Prep(SizeInt32, 0)
  624. b.PlaceInt32(x)
  625. }
  626. // PrependInt64 prepends a int64 to the Builder buffer.
  627. // Aligns and checks for space.
  628. func (b *Builder) PrependInt64(x int64) {
  629. b.Prep(SizeInt64, 0)
  630. b.PlaceInt64(x)
  631. }
  632. // PrependFloat32 prepends a float32 to the Builder buffer.
  633. // Aligns and checks for space.
  634. func (b *Builder) PrependFloat32(x float32) {
  635. b.Prep(SizeFloat32, 0)
  636. b.PlaceFloat32(x)
  637. }
  638. // PrependFloat64 prepends a float64 to the Builder buffer.
  639. // Aligns and checks for space.
  640. func (b *Builder) PrependFloat64(x float64) {
  641. b.Prep(SizeFloat64, 0)
  642. b.PlaceFloat64(x)
  643. }
  644. // PrependByte prepends a byte to the Builder buffer.
  645. // Aligns and checks for space.
  646. func (b *Builder) PrependByte(x byte) {
  647. b.Prep(SizeByte, 0)
  648. b.PlaceByte(x)
  649. }
  650. // PrependVOffsetT prepends a VOffsetT to the Builder buffer.
  651. // Aligns and checks for space.
  652. func (b *Builder) PrependVOffsetT(x VOffsetT) {
  653. b.Prep(SizeVOffsetT, 0)
  654. b.PlaceVOffsetT(x)
  655. }
  656. // PlaceBool prepends a bool to the Builder, without checking for space.
  657. func (b *Builder) PlaceBool(x bool) {
  658. b.head -= UOffsetT(SizeBool)
  659. WriteBool(b.Bytes[b.head:], x)
  660. }
  661. // PlaceUint8 prepends a uint8 to the Builder, without checking for space.
  662. func (b *Builder) PlaceUint8(x uint8) {
  663. b.head -= UOffsetT(SizeUint8)
  664. WriteUint8(b.Bytes[b.head:], x)
  665. }
  666. // PlaceUint16 prepends a uint16 to the Builder, without checking for space.
  667. func (b *Builder) PlaceUint16(x uint16) {
  668. b.head -= UOffsetT(SizeUint16)
  669. WriteUint16(b.Bytes[b.head:], x)
  670. }
  671. // PlaceUint32 prepends a uint32 to the Builder, without checking for space.
  672. func (b *Builder) PlaceUint32(x uint32) {
  673. b.head -= UOffsetT(SizeUint32)
  674. WriteUint32(b.Bytes[b.head:], x)
  675. }
  676. // PlaceUint64 prepends a uint64 to the Builder, without checking for space.
  677. func (b *Builder) PlaceUint64(x uint64) {
  678. b.head -= UOffsetT(SizeUint64)
  679. WriteUint64(b.Bytes[b.head:], x)
  680. }
  681. // PlaceInt8 prepends a int8 to the Builder, without checking for space.
  682. func (b *Builder) PlaceInt8(x int8) {
  683. b.head -= UOffsetT(SizeInt8)
  684. WriteInt8(b.Bytes[b.head:], x)
  685. }
  686. // PlaceInt16 prepends a int16 to the Builder, without checking for space.
  687. func (b *Builder) PlaceInt16(x int16) {
  688. b.head -= UOffsetT(SizeInt16)
  689. WriteInt16(b.Bytes[b.head:], x)
  690. }
  691. // PlaceInt32 prepends a int32 to the Builder, without checking for space.
  692. func (b *Builder) PlaceInt32(x int32) {
  693. b.head -= UOffsetT(SizeInt32)
  694. WriteInt32(b.Bytes[b.head:], x)
  695. }
  696. // PlaceInt64 prepends a int64 to the Builder, without checking for space.
  697. func (b *Builder) PlaceInt64(x int64) {
  698. b.head -= UOffsetT(SizeInt64)
  699. WriteInt64(b.Bytes[b.head:], x)
  700. }
  701. // PlaceFloat32 prepends a float32 to the Builder, without checking for space.
  702. func (b *Builder) PlaceFloat32(x float32) {
  703. b.head -= UOffsetT(SizeFloat32)
  704. WriteFloat32(b.Bytes[b.head:], x)
  705. }
  706. // PlaceFloat64 prepends a float64 to the Builder, without checking for space.
  707. func (b *Builder) PlaceFloat64(x float64) {
  708. b.head -= UOffsetT(SizeFloat64)
  709. WriteFloat64(b.Bytes[b.head:], x)
  710. }
  711. // PlaceByte prepends a byte to the Builder, without checking for space.
  712. func (b *Builder) PlaceByte(x byte) {
  713. b.head -= UOffsetT(SizeByte)
  714. WriteByte(b.Bytes[b.head:], x)
  715. }
  716. // PlaceVOffsetT prepends a VOffsetT to the Builder, without checking for space.
  717. func (b *Builder) PlaceVOffsetT(x VOffsetT) {
  718. b.head -= UOffsetT(SizeVOffsetT)
  719. WriteVOffsetT(b.Bytes[b.head:], x)
  720. }
  721. // PlaceSOffsetT prepends a SOffsetT to the Builder, without checking for space.
  722. func (b *Builder) PlaceSOffsetT(x SOffsetT) {
  723. b.head -= UOffsetT(SizeSOffsetT)
  724. WriteSOffsetT(b.Bytes[b.head:], x)
  725. }
  726. // PlaceUOffsetT prepends a UOffsetT to the Builder, without checking for space.
  727. func (b *Builder) PlaceUOffsetT(x UOffsetT) {
  728. b.head -= UOffsetT(SizeUOffsetT)
  729. WriteUOffsetT(b.Bytes[b.head:], x)
  730. }