Skip to content
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

Decouple buffer deallocation from ffi and allow creating buffers from rust vec #1494

Merged
merged 7 commits into from
Apr 7, 2022
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 30 additions & 0 deletions arrow/src/alloc/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,11 @@
//! regions, cache and allocation alignments.

use std::alloc::{handle_alloc_error, Layout};
use std::fmt::{Debug, Formatter};
use std::mem::size_of;
use std::panic::RefUnwindSafe;
use std::ptr::NonNull;
use std::sync::Arc;

mod alignment;
mod types;
Expand Down Expand Up @@ -121,3 +124,30 @@ pub unsafe fn reallocate<T: NativeType>(
handle_alloc_error(Layout::from_size_align_unchecked(new_size, ALIGNMENT))
})
}

/// The owner of an allocation, that is not natively allocated.
/// The trait implementation is responsible for dropping the allocations once no more references exist.
pub trait Allocation: RefUnwindSafe {}
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The trait bound on RefUnwindSafe was needed to make one test compile. I'll need to check that in more detail and document why it is required.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I added an explicit test that Buffer is UnwindSafe to make this requirement clearer.

jhorstmann marked this conversation as resolved.
Show resolved Hide resolved

impl<T: RefUnwindSafe> Allocation for T {}

/// Mode of deallocating memory regions
pub enum Deallocation {
/// Native deallocation, using Rust deallocator with Arrow-specific memory alignment
Native(usize),
/// Foreign interface, via a callback
jhorstmann marked this conversation as resolved.
Show resolved Hide resolved
Foreign(Arc<dyn Allocation>),
}

impl Debug for Deallocation {
fn fmt(&self, f: &mut Formatter) -> std::fmt::Result {
match self {
Deallocation::Native(capacity) => {
jhorstmann marked this conversation as resolved.
Show resolved Hide resolved
write!(f, "Deallocation::Native {{ capacity: {} }}", capacity)
}
Deallocation::Foreign(_) => {
write!(f, "Deallocation::Foreign {{ capacity: unknown }}")
}
}
}
}
53 changes: 51 additions & 2 deletions arrow/src/array/data.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1459,10 +1459,11 @@ impl ArrayDataBuilder {
#[cfg(test)]
mod tests {
use super::*;
use std::ptr::NonNull;

use crate::array::{
Array, BooleanBuilder, Int32Array, Int32Builder, Int64Array, StringArray,
StructBuilder, UInt64Array,
make_array, Array, BooleanBuilder, Int32Array, Int32Builder, Int64Array,
StringArray, StructBuilder, UInt64Array,
};
use crate::buffer::Buffer;
use crate::datatypes::Field;
Expand Down Expand Up @@ -2594,4 +2595,52 @@ mod tests {

assert_eq!(&struct_array_slice, &cloned);
}

#[test]
fn test_string_data_from_foreign() {
let mut strings = "foobarfoobar".to_owned();
let mut offsets = vec![0_i32, 0, 3, 6, 12];
let mut bitmap = vec![0b1110_u8];

let strings_buffer = unsafe {
Buffer::from_foreign(
NonNull::new_unchecked(strings.as_mut_ptr()),
strings.len(),
Arc::new(strings),
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It seems pretty neat to me that the ownership of the Vec is transferred to Arc which is then stored (as dyn Allocation)

)
};
let offsets_buffer = unsafe {
Buffer::from_foreign(
NonNull::new_unchecked(offsets.as_mut_ptr() as *mut u8),
offsets.len() * std::mem::size_of::<i32>(),
Arc::new(offsets),
)
};
let null_buffer = unsafe {
Buffer::from_foreign(
NonNull::new_unchecked(bitmap.as_mut_ptr()),
bitmap.len(),
Arc::new(bitmap),
)
};

let data = ArrayData::try_new(
DataType::Utf8,
4,
None,
Some(null_buffer),
0,
vec![offsets_buffer, strings_buffer],
vec![],
)
.unwrap();

let array = make_array(data);
let array = array.as_any().downcast_ref::<StringArray>().unwrap();

let expected =
StringArray::from(vec![None, Some("foo"), Some("bar"), Some("foobar")]);

assert_eq!(array, &expected);
}
}
35 changes: 26 additions & 9 deletions arrow/src/buffer/immutable.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,12 +21,9 @@ use std::ptr::NonNull;
use std::sync::Arc;
use std::{convert::AsRef, usize};

use crate::alloc::{Allocation, Deallocation};
use crate::util::bit_chunk_iterator::{BitChunks, UnalignedBitChunk};
use crate::{
bytes::{Bytes, Deallocation},
datatypes::ArrowNativeType,
ffi,
};
use crate::{bytes::Bytes, datatypes::ArrowNativeType};

use super::ops::bitwise_unary_op_helper;
use super::MutableBuffer;
Expand Down Expand Up @@ -86,18 +83,18 @@ impl Buffer {
///
/// * `ptr` - Pointer to raw parts
/// * `len` - Length of raw parts in **bytes**
/// * `data` - An [ffi::FFI_ArrowArray] with the data
/// * `owner` - A [crate::alloc::Allocation] which is responsible for freeing that data
///
/// # Safety
///
/// This function is unsafe as there is no guarantee that the given pointer is valid for `len`
/// bytes and that the foreign deallocator frees the region.
pub unsafe fn from_unowned(
pub unsafe fn from_foreign(
ptr: NonNull<u8>,
len: usize,
data: Arc<ffi::FFI_ArrowArray>,
owner: Arc<dyn Allocation>,
) -> Self {
Buffer::build_with_arguments(ptr, len, Deallocation::Foreign(data))
Buffer::build_with_arguments(ptr, len, Deallocation::Foreign(owner))
}

/// Auxiliary method to create a new Buffer
Expand Down Expand Up @@ -533,4 +530,24 @@ mod tests {
Buffer::from(&[0b01101101, 0b10101010]).count_set_bits_offset(7, 9)
);
}

#[test]
fn test_from_foreign_vec() {
let mut vector = vec![1_i32, 2, 3, 4, 5];
let buffer = unsafe {
Buffer::from_foreign(
NonNull::new_unchecked(vector.as_mut_ptr() as *mut u8),
vector.len() * std::mem::size_of::<i32>(),
Arc::new(vector),
)
};

let slice = unsafe { buffer.typed_data::<i32>() };
assert_eq!(slice, &[1, 2, 3, 4, 5]);

let buffer = buffer.slice(std::mem::size_of::<i32>());

let slice = unsafe { buffer.typed_data::<i32>() };
assert_eq!(slice, &[2, 3, 4, 5]);
}
}
3 changes: 2 additions & 1 deletion arrow/src/buffer/mutable.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,10 @@
// under the License.

use super::Buffer;
use crate::alloc::Deallocation;
use crate::{
alloc,
bytes::{Bytes, Deallocation},
bytes::Bytes,
datatypes::{ArrowNativeType, ToByteSlice},
util::bit_util,
};
Expand Down
25 changes: 2 additions & 23 deletions arrow/src/bytes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,31 +21,10 @@

use core::slice;
use std::ptr::NonNull;
use std::sync::Arc;
use std::{fmt::Debug, fmt::Formatter};

use crate::{alloc, ffi};

/// Mode of deallocating memory regions
pub enum Deallocation {
/// Native deallocation, using Rust deallocator with Arrow-specific memory alignment
Native(usize),
/// Foreign interface, via a callback
Foreign(Arc<ffi::FFI_ArrowArray>),
}

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 }}")
}
}
}
}
use crate::alloc;
use crate::alloc::Deallocation;

/// 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
Expand Down
2 changes: 1 addition & 1 deletion arrow/src/ffi.rs
Original file line number Diff line number Diff line change
Expand Up @@ -538,7 +538,7 @@ unsafe fn create_buffer(
assert!(index < array.n_buffers as usize);
let ptr = *buffers.add(index);

NonNull::new(ptr as *mut u8).map(|ptr| Buffer::from_unowned(ptr, len, owner))
NonNull::new(ptr as *mut u8).map(|ptr| Buffer::from_foreign(ptr, len, owner))
}

fn create_child(
Expand Down