You are viewing a plain text version of this content. The canonical link for it is here.
Posted to github@arrow.apache.org by "tustvold (via GitHub)" <gi...@apache.org> on 2023/03/23 18:21:49 UTC

[GitHub] [arrow-rs] tustvold opened a new pull request, #3920: Add Zero-Copy Conversion between Vec and MutableBuffer

tustvold opened a new pull request, #3920:
URL: https://github.com/apache/arrow-rs/pull/3920

   # Which issue does this PR close?
   
   <!--
   We generally require a GitHub issue to be filed for all bug fixes and enhancements and this helps us generate change logs for our releases. You can link an issue to this PR using the GitHub syntax. For example `Closes #123` indicates that this PR will close issue #123.
   -->
   
   Closes #3516
   
   # Rationale for this change
    
   <!--
   Why are you proposing this change? If this is already explained clearly in the issue then this section is not needed.
   Explaining clearly why changes are proposed helps reviewers understand your changes and offer better suggestions for fixes.
   -->
   
   https://github.com/apache/arrow-rs/pull/3756 only added zero-copy conversion between `Vec` and `Buffer` in order to keep the scope of the change down. Unfortunately as discovered in #3917 this causes issues for the APIs that allow converting an Array back into a builder, as the builders use MutableBuffer and therefore are restricted by the alignment expectations of `MutableBuffer`.
   
   # What changes are included in this PR?
   
   <!--
   There is no need to duplicate the description in the issue here but it is sometimes worth providing a summary of the individual changes in this PR.
   -->
   
   Adds zero-copy conversion to `MutableBuffer` by storing the `Layout` inline.
   
   # Are there any user-facing changes?
   
   This changes what can and can't be converted to a MutableBuffer, and removes some low-level deprecated APIs. Downstream impact is likely to be extremely marginal.
   
   <!--
   If there are user-facing changes then we may require documentation to be updated before approving the PR.
   -->
   
   <!---
   If there are any breaking changes to public APIs, please add the `breaking change` label.
   -->
   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [arrow-rs] tustvold commented on a diff in pull request #3920: Add Zero-Copy Conversion between Vec and MutableBuffer

Posted by "tustvold (via GitHub)" <gi...@apache.org>.
tustvold commented on code in PR #3920:
URL: https://github.com/apache/arrow-rs/pull/3920#discussion_r1146645005


##########
arrow-buffer/src/buffer/mutable.rs:
##########
@@ -89,35 +97,46 @@ impl MutableBuffer {
     /// let data = buffer.as_slice_mut();
     /// assert_eq!(data[126], 0u8);
     /// ```
-    #[allow(deprecated)]
     pub fn from_len_zeroed(len: usize) -> Self {
-        let new_capacity = bit_util::round_upto_multiple_of_64(len);
-        let ptr = alloc::allocate_aligned_zeroed(new_capacity);
-        Self {
-            data: ptr,
-            len,
-            capacity: new_capacity,
-        }
+        let layout = Layout::from_size_align(len, ALIGNMENT).unwrap();
+        let data = match layout.size() {
+            0 => dangling_ptr(),
+            _ => {
+                // Safety: Verified size != 0
+                let raw_ptr = unsafe { std::alloc::alloc_zeroed(layout) };
+                NonNull::new(raw_ptr).unwrap_or_else(|| handle_alloc_error(layout))
+            }
+        };
+        Self { data, len, layout }
+    }
+
+    /// Create a [`MutableBuffer`] from the provided [`Vec`] without copying
+    #[inline]
+    pub fn from_vec<T: ArrowNativeType>(vec: Vec<T>) -> Self {
+        // Safety

Review Comment:
   This is the logic from `Buffer::from_vec`



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [arrow-rs] tustvold merged pull request #3920: Add Zero-Copy Conversion between Vec and MutableBuffer

Posted by "tustvold (via GitHub)" <gi...@apache.org>.
tustvold merged PR #3920:
URL: https://github.com/apache/arrow-rs/pull/3920


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [arrow-rs] alamb commented on pull request #3920: Add Zero-Copy Conversion between Vec and MutableBuffer

Posted by "alamb (via GitHub)" <gi...@apache.org>.
alamb commented on PR #3920:
URL: https://github.com/apache/arrow-rs/pull/3920#issuecomment-1481882068

   I think @viirya  should take a close look at this and make sure it is compatible with their usecase.
   
   cc @avantgardnerio  as I think you had a similar usecase with modifying data a while ago


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [arrow-rs] viirya commented on a diff in pull request #3920: Add Zero-Copy Conversion between Vec and MutableBuffer

Posted by "viirya (via GitHub)" <gi...@apache.org>.
viirya commented on code in PR #3920:
URL: https://github.com/apache/arrow-rs/pull/3920#discussion_r1148138174


##########
arrow-buffer/src/buffer/mutable.rs:
##########
@@ -67,14 +68,21 @@ impl MutableBuffer {
 
     /// Allocate a new [MutableBuffer] with initial capacity to be at least `capacity`.
     #[inline]
-    #[allow(deprecated)]
     pub fn with_capacity(capacity: usize) -> Self {
         let capacity = bit_util::round_upto_multiple_of_64(capacity);
-        let ptr = alloc::allocate_aligned(capacity);
+        let layout = Layout::from_size_align(capacity, ALIGNMENT).unwrap();

Review Comment:
   Do we still need `round_upto_multiple_of_64`? `from_size_align` seems also rounding `capacity`?



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [arrow-rs] tustvold commented on a diff in pull request #3920: Add Zero-Copy Conversion between Vec and MutableBuffer

Posted by "tustvold (via GitHub)" <gi...@apache.org>.
tustvold commented on code in PR #3920:
URL: https://github.com/apache/arrow-rs/pull/3920#discussion_r1148350060


##########
arrow-buffer/src/buffer/mutable.rs:
##########
@@ -67,14 +68,21 @@ impl MutableBuffer {
 
     /// Allocate a new [MutableBuffer] with initial capacity to be at least `capacity`.
     #[inline]
-    #[allow(deprecated)]
     pub fn with_capacity(capacity: usize) -> Self {
         let capacity = bit_util::round_upto_multiple_of_64(capacity);
-        let ptr = alloc::allocate_aligned(capacity);
+        let layout = Layout::from_size_align(capacity, ALIGNMENT).unwrap();

Review Comment:
   > from_size_align seems also rounding capacity
   
   It doesn't round, it just verifies that the allocation isn't large enough to overflow isize and cause UB



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [arrow-rs] tustvold commented on a diff in pull request #3920: Add Zero-Copy Conversion between Vec and MutableBuffer

Posted by "tustvold (via GitHub)" <gi...@apache.org>.
tustvold commented on code in PR #3920:
URL: https://github.com/apache/arrow-rs/pull/3920#discussion_r1148349944


##########
arrow-buffer/src/buffer/mutable.rs:
##########
@@ -89,35 +97,46 @@ impl MutableBuffer {
     /// let data = buffer.as_slice_mut();
     /// assert_eq!(data[126], 0u8);
     /// ```
-    #[allow(deprecated)]
     pub fn from_len_zeroed(len: usize) -> Self {
-        let new_capacity = bit_util::round_upto_multiple_of_64(len);
-        let ptr = alloc::allocate_aligned_zeroed(new_capacity);
-        Self {
-            data: ptr,
-            len,
-            capacity: new_capacity,
-        }
+        let layout = Layout::from_size_align(len, ALIGNMENT).unwrap();
+        let data = match layout.size() {
+            0 => dangling_ptr(),
+            _ => {
+                // Safety: Verified size != 0
+                let raw_ptr = unsafe { std::alloc::alloc_zeroed(layout) };
+                NonNull::new(raw_ptr).unwrap_or_else(|| handle_alloc_error(layout))
+            }
+        };
+        Self { data, len, layout }
+    }
+
+    /// Create a [`MutableBuffer`] from the provided [`Vec`] without copying
+    #[inline]
+    pub fn from_vec<T: ArrowNativeType>(vec: Vec<T>) -> Self {
+        // Safety
+        // Vec::as_ptr guaranteed to not be null and ArrowNativeType are trivially transmutable
+        let data = unsafe { NonNull::new_unchecked(vec.as_ptr() as _) };
+        let len = vec.len() * mem::size_of::<T>();
+        // Safety
+        // Vec guaranteed to have a valid layout matching that of `Layout::array`
+        // This is based on `RawVec::current_memory`
+        let layout = unsafe { Layout::array::<T>(vec.capacity()).unwrap_unchecked() };
+        mem::forget(vec);
+        Self { data, len, layout }
     }
 
     /// Allocates a new [MutableBuffer] from given `Bytes`.
     pub(crate) fn from_bytes(bytes: Bytes) -> Result<Self, Bytes> {
-        let capacity = match bytes.deallocation() {
-            Deallocation::Standard(layout) if layout.align() == ALIGNMENT => {
-                layout.size()
-            }
+        let layout = match bytes.deallocation() {

Review Comment:
   Correct, we can handle any alignment now



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [arrow-rs] viirya commented on pull request #3920: Add Zero-Copy Conversion between Vec and MutableBuffer

Posted by "viirya (via GitHub)" <gi...@apache.org>.
viirya commented on PR #3920:
URL: https://github.com/apache/arrow-rs/pull/3920#issuecomment-1481985806

   I'll review this today or tomorrow.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [arrow-rs] tustvold commented on a diff in pull request #3920: Add Zero-Copy Conversion between Vec and MutableBuffer

Posted by "tustvold (via GitHub)" <gi...@apache.org>.
tustvold commented on code in PR #3920:
URL: https://github.com/apache/arrow-rs/pull/3920#discussion_r1146646470


##########
arrow-buffer/src/buffer/mutable.rs:
##########
@@ -455,19 +480,12 @@ impl MutableBuffer {
     }
 }
 
-/// # Safety
-/// `ptr` must be allocated for `old_capacity`.
-#[cold]
-#[allow(deprecated)]
-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 = alloc::reallocate(ptr, old_capacity, new_capacity);
-    (ptr, new_capacity)
+#[inline]
+fn dangling_ptr() -> NonNull<u8> {
+    // SAFETY: ALIGNMENT is a non-zero usize which is then casted
+    // to a *mut T. Therefore, `ptr` is not null and the conditions for
+    // calling new_unchecked() are respected.
+    unsafe { NonNull::new_unchecked(ALIGNMENT as *mut u8) }

Review Comment:
   This is moved from the alloc module



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [arrow-rs] tustvold commented on pull request #3920: Add Zero-Copy Conversion between Vec and MutableBuffer

Posted by "tustvold (via GitHub)" <gi...@apache.org>.
tustvold commented on PR #3920:
URL: https://github.com/apache/arrow-rs/pull/3920#issuecomment-1481692015

   I plan to run the benchmarks to confirm no performance regression


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [arrow-rs] viirya commented on a diff in pull request #3920: Add Zero-Copy Conversion between Vec and MutableBuffer

Posted by "viirya (via GitHub)" <gi...@apache.org>.
viirya commented on code in PR #3920:
URL: https://github.com/apache/arrow-rs/pull/3920#discussion_r1148139062


##########
arrow-buffer/src/buffer/mutable.rs:
##########
@@ -89,35 +97,46 @@ impl MutableBuffer {
     /// let data = buffer.as_slice_mut();
     /// assert_eq!(data[126], 0u8);
     /// ```
-    #[allow(deprecated)]
     pub fn from_len_zeroed(len: usize) -> Self {
-        let new_capacity = bit_util::round_upto_multiple_of_64(len);
-        let ptr = alloc::allocate_aligned_zeroed(new_capacity);
-        Self {
-            data: ptr,
-            len,
-            capacity: new_capacity,
-        }
+        let layout = Layout::from_size_align(len, ALIGNMENT).unwrap();
+        let data = match layout.size() {
+            0 => dangling_ptr(),
+            _ => {
+                // Safety: Verified size != 0
+                let raw_ptr = unsafe { std::alloc::alloc_zeroed(layout) };
+                NonNull::new(raw_ptr).unwrap_or_else(|| handle_alloc_error(layout))
+            }
+        };
+        Self { data, len, layout }
+    }
+
+    /// Create a [`MutableBuffer`] from the provided [`Vec`] without copying
+    #[inline]
+    pub fn from_vec<T: ArrowNativeType>(vec: Vec<T>) -> Self {
+        // Safety
+        // Vec::as_ptr guaranteed to not be null and ArrowNativeType are trivially transmutable
+        let data = unsafe { NonNull::new_unchecked(vec.as_ptr() as _) };
+        let len = vec.len() * mem::size_of::<T>();
+        // Safety
+        // Vec guaranteed to have a valid layout matching that of `Layout::array`
+        // This is based on `RawVec::current_memory`
+        let layout = unsafe { Layout::array::<T>(vec.capacity()).unwrap_unchecked() };
+        mem::forget(vec);
+        Self { data, len, layout }
     }
 
     /// Allocates a new [MutableBuffer] from given `Bytes`.
     pub(crate) fn from_bytes(bytes: Bytes) -> Result<Self, Bytes> {
-        let capacity = match bytes.deallocation() {
-            Deallocation::Standard(layout) if layout.align() == ALIGNMENT => {
-                layout.size()
-            }
+        let layout = match bytes.deallocation() {

Review Comment:
   The alignment of `bytes` doesn't matter now?



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [arrow-rs] tustvold commented on pull request #3920: Add Zero-Copy Conversion between Vec and MutableBuffer

Posted by "tustvold (via GitHub)" <gi...@apache.org>.
tustvold commented on PR #3920:
URL: https://github.com/apache/arrow-rs/pull/3920#issuecomment-1481989267

   > I'll review this today or tomorrow.
   
   Thank you :heart: 
   
   To be clear this is a strictly additive change, it allows `into_mut` for arrays containing `Buffer` created from `Vec`, in addition to the current support for `Buffer` created from `MutableBuffer`


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [arrow-rs] tustvold commented on a diff in pull request #3920: Add Zero-Copy Conversion between Vec and MutableBuffer

Posted by "tustvold (via GitHub)" <gi...@apache.org>.
tustvold commented on code in PR #3920:
URL: https://github.com/apache/arrow-rs/pull/3920#discussion_r1146644724


##########
arrow-buffer/src/buffer/immutable.rs:
##########
@@ -810,7 +800,8 @@ mod tests {
         b.into_mutable().unwrap();
 
         let b = Buffer::from_vec(vec![1_u32, 3, 5]);
-        let b = b.into_mutable().unwrap_err(); // Invalid layout
+        let b = b.into_mutable().unwrap();

Review Comment:
   This is now possible :tada:



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [arrow-rs] tustvold commented on a diff in pull request #3920: Add Zero-Copy Conversion between Vec and MutableBuffer

Posted by "tustvold (via GitHub)" <gi...@apache.org>.
tustvold commented on code in PR #3920:
URL: https://github.com/apache/arrow-rs/pull/3920#discussion_r1146646123


##########
arrow-buffer/src/buffer/mutable.rs:
##########
@@ -67,14 +68,21 @@ impl MutableBuffer {
 
     /// Allocate a new [MutableBuffer] with initial capacity to be at least `capacity`.
     #[inline]
-    #[allow(deprecated)]
     pub fn with_capacity(capacity: usize) -> Self {
         let capacity = bit_util::round_upto_multiple_of_64(capacity);
-        let ptr = alloc::allocate_aligned(capacity);
+        let layout = Layout::from_size_align(capacity, ALIGNMENT).unwrap();

Review Comment:
   The previous allocation methods used `from_size_align_unchecked`, this was technically incorrect as it didn't check capacity doesn't overflow `isize`



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org