possibility to create a vector from an iterator (#6135)

This commit is contained in:
Kamil Rojewski 2020-09-28 18:45:48 +02:00 committed by GitHub
parent ab01ae1620
commit 2eedc769d5
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1 changed files with 19 additions and 0 deletions

View File

@ -20,6 +20,7 @@ use std::cmp::max;
use std::marker::PhantomData; use std::marker::PhantomData;
use std::ptr::write_bytes; use std::ptr::write_bytes;
use std::slice::from_raw_parts; use std::slice::from_raw_parts;
use std::iter::{DoubleEndedIterator, ExactSizeIterator};
use endian_scalar::{emplace_scalar, read_scalar_at}; use endian_scalar::{emplace_scalar, read_scalar_at};
use primitives::*; use primitives::*;
@ -328,6 +329,24 @@ impl<'fbb> FlatBufferBuilder<'fbb> {
WIPOffset::new(self.push::<UOffsetT>(items.len() as UOffsetT).value()) WIPOffset::new(self.push::<UOffsetT>(items.len() as UOffsetT).value())
} }
/// Create a vector of Push-able objects.
///
/// Speed-sensitive users may wish to reduce memory usage by creating the
/// vector manually: use `start_vector`, `push`, and `end_vector`.
#[inline]
pub fn create_vector_from_iter<T: Push + Copy>(
&mut self,
items: impl ExactSizeIterator<Item = T> + DoubleEndedIterator,
) -> WIPOffset<Vector<'fbb, T::Output>> {
let elem_size = T::size();
let len = items.len();
self.align(len * elem_size, T::alignment().max_of(SIZE_UOFFSET));
for item in items.rev() {
self.push(item);
}
WIPOffset::new(self.push::<UOffsetT>(len as UOffsetT).value())
}
/// Set whether default values are stored. /// Set whether default values are stored.
/// ///
/// In order to save space, fields that are set to their default value /// In order to save space, fields that are set to their default value