-
Notifications
You must be signed in to change notification settings - Fork 4k
ARROW-11291: [Rust] Add extend to MutableBuffer (-20% for arithmetic, -97% for length) #9235
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Closed
Closed
Changes from all commits
Commits
Show all changes
11 commits
Select commit
Hold shift + click to select a range
c8eba36
Fixed bench
jorgecarleitao 4a38006
Added methods to extend MutableBuffer from iterators.
jorgecarleitao cba4b64
Improved performance of length.
jorgecarleitao aa5f503
Improved performance of arithmetic ops.
jorgecarleitao 681cf45
Fixed error.
jorgecarleitao fb03464
Benchmark extend vs extend_from_trusted_len_iter
mbrubeck b96559e
Optimize extend_from_iter
mbrubeck ff89f4a
Improved comment.
jorgecarleitao 579b8db
fmt
jorgecarleitao 844e20a
Improved API.
jorgecarleitao 018a400
Added extra safeguard.
jorgecarleitao File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -23,19 +23,19 @@ use packed_simd::u8x64; | |
|
|
||
| use crate::{ | ||
| bytes::{Bytes, Deallocation}, | ||
| datatypes::ToByteSlice, | ||
| datatypes::{ArrowNativeType, ToByteSlice}, | ||
| ffi, | ||
| }; | ||
|
|
||
| use std::convert::AsRef; | ||
| use std::fmt::Debug; | ||
| use std::iter::FromIterator; | ||
| use std::ops::{BitAnd, BitOr, Not}; | ||
| use std::ptr::NonNull; | ||
| use std::sync::Arc; | ||
| use std::{convert::AsRef, usize}; | ||
|
|
||
| #[cfg(feature = "avx512")] | ||
| use crate::arch::avx512::*; | ||
| use crate::datatypes::ArrowNativeType; | ||
| use crate::error::{ArrowError, Result}; | ||
| use crate::memory; | ||
| use crate::util::bit_chunk_iterator::BitChunks; | ||
|
|
@@ -697,6 +697,7 @@ unsafe impl Sync for Buffer {} | |
| unsafe impl Send for Buffer {} | ||
|
|
||
| impl From<MutableBuffer> for Buffer { | ||
| #[inline] | ||
| fn from(buffer: MutableBuffer) -> Self { | ||
| buffer.into_buffer() | ||
| } | ||
|
|
@@ -727,13 +728,14 @@ pub struct MutableBuffer { | |
|
|
||
| impl MutableBuffer { | ||
| /// Allocate a new [MutableBuffer] with initial capacity to be at least `capacity`. | ||
| #[inline] | ||
| pub fn new(capacity: usize) -> Self { | ||
| let new_capacity = bit_util::round_upto_multiple_of_64(capacity); | ||
| let ptr = memory::allocate_aligned(new_capacity); | ||
| let capacity = bit_util::round_upto_multiple_of_64(capacity); | ||
| let ptr = memory::allocate_aligned(capacity); | ||
| Self { | ||
| data: ptr, | ||
| len: 0, | ||
| capacity: new_capacity, | ||
| capacity, | ||
| } | ||
| } | ||
|
|
||
|
|
@@ -810,10 +812,14 @@ impl MutableBuffer { | |
| pub fn reserve(&mut self, additional: usize) { | ||
| let required_cap = self.len + additional; | ||
| if required_cap > self.capacity { | ||
| let new_capacity = bit_util::round_upto_multiple_of_64(required_cap); | ||
| let new_capacity = std::cmp::max(new_capacity, self.capacity * 2); | ||
| self.data = | ||
| unsafe { memory::reallocate(self.data, self.capacity, new_capacity) }; | ||
| // JUSTIFICATION | ||
| // Benefit | ||
| // necessity | ||
| // Soundness | ||
| // `self.data` is valid for `self.capacity`. | ||
| let (ptr, new_capacity) = | ||
| unsafe { reallocate(self.data, self.capacity, required_cap) }; | ||
| self.data = ptr; | ||
| self.capacity = new_capacity; | ||
| } | ||
| } | ||
|
|
@@ -899,6 +905,7 @@ impl MutableBuffer { | |
| self.into_buffer() | ||
| } | ||
|
|
||
| #[inline] | ||
| fn into_buffer(self) -> Buffer { | ||
| let buffer_data = unsafe { | ||
| Bytes::new(self.data, self.len, Deallocation::Native(self.capacity)) | ||
|
|
@@ -963,11 +970,167 @@ impl MutableBuffer { | |
|
|
||
| /// Extends the buffer by `additional` bytes equal to `0u8`, incrementing its capacity if needed. | ||
| #[inline] | ||
| pub fn extend(&mut self, additional: usize) { | ||
| pub fn extend_zeros(&mut self, additional: usize) { | ||
| self.resize(self.len + additional, 0); | ||
| } | ||
| } | ||
|
|
||
| /// # Safety | ||
| /// `ptr` must be allocated for `old_capacity`. | ||
| #[inline] | ||
| unsafe fn reallocate( | ||
| ptr: NonNull<u8>, | ||
| old_capacity: usize, | ||
| new_capacity: usize, | ||
| ) -> (NonNull<u8>, usize) { | ||
| let new_capacity = bit_util::round_upto_multiple_of_64(new_capacity); | ||
| let new_capacity = std::cmp::max(new_capacity, old_capacity * 2); | ||
| let ptr = memory::reallocate(ptr, old_capacity, new_capacity); | ||
| (ptr, new_capacity) | ||
| } | ||
|
|
||
| impl<A: ArrowNativeType> Extend<A> for MutableBuffer { | ||
| #[inline] | ||
| fn extend<T: IntoIterator<Item = A>>(&mut self, iter: T) { | ||
| let iterator = iter.into_iter(); | ||
| self.extend_from_iter(iterator) | ||
| } | ||
| } | ||
|
|
||
| impl MutableBuffer { | ||
| #[inline] | ||
| fn extend_from_iter<T: ArrowNativeType, I: Iterator<Item = T>>( | ||
| &mut self, | ||
| mut iterator: I, | ||
| ) { | ||
| let size = std::mem::size_of::<T>(); | ||
| let (lower, _) = iterator.size_hint(); | ||
| let additional = lower * size; | ||
| self.reserve(additional); | ||
|
|
||
| // this is necessary because of https://github.com/rust-lang/rust/issues/32155 | ||
| let mut len = SetLenOnDrop::new(&mut self.len); | ||
| let mut dst = unsafe { self.data.as_ptr().add(len.local_len) as *mut T }; | ||
| let capacity = self.capacity; | ||
|
|
||
| while len.local_len + size <= capacity { | ||
| if let Some(item) = iterator.next() { | ||
| unsafe { | ||
| std::ptr::write(dst, item); | ||
| dst = dst.add(1); | ||
| } | ||
| len.local_len += size; | ||
| } else { | ||
| break; | ||
| } | ||
| } | ||
| drop(len); | ||
|
|
||
| iterator.for_each(|item| self.push(item)); | ||
jorgecarleitao marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| } | ||
| } | ||
|
|
||
| impl Buffer { | ||
| /// Creates a [`Buffer`] from an [`Iterator`] with a trusted (upper) length. | ||
| /// Prefer this to `collect` whenever possible, as it is faster ~60% faster. | ||
| /// # Example | ||
| /// ``` | ||
| /// # use arrow::buffer::Buffer; | ||
| /// let v = vec![1u32]; | ||
| /// let iter = v.iter().map(|x| x * 2); | ||
| /// let buffer = unsafe { Buffer::from_trusted_len_iter(iter) }; | ||
| /// assert_eq!(buffer.len(), 4) // u32 has 4 bytes | ||
| /// ``` | ||
| /// # Safety | ||
| /// This method assumes that the iterator's size is correct and is undefined behavior | ||
| /// to use it on an iterator that reports an incorrect length. | ||
| // This implementation is required for two reasons: | ||
| // 1. there is no trait `TrustedLen` in stable rust and therefore | ||
| // we can't specialize `extend` for `TrustedLen` like `Vec` does. | ||
| // 2. `from_trusted_len_iter` is faster. | ||
| pub unsafe fn from_trusted_len_iter<T: ArrowNativeType, I: Iterator<Item = T>>( | ||
| iterator: I, | ||
| ) -> Self { | ||
| let (_, upper) = iterator.size_hint(); | ||
| let upper = upper.expect("from_trusted_len_iter requires an upper limit"); | ||
| let len = upper * std::mem::size_of::<T>(); | ||
|
|
||
| let mut buffer = MutableBuffer::new(len); | ||
|
|
||
| let mut dst = buffer.data.as_ptr() as *mut T; | ||
| for item in iterator { | ||
| // note how there is no reserve here (compared with `extend_from_iter`) | ||
| std::ptr::write(dst, item); | ||
| dst = dst.add(1); | ||
| } | ||
| assert_eq!( | ||
| dst.offset_from(buffer.data.as_ptr() as *mut T) as usize, | ||
| upper, | ||
| "Trusted iterator length was not accurately reported" | ||
| ); | ||
| buffer.len = len; | ||
jorgecarleitao marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| buffer.into() | ||
| } | ||
|
|
||
| /// Creates a [`Buffer`] from an [`Iterator`] with a trusted (upper) length or errors | ||
| /// if any of the items of the iterator is an error. | ||
| /// Prefer this to `collect` whenever possible, as it is faster ~60% faster. | ||
| /// # Safety | ||
| /// This method assumes that the iterator's size is correct and is undefined behavior | ||
| /// to use it on an iterator that reports an incorrect length. | ||
| pub unsafe fn try_from_trusted_len_iter< | ||
| E, | ||
| T: ArrowNativeType, | ||
| I: Iterator<Item = std::result::Result<T, E>>, | ||
| >( | ||
| iterator: I, | ||
| ) -> std::result::Result<Self, E> { | ||
| let (_, upper) = iterator.size_hint(); | ||
| let upper = upper.expect("try_from_trusted_len_iter requires an upper limit"); | ||
| let len = upper * std::mem::size_of::<T>(); | ||
|
|
||
| let mut buffer = MutableBuffer::new(len); | ||
|
|
||
| let mut dst = buffer.data.as_ptr() as *mut T; | ||
| for item in iterator { | ||
| // note how there is no reserve here (compared with `extend_from_iter`) | ||
| std::ptr::write(dst, item?); | ||
| dst = dst.add(1); | ||
| } | ||
| assert_eq!( | ||
| dst.offset_from(buffer.data.as_ptr() as *mut T) as usize, | ||
| upper, | ||
| "Trusted iterator length was not accurately reported" | ||
| ); | ||
| buffer.len = len; | ||
| Ok(buffer.into()) | ||
| } | ||
| } | ||
|
|
||
| impl<T: ArrowNativeType> FromIterator<T> for Buffer { | ||
| fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self { | ||
| let mut iterator = iter.into_iter(); | ||
| let size = std::mem::size_of::<T>(); | ||
|
|
||
| // first iteration, which will likely reserve sufficient space for the buffer. | ||
| let mut buffer = match iterator.next() { | ||
| None => MutableBuffer::new(0), | ||
| Some(element) => { | ||
| let (lower, _) = iterator.size_hint(); | ||
| let mut buffer = MutableBuffer::new(lower.saturating_add(1) * size); | ||
| unsafe { | ||
| std::ptr::write(buffer.as_mut_ptr() as *mut T, element); | ||
| buffer.len = size; | ||
| } | ||
| buffer | ||
| } | ||
| }; | ||
|
|
||
| buffer.extend_from_iter(iterator); | ||
| buffer.into() | ||
| } | ||
| } | ||
|
|
||
| impl std::ops::Deref for MutableBuffer { | ||
| type Target = [u8]; | ||
|
|
||
|
|
@@ -1003,6 +1166,28 @@ impl PartialEq for MutableBuffer { | |
| unsafe impl Sync for MutableBuffer {} | ||
| unsafe impl Send for MutableBuffer {} | ||
|
|
||
| struct SetLenOnDrop<'a> { | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. this construct is fascinating, but I will take your word that it was necessary for speedup |
||
| len: &'a mut usize, | ||
| local_len: usize, | ||
| } | ||
|
|
||
| impl<'a> SetLenOnDrop<'a> { | ||
| #[inline] | ||
| fn new(len: &'a mut usize) -> Self { | ||
| SetLenOnDrop { | ||
| local_len: *len, | ||
| len, | ||
| } | ||
| } | ||
| } | ||
|
|
||
| impl Drop for SetLenOnDrop<'_> { | ||
| #[inline] | ||
| fn drop(&mut self) { | ||
| *self.len = self.local_len; | ||
| } | ||
| } | ||
|
|
||
| #[cfg(test)] | ||
| mod tests { | ||
| use std::thread; | ||
|
|
@@ -1172,6 +1357,29 @@ mod tests { | |
| assert_eq!(b"hello arrow", buf.as_slice()); | ||
| } | ||
|
|
||
| #[test] | ||
| fn mutable_extend_from_iter() { | ||
| let mut buf = MutableBuffer::new(0); | ||
| buf.extend(vec![1u32, 2]); | ||
| assert_eq!(8, buf.len()); | ||
| assert_eq!(&[1u8, 0, 0, 0, 2, 0, 0, 0], buf.as_slice()); | ||
|
|
||
| buf.extend(vec![3u32, 4]); | ||
| assert_eq!(16, buf.len()); | ||
| assert_eq!( | ||
| &[1u8, 0, 0, 0, 2, 0, 0, 0, 3, 0, 0, 0, 4, 0, 0, 0], | ||
| buf.as_slice() | ||
| ); | ||
| } | ||
|
|
||
| #[test] | ||
| fn test_from_trusted_len_iter() { | ||
| let iter = vec![1u32, 2].into_iter(); | ||
| let buf = unsafe { Buffer::from_trusted_len_iter(iter) }; | ||
| assert_eq!(8, buf.len()); | ||
| assert_eq!(&[1u8, 0, 0, 0, 2, 0, 0, 0], buf.as_slice()); | ||
| } | ||
|
|
||
| #[test] | ||
| fn test_mutable_reserve() { | ||
| let mut buf = MutableBuffer::new(1); | ||
|
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.