use std::slice;
use std::{fmt::Debug, fmt::Formatter};
use std::{ptr::NonNull, sync::Arc};
use crate::ffi;
use crate::types::NativeType;
#[cfg(feature = "cache_aligned")]
use crate::vec::AlignedVec as Vec;
pub enum Deallocation {
Native(usize),
Foreign(Arc<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 }}")
}
}
}
}
pub struct Bytes<T: NativeType> {
ptr: NonNull<T>,
len: usize,
deallocation: Deallocation,
}
impl<T: NativeType> Bytes<T> {
#[inline]
pub unsafe fn new(ptr: std::ptr::NonNull<T>, len: usize, deallocation: Deallocation) -> Self {
Self {
ptr,
len,
deallocation,
}
}
#[inline]
fn as_slice(&self) -> &[T] {
self
}
#[inline]
pub fn len(&self) -> usize {
self.len
}
#[inline]
pub fn ptr(&self) -> NonNull<T> {
self.ptr
}
}
impl<T: NativeType> Drop for Bytes<T> {
#[inline]
fn drop(&mut self) {
match &self.deallocation {
Deallocation::Native(capacity) => unsafe {
#[cfg(feature = "cache_aligned")]
let _ = Vec::from_raw_parts(self.ptr, self.len, *capacity);
#[cfg(not(feature = "cache_aligned"))]
let _ = Vec::from_raw_parts(self.ptr.as_ptr(), self.len, *capacity);
},
Deallocation::Foreign(_) => (),
}
}
}
impl<T: NativeType> std::ops::Deref for Bytes<T> {
type Target = [T];
fn deref(&self) -> &[T] {
unsafe { slice::from_raw_parts(self.ptr.as_ptr(), self.len) }
}
}
impl<T: NativeType> PartialEq for Bytes<T> {
fn eq(&self, other: &Bytes<T>) -> bool {
self.as_slice() == other.as_slice()
}
}
impl<T: NativeType> Debug for Bytes<T> {
fn fmt(&self, f: &mut Formatter) -> std::fmt::Result {
write!(f, "Bytes {{ ptr: {:?}, len: {}, data: ", self.ptr, self.len,)?;
f.debug_list().entries(self.iter()).finish()?;
write!(f, " }}")
}
}
unsafe impl<T: NativeType> Send for Bytes<T> {}
unsafe impl<T: NativeType> Sync for Bytes<T> {}