use std::{
marker::PhantomData,
mem::{MaybeUninit, align_of, size_of},
num::Wrapping,
ops::{Bound, Range, RangeBounds},
ptr::NonNull,
sync::{
Arc,
atomic::{AtomicU64, Ordering},
},
};
#[cfg(feature = "macros")]
pub use singe_cuda_macros::{
AnyBitPatternDeviceRepr, DeviceRepr, NoUninitDeviceRepr, ZeroableDeviceRepr,
};
use crate::{
context::Context,
error::{Error, Result},
memory::{
DeviceAllocation, DeviceMemory,
transfer::{self, copy_device},
},
stream::Stream,
types::{Complex, bf16, f4e2m1, f6e2m3, f6e3m2, f8e4m3, f8e5m2, f8ue5m3, f8ue8m0, f16},
utility::ranges_overlap,
};
pub unsafe trait DeviceRepr: Copy + 'static {
const LAYOUT: () = ();
}
pub unsafe trait ZeroableDeviceRepr: DeviceRepr {}
pub unsafe trait NoUninitDeviceRepr: DeviceRepr {}
pub unsafe trait AnyBitPatternDeviceRepr: ZeroableDeviceRepr {}
pub unsafe trait DeviceOutput<T: DeviceRepr>: DeviceRange<T> {
fn as_mut_ptr(&mut self) -> *mut T;
}
macro_rules! impl_device_repr {
($($ty:ty),* $(,)?) => {
$(
unsafe impl DeviceRepr for $ty {}
unsafe impl NoUninitDeviceRepr for $ty {}
unsafe impl ZeroableDeviceRepr for $ty {}
unsafe impl AnyBitPatternDeviceRepr for $ty {}
)*
};
}
impl_device_repr!(
(),
u8,
u16,
u32,
u64,
u128,
usize,
i8,
i16,
i32,
i64,
i128,
isize,
f32,
f64,
f16,
bf16,
f8e4m3,
f8e5m2,
f8ue8m0,
f8ue5m3,
f6e2m3,
f6e3m2,
f4e2m1,
);
unsafe impl DeviceRepr for bool {}
unsafe impl NoUninitDeviceRepr for bool {}
unsafe impl ZeroableDeviceRepr for bool {}
unsafe impl<T: DeviceRepr, const N: usize> DeviceRepr for [T; N] {
const LAYOUT: () = T::LAYOUT;
}
unsafe impl<T: ZeroableDeviceRepr, const N: usize> ZeroableDeviceRepr for [T; N] {}
unsafe impl<T: NoUninitDeviceRepr, const N: usize> NoUninitDeviceRepr for [T; N] {}
unsafe impl<T: AnyBitPatternDeviceRepr, const N: usize> AnyBitPatternDeviceRepr for [T; N] {}
unsafe impl<T: DeviceRepr> DeviceRepr for Wrapping<T> {
const LAYOUT: () = T::LAYOUT;
}
unsafe impl<T: ZeroableDeviceRepr> ZeroableDeviceRepr for Wrapping<T> {}
unsafe impl<T: NoUninitDeviceRepr> NoUninitDeviceRepr for Wrapping<T> {}
unsafe impl<T: AnyBitPatternDeviceRepr> AnyBitPatternDeviceRepr for Wrapping<T> {}
unsafe impl<T: DeviceRepr> DeviceRepr for Complex<T> {
const LAYOUT: () = T::LAYOUT;
}
unsafe impl<T: ZeroableDeviceRepr> ZeroableDeviceRepr for Complex<T> {}
unsafe impl<T: NoUninitDeviceRepr> NoUninitDeviceRepr for Complex<T> {}
unsafe impl<T: AnyBitPatternDeviceRepr> AnyBitPatternDeviceRepr for Complex<T> {}
unsafe impl<T: DeviceRepr> DeviceRepr for MaybeUninit<T> {
const LAYOUT: () = T::LAYOUT;
}
unsafe impl<T: DeviceRepr> ZeroableDeviceRepr for MaybeUninit<T> {}
unsafe impl<T: DeviceRepr> AnyBitPatternDeviceRepr for MaybeUninit<T> {}
unsafe impl<T: ?Sized + 'static> DeviceRepr for PhantomData<T> {}
unsafe impl<T: ?Sized + 'static> ZeroableDeviceRepr for PhantomData<T> {}
unsafe impl<T: ?Sized + 'static> NoUninitDeviceRepr for PhantomData<T> {}
unsafe impl<T: ?Sized + 'static> AnyBitPatternDeviceRepr for PhantomData<T> {}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct AllocationId(u64);
impl AllocationId {
pub fn create() -> Self {
static NEXT_ID: AtomicU64 = AtomicU64::new(1);
Self(
NEXT_ID
.try_update(Ordering::Relaxed, Ordering::Relaxed, |id| id.checked_add(1))
.expect("allocation identity exhausted"),
)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct HostRegion<'a> {
context: &'a Arc<Context>,
allocation_id: AllocationId,
allocation_bytes: usize,
offset: usize,
bytes: usize,
portable: bool,
}
impl<'a> HostRegion<'a> {
#[must_use]
pub unsafe fn from_raw_parts(
context: &'a Arc<Context>,
allocation_id: AllocationId,
bytes: usize,
portable: bool,
) -> Self {
Self {
context,
allocation_id,
allocation_bytes: bytes,
offset: 0,
bytes,
portable,
}
}
#[must_use]
pub fn context(self) -> &'a Arc<Context> {
self.context
}
#[must_use]
pub const fn allocation_id(self) -> AllocationId {
self.allocation_id
}
#[must_use]
pub const fn allocation_byte_len(self) -> usize {
self.allocation_bytes
}
#[must_use]
pub const fn byte_len(self) -> usize {
self.bytes
}
#[must_use]
pub const fn is_portable(self) -> bool {
self.portable
}
#[must_use]
pub fn byte_range(self) -> Range<usize> {
self.offset..self.offset + self.bytes
}
pub fn slice<R: RangeBounds<usize>>(self, range: R) -> Result<Self> {
let (start, end) = bounds_to_range(range, self.bytes)?;
Ok(Self {
offset: self.offset + start,
bytes: end - start,
..self
})
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct DeviceRegion<'a> {
context: &'a Arc<Context>,
stream: Option<&'a Stream>,
allocation_id: AllocationId,
base: *mut u8,
allocation_bytes: usize,
offset: usize,
bytes: usize,
}
impl<'a> DeviceRegion<'a> {
pub unsafe fn from_raw_parts(
context: &'a Arc<Context>,
allocation_id: AllocationId,
base: *mut u8,
bytes: usize,
) -> Result<Self> {
if bytes != 0 && base.is_null() {
return Err(Error::null_pointer("base"));
}
base.addr()
.checked_add(bytes)
.ok_or_else(|| Error::out_of_range("region end address"))?;
Ok(Self {
context,
stream: None,
allocation_id,
base,
allocation_bytes: bytes,
offset: 0,
bytes,
})
}
#[must_use]
pub fn context(self) -> &'a Arc<Context> {
self.context
}
#[must_use]
pub const fn stream(self) -> Option<&'a Stream> {
self.stream
}
pub unsafe fn with_stream(self, stream: &'a Stream) -> Result<Self> {
if stream.context() != self.context {
return Err(Error::StreamContextMismatch);
}
Ok(Self {
stream: Some(stream),
..self
})
}
pub fn order_on(self, stream: &Stream) -> Result<()> {
if stream.context() != self.context {
return Err(Error::StreamContextMismatch);
}
if let Some(ready) = self.stream {
stream.join(ready)?;
}
Ok(())
}
pub fn synchronize(self) -> Result<()> {
let _guard = self.context.acquire_host_access(&[self])?;
Ok(())
}
#[must_use]
pub const fn allocation_id(self) -> AllocationId {
self.allocation_id
}
#[must_use]
pub const fn allocation_byte_len(self) -> usize {
self.allocation_bytes
}
#[must_use]
pub const fn byte_len(self) -> usize {
self.bytes
}
#[must_use]
pub fn byte_range(self) -> Range<usize> {
self.offset..self.offset + self.bytes
}
#[must_use]
pub fn overlaps(self, other: Self) -> bool {
self.allocation_id == other.allocation_id
&& ranges_overlap(&self.byte_range(), &other.byte_range())
}
#[must_use]
pub fn as_ptr(self) -> *mut u8 {
self.base.wrapping_add(self.offset)
}
pub fn ensure_aligned(self, alignment: usize, name: &'static str) -> Result<()> {
if self.bytes != 0 && !self.as_ptr().addr().is_multiple_of(alignment) {
return Err(Error::misaligned(name, alignment));
}
Ok(())
}
pub fn slice<R: RangeBounds<usize>>(self, range: R) -> Result<Self> {
let (start, end) = bounds_to_range(range, self.bytes)?;
Ok(Self {
offset: self.offset + start,
bytes: end - start,
..self
})
}
}
pub unsafe trait DeviceRegionProvider {
fn region(&self) -> DeviceRegion<'_>;
}
#[derive(Debug)]
pub struct OwnedDeviceRegion<O: DeviceRegionProvider + 'static = DeviceAllocation> {
owner: Arc<O>,
range: Range<usize>,
readiness: Option<Stream>,
}
impl<O: DeviceRegionProvider + 'static> OwnedDeviceRegion<O> {
pub fn from_owner(owner: Arc<O>, range: Range<usize>) -> Result<Self> {
owner.region().slice(range.clone())?;
Ok(Self {
owner,
range,
readiness: None,
})
}
#[must_use]
pub(crate) fn into_owner(self) -> Arc<O> {
self.owner
}
#[must_use]
pub fn owner(&self) -> &Arc<O> {
&self.owner
}
#[must_use]
pub fn context(&self) -> &Arc<Context> {
self.owner.region().context()
}
#[must_use]
pub fn byte_len(&self) -> usize {
self.range.len()
}
pub fn slice<R: RangeBounds<usize>>(mut self, range: R) -> Result<Self> {
let (start, end) = bounds_to_range(range, self.range.len())?;
self.range = self.range.start + start..self.range.start + end;
Ok(self)
}
pub unsafe fn with_stream(mut self, stream: &Stream) -> Result<Self> {
if self.context() != stream.context() {
return Err(Error::StreamContextMismatch);
}
self.readiness = Some(stream.clone());
Ok(self)
}
}
impl<O: DeviceRegionProvider + 'static> Clone for OwnedDeviceRegion<O> {
fn clone(&self) -> Self {
Self {
owner: Arc::clone(&self.owner),
range: self.range.clone(),
readiness: self.readiness.clone(),
}
}
}
unsafe impl<O: DeviceRegionProvider + 'static> DeviceRegionProvider for OwnedDeviceRegion<O> {
fn region(&self) -> DeviceRegion<'_> {
let region = self
.owner
.region()
.slice(self.range.clone())
.expect("retained range exceeds its allocation");
self.readiness.as_ref().map_or(region, |stream| {
unsafe { region.with_stream(stream) }
.expect("retained readiness stream context mismatch")
})
}
}
impl OwnedDeviceRegion {
#[must_use]
pub fn from_memory<T: DeviceRepr>(memory: &DeviceMemory<T>) -> Self {
Self {
owner: Arc::clone(memory.allocation()),
range: memory.region().byte_range(),
readiness: None,
}
}
}
pub(crate) fn cast_length<T: DeviceRepr>(region: DeviceRegion<'_>) -> Result<usize> {
let () = T::LAYOUT;
let size = size_of::<T>();
if size == 0 {
return Err(Error::not_positive("element size"));
}
if !region.byte_len().is_multiple_of(size) {
return Err(Error::misaligned("region byte length", size));
}
if region.byte_len() != 0 && !region.as_ptr().addr().is_multiple_of(align_of::<T>()) {
return Err(Error::misaligned("region address", align_of::<T>()));
}
Ok(region.byte_len() / size)
}
pub unsafe trait DeviceRange<T: DeviceRepr>: DeviceRegionProvider {
fn context(&self) -> &Arc<Context> {
self.region().context()
}
fn as_device_ptr(&self) -> *const T {
if self.is_empty() {
NonNull::<T>::dangling().as_ptr()
} else {
self.region().as_ptr().cast()
}
}
fn len(&self) -> usize;
fn is_empty(&self) -> bool {
self.len() == 0
}
fn byte_len(&self) -> Result<usize> {
let () = T::LAYOUT;
self.len()
.checked_mul(size_of::<T>())
.ok_or_else(|| Error::out_of_range("input byte length"))
}
}
pub unsafe trait DeviceSlice<T: DeviceRepr>: DeviceRange<T> {}
pub unsafe trait DeviceSliceMut<T: DeviceRepr>: DeviceSlice<T> + DeviceOutput<T> {}
pub unsafe trait HostSlice<T: DeviceRepr> {
fn as_host_ptr(&self) -> *const T;
fn len(&self) -> usize;
fn is_empty(&self) -> bool {
self.len() == 0
}
}
pub unsafe trait HostSliceMut<T: DeviceRepr>: HostSlice<T> {
fn as_host_mut_ptr(&mut self) -> *mut T;
}
#[derive(Debug, Clone, Copy)]
pub struct DeviceInputView<'a, T: DeviceRepr> {
region: DeviceRegion<'a>,
length: usize,
_t: PhantomData<&'a MaybeUninit<T>>,
}
impl<'a, T: DeviceRepr> DeviceInputView<'a, T> {
pub fn create(region: DeviceRegion<'a>) -> Result<Self> {
let length = cast_length::<T>(region)?;
Ok(Self {
region,
length,
_t: PhantomData,
})
}
pub fn from_buffer<B: DeviceRange<T> + ?Sized>(buffer: &'a B) -> Self {
let () = T::LAYOUT;
Self {
region: buffer.region(),
length: buffer.len(),
_t: PhantomData,
}
}
#[must_use]
pub fn as_ptr(&self) -> *const T {
if self.length == 0 {
NonNull::<T>::dangling().as_ptr()
} else {
self.region.as_ptr().cast()
}
}
#[must_use]
pub const fn len(&self) -> usize {
self.length
}
#[must_use]
pub const fn is_empty(&self) -> bool {
self.length == 0
}
#[must_use]
pub fn context(&self) -> &'a Arc<Context> {
self.region.context()
}
#[must_use]
pub const fn region(&self) -> DeviceRegion<'a> {
self.region
}
pub fn slice<R: RangeBounds<usize>>(self, range: R) -> Result<Self> {
let (start, end) = bounds_to_range(range, self.length)?;
Ok(Self {
region: self
.region
.slice(start * size_of::<T>()..end * size_of::<T>())?,
length: end - start,
_t: PhantomData,
})
}
pub fn cast<U: DeviceRepr>(self) -> Result<DeviceInputView<'a, U>> {
DeviceInputView::create(self.region)
}
}
unsafe impl<T: DeviceRepr> DeviceRegionProvider for DeviceInputView<'_, T> {
fn region(&self) -> DeviceRegion<'_> {
self.region
}
}
unsafe impl<T: DeviceRepr> DeviceRange<T> for DeviceInputView<'_, T> {
fn as_device_ptr(&self) -> *const T {
self.as_ptr()
}
fn len(&self) -> usize {
self.length
}
}
#[derive(Debug, Clone, Copy)]
pub struct DeviceView<'a, T: DeviceRepr> {
region: DeviceRegion<'a>,
length: usize,
_t: PhantomData<&'a T>,
}
#[derive(Debug)]
pub struct DeviceViewMut<'a, T: DeviceRepr> {
region: DeviceRegion<'a>,
length: usize,
_t: PhantomData<&'a mut T>,
}
#[derive(Debug)]
pub struct DeviceOutputView<'a, T: DeviceRepr> {
region: DeviceRegion<'a>,
length: usize,
_t: PhantomData<&'a mut MaybeUninit<T>>,
}
impl<'a, T: DeviceRepr> DeviceOutputView<'a, T> {
#[must_use]
pub fn into_region(self) -> DeviceRegion<'a> {
self.region
}
pub unsafe fn from_raw_parts(region: DeviceRegion<'a>, length: usize) -> Result<Self> {
validate_view::<T>(region, length)?;
Ok(Self {
region,
length,
_t: PhantomData,
})
}
pub fn from_output<B: DeviceOutput<T> + ?Sized>(output: &'a mut B) -> Self {
let () = T::LAYOUT;
Self {
region: output.region(),
length: output.len(),
_t: PhantomData,
}
}
pub fn reborrow(&mut self) -> DeviceOutputView<'_, T> {
DeviceOutputView::from_output(self)
}
#[must_use]
pub const fn len(&self) -> usize {
self.length
}
#[must_use]
pub const fn is_empty(&self) -> bool {
self.length == 0
}
pub fn as_mut_ptr(&mut self) -> *mut T {
self.region.as_ptr().cast()
}
#[must_use]
pub fn context(&self) -> &Arc<Context> {
self.region.context()
}
pub fn slice<R: RangeBounds<usize>>(self, range: R) -> Result<Self> {
let (start, end) = bounds_to_range(range, self.length)?;
Ok(Self {
region: self
.region
.slice(start * size_of::<T>()..end * size_of::<T>())?,
length: end - start,
_t: PhantomData,
})
}
pub fn split_at_mut(self, mid: usize) -> Result<(Self, Self)> {
if mid > self.length {
return Err(Error::buffer_too_small("view", mid, self.length));
}
let boundary = mid * size_of::<T>();
let left = Self {
region: self.region.slice(..boundary)?,
length: mid,
_t: PhantomData,
};
let right = Self {
region: self.region.slice(boundary..)?,
length: self.length - mid,
_t: PhantomData,
};
Ok((left, right))
}
}
unsafe impl<T: DeviceRepr> DeviceRegionProvider for DeviceOutputView<'_, T> {
fn region(&self) -> DeviceRegion<'_> {
self.region
}
}
unsafe impl<T: DeviceRepr> DeviceRange<T> for DeviceOutputView<'_, T> {
fn len(&self) -> usize {
self.length
}
}
unsafe impl<T: DeviceRepr> DeviceOutput<T> for DeviceOutputView<'_, T> {
fn as_mut_ptr(&mut self) -> *mut T {
self.region.as_ptr().cast()
}
}
fn validate_view<T: DeviceRepr>(region: DeviceRegion<'_>, length: usize) -> Result<()> {
let () = T::LAYOUT;
let bytes = length
.checked_mul(size_of::<T>())
.ok_or_else(|| Error::out_of_range("view byte length"))?;
if bytes != region.byte_len() {
return Err(Error::size_mismatch(
"view region",
bytes,
region.byte_len(),
));
}
if length != 0 && size_of::<T>() == 0 {
return Err(Error::not_positive("element size"));
}
if length != 0 && !region.as_ptr().addr().is_multiple_of(align_of::<T>()) {
return Err(Error::misaligned("view address", align_of::<T>()));
}
Ok(())
}
impl<'a, T: DeviceRepr> DeviceView<'a, T> {
#[must_use]
pub fn into_region(self) -> DeviceRegion<'a> {
self.region
}
pub unsafe fn from_raw_parts(region: DeviceRegion<'a>, length: usize) -> Result<Self> {
validate_view::<T>(region, length)?;
Ok(Self {
region,
length,
_t: PhantomData,
})
}
#[must_use]
pub fn from_memory(memory: &'a DeviceMemory<T>) -> Self {
let () = T::LAYOUT;
Self {
region: memory.region(),
length: memory.len(),
_t: PhantomData,
}
}
pub fn from_buffer<B: DeviceSlice<T> + ?Sized>(buffer: &'a B) -> Self {
let () = T::LAYOUT;
Self {
region: buffer.region(),
length: buffer.len(),
_t: PhantomData,
}
}
#[must_use]
pub fn as_ptr(&self) -> *const T {
if self.length == 0 {
NonNull::<T>::dangling().as_ptr()
} else {
self.region.as_ptr().cast()
}
}
#[must_use]
pub const fn len(&self) -> usize {
self.length
}
#[must_use]
pub const fn is_empty(&self) -> bool {
self.length == 0
}
#[must_use]
pub fn context(&self) -> &'a Arc<Context> {
self.region.context()
}
#[must_use]
pub const fn region(&self) -> DeviceRegion<'a> {
self.region
}
pub fn copy_to_host(&self, destination: &mut [T]) -> Result<()>
where
T: AnyBitPatternDeviceRepr,
{
transfer::copy_to_host(self, destination)
}
pub fn copy_to_host_vec(&self) -> Result<Vec<T>>
where
T: AnyBitPatternDeviceRepr,
{
transfer::copy_to_host_vec(self)
}
pub fn slice<R: RangeBounds<usize>>(self, range: R) -> Result<Self> {
let (start, end) = bounds_to_range(range, self.length)?;
let region = self
.region
.slice(start * size_of::<T>()..end * size_of::<T>())?;
Ok(Self {
region,
length: end - start,
_t: PhantomData,
})
}
pub fn cast<U: AnyBitPatternDeviceRepr>(self) -> Result<DeviceView<'a, U>>
where
T: NoUninitDeviceRepr,
{
let () = T::LAYOUT;
unsafe { self.cast_unchecked() }
}
pub unsafe fn cast_unchecked<U: DeviceRepr>(self) -> Result<DeviceView<'a, U>> {
let length = cast_length::<U>(self.region)?;
Ok(DeviceView {
region: self.region,
length,
_t: PhantomData,
})
}
}
impl<'a, T: DeviceRepr> DeviceViewMut<'a, T> {
#[must_use]
pub fn into_region(self) -> DeviceRegion<'a> {
self.region
}
pub unsafe fn from_raw_parts(region: DeviceRegion<'a>, length: usize) -> Result<Self> {
validate_view::<T>(region, length)?;
Ok(Self {
region,
length,
_t: PhantomData,
})
}
pub fn from_memory(memory: &'a mut DeviceMemory<T>) -> Self {
let () = T::LAYOUT;
Self {
region: memory.region(),
length: memory.len(),
_t: PhantomData,
}
}
pub fn from_buffer<B: DeviceSliceMut<T> + ?Sized>(buffer: &'a mut B) -> Self {
let () = T::LAYOUT;
Self {
region: buffer.region(),
length: buffer.len(),
_t: PhantomData,
}
}
pub fn reborrow(&mut self) -> DeviceViewMut<'_, T> {
DeviceViewMut {
region: self.region(),
length: self.length,
_t: PhantomData,
}
}
#[must_use]
pub fn as_ptr(&self) -> *const T {
if self.length == 0 {
NonNull::<T>::dangling().as_ptr()
} else {
self.region.as_ptr().cast()
}
}
pub fn as_mut_ptr(&mut self) -> *mut T {
self.as_ptr().cast_mut()
}
#[must_use]
pub const fn len(&self) -> usize {
self.length
}
#[must_use]
pub const fn is_empty(&self) -> bool {
self.length == 0
}
#[must_use]
pub fn context(&self) -> &Arc<Context> {
self.region.context()
}
#[must_use]
pub fn region(&self) -> DeviceRegion<'_> {
self.region
}
pub fn copy_from_host(&mut self, source: &[T]) -> Result<()> {
transfer::copy_from_host(self, source)
}
pub fn copy_from_device<B: DeviceSlice<T> + ?Sized>(&mut self, source: &B) -> Result<()> {
copy_device(self, source)
}
pub fn copy_to_host(&self, destination: &mut [T]) -> Result<()>
where
T: AnyBitPatternDeviceRepr,
{
self.as_view().copy_to_host(destination)
}
pub fn copy_to_host_vec(&self) -> Result<Vec<T>>
where
T: AnyBitPatternDeviceRepr,
{
self.as_view().copy_to_host_vec()
}
#[must_use]
pub fn as_view(&self) -> DeviceView<'_, T> {
DeviceView {
region: self.region,
length: self.length,
_t: PhantomData,
}
}
pub fn slice<R: RangeBounds<usize>>(&self, range: R) -> Result<DeviceView<'_, T>> {
self.as_view().slice(range)
}
pub fn slice_mut<R: RangeBounds<usize>>(&mut self, range: R) -> Result<DeviceViewMut<'_, T>> {
let (start, end) = bounds_to_range(range, self.length)?;
let region = self
.region
.slice(start * size_of::<T>()..end * size_of::<T>())?;
Ok(DeviceViewMut {
region,
length: end - start,
_t: PhantomData,
})
}
pub fn split_at_mut(
&mut self,
mid: usize,
) -> Result<(DeviceViewMut<'_, T>, DeviceViewMut<'_, T>)> {
if mid > self.length {
return Err(Error::buffer_too_small("view", mid, self.length));
}
let bytes = mid * size_of::<T>();
Ok((
DeviceViewMut {
region: self.region.slice(..bytes)?,
length: mid,
_t: PhantomData,
},
DeviceViewMut {
region: self.region.slice(bytes..)?,
length: self.length - mid,
_t: PhantomData,
},
))
}
pub fn cast<U: AnyBitPatternDeviceRepr + NoUninitDeviceRepr>(
self,
) -> Result<DeviceViewMut<'a, U>>
where
T: AnyBitPatternDeviceRepr + NoUninitDeviceRepr,
{
let () = T::LAYOUT;
unsafe { self.cast_unchecked() }
}
pub unsafe fn cast_unchecked<U: DeviceRepr>(self) -> Result<DeviceViewMut<'a, U>> {
let length = cast_length::<U>(self.region)?;
Ok(DeviceViewMut {
region: self.region,
length,
_t: PhantomData,
})
}
}
unsafe impl<T: DeviceRepr> DeviceRegionProvider for DeviceView<'_, T> {
fn region(&self) -> DeviceRegion<'_> {
self.region
}
}
unsafe impl<T: DeviceRepr> DeviceRegionProvider for DeviceViewMut<'_, T> {
fn region(&self) -> DeviceRegion<'_> {
self.region
}
}
unsafe impl<T: DeviceRepr> DeviceOutput<T> for DeviceViewMut<'_, T> {
fn as_mut_ptr(&mut self) -> *mut T {
self.as_mut_ptr()
}
}
unsafe impl<T: DeviceRepr> DeviceRange<T> for DeviceViewMut<'_, MaybeUninit<T>> {
fn len(&self) -> usize {
self.length
}
}
unsafe impl<T: DeviceRepr> DeviceOutput<T> for DeviceViewMut<'_, MaybeUninit<T>> {
fn as_mut_ptr(&mut self) -> *mut T {
self.as_mut_ptr().cast()
}
}
impl<'a, T: DeviceRepr> DeviceViewMut<'a, MaybeUninit<T>> {
pub fn output(&mut self) -> DeviceOutputView<'_, T> {
DeviceOutputView::from_output(self)
}
#[must_use]
pub unsafe fn assume_init(self) -> DeviceViewMut<'a, T> {
let () = T::LAYOUT;
DeviceViewMut {
region: self.region,
length: self.length,
_t: PhantomData,
}
}
}
impl<T: DeviceRepr> DeviceMemory<T> {
#[must_use]
pub fn view(&self) -> DeviceView<'_, T> {
DeviceView::from_memory(self)
}
pub fn view_mut(&mut self) -> DeviceViewMut<'_, T> {
DeviceViewMut::from_memory(self)
}
}
impl<T: DeviceRepr> DeviceMemory<MaybeUninit<T>> {
pub fn output(&mut self) -> DeviceOutputView<'_, T> {
DeviceOutputView::from_output(self)
}
}
unsafe impl<T: DeviceRepr> DeviceRange<T> for DeviceMemory<T> {
fn as_device_ptr(&self) -> *const T {
self.as_ptr()
}
fn len(&self) -> usize {
self.len()
}
}
unsafe impl<T: DeviceRepr> DeviceSlice<T> for DeviceMemory<T> {}
unsafe impl<T: DeviceRepr> DeviceSliceMut<T> for DeviceMemory<T> {}
unsafe impl<T: DeviceRepr> DeviceRange<T> for DeviceView<'_, T> {
fn as_device_ptr(&self) -> *const T {
self.as_ptr()
}
fn len(&self) -> usize {
self.length
}
}
unsafe impl<T: DeviceRepr> DeviceSlice<T> for DeviceView<'_, T> {}
unsafe impl<T: DeviceRepr> DeviceRange<T> for DeviceViewMut<'_, T> {
fn as_device_ptr(&self) -> *const T {
self.as_ptr()
}
fn len(&self) -> usize {
self.length
}
}
unsafe impl<T: DeviceRepr> DeviceSlice<T> for DeviceViewMut<'_, T> {}
unsafe impl<T: DeviceRepr> DeviceSliceMut<T> for DeviceViewMut<'_, T> {}
unsafe impl<T: DeviceRepr> HostSlice<T> for [T] {
fn as_host_ptr(&self) -> *const T {
self.as_ptr()
}
fn len(&self) -> usize {
self.len()
}
}
unsafe impl<T: DeviceRepr> HostSliceMut<T> for [T] {
fn as_host_mut_ptr(&mut self) -> *mut T {
self.as_mut_ptr()
}
}
unsafe impl<T: DeviceRepr, const N: usize> HostSlice<T> for [T; N] {
fn as_host_ptr(&self) -> *const T {
self.as_ptr()
}
fn len(&self) -> usize {
N
}
}
unsafe impl<T: DeviceRepr, const N: usize> HostSliceMut<T> for [T; N] {
fn as_host_mut_ptr(&mut self) -> *mut T {
self.as_mut_ptr()
}
}
unsafe impl<T: DeviceRepr> HostSlice<T> for Vec<T> {
fn as_host_ptr(&self) -> *const T {
self.as_ptr()
}
fn len(&self) -> usize {
self.len()
}
}
unsafe impl<T: DeviceRepr> HostSliceMut<T> for Vec<T> {
fn as_host_mut_ptr(&mut self) -> *mut T {
self.as_mut_ptr()
}
}
fn bounds_to_range<R: RangeBounds<usize>>(range: R, length: usize) -> Result<(usize, usize)> {
let start = match range.start_bound() {
Bound::Included(&value) => value,
Bound::Excluded(&value) => value
.checked_add(1)
.ok_or_else(|| Error::out_of_range("range start"))?,
Bound::Unbounded => 0,
};
let end = match range.end_bound() {
Bound::Included(&value) => value
.checked_add(1)
.ok_or_else(|| Error::out_of_range("range end"))?,
Bound::Excluded(&value) => value,
Bound::Unbounded => length,
};
if start > end {
return Err(Error::out_of_range("range start"));
}
if end > length {
return Err(Error::buffer_too_small("range", end, length));
}
Ok((start, end))
}