mod pool;
mod slice;
use std::{
alloc::{AllocError, Allocator, Layout},
ptr::{self, NonNull},
result::Result as StdResult,
sync::Arc,
};
pub(crate) use self::pool::PinnedPool;
use self::pool::same_class;
pub use self::{pool::PinnedStats, slice::PinnedVecExt};
use crate::{
context::Context,
error::{Error, Result},
view::{DeviceRegion, HostRegion, ZeroableDeviceRepr},
};
#[derive(Debug, Clone)]
pub struct PinnedHost(Arc<Context>);
pub type PinnedVec<T> = Vec<T, PinnedHost>;
impl Context {
#[must_use]
pub fn pinned_host(self: &Arc<Self>) -> PinnedHost {
PinnedHost(Arc::clone(self))
}
}
impl PinnedHost {
#[must_use]
pub fn context(&self) -> &Arc<Context> {
&self.0
}
pub fn with_capacity<T>(&self, capacity: usize) -> Result<PinnedVec<T>> {
let layout = Layout::array::<T>(capacity)
.map_err(|_| Error::out_of_range("pinned vector capacity"))?;
let block = self.allocate_block(layout)?;
Ok(
unsafe {
Vec::from_raw_parts_in(block.cast::<T>().as_ptr(), 0, capacity, self.clone())
},
)
}
pub fn from_slice<T: Copy>(&self, values: &[T]) -> Result<PinnedVec<T>> {
let mut vector = self.with_capacity(values.len())?;
vector.extend_from_slice(values);
Ok(vector)
}
pub fn zeroed<T: ZeroableDeviceRepr>(&self, length: usize) -> Result<PinnedVec<T>> {
let mut vector = self.with_capacity::<T>(length)?;
unsafe {
ptr::write_bytes(vector.as_mut_ptr(), 0, length);
vector.set_len(length);
}
Ok(vector)
}
pub fn release_cached(&self) -> Result<()> {
self.0.pinned.release_cached(&self.0)
}
#[must_use]
pub fn stats(&self) -> PinnedStats {
self.0.pinned.stats()
}
pub(crate) fn host_region(&self, pointer: *const u8, bytes: usize) -> HostRegion<'_> {
self.0.pinned.host_region(&self.0, pointer, bytes)
}
pub(crate) fn device_region(
&self,
pointer: *const u8,
bytes: usize,
) -> Result<DeviceRegion<'_>> {
self.0.pinned.device_region(&self.0, pointer, bytes)
}
unsafe fn resize(
&self,
block: NonNull<u8>,
old: Layout,
new: Layout,
zeroed: bool,
) -> StdResult<NonNull<[u8]>, AllocError> {
if old.size() != 0 && new.size() != 0 && same_class(old, new) {
if zeroed && new.size() > old.size() {
unsafe {
ptr::write_bytes(block.add(old.size()).as_ptr(), 0, new.size() - old.size());
};
}
return Ok(NonNull::slice_from_raw_parts(block, new.size()));
}
let moved = if zeroed {
self.allocate_zeroed(new)?
} else {
self.allocate(new)?
};
unsafe {
ptr::copy_nonoverlapping(
block.as_ptr(),
moved.cast::<u8>().as_ptr(),
old.size().min(new.size()),
);
self.deallocate(block, old);
}
Ok(moved)
}
fn allocate_block(&self, layout: Layout) -> Result<NonNull<u8>> {
if layout.size() == 0 {
return NonNull::new(ptr::without_provenance_mut(layout.align()))
.ok_or(Error::NullHandle);
}
self.0.pinned.allocate(&self.0, layout)
}
}
unsafe impl Allocator for PinnedHost {
fn allocate(&self, layout: Layout) -> StdResult<NonNull<[u8]>, AllocError> {
let block = self.allocate_block(layout).map_err(|_| AllocError)?;
Ok(NonNull::slice_from_raw_parts(block, layout.size()))
}
unsafe fn deallocate(&self, block: NonNull<u8>, layout: Layout) {
if layout.size() != 0 {
self.0.pinned.deallocate(block, layout);
}
}
unsafe fn grow(
&self,
block: NonNull<u8>,
old: Layout,
new: Layout,
) -> StdResult<NonNull<[u8]>, AllocError> {
unsafe { self.resize(block, old, new, false) }
}
unsafe fn grow_zeroed(
&self,
block: NonNull<u8>,
old: Layout,
new: Layout,
) -> StdResult<NonNull<[u8]>, AllocError> {
unsafe { self.resize(block, old, new, true) }
}
unsafe fn shrink(
&self,
block: NonNull<u8>,
old: Layout,
new: Layout,
) -> StdResult<NonNull<[u8]>, AllocError> {
unsafe { self.resize(block, old, new, false) }
}
}