You are viewing a plain text version of this content. The canonical link for it is here.
Posted to github@arrow.apache.org by GitBox <gi...@apache.org> on 2020/10/01 10:49:53 UTC

[GitHub] [arrow] jorgecarleitao opened a new pull request #8316: ARROW-10149: [Rust] Improved support for externally owned memory regions

jorgecarleitao opened a new pull request #8316:
URL: https://github.com/apache/arrow/pull/8316


   ## Background
   
   Currently, a memory region (`arrow::buffer::BufferData`) always knows its capacity, that it uses to `drop` itself once it is no longer needed. It also knows whether it needs to be dropped or not via `BufferData::owner: bool`.
   
   However, this is insufficient for the purposes of supporting the C Data Interface, which requires informing the owner that the region is no longer needed, typically via a function call (`release`), for reference counting by the owner of the region.
   
   ## This PR
   
   This PR generalizes `BufferData` (and renames it to `Bytes`, which is more natural name for this structure, a-la `bytes::Bytes`) to support foreign deallocators. Specifically, it accepts two deallocation modes:
   
   * `Native(usize)`: the current implementation
   * `Foreign(Fn)`: an implementation that calls a function (which can be used to call a FFI)
   
   FYI @pitrou , @nevi-me @paddyhoran @sunchao 
   
   Related to #8052 , which IMO is blocked by this functionality.


----------------------------------------------------------------
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.

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



[GitHub] [arrow] jorgecarleitao closed pull request #8316: ARROW-10149: [Rust] Improved support for externally owned memory regions

Posted by GitBox <gi...@apache.org>.
jorgecarleitao closed pull request #8316:
URL: https://github.com/apache/arrow/pull/8316


   


----------------------------------------------------------------
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.

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



[GitHub] [arrow] pitrou commented on a change in pull request #8316: ARROW-10149: [Rust] Improved support for externally owned memory regions

Posted by GitBox <gi...@apache.org>.
pitrou commented on a change in pull request #8316:
URL: https://github.com/apache/arrow/pull/8316#discussion_r499144656



##########
File path: rust/arrow/src/bytes.rs
##########
@@ -0,0 +1,185 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+//! This module contains an implementation of a contiguous immutable memory region that knows
+//! how to de-allocate itself, [`Bytes`].
+//! Note that this is a low-level functionality of this crate, and is only required to be used
+//! when implementing FFI.
+
+use core::slice;
+use std::{fmt::Debug, fmt::Formatter, sync::Arc};
+
+use crate::memory;
+
+/// function resposible for de-allocating `Bytes`.
+pub type DropFn = Arc<dyn Fn(&mut Bytes)>;
+
+/// Mode of deallocating memory regions
+pub enum Deallocation {
+    /// Native deallocation, using Rust deallocator with Arrow-specific memory aligment
+    Native(usize),
+    /// Foreign deallocation, using some other form of memory deallocation
+    Foreign(DropFn),
+}
+
+impl Debug for Deallocation {
+    fn fmt(&self, f: &mut Formatter) -> std::fmt::Result {
+        match self {
+            Deallocation::Native(capacity) => {
+                write!(f, "Deallocation::Native {{ capacity: {} }}", capacity)
+            }
+            Deallocation::Foreign(_) => {
+                write!(f, "Deallocation::Foreign {{ capacity: unknown }}")
+            }
+        }
+    }
+}
+
+/// A continuous, fixed-size, immutable memory region that knows how to de-allocate itself.
+/// This structs' API is inspired by the `bytes::Bytes`, but it is not limited to using rust's
+/// global allocator nor u8 aligmnent.
+///
+/// In the most common case, this buffer is allocated using [`allocate_aligned`](memory::allocate_aligned)
+/// and deallocated accordingly [`free_aligned`](memory::free_aligned).
+/// When the region is allocated by an foreign allocator, [Deallocation::Foreign], this calls the
+/// foreign deallocator to deallocate the region when it is no longer needed.
+pub struct Bytes {
+    /// The raw pointer to be begining of the region
+    ptr: *const u8,
+
+    /// The number of bytes visible to this region. This is always smaller than its capacity (when avaliable).
+    len: usize,
+
+    /// how to deallocate this region
+    deallocation: Deallocation,
+}
+
+impl Bytes {
+    /// Takes ownership of an allocated memory region,
+    ///
+    /// # Arguments
+    ///
+    /// * `ptr` - Pointer to raw parts
+    /// * `len` - Length of raw parts in **bytes**
+    /// * `capacity` - Total allocated memory for the pointer `ptr`, in **bytes**
+    ///
+    /// # Safety
+    ///
+    /// This function is unsafe as there is no guarantee that the given pointer is valid for `len`
+    /// bytes. If the `ptr` and `capacity` come from a `Buffer`, then this is guaranteed.
+    pub unsafe fn new(ptr: *const u8, len: usize, deallocation: Deallocation) -> Bytes {
+        Bytes {
+            ptr,
+            len,
+            deallocation,
+        }
+    }
+
+    #[inline]
+    pub fn as_slice(&self) -> &[u8] {
+        unsafe { slice::from_raw_parts(self.ptr, self.len) }
+    }
+
+    #[inline]
+    pub fn len(&self) -> usize {
+        self.len
+    }
+
+    #[inline]
+    pub fn is_empty(&self) -> bool {
+        self.len == 0
+    }
+
+    #[inline]
+    pub fn raw_data(&self) -> *const u8 {
+        self.ptr
+    }
+
+    #[inline]
+    pub fn raw_data_mut(&mut self) -> *mut u8 {
+        self.ptr as *mut u8
+    }
+
+    pub fn capacity(&self) -> usize {
+        match self.deallocation {
+            Deallocation::Native(capacity) => capacity,
+            // we cannot determine this in general,
+            // and thus we state that this is externally-owned memory
+            Deallocation::Foreign(_) => 0,
+        }
+    }
+}
+
+impl Drop for Bytes {
+    #[inline]
+    fn drop(&mut self) {
+        match &self.deallocation {
+            Deallocation::Native(capacity) => {
+                if !self.ptr.is_null() {
+                    unsafe { memory::free_aligned(self.ptr as *mut u8, *capacity) };
+                }
+            }
+            Deallocation::Foreign(drop) => {
+                (drop.clone())(self);
+            }
+        }
+    }
+}
+
+impl PartialEq for Bytes {
+    fn eq(&self, other: &Bytes) -> bool {
+        self.as_slice() == other.as_slice()
+    }
+}
+
+impl Debug for Bytes {
+    fn fmt(&self, f: &mut Formatter) -> std::fmt::Result {
+        write!(f, "Bytes {{ ptr: {:?}, len: {}, data: ", self.ptr, self.len,)?;
+
+        f.debug_list().entries(self.as_slice().iter()).finish()?;
+
+        write!(f, " }}")
+    }
+}
+
+#[cfg(test)]
+mod tests {
+    use super::*;
+
+    #[test]
+    fn test_dealloc() {
+        let a = Box::new(b"hello");
+
+        let dealloc = Arc::new(|bytes: &mut Bytes| {
+            // println!(""); seems to be the only way to validate that this is actually called

Review comment:
       By the way, by definition a destructor will mutate some state (visible or not), so it seems `FnMut` may be fine too.




----------------------------------------------------------------
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.

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



[GitHub] [arrow] jorgecarleitao commented on pull request #8316: ARROW-10149: [Rust] Improved support for externally owned memory regions

Posted by GitBox <gi...@apache.org>.
jorgecarleitao commented on pull request #8316:
URL: https://github.com/apache/arrow/pull/8316#issuecomment-705944089


   Closing in favor of #8401 


----------------------------------------------------------------
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.

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



[GitHub] [arrow] pitrou commented on a change in pull request #8316: ARROW-10149: [Rust] Improved support for externally owned memory regions

Posted by GitBox <gi...@apache.org>.
pitrou commented on a change in pull request #8316:
URL: https://github.com/apache/arrow/pull/8316#discussion_r498885291



##########
File path: rust/arrow/src/bytes.rs
##########
@@ -0,0 +1,185 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+//! This module contains an implementation of a contiguous immutable memory region that knows
+//! how to de-allocate itself, [`Bytes`].
+//! Note that this is a low-level functionality of this crate, and is only required to be used
+//! when implementing FFI.
+
+use core::slice;
+use std::{fmt::Debug, fmt::Formatter, sync::Arc};
+
+use crate::memory;
+
+/// function resposible for de-allocating `Bytes`.
+pub type DropFn = Arc<dyn Fn(&mut Bytes)>;
+
+/// Mode of deallocating memory regions
+pub enum Deallocation {
+    /// Native deallocation, using Rust deallocator with Arrow-specific memory aligment
+    Native(usize),
+    /// Foreign deallocation, using some other form of memory deallocation
+    Foreign(DropFn),
+}
+
+impl Debug for Deallocation {
+    fn fmt(&self, f: &mut Formatter) -> std::fmt::Result {
+        match self {
+            Deallocation::Native(capacity) => {
+                write!(f, "Deallocation::Native {{ capacity: {} }}", capacity)
+            }
+            Deallocation::Foreign(_) => {
+                write!(f, "Deallocation::Foreign {{ capacity: unknown }}")
+            }
+        }
+    }
+}
+
+/// A continuous, fixed-size, immutable memory region that knows how to de-allocate itself.
+/// This structs' API is inspired by the `bytes::Bytes`, but it is not limited to using rust's
+/// global allocator nor u8 aligmnent.
+///
+/// In the most common case, this buffer is allocated using [`allocate_aligned`](memory::allocate_aligned)
+/// and deallocated accordingly [`free_aligned`](memory::free_aligned).
+/// When the region is allocated by an foreign allocator, [Deallocation::Foreign], this calls the
+/// foreign deallocator to deallocate the region when it is no longer needed.
+pub struct Bytes {
+    /// The raw pointer to be begining of the region
+    ptr: *const u8,
+
+    /// The number of bytes visible to this region. This is always smaller than its capacity (when avaliable).
+    len: usize,
+
+    /// how to deallocate this region
+    deallocation: Deallocation,
+}
+
+impl Bytes {
+    /// Takes ownership of an allocated memory region,
+    ///
+    /// # Arguments
+    ///
+    /// * `ptr` - Pointer to raw parts
+    /// * `len` - Length of raw parts in **bytes**
+    /// * `capacity` - Total allocated memory for the pointer `ptr`, in **bytes**
+    ///
+    /// # Safety
+    ///
+    /// This function is unsafe as there is no guarantee that the given pointer is valid for `len`
+    /// bytes. If the `ptr` and `capacity` come from a `Buffer`, then this is guaranteed.
+    pub unsafe fn new(ptr: *const u8, len: usize, deallocation: Deallocation) -> Bytes {
+        Bytes {
+            ptr,
+            len,
+            deallocation,
+        }
+    }
+
+    #[inline]
+    pub fn as_slice(&self) -> &[u8] {
+        unsafe { slice::from_raw_parts(self.ptr, self.len) }
+    }
+
+    #[inline]
+    pub fn len(&self) -> usize {
+        self.len
+    }
+
+    #[inline]
+    pub fn is_empty(&self) -> bool {
+        self.len == 0
+    }
+
+    #[inline]
+    pub fn raw_data(&self) -> *const u8 {
+        self.ptr
+    }
+
+    #[inline]
+    pub fn raw_data_mut(&mut self) -> *mut u8 {
+        self.ptr as *mut u8
+    }
+
+    pub fn capacity(&self) -> usize {
+        match self.deallocation {
+            Deallocation::Native(capacity) => capacity,
+            // we cannot determine this in general,
+            // and thus we state that this is externally-owned memory
+            Deallocation::Foreign(_) => 0,
+        }
+    }
+}
+
+impl Drop for Bytes {
+    #[inline]
+    fn drop(&mut self) {
+        match &self.deallocation {
+            Deallocation::Native(capacity) => {
+                if !self.ptr.is_null() {
+                    unsafe { memory::free_aligned(self.ptr as *mut u8, *capacity) };
+                }
+            }
+            Deallocation::Foreign(drop) => {
+                (drop.clone())(self);
+            }
+        }
+    }
+}
+
+impl PartialEq for Bytes {
+    fn eq(&self, other: &Bytes) -> bool {
+        self.as_slice() == other.as_slice()
+    }
+}
+
+impl Debug for Bytes {
+    fn fmt(&self, f: &mut Formatter) -> std::fmt::Result {
+        write!(f, "Bytes {{ ptr: {:?}, len: {}, data: ", self.ptr, self.len,)?;
+
+        f.debug_list().entries(self.as_slice().iter()).finish()?;
+
+        write!(f, " }}")
+    }
+}
+
+#[cfg(test)]
+mod tests {
+    use super::*;
+
+    #[test]
+    fn test_dealloc() {
+        let a = Box::new(b"hello");
+
+        let dealloc = Arc::new(|bytes: &mut Bytes| {
+            // println!(""); seems to be the only way to validate that this is actually called

Review comment:
       Perhaps using a closure that mutates a captured variable?
   Apparently you need to use either `FnMut` or a `Cell`:
   https://stackoverflow.com/questions/38677736/passing-a-closure-that-modifies-its-environment-to-a-function-in-rust




----------------------------------------------------------------
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.

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



[GitHub] [arrow] jorgecarleitao commented on pull request #8316: ARROW-10149: [Rust] Improved support for externally owned memory regions

Posted by GitBox <gi...@apache.org>.
jorgecarleitao commented on pull request #8316:
URL: https://github.com/apache/arrow/pull/8316#issuecomment-705944089


   Closing in favor of #8401 


----------------------------------------------------------------
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.

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



[GitHub] [arrow] jorgecarleitao closed pull request #8316: ARROW-10149: [Rust] Improved support for externally owned memory regions

Posted by GitBox <gi...@apache.org>.
jorgecarleitao closed pull request #8316:
URL: https://github.com/apache/arrow/pull/8316


   


----------------------------------------------------------------
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.

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



[GitHub] [arrow] jorgecarleitao commented on a change in pull request #8316: ARROW-10149: [Rust] Improved support for externally owned memory regions

Posted by GitBox <gi...@apache.org>.
jorgecarleitao commented on a change in pull request #8316:
URL: https://github.com/apache/arrow/pull/8316#discussion_r499142164



##########
File path: rust/arrow/src/bytes.rs
##########
@@ -0,0 +1,185 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+//! This module contains an implementation of a contiguous immutable memory region that knows
+//! how to de-allocate itself, [`Bytes`].
+//! Note that this is a low-level functionality of this crate, and is only required to be used
+//! when implementing FFI.
+
+use core::slice;
+use std::{fmt::Debug, fmt::Formatter, sync::Arc};
+
+use crate::memory;
+
+/// function resposible for de-allocating `Bytes`.
+pub type DropFn = Arc<dyn Fn(&mut Bytes)>;
+
+/// Mode of deallocating memory regions
+pub enum Deallocation {
+    /// Native deallocation, using Rust deallocator with Arrow-specific memory aligment
+    Native(usize),
+    /// Foreign deallocation, using some other form of memory deallocation
+    Foreign(DropFn),
+}
+
+impl Debug for Deallocation {
+    fn fmt(&self, f: &mut Formatter) -> std::fmt::Result {
+        match self {
+            Deallocation::Native(capacity) => {
+                write!(f, "Deallocation::Native {{ capacity: {} }}", capacity)
+            }
+            Deallocation::Foreign(_) => {
+                write!(f, "Deallocation::Foreign {{ capacity: unknown }}")
+            }
+        }
+    }
+}
+
+/// A continuous, fixed-size, immutable memory region that knows how to de-allocate itself.
+/// This structs' API is inspired by the `bytes::Bytes`, but it is not limited to using rust's
+/// global allocator nor u8 aligmnent.
+///
+/// In the most common case, this buffer is allocated using [`allocate_aligned`](memory::allocate_aligned)
+/// and deallocated accordingly [`free_aligned`](memory::free_aligned).
+/// When the region is allocated by an foreign allocator, [Deallocation::Foreign], this calls the
+/// foreign deallocator to deallocate the region when it is no longer needed.
+pub struct Bytes {
+    /// The raw pointer to be begining of the region
+    ptr: *const u8,
+
+    /// The number of bytes visible to this region. This is always smaller than its capacity (when avaliable).
+    len: usize,
+
+    /// how to deallocate this region
+    deallocation: Deallocation,
+}
+
+impl Bytes {
+    /// Takes ownership of an allocated memory region,
+    ///
+    /// # Arguments
+    ///
+    /// * `ptr` - Pointer to raw parts
+    /// * `len` - Length of raw parts in **bytes**
+    /// * `capacity` - Total allocated memory for the pointer `ptr`, in **bytes**
+    ///
+    /// # Safety
+    ///
+    /// This function is unsafe as there is no guarantee that the given pointer is valid for `len`
+    /// bytes. If the `ptr` and `capacity` come from a `Buffer`, then this is guaranteed.
+    pub unsafe fn new(ptr: *const u8, len: usize, deallocation: Deallocation) -> Bytes {
+        Bytes {
+            ptr,
+            len,
+            deallocation,
+        }
+    }
+
+    #[inline]
+    pub fn as_slice(&self) -> &[u8] {
+        unsafe { slice::from_raw_parts(self.ptr, self.len) }
+    }
+
+    #[inline]
+    pub fn len(&self) -> usize {
+        self.len
+    }
+
+    #[inline]
+    pub fn is_empty(&self) -> bool {
+        self.len == 0
+    }
+
+    #[inline]
+    pub fn raw_data(&self) -> *const u8 {
+        self.ptr
+    }
+
+    #[inline]
+    pub fn raw_data_mut(&mut self) -> *mut u8 {
+        self.ptr as *mut u8
+    }
+
+    pub fn capacity(&self) -> usize {
+        match self.deallocation {
+            Deallocation::Native(capacity) => capacity,
+            // we cannot determine this in general,
+            // and thus we state that this is externally-owned memory
+            Deallocation::Foreign(_) => 0,
+        }
+    }
+}
+
+impl Drop for Bytes {
+    #[inline]
+    fn drop(&mut self) {
+        match &self.deallocation {
+            Deallocation::Native(capacity) => {
+                if !self.ptr.is_null() {
+                    unsafe { memory::free_aligned(self.ptr as *mut u8, *capacity) };
+                }
+            }
+            Deallocation::Foreign(drop) => {
+                (drop.clone())(self);
+            }
+        }
+    }
+}
+
+impl PartialEq for Bytes {
+    fn eq(&self, other: &Bytes) -> bool {
+        self.as_slice() == other.as_slice()
+    }
+}
+
+impl Debug for Bytes {
+    fn fmt(&self, f: &mut Formatter) -> std::fmt::Result {
+        write!(f, "Bytes {{ ptr: {:?}, len: {}, data: ", self.ptr, self.len,)?;
+
+        f.debug_list().entries(self.as_slice().iter()).finish()?;
+
+        write!(f, " }}")
+    }
+}
+
+#[cfg(test)]
+mod tests {
+    use super::*;
+
+    #[test]
+    fn test_dealloc() {
+        let a = Box::new(b"hello");
+
+        let dealloc = Arc::new(|bytes: &mut Bytes| {
+            // println!(""); seems to be the only way to validate that this is actually called

Review comment:
       ```rust
           let b = Cell::new(false);
           let dealloc = Arc::new(|bytes: &mut Bytes| {
               *b.get_mut() = true;
               assert_eq!(bytes.as_slice(), &b"hello"[1..4]);
           });
   ```
   
   does not compile because it requires moving `b` to inside the closure: if we move `b` to inside the closure (using `move`), the closure is no longer `Fn`, but `FnMut`. If the closure is `FnMut`, we can no longer wrap it inside an `Arc`, as `Arc` is immutable. To make it immutable, we need to wrap it around a `Mutex`.
   
   The difference between the code we are going here and the example in SO is that we have an immutable function, as the underlying resource that this function acts upon is outside rust. I.e. from rust's perspective, the function is `Fn`.
   
   One way to test this would be to make the closure to write something to a file, and verify that that was written. I.e. test that the function mutated something outside of Rust.




----------------------------------------------------------------
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.

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



[GitHub] [arrow] jorgecarleitao commented on a change in pull request #8316: ARROW-10149: [Rust] Improved support for externally owned memory regions

Posted by GitBox <gi...@apache.org>.
jorgecarleitao commented on a change in pull request #8316:
URL: https://github.com/apache/arrow/pull/8316#discussion_r499122228



##########
File path: rust/arrow/src/bytes.rs
##########
@@ -0,0 +1,185 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+//! This module contains an implementation of a contiguous immutable memory region that knows
+//! how to de-allocate itself, [`Bytes`].
+//! Note that this is a low-level functionality of this crate, and is only required to be used
+//! when implementing FFI.
+
+use core::slice;
+use std::{fmt::Debug, fmt::Formatter, sync::Arc};
+
+use crate::memory;
+
+/// function resposible for de-allocating `Bytes`.
+pub type DropFn = Arc<dyn Fn(&mut Bytes)>;
+
+/// Mode of deallocating memory regions
+pub enum Deallocation {
+    /// Native deallocation, using Rust deallocator with Arrow-specific memory aligment
+    Native(usize),
+    /// Foreign deallocation, using some other form of memory deallocation
+    Foreign(DropFn),
+}
+
+impl Debug for Deallocation {
+    fn fmt(&self, f: &mut Formatter) -> std::fmt::Result {
+        match self {
+            Deallocation::Native(capacity) => {
+                write!(f, "Deallocation::Native {{ capacity: {} }}", capacity)
+            }
+            Deallocation::Foreign(_) => {
+                write!(f, "Deallocation::Foreign {{ capacity: unknown }}")
+            }
+        }
+    }
+}
+
+/// A continuous, fixed-size, immutable memory region that knows how to de-allocate itself.
+/// This structs' API is inspired by the `bytes::Bytes`, but it is not limited to using rust's
+/// global allocator nor u8 aligmnent.
+///
+/// In the most common case, this buffer is allocated using [`allocate_aligned`](memory::allocate_aligned)
+/// and deallocated accordingly [`free_aligned`](memory::free_aligned).
+/// When the region is allocated by an foreign allocator, [Deallocation::Foreign], this calls the
+/// foreign deallocator to deallocate the region when it is no longer needed.
+pub struct Bytes {
+    /// The raw pointer to be begining of the region
+    ptr: *const u8,
+
+    /// The number of bytes visible to this region. This is always smaller than its capacity (when avaliable).
+    len: usize,
+
+    /// how to deallocate this region
+    deallocation: Deallocation,
+}
+
+impl Bytes {
+    /// Takes ownership of an allocated memory region,
+    ///
+    /// # Arguments
+    ///
+    /// * `ptr` - Pointer to raw parts
+    /// * `len` - Length of raw parts in **bytes**
+    /// * `capacity` - Total allocated memory for the pointer `ptr`, in **bytes**
+    ///
+    /// # Safety
+    ///
+    /// This function is unsafe as there is no guarantee that the given pointer is valid for `len`
+    /// bytes. If the `ptr` and `capacity` come from a `Buffer`, then this is guaranteed.
+    pub unsafe fn new(ptr: *const u8, len: usize, deallocation: Deallocation) -> Bytes {
+        Bytes {
+            ptr,
+            len,
+            deallocation,
+        }
+    }
+
+    #[inline]
+    pub fn as_slice(&self) -> &[u8] {
+        unsafe { slice::from_raw_parts(self.ptr, self.len) }
+    }
+
+    #[inline]
+    pub fn len(&self) -> usize {
+        self.len
+    }
+
+    #[inline]
+    pub fn is_empty(&self) -> bool {
+        self.len == 0
+    }
+
+    #[inline]
+    pub fn raw_data(&self) -> *const u8 {
+        self.ptr
+    }
+
+    #[inline]
+    pub fn raw_data_mut(&mut self) -> *mut u8 {
+        self.ptr as *mut u8
+    }
+
+    pub fn capacity(&self) -> usize {
+        match self.deallocation {
+            Deallocation::Native(capacity) => capacity,
+            // we cannot determine this in general,
+            // and thus we state that this is externally-owned memory
+            Deallocation::Foreign(_) => 0,
+        }
+    }
+}
+
+impl Drop for Bytes {
+    #[inline]
+    fn drop(&mut self) {
+        match &self.deallocation {
+            Deallocation::Native(capacity) => {
+                if !self.ptr.is_null() {
+                    unsafe { memory::free_aligned(self.ptr as *mut u8, *capacity) };
+                }
+            }
+            Deallocation::Foreign(drop) => {
+                (drop.clone())(self);
+            }
+        }
+    }
+}
+
+impl PartialEq for Bytes {
+    fn eq(&self, other: &Bytes) -> bool {
+        self.as_slice() == other.as_slice()
+    }
+}
+
+impl Debug for Bytes {
+    fn fmt(&self, f: &mut Formatter) -> std::fmt::Result {
+        write!(f, "Bytes {{ ptr: {:?}, len: {}, data: ", self.ptr, self.len,)?;
+
+        f.debug_list().entries(self.as_slice().iter()).finish()?;
+
+        write!(f, " }}")
+    }
+}
+
+#[cfg(test)]
+mod tests {
+    use super::*;
+
+    #[test]
+    fn test_dealloc() {
+        let a = Box::new(b"hello");
+
+        let dealloc = Arc::new(|bytes: &mut Bytes| {
+            // println!(""); seems to be the only way to validate that this is actually called

Review comment:
       Done. I had to introduce a `Mutex`, because a `FnMut` is now mutable, while the data itself is not. I am not very happy with this, but it makes sense as we cannot assume that the C data interface is thread-safe, right?




----------------------------------------------------------------
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.

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



[GitHub] [arrow] jorgecarleitao commented on a change in pull request #8316: ARROW-10149: [Rust] Improved support for externally owned memory regions

Posted by GitBox <gi...@apache.org>.
jorgecarleitao commented on a change in pull request #8316:
URL: https://github.com/apache/arrow/pull/8316#discussion_r498218274



##########
File path: rust/arrow/src/buffer.rs
##########
@@ -253,20 +156,6 @@ impl Buffer {
             self.len() / mem::size_of::<T>(),
         )
     }
-
-    /// Returns an empty buffer.
-    pub fn empty() -> Self {

Review comment:
       This was not being used, and thus I dropped it.




----------------------------------------------------------------
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.

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



[GitHub] [arrow] pitrou commented on a change in pull request #8316: ARROW-10149: [Rust] Improved support for externally owned memory regions

Posted by GitBox <gi...@apache.org>.
pitrou commented on a change in pull request #8316:
URL: https://github.com/apache/arrow/pull/8316#discussion_r499159036



##########
File path: rust/arrow/src/bytes.rs
##########
@@ -0,0 +1,185 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+//! This module contains an implementation of a contiguous immutable memory region that knows
+//! how to de-allocate itself, [`Bytes`].
+//! Note that this is a low-level functionality of this crate, and is only required to be used
+//! when implementing FFI.
+
+use core::slice;
+use std::{fmt::Debug, fmt::Formatter, sync::Arc};
+
+use crate::memory;
+
+/// function resposible for de-allocating `Bytes`.
+pub type DropFn = Arc<dyn Fn(&mut Bytes)>;
+
+/// Mode of deallocating memory regions
+pub enum Deallocation {
+    /// Native deallocation, using Rust deallocator with Arrow-specific memory aligment
+    Native(usize),
+    /// Foreign deallocation, using some other form of memory deallocation
+    Foreign(DropFn),
+}
+
+impl Debug for Deallocation {
+    fn fmt(&self, f: &mut Formatter) -> std::fmt::Result {
+        match self {
+            Deallocation::Native(capacity) => {
+                write!(f, "Deallocation::Native {{ capacity: {} }}", capacity)
+            }
+            Deallocation::Foreign(_) => {
+                write!(f, "Deallocation::Foreign {{ capacity: unknown }}")
+            }
+        }
+    }
+}
+
+/// A continuous, fixed-size, immutable memory region that knows how to de-allocate itself.
+/// This structs' API is inspired by the `bytes::Bytes`, but it is not limited to using rust's
+/// global allocator nor u8 aligmnent.
+///
+/// In the most common case, this buffer is allocated using [`allocate_aligned`](memory::allocate_aligned)
+/// and deallocated accordingly [`free_aligned`](memory::free_aligned).
+/// When the region is allocated by an foreign allocator, [Deallocation::Foreign], this calls the
+/// foreign deallocator to deallocate the region when it is no longer needed.
+pub struct Bytes {
+    /// The raw pointer to be begining of the region
+    ptr: *const u8,
+
+    /// The number of bytes visible to this region. This is always smaller than its capacity (when avaliable).
+    len: usize,
+
+    /// how to deallocate this region
+    deallocation: Deallocation,
+}
+
+impl Bytes {
+    /// Takes ownership of an allocated memory region,
+    ///
+    /// # Arguments
+    ///
+    /// * `ptr` - Pointer to raw parts
+    /// * `len` - Length of raw parts in **bytes**
+    /// * `capacity` - Total allocated memory for the pointer `ptr`, in **bytes**
+    ///
+    /// # Safety
+    ///
+    /// This function is unsafe as there is no guarantee that the given pointer is valid for `len`
+    /// bytes. If the `ptr` and `capacity` come from a `Buffer`, then this is guaranteed.
+    pub unsafe fn new(ptr: *const u8, len: usize, deallocation: Deallocation) -> Bytes {
+        Bytes {
+            ptr,
+            len,
+            deallocation,
+        }
+    }
+
+    #[inline]
+    pub fn as_slice(&self) -> &[u8] {
+        unsafe { slice::from_raw_parts(self.ptr, self.len) }
+    }
+
+    #[inline]
+    pub fn len(&self) -> usize {
+        self.len
+    }
+
+    #[inline]
+    pub fn is_empty(&self) -> bool {
+        self.len == 0
+    }
+
+    #[inline]
+    pub fn raw_data(&self) -> *const u8 {
+        self.ptr
+    }
+
+    #[inline]
+    pub fn raw_data_mut(&mut self) -> *mut u8 {
+        self.ptr as *mut u8
+    }
+
+    pub fn capacity(&self) -> usize {
+        match self.deallocation {
+            Deallocation::Native(capacity) => capacity,
+            // we cannot determine this in general,
+            // and thus we state that this is externally-owned memory
+            Deallocation::Foreign(_) => 0,
+        }
+    }
+}
+
+impl Drop for Bytes {
+    #[inline]
+    fn drop(&mut self) {
+        match &self.deallocation {
+            Deallocation::Native(capacity) => {
+                if !self.ptr.is_null() {
+                    unsafe { memory::free_aligned(self.ptr as *mut u8, *capacity) };
+                }
+            }
+            Deallocation::Foreign(drop) => {
+                (drop.clone())(self);
+            }
+        }
+    }
+}
+
+impl PartialEq for Bytes {
+    fn eq(&self, other: &Bytes) -> bool {
+        self.as_slice() == other.as_slice()
+    }
+}
+
+impl Debug for Bytes {
+    fn fmt(&self, f: &mut Formatter) -> std::fmt::Result {
+        write!(f, "Bytes {{ ptr: {:?}, len: {}, data: ", self.ptr, self.len,)?;
+
+        f.debug_list().entries(self.as_slice().iter()).finish()?;
+
+        write!(f, " }}")
+    }
+}
+
+#[cfg(test)]
+mod tests {
+    use super::*;
+
+    #[test]
+    fn test_dealloc() {
+        let a = Box::new(b"hello");
+
+        let dealloc = Arc::new(|bytes: &mut Bytes| {
+            // println!(""); seems to be the only way to validate that this is actually called

Review comment:
       I have no idea, I am out of my depth here (not a Rust developer :-)).




----------------------------------------------------------------
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.

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



[GitHub] [arrow] pitrou commented on a change in pull request #8316: ARROW-10149: [Rust] Improved support for externally owned memory regions

Posted by GitBox <gi...@apache.org>.
pitrou commented on a change in pull request #8316:
URL: https://github.com/apache/arrow/pull/8316#discussion_r499128950



##########
File path: rust/arrow/src/bytes.rs
##########
@@ -0,0 +1,185 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+//! This module contains an implementation of a contiguous immutable memory region that knows
+//! how to de-allocate itself, [`Bytes`].
+//! Note that this is a low-level functionality of this crate, and is only required to be used
+//! when implementing FFI.
+
+use core::slice;
+use std::{fmt::Debug, fmt::Formatter, sync::Arc};
+
+use crate::memory;
+
+/// function resposible for de-allocating `Bytes`.
+pub type DropFn = Arc<dyn Fn(&mut Bytes)>;
+
+/// Mode of deallocating memory regions
+pub enum Deallocation {
+    /// Native deallocation, using Rust deallocator with Arrow-specific memory aligment
+    Native(usize),
+    /// Foreign deallocation, using some other form of memory deallocation
+    Foreign(DropFn),
+}
+
+impl Debug for Deallocation {
+    fn fmt(&self, f: &mut Formatter) -> std::fmt::Result {
+        match self {
+            Deallocation::Native(capacity) => {
+                write!(f, "Deallocation::Native {{ capacity: {} }}", capacity)
+            }
+            Deallocation::Foreign(_) => {
+                write!(f, "Deallocation::Foreign {{ capacity: unknown }}")
+            }
+        }
+    }
+}
+
+/// A continuous, fixed-size, immutable memory region that knows how to de-allocate itself.
+/// This structs' API is inspired by the `bytes::Bytes`, but it is not limited to using rust's
+/// global allocator nor u8 aligmnent.
+///
+/// In the most common case, this buffer is allocated using [`allocate_aligned`](memory::allocate_aligned)
+/// and deallocated accordingly [`free_aligned`](memory::free_aligned).
+/// When the region is allocated by an foreign allocator, [Deallocation::Foreign], this calls the
+/// foreign deallocator to deallocate the region when it is no longer needed.
+pub struct Bytes {
+    /// The raw pointer to be begining of the region
+    ptr: *const u8,
+
+    /// The number of bytes visible to this region. This is always smaller than its capacity (when avaliable).
+    len: usize,
+
+    /// how to deallocate this region
+    deallocation: Deallocation,
+}
+
+impl Bytes {
+    /// Takes ownership of an allocated memory region,
+    ///
+    /// # Arguments
+    ///
+    /// * `ptr` - Pointer to raw parts
+    /// * `len` - Length of raw parts in **bytes**
+    /// * `capacity` - Total allocated memory for the pointer `ptr`, in **bytes**
+    ///
+    /// # Safety
+    ///
+    /// This function is unsafe as there is no guarantee that the given pointer is valid for `len`
+    /// bytes. If the `ptr` and `capacity` come from a `Buffer`, then this is guaranteed.
+    pub unsafe fn new(ptr: *const u8, len: usize, deallocation: Deallocation) -> Bytes {
+        Bytes {
+            ptr,
+            len,
+            deallocation,
+        }
+    }
+
+    #[inline]
+    pub fn as_slice(&self) -> &[u8] {
+        unsafe { slice::from_raw_parts(self.ptr, self.len) }
+    }
+
+    #[inline]
+    pub fn len(&self) -> usize {
+        self.len
+    }
+
+    #[inline]
+    pub fn is_empty(&self) -> bool {
+        self.len == 0
+    }
+
+    #[inline]
+    pub fn raw_data(&self) -> *const u8 {
+        self.ptr
+    }
+
+    #[inline]
+    pub fn raw_data_mut(&mut self) -> *mut u8 {
+        self.ptr as *mut u8
+    }
+
+    pub fn capacity(&self) -> usize {
+        match self.deallocation {
+            Deallocation::Native(capacity) => capacity,
+            // we cannot determine this in general,
+            // and thus we state that this is externally-owned memory
+            Deallocation::Foreign(_) => 0,
+        }
+    }
+}
+
+impl Drop for Bytes {
+    #[inline]
+    fn drop(&mut self) {
+        match &self.deallocation {
+            Deallocation::Native(capacity) => {
+                if !self.ptr.is_null() {
+                    unsafe { memory::free_aligned(self.ptr as *mut u8, *capacity) };
+                }
+            }
+            Deallocation::Foreign(drop) => {
+                (drop.clone())(self);
+            }
+        }
+    }
+}
+
+impl PartialEq for Bytes {
+    fn eq(&self, other: &Bytes) -> bool {
+        self.as_slice() == other.as_slice()
+    }
+}
+
+impl Debug for Bytes {
+    fn fmt(&self, f: &mut Formatter) -> std::fmt::Result {
+        write!(f, "Bytes {{ ptr: {:?}, len: {}, data: ", self.ptr, self.len,)?;
+
+        f.debug_list().entries(self.as_slice().iter()).finish()?;
+
+        write!(f, " }}")
+    }
+}
+
+#[cfg(test)]
+mod tests {
+    use super::*;
+
+    #[test]
+    fn test_dealloc() {
+        let a = Box::new(b"hello");
+
+        let dealloc = Arc::new(|bytes: &mut Bytes| {
+            // println!(""); seems to be the only way to validate that this is actually called

Review comment:
       Why don't you use a `Cell`?




----------------------------------------------------------------
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.

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



[GitHub] [arrow] jorgecarleitao commented on a change in pull request #8316: ARROW-10149: [Rust] Improved support for externally owned memory regions

Posted by GitBox <gi...@apache.org>.
jorgecarleitao commented on a change in pull request #8316:
URL: https://github.com/apache/arrow/pull/8316#discussion_r499158027



##########
File path: rust/arrow/src/bytes.rs
##########
@@ -0,0 +1,185 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+//! This module contains an implementation of a contiguous immutable memory region that knows
+//! how to de-allocate itself, [`Bytes`].
+//! Note that this is a low-level functionality of this crate, and is only required to be used
+//! when implementing FFI.
+
+use core::slice;
+use std::{fmt::Debug, fmt::Formatter, sync::Arc};
+
+use crate::memory;
+
+/// function resposible for de-allocating `Bytes`.
+pub type DropFn = Arc<dyn Fn(&mut Bytes)>;
+
+/// Mode of deallocating memory regions
+pub enum Deallocation {
+    /// Native deallocation, using Rust deallocator with Arrow-specific memory aligment
+    Native(usize),
+    /// Foreign deallocation, using some other form of memory deallocation
+    Foreign(DropFn),
+}
+
+impl Debug for Deallocation {
+    fn fmt(&self, f: &mut Formatter) -> std::fmt::Result {
+        match self {
+            Deallocation::Native(capacity) => {
+                write!(f, "Deallocation::Native {{ capacity: {} }}", capacity)
+            }
+            Deallocation::Foreign(_) => {
+                write!(f, "Deallocation::Foreign {{ capacity: unknown }}")
+            }
+        }
+    }
+}
+
+/// A continuous, fixed-size, immutable memory region that knows how to de-allocate itself.
+/// This structs' API is inspired by the `bytes::Bytes`, but it is not limited to using rust's
+/// global allocator nor u8 aligmnent.
+///
+/// In the most common case, this buffer is allocated using [`allocate_aligned`](memory::allocate_aligned)
+/// and deallocated accordingly [`free_aligned`](memory::free_aligned).
+/// When the region is allocated by an foreign allocator, [Deallocation::Foreign], this calls the
+/// foreign deallocator to deallocate the region when it is no longer needed.
+pub struct Bytes {
+    /// The raw pointer to be begining of the region
+    ptr: *const u8,
+
+    /// The number of bytes visible to this region. This is always smaller than its capacity (when avaliable).
+    len: usize,
+
+    /// how to deallocate this region
+    deallocation: Deallocation,
+}
+
+impl Bytes {
+    /// Takes ownership of an allocated memory region,
+    ///
+    /// # Arguments
+    ///
+    /// * `ptr` - Pointer to raw parts
+    /// * `len` - Length of raw parts in **bytes**
+    /// * `capacity` - Total allocated memory for the pointer `ptr`, in **bytes**
+    ///
+    /// # Safety
+    ///
+    /// This function is unsafe as there is no guarantee that the given pointer is valid for `len`
+    /// bytes. If the `ptr` and `capacity` come from a `Buffer`, then this is guaranteed.
+    pub unsafe fn new(ptr: *const u8, len: usize, deallocation: Deallocation) -> Bytes {
+        Bytes {
+            ptr,
+            len,
+            deallocation,
+        }
+    }
+
+    #[inline]
+    pub fn as_slice(&self) -> &[u8] {
+        unsafe { slice::from_raw_parts(self.ptr, self.len) }
+    }
+
+    #[inline]
+    pub fn len(&self) -> usize {
+        self.len
+    }
+
+    #[inline]
+    pub fn is_empty(&self) -> bool {
+        self.len == 0
+    }
+
+    #[inline]
+    pub fn raw_data(&self) -> *const u8 {
+        self.ptr
+    }
+
+    #[inline]
+    pub fn raw_data_mut(&mut self) -> *mut u8 {
+        self.ptr as *mut u8
+    }
+
+    pub fn capacity(&self) -> usize {
+        match self.deallocation {
+            Deallocation::Native(capacity) => capacity,
+            // we cannot determine this in general,
+            // and thus we state that this is externally-owned memory
+            Deallocation::Foreign(_) => 0,
+        }
+    }
+}
+
+impl Drop for Bytes {
+    #[inline]
+    fn drop(&mut self) {
+        match &self.deallocation {
+            Deallocation::Native(capacity) => {
+                if !self.ptr.is_null() {
+                    unsafe { memory::free_aligned(self.ptr as *mut u8, *capacity) };
+                }
+            }
+            Deallocation::Foreign(drop) => {
+                (drop.clone())(self);
+            }
+        }
+    }
+}
+
+impl PartialEq for Bytes {
+    fn eq(&self, other: &Bytes) -> bool {
+        self.as_slice() == other.as_slice()
+    }
+}
+
+impl Debug for Bytes {
+    fn fmt(&self, f: &mut Formatter) -> std::fmt::Result {
+        write!(f, "Bytes {{ ptr: {:?}, len: {}, data: ", self.ptr, self.len,)?;
+
+        f.debug_list().entries(self.as_slice().iter()).finish()?;
+
+        write!(f, " }}")
+    }
+}
+
+#[cfg(test)]
+mod tests {
+    use super::*;
+
+    #[test]
+    fn test_dealloc() {
+        let a = Box::new(b"hello");
+
+        let dealloc = Arc::new(|bytes: &mut Bytes| {
+            // println!(""); seems to be the only way to validate that this is actually called

Review comment:
       That is awesome! Thanks a lot for the help and insight @pitrou .
   
   The destructor mutates state. Shouldn't that state be only the state of `self`? IMO that is the reason rust's `Drop` requires a mutable ref of self, `fn drop(&mut self)`.




----------------------------------------------------------------
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.

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



[GitHub] [arrow] github-actions[bot] commented on pull request #8316: ARROW-10149: [Rust] Improved support for externally owned memory regions

Posted by GitBox <gi...@apache.org>.
github-actions[bot] commented on pull request #8316:
URL: https://github.com/apache/arrow/pull/8316#issuecomment-702060135


   https://issues.apache.org/jira/browse/ARROW-10149


----------------------------------------------------------------
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.

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



[GitHub] [arrow] jorgecarleitao commented on a change in pull request #8316: ARROW-10149: [Rust] Improved support for externally owned memory regions

Posted by GitBox <gi...@apache.org>.
jorgecarleitao commented on a change in pull request #8316:
URL: https://github.com/apache/arrow/pull/8316#discussion_r499127368



##########
File path: rust/arrow/src/bytes.rs
##########
@@ -0,0 +1,185 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+//! This module contains an implementation of a contiguous immutable memory region that knows
+//! how to de-allocate itself, [`Bytes`].
+//! Note that this is a low-level functionality of this crate, and is only required to be used
+//! when implementing FFI.
+
+use core::slice;
+use std::{fmt::Debug, fmt::Formatter, sync::Arc};
+
+use crate::memory;
+
+/// function resposible for de-allocating `Bytes`.
+pub type DropFn = Arc<dyn Fn(&mut Bytes)>;
+
+/// Mode of deallocating memory regions
+pub enum Deallocation {
+    /// Native deallocation, using Rust deallocator with Arrow-specific memory aligment
+    Native(usize),
+    /// Foreign deallocation, using some other form of memory deallocation
+    Foreign(DropFn),
+}
+
+impl Debug for Deallocation {
+    fn fmt(&self, f: &mut Formatter) -> std::fmt::Result {
+        match self {
+            Deallocation::Native(capacity) => {
+                write!(f, "Deallocation::Native {{ capacity: {} }}", capacity)
+            }
+            Deallocation::Foreign(_) => {
+                write!(f, "Deallocation::Foreign {{ capacity: unknown }}")
+            }
+        }
+    }
+}
+
+/// A continuous, fixed-size, immutable memory region that knows how to de-allocate itself.
+/// This structs' API is inspired by the `bytes::Bytes`, but it is not limited to using rust's
+/// global allocator nor u8 aligmnent.
+///
+/// In the most common case, this buffer is allocated using [`allocate_aligned`](memory::allocate_aligned)
+/// and deallocated accordingly [`free_aligned`](memory::free_aligned).
+/// When the region is allocated by an foreign allocator, [Deallocation::Foreign], this calls the
+/// foreign deallocator to deallocate the region when it is no longer needed.
+pub struct Bytes {
+    /// The raw pointer to be begining of the region
+    ptr: *const u8,
+
+    /// The number of bytes visible to this region. This is always smaller than its capacity (when avaliable).
+    len: usize,
+
+    /// how to deallocate this region
+    deallocation: Deallocation,
+}
+
+impl Bytes {
+    /// Takes ownership of an allocated memory region,
+    ///
+    /// # Arguments
+    ///
+    /// * `ptr` - Pointer to raw parts
+    /// * `len` - Length of raw parts in **bytes**
+    /// * `capacity` - Total allocated memory for the pointer `ptr`, in **bytes**
+    ///
+    /// # Safety
+    ///
+    /// This function is unsafe as there is no guarantee that the given pointer is valid for `len`
+    /// bytes. If the `ptr` and `capacity` come from a `Buffer`, then this is guaranteed.
+    pub unsafe fn new(ptr: *const u8, len: usize, deallocation: Deallocation) -> Bytes {
+        Bytes {
+            ptr,
+            len,
+            deallocation,
+        }
+    }
+
+    #[inline]
+    pub fn as_slice(&self) -> &[u8] {
+        unsafe { slice::from_raw_parts(self.ptr, self.len) }
+    }
+
+    #[inline]
+    pub fn len(&self) -> usize {
+        self.len
+    }
+
+    #[inline]
+    pub fn is_empty(&self) -> bool {
+        self.len == 0
+    }
+
+    #[inline]
+    pub fn raw_data(&self) -> *const u8 {
+        self.ptr
+    }
+
+    #[inline]
+    pub fn raw_data_mut(&mut self) -> *mut u8 {
+        self.ptr as *mut u8
+    }
+
+    pub fn capacity(&self) -> usize {
+        match self.deallocation {
+            Deallocation::Native(capacity) => capacity,
+            // we cannot determine this in general,
+            // and thus we state that this is externally-owned memory
+            Deallocation::Foreign(_) => 0,
+        }
+    }
+}
+
+impl Drop for Bytes {
+    #[inline]
+    fn drop(&mut self) {
+        match &self.deallocation {
+            Deallocation::Native(capacity) => {
+                if !self.ptr.is_null() {
+                    unsafe { memory::free_aligned(self.ptr as *mut u8, *capacity) };
+                }
+            }
+            Deallocation::Foreign(drop) => {
+                (drop.clone())(self);
+            }
+        }
+    }
+}
+
+impl PartialEq for Bytes {
+    fn eq(&self, other: &Bytes) -> bool {
+        self.as_slice() == other.as_slice()
+    }
+}
+
+impl Debug for Bytes {
+    fn fmt(&self, f: &mut Formatter) -> std::fmt::Result {
+        write!(f, "Bytes {{ ptr: {:?}, len: {}, data: ", self.ptr, self.len,)?;
+
+        f.debug_list().entries(self.as_slice().iter()).finish()?;
+
+        write!(f, " }}")
+    }
+}
+
+#[cfg(test)]
+mod tests {
+    use super::*;
+
+    #[test]
+    fn test_dealloc() {
+        let a = Box::new(b"hello");
+
+        let dealloc = Arc::new(|bytes: &mut Bytes| {
+            // println!(""); seems to be the only way to validate that this is actually called

Review comment:
       I reverted this. I do not think that that `Fn` should be mutable, as it is just performing an FFI call, over which Rust does not need to know about mutability. I am still trying to test it, but I think that something like `Arc<dyn Fn(&mut Bytes)>` is a better signature,.
   




----------------------------------------------------------------
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.

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



[GitHub] [arrow] pitrou commented on a change in pull request #8316: ARROW-10149: [Rust] Improved support for externally owned memory regions

Posted by GitBox <gi...@apache.org>.
pitrou commented on a change in pull request #8316:
URL: https://github.com/apache/arrow/pull/8316#discussion_r499144135



##########
File path: rust/arrow/src/bytes.rs
##########
@@ -0,0 +1,185 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+//! This module contains an implementation of a contiguous immutable memory region that knows
+//! how to de-allocate itself, [`Bytes`].
+//! Note that this is a low-level functionality of this crate, and is only required to be used
+//! when implementing FFI.
+
+use core::slice;
+use std::{fmt::Debug, fmt::Formatter, sync::Arc};
+
+use crate::memory;
+
+/// function resposible for de-allocating `Bytes`.
+pub type DropFn = Arc<dyn Fn(&mut Bytes)>;
+
+/// Mode of deallocating memory regions
+pub enum Deallocation {
+    /// Native deallocation, using Rust deallocator with Arrow-specific memory aligment
+    Native(usize),
+    /// Foreign deallocation, using some other form of memory deallocation
+    Foreign(DropFn),
+}
+
+impl Debug for Deallocation {
+    fn fmt(&self, f: &mut Formatter) -> std::fmt::Result {
+        match self {
+            Deallocation::Native(capacity) => {
+                write!(f, "Deallocation::Native {{ capacity: {} }}", capacity)
+            }
+            Deallocation::Foreign(_) => {
+                write!(f, "Deallocation::Foreign {{ capacity: unknown }}")
+            }
+        }
+    }
+}
+
+/// A continuous, fixed-size, immutable memory region that knows how to de-allocate itself.
+/// This structs' API is inspired by the `bytes::Bytes`, but it is not limited to using rust's
+/// global allocator nor u8 aligmnent.
+///
+/// In the most common case, this buffer is allocated using [`allocate_aligned`](memory::allocate_aligned)
+/// and deallocated accordingly [`free_aligned`](memory::free_aligned).
+/// When the region is allocated by an foreign allocator, [Deallocation::Foreign], this calls the
+/// foreign deallocator to deallocate the region when it is no longer needed.
+pub struct Bytes {
+    /// The raw pointer to be begining of the region
+    ptr: *const u8,
+
+    /// The number of bytes visible to this region. This is always smaller than its capacity (when avaliable).
+    len: usize,
+
+    /// how to deallocate this region
+    deallocation: Deallocation,
+}
+
+impl Bytes {
+    /// Takes ownership of an allocated memory region,
+    ///
+    /// # Arguments
+    ///
+    /// * `ptr` - Pointer to raw parts
+    /// * `len` - Length of raw parts in **bytes**
+    /// * `capacity` - Total allocated memory for the pointer `ptr`, in **bytes**
+    ///
+    /// # Safety
+    ///
+    /// This function is unsafe as there is no guarantee that the given pointer is valid for `len`
+    /// bytes. If the `ptr` and `capacity` come from a `Buffer`, then this is guaranteed.
+    pub unsafe fn new(ptr: *const u8, len: usize, deallocation: Deallocation) -> Bytes {
+        Bytes {
+            ptr,
+            len,
+            deallocation,
+        }
+    }
+
+    #[inline]
+    pub fn as_slice(&self) -> &[u8] {
+        unsafe { slice::from_raw_parts(self.ptr, self.len) }
+    }
+
+    #[inline]
+    pub fn len(&self) -> usize {
+        self.len
+    }
+
+    #[inline]
+    pub fn is_empty(&self) -> bool {
+        self.len == 0
+    }
+
+    #[inline]
+    pub fn raw_data(&self) -> *const u8 {
+        self.ptr
+    }
+
+    #[inline]
+    pub fn raw_data_mut(&mut self) -> *mut u8 {
+        self.ptr as *mut u8
+    }
+
+    pub fn capacity(&self) -> usize {
+        match self.deallocation {
+            Deallocation::Native(capacity) => capacity,
+            // we cannot determine this in general,
+            // and thus we state that this is externally-owned memory
+            Deallocation::Foreign(_) => 0,
+        }
+    }
+}
+
+impl Drop for Bytes {
+    #[inline]
+    fn drop(&mut self) {
+        match &self.deallocation {
+            Deallocation::Native(capacity) => {
+                if !self.ptr.is_null() {
+                    unsafe { memory::free_aligned(self.ptr as *mut u8, *capacity) };
+                }
+            }
+            Deallocation::Foreign(drop) => {
+                (drop.clone())(self);
+            }
+        }
+    }
+}
+
+impl PartialEq for Bytes {
+    fn eq(&self, other: &Bytes) -> bool {
+        self.as_slice() == other.as_slice()
+    }
+}
+
+impl Debug for Bytes {
+    fn fmt(&self, f: &mut Formatter) -> std::fmt::Result {
+        write!(f, "Bytes {{ ptr: {:?}, len: {}, data: ", self.ptr, self.len,)?;
+
+        f.debug_list().entries(self.as_slice().iter()).finish()?;
+
+        write!(f, " }}")
+    }
+}
+
+#[cfg(test)]
+mod tests {
+    use super::*;
+
+    #[test]
+    fn test_dealloc() {
+        let a = Box::new(b"hello");
+
+        let dealloc = Arc::new(|bytes: &mut Bytes| {
+            // println!(""); seems to be the only way to validate that this is actually called

Review comment:
       After trying out varying things, I got the following to work:
   ```rust
   use std::cell::Cell;
   use std::sync::Arc;
   
   pub type VoidFn = Arc<dyn Fn()>;
   
   fn main() {
       let integer = Arc::new(Cell::new(5));
       let inner = integer.clone();
       let closure = Arc::new(move || {
           inner.set(inner.get() + 1);
       });
       execute_closure(closure);
       println!("After closure: {}", integer.get());
   }
   
   fn execute_closure(func: VoidFn)
   {
       func();
   }
   ```
   
   I may be missing something though.




----------------------------------------------------------------
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.

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