Austin Schuh | e89fa2d | 2019-08-14 20:24:23 -0700 | [diff] [blame^] | 1 | /* |
| 2 | * Copyright 2018 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 | |
| 17 | extern crate smallvec; |
| 18 | |
| 19 | use std::cmp::max; |
| 20 | use std::marker::PhantomData; |
| 21 | use std::ptr::write_bytes; |
| 22 | use std::slice::from_raw_parts; |
| 23 | |
| 24 | use endian_scalar::{emplace_scalar, read_scalar_at}; |
| 25 | use primitives::*; |
| 26 | use push::{Push, PushAlignment}; |
| 27 | use table::Table; |
| 28 | use vector::{SafeSliceAccess, Vector}; |
| 29 | use vtable::{field_index_to_field_offset, VTable}; |
| 30 | use vtable_writer::VTableWriter; |
| 31 | |
| 32 | pub const N_SMALLVEC_STRING_VECTOR_CAPACITY: usize = 16; |
| 33 | |
| 34 | #[derive(Clone, Copy, Debug, Eq, PartialEq)] |
| 35 | struct FieldLoc { |
| 36 | off: UOffsetT, |
| 37 | id: VOffsetT, |
| 38 | } |
| 39 | |
| 40 | /// FlatBufferBuilder builds a FlatBuffer through manipulating its internal |
| 41 | /// state. It has an owned `Vec<u8>` that grows as needed (up to the hardcoded |
| 42 | /// limit of 2GiB, which is set by the FlatBuffers format). |
| 43 | #[derive(Clone, Debug, Eq, PartialEq)] |
| 44 | pub struct FlatBufferBuilder<'fbb> { |
| 45 | owned_buf: Vec<u8>, |
| 46 | head: usize, |
| 47 | |
| 48 | field_locs: Vec<FieldLoc>, |
| 49 | written_vtable_revpos: Vec<UOffsetT>, |
| 50 | |
| 51 | nested: bool, |
| 52 | finished: bool, |
| 53 | |
| 54 | min_align: usize, |
| 55 | |
| 56 | _phantom: PhantomData<&'fbb ()>, |
| 57 | } |
| 58 | |
| 59 | impl<'fbb> FlatBufferBuilder<'fbb> { |
| 60 | /// Create a FlatBufferBuilder that is ready for writing. |
| 61 | pub fn new() -> Self { |
| 62 | Self::new_with_capacity(0) |
| 63 | } |
| 64 | |
| 65 | /// Create a FlatBufferBuilder that is ready for writing, with a |
| 66 | /// ready-to-use capacity of the provided size. |
| 67 | /// |
| 68 | /// The maximum valid value is `FLATBUFFERS_MAX_BUFFER_SIZE`. |
| 69 | pub fn new_with_capacity(size: usize) -> Self { |
| 70 | // we need to check the size here because we create the backing buffer |
| 71 | // directly, bypassing the typical way of using grow_owned_buf: |
| 72 | assert!( |
| 73 | size <= FLATBUFFERS_MAX_BUFFER_SIZE, |
| 74 | "cannot initialize buffer bigger than 2 gigabytes" |
| 75 | ); |
| 76 | |
| 77 | FlatBufferBuilder { |
| 78 | owned_buf: vec![0u8; size], |
| 79 | head: size, |
| 80 | |
| 81 | field_locs: Vec::new(), |
| 82 | written_vtable_revpos: Vec::new(), |
| 83 | |
| 84 | nested: false, |
| 85 | finished: false, |
| 86 | |
| 87 | min_align: 0, |
| 88 | |
| 89 | _phantom: PhantomData, |
| 90 | } |
| 91 | } |
| 92 | |
| 93 | /// Reset the FlatBufferBuilder internal state. Use this method after a |
| 94 | /// call to a `finish` function in order to re-use a FlatBufferBuilder. |
| 95 | /// |
| 96 | /// This function is the only way to reset the `finished` state and start |
| 97 | /// again. |
| 98 | /// |
| 99 | /// If you are using a FlatBufferBuilder repeatedly, make sure to use this |
| 100 | /// function, because it re-uses the FlatBufferBuilder's existing |
| 101 | /// heap-allocated `Vec<u8>` internal buffer. This offers significant speed |
| 102 | /// improvements as compared to creating a new FlatBufferBuilder for every |
| 103 | /// new object. |
| 104 | pub fn reset(&mut self) { |
| 105 | // memset only the part of the buffer that could be dirty: |
| 106 | { |
| 107 | let to_clear = self.owned_buf.len() - self.head; |
| 108 | let ptr = (&mut self.owned_buf[self.head..]).as_mut_ptr(); |
| 109 | unsafe { |
| 110 | write_bytes(ptr, 0, to_clear); |
| 111 | } |
| 112 | } |
| 113 | |
| 114 | self.head = self.owned_buf.len(); |
| 115 | self.written_vtable_revpos.clear(); |
| 116 | |
| 117 | self.nested = false; |
| 118 | self.finished = false; |
| 119 | |
| 120 | self.min_align = 0; |
| 121 | } |
| 122 | |
| 123 | /// Destroy the FlatBufferBuilder, returning its internal byte vector |
| 124 | /// and the index into it that represents the start of valid data. |
| 125 | pub fn collapse(self) -> (Vec<u8>, usize) { |
| 126 | (self.owned_buf, self.head) |
| 127 | } |
| 128 | |
| 129 | /// Push a Push'able value onto the front of the in-progress data. |
| 130 | /// |
| 131 | /// This function uses traits to provide a unified API for writing |
| 132 | /// scalars, tables, vectors, and WIPOffsets. |
| 133 | #[inline] |
| 134 | pub fn push<P: Push>(&mut self, x: P) -> WIPOffset<P::Output> { |
| 135 | let sz = P::size(); |
| 136 | self.align(sz, P::alignment()); |
| 137 | self.make_space(sz); |
| 138 | { |
| 139 | let (dst, rest) = (&mut self.owned_buf[self.head..]).split_at_mut(sz); |
| 140 | x.push(dst, rest); |
| 141 | } |
| 142 | WIPOffset::new(self.used_space() as UOffsetT) |
| 143 | } |
| 144 | |
| 145 | /// Push a Push'able value onto the front of the in-progress data, and |
| 146 | /// store a reference to it in the in-progress vtable. If the value matches |
| 147 | /// the default, then this is a no-op. |
| 148 | #[inline] |
| 149 | pub fn push_slot<X: Push + PartialEq>(&mut self, slotoff: VOffsetT, x: X, default: X) { |
| 150 | self.assert_nested("push_slot"); |
| 151 | if x == default { |
| 152 | return; |
| 153 | } |
| 154 | self.push_slot_always(slotoff, x); |
| 155 | } |
| 156 | |
| 157 | /// Push a Push'able value onto the front of the in-progress data, and |
| 158 | /// store a reference to it in the in-progress vtable. |
| 159 | #[inline] |
| 160 | pub fn push_slot_always<X: Push>(&mut self, slotoff: VOffsetT, x: X) { |
| 161 | self.assert_nested("push_slot_always"); |
| 162 | let off = self.push(x); |
| 163 | self.track_field(slotoff, off.value()); |
| 164 | } |
| 165 | |
| 166 | /// Retrieve the number of vtables that have been serialized into the |
| 167 | /// FlatBuffer. This is primarily used to check vtable deduplication. |
| 168 | #[inline] |
| 169 | pub fn num_written_vtables(&self) -> usize { |
| 170 | self.written_vtable_revpos.len() |
| 171 | } |
| 172 | |
| 173 | /// Start a Table write. |
| 174 | /// |
| 175 | /// Asserts that the builder is not in a nested state. |
| 176 | /// |
| 177 | /// Users probably want to use `push_slot` to add values after calling this. |
| 178 | #[inline] |
| 179 | pub fn start_table(&mut self) -> WIPOffset<TableUnfinishedWIPOffset> { |
| 180 | self.assert_not_nested( |
| 181 | "start_table can not be called when a table or vector is under construction", |
| 182 | ); |
| 183 | self.nested = true; |
| 184 | |
| 185 | WIPOffset::new(self.used_space() as UOffsetT) |
| 186 | } |
| 187 | |
| 188 | /// End a Table write. |
| 189 | /// |
| 190 | /// Asserts that the builder is in a nested state. |
| 191 | #[inline] |
| 192 | pub fn end_table( |
| 193 | &mut self, |
| 194 | off: WIPOffset<TableUnfinishedWIPOffset>, |
| 195 | ) -> WIPOffset<TableFinishedWIPOffset> { |
| 196 | self.assert_nested("end_table"); |
| 197 | |
| 198 | let o = self.write_vtable(off); |
| 199 | |
| 200 | self.nested = false; |
| 201 | self.field_locs.clear(); |
| 202 | |
| 203 | WIPOffset::new(o.value()) |
| 204 | } |
| 205 | |
| 206 | /// Start a Vector write. |
| 207 | /// |
| 208 | /// Asserts that the builder is not in a nested state. |
| 209 | /// |
| 210 | /// Most users will prefer to call `create_vector`. |
| 211 | /// Speed optimizing users who choose to create vectors manually using this |
| 212 | /// function will want to use `push` to add values. |
| 213 | #[inline] |
| 214 | pub fn start_vector<T: Push>(&mut self, num_items: usize) { |
| 215 | self.assert_not_nested( |
| 216 | "start_vector can not be called when a table or vector is under construction", |
| 217 | ); |
| 218 | self.nested = true; |
| 219 | self.align(num_items * T::size(), T::alignment().max_of(SIZE_UOFFSET)); |
| 220 | } |
| 221 | |
| 222 | /// End a Vector write. |
| 223 | /// |
| 224 | /// Note that the `num_elems` parameter is the number of written items, not |
| 225 | /// the byte count. |
| 226 | /// |
| 227 | /// Asserts that the builder is in a nested state. |
| 228 | #[inline] |
| 229 | pub fn end_vector<T: Push>(&mut self, num_elems: usize) -> WIPOffset<Vector<'fbb, T>> { |
| 230 | self.assert_nested("end_vector"); |
| 231 | self.nested = false; |
| 232 | let o = self.push::<UOffsetT>(num_elems as UOffsetT); |
| 233 | WIPOffset::new(o.value()) |
| 234 | } |
| 235 | |
| 236 | /// Create a utf8 string. |
| 237 | /// |
| 238 | /// The wire format represents this as a zero-terminated byte vector. |
| 239 | #[inline] |
| 240 | pub fn create_string<'a: 'b, 'b>(&'a mut self, s: &'b str) -> WIPOffset<&'fbb str> { |
| 241 | self.assert_not_nested( |
| 242 | "create_string can not be called when a table or vector is under construction", |
| 243 | ); |
| 244 | WIPOffset::new(self.create_byte_string(s.as_bytes()).value()) |
| 245 | } |
| 246 | |
| 247 | /// Create a zero-terminated byte vector. |
| 248 | #[inline] |
| 249 | pub fn create_byte_string(&mut self, data: &[u8]) -> WIPOffset<&'fbb [u8]> { |
| 250 | self.assert_not_nested( |
| 251 | "create_byte_string can not be called when a table or vector is under construction", |
| 252 | ); |
| 253 | self.align(data.len() + 1, PushAlignment::new(SIZE_UOFFSET)); |
| 254 | self.push(0u8); |
| 255 | self.push_bytes_unprefixed(data); |
| 256 | self.push(data.len() as UOffsetT); |
| 257 | WIPOffset::new(self.used_space() as UOffsetT) |
| 258 | } |
| 259 | |
| 260 | /// Create a vector by memcpy'ing. This is much faster than calling |
| 261 | /// `create_vector`, but the underlying type must be represented as |
| 262 | /// little-endian on the host machine. This property is encoded in the |
| 263 | /// type system through the SafeSliceAccess trait. The following types are |
| 264 | /// always safe, on any platform: bool, u8, i8, and any |
| 265 | /// FlatBuffers-generated struct. |
| 266 | #[inline] |
| 267 | pub fn create_vector_direct<'a: 'b, 'b, T: SafeSliceAccess + Push + Sized + 'b>( |
| 268 | &'a mut self, |
| 269 | items: &'b [T], |
| 270 | ) -> WIPOffset<Vector<'fbb, T>> { |
| 271 | self.assert_not_nested( |
| 272 | "create_vector_direct can not be called when a table or vector is under construction", |
| 273 | ); |
| 274 | let elem_size = T::size(); |
| 275 | self.align(items.len() * elem_size, T::alignment().max_of(SIZE_UOFFSET)); |
| 276 | |
| 277 | let bytes = { |
| 278 | let ptr = items.as_ptr() as *const T as *const u8; |
| 279 | unsafe { from_raw_parts(ptr, items.len() * elem_size) } |
| 280 | }; |
| 281 | self.push_bytes_unprefixed(bytes); |
| 282 | self.push(items.len() as UOffsetT); |
| 283 | |
| 284 | WIPOffset::new(self.used_space() as UOffsetT) |
| 285 | } |
| 286 | |
| 287 | /// Create a vector of strings. |
| 288 | /// |
| 289 | /// Speed-sensitive users may wish to reduce memory usage by creating the |
| 290 | /// vector manually: use `start_vector`, `push`, and `end_vector`. |
| 291 | #[inline] |
| 292 | pub fn create_vector_of_strings<'a, 'b>( |
| 293 | &'a mut self, |
| 294 | xs: &'b [&'b str], |
| 295 | ) -> WIPOffset<Vector<'fbb, ForwardsUOffset<&'fbb str>>> { |
| 296 | self.assert_not_nested("create_vector_of_strings can not be called when a table or vector is under construction"); |
| 297 | // internally, smallvec can be a stack-allocated or heap-allocated vector: |
| 298 | // if xs.len() > N_SMALLVEC_STRING_VECTOR_CAPACITY then it will overflow to the heap. |
| 299 | let mut offsets: smallvec::SmallVec<[WIPOffset<&str>; N_SMALLVEC_STRING_VECTOR_CAPACITY]> = |
| 300 | smallvec::SmallVec::with_capacity(xs.len()); |
| 301 | unsafe { |
| 302 | offsets.set_len(xs.len()); |
| 303 | } |
| 304 | |
| 305 | // note that this happens in reverse, because the buffer is built back-to-front: |
| 306 | for (i, &s) in xs.iter().enumerate().rev() { |
| 307 | let o = self.create_string(s); |
| 308 | offsets[i] = o; |
| 309 | } |
| 310 | self.create_vector(&offsets[..]) |
| 311 | } |
| 312 | |
| 313 | /// Create a vector of Push-able objects. |
| 314 | /// |
| 315 | /// Speed-sensitive users may wish to reduce memory usage by creating the |
| 316 | /// vector manually: use `start_vector`, `push`, and `end_vector`. |
| 317 | #[inline] |
| 318 | pub fn create_vector<'a: 'b, 'b, T: Push + Copy + 'b>( |
| 319 | &'a mut self, |
| 320 | items: &'b [T], |
| 321 | ) -> WIPOffset<Vector<'fbb, T::Output>> { |
| 322 | let elem_size = T::size(); |
| 323 | self.align(items.len() * elem_size, T::alignment().max_of(SIZE_UOFFSET)); |
| 324 | for i in (0..items.len()).rev() { |
| 325 | self.push(items[i]); |
| 326 | } |
| 327 | WIPOffset::new(self.push::<UOffsetT>(items.len() as UOffsetT).value()) |
| 328 | } |
| 329 | |
| 330 | /// Get the byte slice for the data that has been written, regardless of |
| 331 | /// whether it has been finished. |
| 332 | #[inline] |
| 333 | pub fn unfinished_data(&self) -> &[u8] { |
| 334 | &self.owned_buf[self.head..] |
| 335 | } |
| 336 | /// Get the byte slice for the data that has been written after a call to |
| 337 | /// one of the `finish` functions. |
| 338 | #[inline] |
| 339 | pub fn finished_data(&self) -> &[u8] { |
| 340 | self.assert_finished("finished_bytes cannot be called when the buffer is not yet finished"); |
| 341 | &self.owned_buf[self.head..] |
| 342 | } |
| 343 | /// Assert that a field is present in the just-finished Table. |
| 344 | /// |
| 345 | /// This is somewhat low-level and is mostly used by the generated code. |
| 346 | #[inline] |
| 347 | pub fn required( |
| 348 | &self, |
| 349 | tab_revloc: WIPOffset<TableFinishedWIPOffset>, |
| 350 | slot_byte_loc: VOffsetT, |
| 351 | assert_msg_name: &'static str, |
| 352 | ) { |
| 353 | let idx = self.used_space() - tab_revloc.value() as usize; |
| 354 | let tab = Table::new(&self.owned_buf[self.head..], idx); |
| 355 | let o = tab.vtable().get(slot_byte_loc) as usize; |
| 356 | assert!(o != 0, "missing required field {}", assert_msg_name); |
| 357 | } |
| 358 | |
| 359 | /// Finalize the FlatBuffer by: aligning it, pushing an optional file |
| 360 | /// identifier on to it, pushing a size prefix on to it, and marking the |
| 361 | /// internal state of the FlatBufferBuilder as `finished`. Afterwards, |
| 362 | /// users can call `finished_data` to get the resulting data. |
| 363 | #[inline] |
| 364 | pub fn finish_size_prefixed<T>(&mut self, root: WIPOffset<T>, file_identifier: Option<&str>) { |
| 365 | self.finish_with_opts(root, file_identifier, true); |
| 366 | } |
| 367 | |
| 368 | /// Finalize the FlatBuffer by: aligning it, pushing an optional file |
| 369 | /// identifier on to it, and marking the internal state of the |
| 370 | /// FlatBufferBuilder as `finished`. Afterwards, users can call |
| 371 | /// `finished_data` to get the resulting data. |
| 372 | #[inline] |
| 373 | pub fn finish<T>(&mut self, root: WIPOffset<T>, file_identifier: Option<&str>) { |
| 374 | self.finish_with_opts(root, file_identifier, false); |
| 375 | } |
| 376 | |
| 377 | /// Finalize the FlatBuffer by: aligning it and marking the internal state |
| 378 | /// of the FlatBufferBuilder as `finished`. Afterwards, users can call |
| 379 | /// `finished_data` to get the resulting data. |
| 380 | #[inline] |
| 381 | pub fn finish_minimal<T>(&mut self, root: WIPOffset<T>) { |
| 382 | self.finish_with_opts(root, None, false); |
| 383 | } |
| 384 | |
| 385 | #[inline] |
| 386 | fn used_space(&self) -> usize { |
| 387 | self.owned_buf.len() - self.head as usize |
| 388 | } |
| 389 | |
| 390 | #[inline] |
| 391 | fn track_field(&mut self, slot_off: VOffsetT, off: UOffsetT) { |
| 392 | let fl = FieldLoc { |
| 393 | id: slot_off, |
| 394 | off: off, |
| 395 | }; |
| 396 | self.field_locs.push(fl); |
| 397 | } |
| 398 | |
| 399 | /// Write the VTable, if it is new. |
| 400 | fn write_vtable( |
| 401 | &mut self, |
| 402 | table_tail_revloc: WIPOffset<TableUnfinishedWIPOffset>, |
| 403 | ) -> WIPOffset<VTableWIPOffset> { |
| 404 | self.assert_nested("write_vtable"); |
| 405 | |
| 406 | // Write the vtable offset, which is the start of any Table. |
| 407 | // We fill its value later. |
| 408 | let object_revloc_to_vtable: WIPOffset<VTableWIPOffset> = |
| 409 | WIPOffset::new(self.push::<UOffsetT>(0xF0F0F0F0 as UOffsetT).value()); |
| 410 | |
| 411 | // Layout of the data this function will create when a new vtable is |
| 412 | // needed. |
| 413 | // -------------------------------------------------------------------- |
| 414 | // vtable starts here |
| 415 | // | x, x -- vtable len (bytes) [u16] |
| 416 | // | x, x -- object inline len (bytes) [u16] |
| 417 | // | x, x -- zero, or num bytes from start of object to field #0 [u16] |
| 418 | // | ... |
| 419 | // | x, x -- zero, or num bytes from start of object to field #n-1 [u16] |
| 420 | // vtable ends here |
| 421 | // table starts here |
| 422 | // | x, x, x, x -- offset (negative direction) to the vtable [i32] |
| 423 | // | aka "vtableoffset" |
| 424 | // | -- table inline data begins here, we don't touch it -- |
| 425 | // table ends here -- aka "table_start" |
| 426 | // -------------------------------------------------------------------- |
| 427 | // |
| 428 | // Layout of the data this function will create when we re-use an |
| 429 | // existing vtable. |
| 430 | // |
| 431 | // We always serialize this particular vtable, then compare it to the |
| 432 | // other vtables we know about to see if there is a duplicate. If there |
| 433 | // is, then we erase the serialized vtable we just made. |
| 434 | // We serialize it first so that we are able to do byte-by-byte |
| 435 | // comparisons with already-serialized vtables. This 1) saves |
| 436 | // bookkeeping space (we only keep revlocs to existing vtables), 2) |
| 437 | // allows us to convert to little-endian once, then do |
| 438 | // fast memcmp comparisons, and 3) by ensuring we are comparing real |
| 439 | // serialized vtables, we can be more assured that we are doing the |
| 440 | // comparisons correctly. |
| 441 | // |
| 442 | // -------------------------------------------------------------------- |
| 443 | // table starts here |
| 444 | // | x, x, x, x -- offset (negative direction) to an existing vtable [i32] |
| 445 | // | aka "vtableoffset" |
| 446 | // | -- table inline data begins here, we don't touch it -- |
| 447 | // table starts here: aka "table_start" |
| 448 | // -------------------------------------------------------------------- |
| 449 | |
| 450 | // fill the WIP vtable with zeros: |
| 451 | let vtable_byte_len = get_vtable_byte_len(&self.field_locs); |
| 452 | self.make_space(vtable_byte_len); |
| 453 | |
| 454 | // compute the length of the table (not vtable!) in bytes: |
| 455 | let table_object_size = object_revloc_to_vtable.value() - table_tail_revloc.value(); |
| 456 | debug_assert!(table_object_size < 0x10000); // vTable use 16bit offsets. |
| 457 | |
| 458 | // Write the VTable (we may delete it afterwards, if it is a duplicate): |
| 459 | let vt_start_pos = self.head; |
| 460 | let vt_end_pos = self.head + vtable_byte_len; |
| 461 | { |
| 462 | // write the vtable header: |
| 463 | let vtfw = &mut VTableWriter::init(&mut self.owned_buf[vt_start_pos..vt_end_pos]); |
| 464 | vtfw.write_vtable_byte_length(vtable_byte_len as VOffsetT); |
| 465 | vtfw.write_object_inline_size(table_object_size as VOffsetT); |
| 466 | |
| 467 | // serialize every FieldLoc to the vtable: |
| 468 | for &fl in self.field_locs.iter() { |
| 469 | let pos: VOffsetT = (object_revloc_to_vtable.value() - fl.off) as VOffsetT; |
| 470 | debug_assert_eq!( |
| 471 | vtfw.get_field_offset(fl.id), |
| 472 | 0, |
| 473 | "tried to write a vtable field multiple times" |
| 474 | ); |
| 475 | vtfw.write_field_offset(fl.id, pos); |
| 476 | } |
| 477 | } |
| 478 | let dup_vt_use = { |
| 479 | let this_vt = VTable::init(&self.owned_buf[..], self.head); |
| 480 | self.find_duplicate_stored_vtable_revloc(this_vt) |
| 481 | }; |
| 482 | |
| 483 | let vt_use = match dup_vt_use { |
| 484 | Some(n) => { |
| 485 | VTableWriter::init(&mut self.owned_buf[vt_start_pos..vt_end_pos]).clear(); |
| 486 | self.head += vtable_byte_len; |
| 487 | n |
| 488 | } |
| 489 | None => { |
| 490 | let new_vt_use = self.used_space() as UOffsetT; |
| 491 | self.written_vtable_revpos.push(new_vt_use); |
| 492 | new_vt_use |
| 493 | } |
| 494 | }; |
| 495 | |
| 496 | { |
| 497 | let n = self.head + self.used_space() - object_revloc_to_vtable.value() as usize; |
| 498 | let saw = read_scalar_at::<UOffsetT>(&self.owned_buf, n); |
| 499 | debug_assert_eq!(saw, 0xF0F0F0F0); |
| 500 | emplace_scalar::<SOffsetT>( |
| 501 | &mut self.owned_buf[n..n + SIZE_SOFFSET], |
| 502 | vt_use as SOffsetT - object_revloc_to_vtable.value() as SOffsetT, |
| 503 | ); |
| 504 | } |
| 505 | |
| 506 | self.field_locs.clear(); |
| 507 | |
| 508 | object_revloc_to_vtable |
| 509 | } |
| 510 | |
| 511 | #[inline] |
| 512 | fn find_duplicate_stored_vtable_revloc(&self, needle: VTable) -> Option<UOffsetT> { |
| 513 | for &revloc in self.written_vtable_revpos.iter().rev() { |
| 514 | let o = VTable::init( |
| 515 | &self.owned_buf[..], |
| 516 | self.head + self.used_space() - revloc as usize, |
| 517 | ); |
| 518 | if needle == o { |
| 519 | return Some(revloc); |
| 520 | } |
| 521 | } |
| 522 | None |
| 523 | } |
| 524 | |
| 525 | // Only call this when you know it is safe to double the size of the buffer. |
| 526 | #[inline] |
| 527 | fn grow_owned_buf(&mut self) { |
| 528 | let old_len = self.owned_buf.len(); |
| 529 | let new_len = max(1, old_len * 2); |
| 530 | |
| 531 | let starting_active_size = self.used_space(); |
| 532 | |
| 533 | let diff = new_len - old_len; |
| 534 | self.owned_buf.resize(new_len, 0); |
| 535 | self.head += diff; |
| 536 | |
| 537 | let ending_active_size = self.used_space(); |
| 538 | debug_assert_eq!(starting_active_size, ending_active_size); |
| 539 | |
| 540 | if new_len == 1 { |
| 541 | return; |
| 542 | } |
| 543 | |
| 544 | // calculate the midpoint, and safely copy the old end data to the new |
| 545 | // end position: |
| 546 | let middle = new_len / 2; |
| 547 | { |
| 548 | let (left, right) = &mut self.owned_buf[..].split_at_mut(middle); |
| 549 | right.copy_from_slice(left); |
| 550 | } |
| 551 | // finally, zero out the old end data. |
| 552 | { |
| 553 | let ptr = (&mut self.owned_buf[..middle]).as_mut_ptr(); |
| 554 | unsafe { |
| 555 | write_bytes(ptr, 0, middle); |
| 556 | } |
| 557 | } |
| 558 | } |
| 559 | |
| 560 | // with or without a size prefix changes how we load the data, so finish* |
| 561 | // functions are split along those lines. |
| 562 | fn finish_with_opts<T>( |
| 563 | &mut self, |
| 564 | root: WIPOffset<T>, |
| 565 | file_identifier: Option<&str>, |
| 566 | size_prefixed: bool, |
| 567 | ) { |
| 568 | self.assert_not_finished("buffer cannot be finished when it is already finished"); |
| 569 | self.assert_not_nested( |
| 570 | "buffer cannot be finished when a table or vector is under construction", |
| 571 | ); |
| 572 | self.written_vtable_revpos.clear(); |
| 573 | |
| 574 | let to_align = { |
| 575 | // for the root offset: |
| 576 | let a = SIZE_UOFFSET; |
| 577 | // for the size prefix: |
| 578 | let b = if size_prefixed { SIZE_UOFFSET } else { 0 }; |
| 579 | // for the file identifier (a string that is not zero-terminated): |
| 580 | let c = if file_identifier.is_some() { |
| 581 | FILE_IDENTIFIER_LENGTH |
| 582 | } else { |
| 583 | 0 |
| 584 | }; |
| 585 | a + b + c |
| 586 | }; |
| 587 | |
| 588 | { |
| 589 | let ma = PushAlignment::new(self.min_align); |
| 590 | self.align(to_align, ma); |
| 591 | } |
| 592 | |
| 593 | if let Some(ident) = file_identifier { |
| 594 | debug_assert_eq!(ident.len(), FILE_IDENTIFIER_LENGTH); |
| 595 | self.push_bytes_unprefixed(ident.as_bytes()); |
| 596 | } |
| 597 | |
| 598 | self.push(root); |
| 599 | |
| 600 | if size_prefixed { |
| 601 | let sz = self.used_space() as UOffsetT; |
| 602 | self.push::<UOffsetT>(sz); |
| 603 | } |
| 604 | self.finished = true; |
| 605 | } |
| 606 | |
| 607 | #[inline] |
| 608 | fn align(&mut self, len: usize, alignment: PushAlignment) { |
| 609 | self.track_min_align(alignment.value()); |
| 610 | let s = self.used_space() as usize; |
| 611 | self.make_space(padding_bytes(s + len, alignment.value())); |
| 612 | } |
| 613 | |
| 614 | #[inline] |
| 615 | fn track_min_align(&mut self, alignment: usize) { |
| 616 | self.min_align = max(self.min_align, alignment); |
| 617 | } |
| 618 | |
| 619 | #[inline] |
| 620 | fn push_bytes_unprefixed(&mut self, x: &[u8]) -> UOffsetT { |
| 621 | let n = self.make_space(x.len()); |
| 622 | &mut self.owned_buf[n..n + x.len()].copy_from_slice(x); |
| 623 | |
| 624 | n as UOffsetT |
| 625 | } |
| 626 | |
| 627 | #[inline] |
| 628 | fn make_space(&mut self, want: usize) -> usize { |
| 629 | self.ensure_capacity(want); |
| 630 | self.head -= want; |
| 631 | self.head |
| 632 | } |
| 633 | |
| 634 | #[inline] |
| 635 | fn ensure_capacity(&mut self, want: usize) -> usize { |
| 636 | if self.unused_ready_space() >= want { |
| 637 | return want; |
| 638 | } |
| 639 | assert!( |
| 640 | want <= FLATBUFFERS_MAX_BUFFER_SIZE, |
| 641 | "cannot grow buffer beyond 2 gigabytes" |
| 642 | ); |
| 643 | |
| 644 | while self.unused_ready_space() < want { |
| 645 | self.grow_owned_buf(); |
| 646 | } |
| 647 | want |
| 648 | } |
| 649 | #[inline] |
| 650 | fn unused_ready_space(&self) -> usize { |
| 651 | self.head |
| 652 | } |
| 653 | #[inline] |
| 654 | fn assert_nested(&self, fn_name: &'static str) { |
| 655 | // we don't assert that self.field_locs.len() >0 because the vtable |
| 656 | // could be empty (e.g. for empty tables, or for all-default values). |
| 657 | debug_assert!( |
| 658 | self.nested, |
| 659 | format!( |
| 660 | "incorrect FlatBufferBuilder usage: {} must be called while in a nested state", |
| 661 | fn_name |
| 662 | ) |
| 663 | ); |
| 664 | } |
| 665 | #[inline] |
| 666 | fn assert_not_nested(&self, msg: &'static str) { |
| 667 | debug_assert!(!self.nested, msg); |
| 668 | } |
| 669 | #[inline] |
| 670 | fn assert_finished(&self, msg: &'static str) { |
| 671 | debug_assert!(self.finished, msg); |
| 672 | } |
| 673 | #[inline] |
| 674 | fn assert_not_finished(&self, msg: &'static str) { |
| 675 | debug_assert!(!self.finished, msg); |
| 676 | } |
| 677 | } |
| 678 | |
| 679 | /// Compute the length of the vtable needed to represent the provided FieldLocs. |
| 680 | /// If there are no FieldLocs, then provide the minimum number of bytes |
| 681 | /// required: enough to write the VTable header. |
| 682 | #[inline] |
| 683 | fn get_vtable_byte_len(field_locs: &[FieldLoc]) -> usize { |
| 684 | let max_voffset = field_locs.iter().map(|fl| fl.id).max(); |
| 685 | match max_voffset { |
| 686 | None => field_index_to_field_offset(0) as usize, |
| 687 | Some(mv) => mv as usize + SIZE_VOFFSET, |
| 688 | } |
| 689 | } |
| 690 | |
| 691 | #[inline] |
| 692 | fn padding_bytes(buf_size: usize, scalar_size: usize) -> usize { |
| 693 | // ((!buf_size) + 1) & (scalar_size - 1) |
| 694 | (!buf_size).wrapping_add(1) & (scalar_size.wrapping_sub(1)) |
| 695 | } |
| 696 | |
| 697 | impl<'fbb> Default for FlatBufferBuilder<'fbb> { |
| 698 | fn default() -> Self { |
| 699 | Self::new_with_capacity(0) |
| 700 | } |
| 701 | } |