mod sealed {
use crate::memory::array::ArrayFormat;
#[expect(
unnameable_types,
reason = "sealed supertrait that other crates must not name or implement"
)]
pub trait Pixel {
const FORMAT: ArrayFormat;
const CHANNELS: u32;
}
}
use std::{
ffi::c_void,
fmt,
marker::PhantomData,
mem::{self, ManuallyDrop, MaybeUninit},
ops::{Deref, DerefMut, Range},
ptr,
result::Result as StdResult,
sync::Arc,
};
use bitflags::parser;
use half::f16;
use singe_core::report_cleanup_failure;
use singe_cuda_sys::driver as sys;
use crate::{
context::Context,
error::{Error, Result},
stream::{AsStream, StreamBinding, StreamScope},
submission::{Access, AccessMode},
try_ffi,
utility::{driver_enum, to_u64, to_usize},
view::{AllocationId, AnyBitPatternDeviceRepr, DeviceOutput, DeviceSlice, DeviceViewMut},
};
driver_enum! {
pub enum ArrayFormat: sys::CUarray_format {
U8 = CU_AD_FORMAT_UNSIGNED_INT8,
U16 = CU_AD_FORMAT_UNSIGNED_INT16,
U32 = CU_AD_FORMAT_UNSIGNED_INT32,
I8 = CU_AD_FORMAT_SIGNED_INT8,
I16 = CU_AD_FORMAT_SIGNED_INT16,
I32 = CU_AD_FORMAT_SIGNED_INT32,
F16 = CU_AD_FORMAT_HALF,
F32 = CU_AD_FORMAT_FLOAT,
}
}
pub trait ArrayElement: AnyBitPatternDeviceRepr + Send + Sync + sealed::Pixel {}
macro_rules! pixels {
($($ty:ty => $format:ident),* $(,)?) => {$ (
impl sealed::Pixel for $ty {
const FORMAT: ArrayFormat = ArrayFormat::$format;
const CHANNELS: u32 = 1;
}
impl ArrayElement for $ty {}
impl sealed::Pixel for [$ty; 2] {
const FORMAT: ArrayFormat = ArrayFormat::$format;
const CHANNELS: u32 = 2;
}
impl ArrayElement for [$ty; 2] {}
impl sealed::Pixel for [$ty; 4] {
const FORMAT: ArrayFormat = ArrayFormat::$format;
const CHANNELS: u32 = 4;
}
impl ArrayElement for [$ty; 4] {}
)*};
}
pixels!(u8 => U8, u16 => U16,
u32 => U32, i8 => I8,
i16 => I16, i32 => I32,
f16 => F16, f32 => F32);
#[derive(Debug)]
pub struct Uninitialized;
#[derive(Debug)]
pub struct Initialized;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum ArrayShape {
D1 {
width: usize,
},
D2 {
width: usize,
height: usize,
},
D3 {
width: usize,
height: usize,
depth: usize,
},
Layered1D {
width: usize,
layers: usize,
},
Layered2D {
width: usize,
height: usize,
layers: usize,
},
Cube {
edge: usize,
},
CubeArray {
edge: usize,
cubes: usize,
},
}
bitflags::bitflags! {
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
pub struct ArrayFlags: u32 {
const SURFACE_LOAD_STORE = sys::CUDA_ARRAY3D_SURFACE_LDST;
const TEXTURE_GATHER = sys::CUDA_ARRAY3D_TEXTURE_GATHER;
const DEPTH_TEXTURE = sys::CUDA_ARRAY3D_DEPTH_TEXTURE;
const COLOR_ATTACHMENT = sys::CUDA_ARRAY3D_COLOR_ATTACHMENT;
const VIDEO_ENCODE_DECODE = sys::CUDA_ARRAY3D_VIDEO_ENCODE_DECODE;
}
}
impl fmt::Display for ArrayFlags {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
parser::to_writer(self, f)
}
}
impl ArrayShape {
fn native_dimensions(self) -> Result<([usize; 3], u32)> {
let (dimensions, flags) = match self {
Self::D1 { width } => ([width, 0, 0], 0),
Self::D2 { width, height } => ([width, height, 0], 0),
Self::D3 {
width,
height,
depth,
} => ([width, height, depth], 0),
Self::Layered1D { width, layers } => ([width, 0, layers], sys::CUDA_ARRAY3D_LAYERED),
Self::Layered2D {
width,
height,
layers,
} => ([width, height, layers], sys::CUDA_ARRAY3D_LAYERED),
Self::Cube { edge } => ([edge, edge, 6], sys::CUDA_ARRAY3D_CUBEMAP),
Self::CubeArray { edge, cubes } => (
[
edge,
edge,
cubes
.checked_mul(6)
.ok_or_else(|| Error::out_of_range("cube layer count"))?,
],
sys::CUDA_ARRAY3D_CUBEMAP | sys::CUDA_ARRAY3D_LAYERED,
),
};
let valid = match self {
Self::D1 { width } => width != 0,
Self::D2 { width, height } => width != 0 && height != 0,
Self::D3 {
width,
height,
depth,
} => width != 0 && height != 0 && depth != 0,
Self::Layered1D { width, layers } => width != 0 && layers != 0,
Self::Layered2D {
width,
height,
layers,
} => width != 0 && height != 0 && layers != 0,
Self::Cube { edge } => edge != 0,
Self::CubeArray { edge, cubes } => edge != 0 && cubes != 0,
};
if !valid {
return Err(Error::not_positive("array dimension"));
}
Ok((dimensions, flags))
}
pub fn extent(self) -> Result<[usize; 3]> {
let (dimensions, _) = self.native_dimensions()?;
Ok(dimensions.map(|dimension| dimension.max(1)))
}
fn at_level(self, level: u32) -> Self {
let shrink = |value: usize| value.checked_shr(level).unwrap_or(0).max(1);
match self {
Self::D1 { width } => Self::D1 {
width: shrink(width),
},
Self::D2 { width, height } => Self::D2 {
width: shrink(width),
height: shrink(height),
},
Self::D3 {
width,
height,
depth,
} => Self::D3 {
width: shrink(width),
height: shrink(height),
depth: shrink(depth),
},
Self::Layered1D { width, layers } => Self::Layered1D {
width: shrink(width),
layers,
},
Self::Layered2D {
width,
height,
layers,
} => Self::Layered2D {
width: shrink(width),
height: shrink(height),
layers,
},
Self::Cube { edge } => Self::Cube { edge: shrink(edge) },
Self::CubeArray { edge, cubes } => Self::CubeArray {
edge: shrink(edge),
cubes,
},
}
}
fn maximum_levels(self) -> u32 {
let maximum = match self {
Self::D1 { width } | Self::Layered1D { width, .. } => width,
Self::D2 { width, height } | Self::Layered2D { width, height, .. } => width.max(height),
Self::D3 {
width,
height,
depth,
} => width.max(height).max(depth),
Self::Cube { edge } | Self::CubeArray { edge, .. } => edge,
};
maximum.bit_width()
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ArrayRegion {
pub origin: [usize; 3],
pub extent: [usize; 3],
}
impl ArrayRegion {
#[must_use]
pub const fn new(origin: [usize; 3], extent: [usize; 3]) -> Self {
Self { origin, extent }
}
pub fn full(shape: ArrayShape) -> Result<Self> {
Ok(Self::new([0; 3], shape.extent()?))
}
fn len(self) -> Result<usize> {
volume(self.extent)
}
fn validate(self, shape: ArrayShape) -> Result<()> {
for ((origin, extent), bound) in self
.origin
.into_iter()
.zip(self.extent)
.zip(shape.extent()?)
{
let end = origin
.checked_add(extent)
.ok_or_else(|| Error::out_of_range("array region end"))?;
if end > bound {
return Err(Error::buffer_too_small("array", end, bound));
}
}
self.len()?;
Ok(())
}
}
fn volume(extent: [usize; 3]) -> Result<usize> {
extent.into_iter().try_fold(1usize, |count, dimension| {
count
.checked_mul(dimension)
.ok_or_else(|| Error::out_of_range("array element count"))
})
}
#[derive(Debug)]
pub struct ArrayAllocation {
context: Arc<Context>,
handle: sys::CUarray,
id: AllocationId,
range: Range<usize>,
shape: ArrayShape,
flags: ArrayFlags,
format: ArrayFormat,
channels: u32,
parent: Option<Arc<MipmappedAllocation>>,
}
unsafe impl Send for ArrayAllocation {}
unsafe impl Sync for ArrayAllocation {}
impl ArrayAllocation {
#[must_use]
pub fn context(&self) -> &Arc<Context> {
&self.context
}
#[must_use]
pub fn as_raw(&self) -> sys::CUarray {
self.handle
}
#[must_use]
pub fn allocation_id(&self) -> AllocationId {
self.id
}
#[must_use]
pub fn byte_range(&self) -> Range<usize> {
self.range.clone()
}
#[must_use]
pub fn shape(&self) -> ArrayShape {
self.shape
}
#[must_use]
pub fn flags(&self) -> ArrayFlags {
self.flags
}
#[must_use]
pub fn format(&self) -> ArrayFormat {
self.format
}
#[must_use]
pub fn channels(&self) -> u32 {
self.channels
}
#[must_use]
pub fn access(&self, mode: AccessMode) -> Access {
Access::allocation(&self.context, self.id, self.range.clone(), mode)
}
}
impl Drop for ArrayAllocation {
fn drop(&mut self) {
if self.handle.is_null() || self.parent.is_some() {
return;
}
if let Err(error) = self.context.bind() {
report_cleanup_failure("bind the cuda context to destroy", "cuda array", &error);
return;
}
if let Err(error) = unsafe { try_ffi!(sys::cuArrayDestroy(self.handle)) } {
report_cleanup_failure("destroy", "cuda array", &error);
}
}
}
#[derive(Debug)]
pub struct RawArray {
pub handle: sys::CUarray,
pub context: Arc<Context>,
pub shape: ArrayShape,
pub flags: ArrayFlags,
}
#[derive(Debug)]
pub struct Array<T: ArrayElement, S = Initialized> {
allocation: Arc<ArrayAllocation>,
marker: PhantomData<(T, S)>,
}
impl<T: ArrayElement, S> Array<T, S> {
#[must_use]
pub fn allocation(&self) -> &Arc<ArrayAllocation> {
&self.allocation
}
#[must_use]
pub fn context(&self) -> &Arc<Context> {
self.allocation.context()
}
#[must_use]
pub fn as_raw(&self) -> sys::CUarray {
self.allocation.as_raw()
}
#[must_use]
pub fn shape(&self) -> ArrayShape {
self.allocation.shape
}
#[must_use]
pub fn flags(&self) -> ArrayFlags {
self.allocation.flags
}
#[must_use]
pub fn len(&self) -> usize {
self.allocation.range.len() / size_of::<T>()
}
#[must_use]
pub fn is_empty(&self) -> bool {
false
}
fn endpoint(&self, region: ArrayRegion) -> Result<ArrayEndpoint> {
region.validate(self.shape())?;
Ok(ArrayEndpoint {
handle: self.as_raw(),
origin: [
to_u64(
region.origin[0]
.checked_mul(size_of::<T>())
.ok_or_else(|| Error::out_of_range("array x offset"))?,
"array x offset",
)?,
to_u64(region.origin[1], "array y offset")?,
to_u64(region.origin[2], "array z offset")?,
],
})
}
fn run_copy(&self, raw: &sys::CUDA_MEMCPY3D, accesses: &[Access]) -> Result<()> {
let _guard = self.context().acquire_accesses(accesses)?;
self.context().bind()?;
let binding = StreamBinding::Default(Arc::clone(self.context()));
binding.sync_scope(|| unsafe { try_ffi!(sys::cuMemcpy3DAsync_v2(raw, binding.as_raw())) })
}
pub fn copy_from_host(&mut self, region: ArrayRegion, source: &[T]) -> Result<()> {
let expected = region.len()?;
if source.len() != expected {
return Err(Error::length_mismatch(
"host source",
expected,
source.len(),
));
}
let raw = transfer::<T>(
region.extent,
CopySource::Host(source.as_ptr().cast()),
CopyDestination::Array(self.endpoint(region)?),
)?;
self.run_copy(&raw, &[self.allocation.access(AccessMode::Write)])
}
pub fn copy_from_host_scoped<'env>(
&'env mut self,
region: ArrayRegion,
source: &'env [T],
scope: &StreamScope<'_, 'env>,
) -> Result<()> {
if self.context() != scope.stream().context() {
return Err(Error::MemoryContextMismatch);
}
let expected = region.len()?;
if source.len() != expected {
return Err(Error::length_mismatch(
"host source",
expected,
source.len(),
));
}
let raw = transfer::<T>(
region.extent,
CopySource::Host(source.as_ptr().cast()),
CopyDestination::Array(self.endpoint(region)?),
)?;
let accesses = [self.allocation.access(AccessMode::Write)];
unsafe {
scope.enqueue(&accesses, || {
try_ffi!(sys::cuMemcpy3DAsync_v2(
&raw const raw,
scope.stream().as_raw()
))
})
}
}
pub fn copy_from_device<B: DeviceSlice<T> + ?Sized>(
&mut self,
region: ArrayRegion,
source: &B,
) -> Result<()> {
if source.context() != self.context() {
return Err(Error::MemoryContextMismatch);
}
let expected = region.len()?;
if source.len() != expected {
return Err(Error::length_mismatch(
"device source",
expected,
source.len(),
));
}
let source_address = to_u64(source.as_device_ptr().addr(), "device source address")?;
let raw = transfer::<T>(
region.extent,
CopySource::Device(source_address),
CopyDestination::Array(self.endpoint(region)?),
)?;
self.run_copy(
&raw,
&[
self.allocation.access(AccessMode::Write),
Access::new(source.region(), AccessMode::Read),
],
)
}
pub fn copy_from_array(
&mut self,
destination: [usize; 3],
source: &Array<T>,
source_region: ArrayRegion,
) -> Result<()> {
if source.context() != self.context() {
return Err(Error::MemoryContextMismatch);
}
source_region.validate(source.shape())?;
let region = ArrayRegion::new(destination, source_region.extent);
region.validate(self.shape())?;
if self.as_raw() == source.as_raw()
&& (0..3).all(|axis| {
destination[axis] < source_region.origin[axis] + source_region.extent[axis]
&& source_region.origin[axis] < destination[axis] + region.extent[axis]
})
{
return Err(Error::out_of_range("overlapping array regions"));
}
let raw = transfer::<T>(
region.extent,
CopySource::Array(source.endpoint(source_region)?),
CopyDestination::Array(self.endpoint(region)?),
)?;
self.run_copy(
&raw,
&[
self.allocation.access(AccessMode::Write),
source.allocation.access(AccessMode::Read),
],
)
}
pub fn into_raw(self) -> StdResult<RawArray, Self> {
if self.allocation.parent.is_some() || Arc::strong_count(&self.allocation) != 1 {
return Err(self);
}
let shape = self.shape();
let flags = self.flags();
match Arc::try_unwrap(self.allocation) {
Ok(mut allocation) => Ok(RawArray {
handle: mem::replace(&mut allocation.handle, ptr::null_mut()),
context: Arc::clone(&allocation.context),
shape,
flags,
}),
Err(allocation) => Err(Self {
allocation,
marker: PhantomData,
}),
}
}
}
struct ArrayEndpoint {
handle: sys::CUarray,
origin: [u64; 3],
}
enum CopySource {
Host(*const c_void),
Device(sys::CUdeviceptr),
Array(ArrayEndpoint),
}
enum CopyDestination {
Host(*mut c_void),
Device(sys::CUdeviceptr),
Array(ArrayEndpoint),
}
fn transfer<T: ArrayElement>(
extent: [usize; 3],
source: CopySource,
destination: CopyDestination,
) -> Result<sys::CUDA_MEMCPY3D> {
let row_bytes = extent[0]
.checked_mul(size_of::<T>())
.ok_or_else(|| Error::out_of_range("array row bytes"))?;
volume(extent)?
.checked_mul(size_of::<T>())
.ok_or_else(|| Error::out_of_range("array transfer bytes"))?;
let mut raw = MaybeUninit::<sys::CUDA_MEMCPY3D>::zeroed();
let mut raw = unsafe {
(*raw.as_mut_ptr()).srcMemoryType = sys::CUmemorytype::CU_MEMORYTYPE_HOST;
(*raw.as_mut_ptr()).dstMemoryType = sys::CUmemorytype::CU_MEMORYTYPE_HOST;
raw.assume_init()
};
raw.WidthInBytes = to_u64(row_bytes, "array row bytes")?;
raw.Height = to_u64(extent[1], "array transfer height")?;
raw.Depth = to_u64(extent[2], "array transfer depth")?;
match source {
CopySource::Host(pointer) => {
raw.srcHost = pointer;
raw.srcPitch = raw.WidthInBytes;
raw.srcHeight = raw.Height;
}
CopySource::Device(pointer) => {
raw.srcMemoryType = sys::CUmemorytype::CU_MEMORYTYPE_DEVICE;
raw.srcDevice = pointer;
raw.srcPitch = raw.WidthInBytes;
raw.srcHeight = raw.Height;
}
CopySource::Array(array) => {
raw.srcMemoryType = sys::CUmemorytype::CU_MEMORYTYPE_ARRAY;
raw.srcArray = array.handle;
[raw.srcXInBytes, raw.srcY, raw.srcZ] = array.origin;
}
}
match destination {
CopyDestination::Host(pointer) => {
raw.dstHost = pointer;
raw.dstPitch = raw.WidthInBytes;
raw.dstHeight = raw.Height;
}
CopyDestination::Device(pointer) => {
raw.dstMemoryType = sys::CUmemorytype::CU_MEMORYTYPE_DEVICE;
raw.dstDevice = pointer;
raw.dstPitch = raw.WidthInBytes;
raw.dstHeight = raw.Height;
}
CopyDestination::Array(array) => {
raw.dstMemoryType = sys::CUmemorytype::CU_MEMORYTYPE_ARRAY;
raw.dstArray = array.handle;
[raw.dstXInBytes, raw.dstY, raw.dstZ] = array.origin;
}
}
Ok(raw)
}
fn descriptor<T: ArrayElement>(
shape: ArrayShape,
flags: ArrayFlags,
) -> Result<(sys::CUDA_ARRAY3D_DESCRIPTOR, usize)> {
let (dimensions, shape_flags) = shape.native_dimensions()?;
let bytes = volume(shape.extent()?)?
.checked_mul(size_of::<T>())
.ok_or_else(|| Error::out_of_range("array byte size"))?;
let descriptor = sys::CUDA_ARRAY3D_DESCRIPTOR {
Width: to_u64(dimensions[0], "array width")?,
Height: to_u64(dimensions[1], "array height")?,
Depth: to_u64(dimensions[2], "array depth")?,
Format: T::FORMAT.into(),
NumChannels: T::CHANNELS,
Flags: flags.bits() | shape_flags,
};
Ok((descriptor, bytes))
}
impl<T: ArrayElement> Array<T> {
pub fn create_uninit(
context: &Arc<Context>,
shape: ArrayShape,
flags: ArrayFlags,
) -> Result<Array<T, Uninitialized>> {
if flags.bits() & !ArrayFlags::all().bits() != 0 {
return Err(Error::out_of_range("array flags"));
}
let (descriptor, bytes) = descriptor::<T>(shape, flags)?;
context.bind()?;
let mut handle = ptr::null_mut();
unsafe {
try_ffi!(sys::cuArray3DCreate_v2(
&raw mut handle,
&raw const descriptor
))?;
}
if handle.is_null() {
return Err(Error::NullHandle);
}
Ok(Array {
allocation: Arc::new(ArrayAllocation {
context: Arc::clone(context),
handle,
id: AllocationId::create(),
range: 0..bytes,
shape,
flags,
format: T::FORMAT,
channels: T::CHANNELS,
parent: None,
}),
marker: PhantomData,
})
}
}
impl<T: ArrayElement> Array<T, Uninitialized> {
pub fn initialize(mut self, source: &[T]) -> Result<Array<T>> {
self.copy_from_host(ArrayRegion::full(self.shape())?, source)?;
Ok(unsafe { self.assume_init() })
}
#[must_use]
pub unsafe fn assume_init(self) -> Array<T> {
Array {
allocation: self.allocation,
marker: PhantomData,
}
}
pub unsafe fn from_raw(raw: RawArray) -> Result<Self> {
let RawArray {
handle,
context,
shape,
flags,
} = raw;
if handle.is_null() {
return Err(Error::NullHandle);
}
let (expected, bytes) = descriptor::<T>(shape, flags)?;
context.bind()?;
let mut actual = MaybeUninit::<sys::CUDA_ARRAY3D_DESCRIPTOR>::uninit();
unsafe {
try_ffi!(sys::cuArray3DGetDescriptor_v2(actual.as_mut_ptr(), handle))?;
}
let actual = unsafe { actual.assume_init() };
if expected != actual {
return Err(Error::out_of_range("array descriptor"));
}
Ok(Self {
allocation: Arc::new(ArrayAllocation {
context,
handle,
id: AllocationId::create(),
range: 0..bytes,
shape,
flags,
format: T::FORMAT,
channels: T::CHANNELS,
parent: None,
}),
marker: PhantomData,
})
}
}
impl<T: ArrayElement> Array<T> {
pub fn from_slice(
context: &Arc<Context>,
shape: ArrayShape,
flags: ArrayFlags,
source: &[T],
) -> Result<Self> {
Self::create_uninit(context, shape, flags)?.initialize(source)
}
pub fn copy_to_host(&self, region: ArrayRegion, destination: &mut [T]) -> Result<()> {
let expected = region.len()?;
if destination.len() != expected {
return Err(Error::length_mismatch(
"host destination",
expected,
destination.len(),
));
}
let raw = transfer::<T>(
region.extent,
CopySource::Array(self.endpoint(region)?),
CopyDestination::Host(destination.as_mut_ptr().cast()),
)?;
self.run_copy(&raw, &[self.allocation.access(AccessMode::Read)])
}
pub fn to_vec(&self, region: ArrayRegion) -> Result<Vec<T>> {
region.validate(self.shape())?;
let mut values = vec![MaybeUninit::<T>::uninit(); region.len()?];
let raw = transfer::<T>(
region.extent,
CopySource::Array(self.endpoint(region)?),
CopyDestination::Host(values.as_mut_ptr().cast()),
)?;
self.run_copy(&raw, &[self.allocation.access(AccessMode::Read)])?;
let mut values = ManuallyDrop::new(values);
Ok(unsafe {
Vec::from_raw_parts(values.as_mut_ptr().cast(), values.len(), values.capacity())
})
}
pub fn copy_to_device<'a, B: DeviceOutput<T> + ?Sized>(
&self,
region: ArrayRegion,
destination: &'a mut B,
) -> Result<DeviceViewMut<'a, T>> {
if destination.context() != self.context() {
return Err(Error::MemoryContextMismatch);
}
let expected = region.len()?;
if destination.len() != expected {
return Err(Error::length_mismatch(
"device destination",
expected,
destination.len(),
));
}
let destination_address = to_u64(
destination.as_mut_ptr().addr(),
"device destination address",
)?;
let raw = transfer::<T>(
region.extent,
CopySource::Array(self.endpoint(region)?),
CopyDestination::Device(destination_address),
)?;
self.run_copy(
&raw,
&[
self.allocation.access(AccessMode::Read),
Access::new(destination.region(), AccessMode::Write),
],
)?;
unsafe { DeviceViewMut::from_raw_parts(destination.region(), destination.len()) }
}
pub fn copy_to_host_scoped<'env>(
&'env self,
region: ArrayRegion,
destination: &'env mut [T],
scope: &StreamScope<'_, 'env>,
) -> Result<()> {
if self.context() != scope.stream().context() {
return Err(Error::MemoryContextMismatch);
}
let expected = region.len()?;
if destination.len() != expected {
return Err(Error::length_mismatch(
"host destination",
expected,
destination.len(),
));
}
let raw = transfer::<T>(
region.extent,
CopySource::Array(self.endpoint(region)?),
CopyDestination::Host(destination.as_mut_ptr().cast()),
)?;
let accesses = [self.allocation.access(AccessMode::Read)];
unsafe {
scope.enqueue(&accesses, || {
try_ffi!(sys::cuMemcpy3DAsync_v2(
&raw const raw,
scope.stream().as_raw()
))
})
}
}
}
#[derive(Debug)]
pub struct MipmappedAllocation {
context: Arc<Context>,
handle: sys::CUmipmappedArray,
id: AllocationId,
shape: ArrayShape,
flags: ArrayFlags,
levels: u32,
ranges: Vec<Range<usize>>,
}
unsafe impl Send for MipmappedAllocation {}
unsafe impl Sync for MipmappedAllocation {}
impl MipmappedAllocation {
#[must_use]
pub fn context(&self) -> &Arc<Context> {
&self.context
}
#[must_use]
pub fn as_raw(&self) -> sys::CUmipmappedArray {
self.handle
}
#[must_use]
pub fn levels(&self) -> u32 {
self.levels
}
#[must_use]
pub fn shape(&self) -> ArrayShape {
self.shape
}
#[must_use]
pub fn flags(&self) -> ArrayFlags {
self.flags
}
#[must_use]
pub fn allocation_id(&self) -> AllocationId {
self.id
}
#[must_use]
pub fn access(&self, mode: AccessMode) -> Access {
Access::allocation(
&self.context,
self.id,
0..self.ranges.last().map_or(0, |range| range.end),
mode,
)
}
}
impl Drop for MipmappedAllocation {
fn drop(&mut self) {
if self.handle.is_null() {
return;
}
if let Err(error) = self.context.bind() {
report_cleanup_failure(
"bind the cuda context to destroy",
"cuda mipmapped array",
&error,
);
return;
}
if let Err(error) = unsafe { try_ffi!(sys::cuMipmappedArrayDestroy(self.handle)) } {
report_cleanup_failure("destroy", "cuda mipmapped array", &error);
}
}
}
#[derive(Debug)]
pub struct RawMipmappedArray {
pub handle: sys::CUmipmappedArray,
pub context: Arc<Context>,
pub shape: ArrayShape,
pub flags: ArrayFlags,
pub levels: u32,
}
#[derive(Debug)]
pub struct MipmappedArray<T: ArrayElement, S = Initialized> {
allocation: Arc<MipmappedAllocation>,
marker: PhantomData<(T, S)>,
}
impl<T: ArrayElement, S> MipmappedArray<T, S> {
#[must_use]
pub fn allocation(&self) -> &Arc<MipmappedAllocation> {
&self.allocation
}
#[must_use]
pub fn as_raw(&self) -> sys::CUmipmappedArray {
self.allocation.as_raw()
}
#[must_use]
pub fn context(&self) -> &Arc<Context> {
self.allocation.context()
}
#[must_use]
pub fn levels(&self) -> u32 {
self.allocation.levels
}
fn array_at_level(&self, level: u32) -> Result<Array<T, S>> {
if level >= self.levels() {
return Err(Error::out_of_range("mipmap level"));
}
self.context().bind()?;
let mut handle = ptr::null_mut();
unsafe {
try_ffi!(sys::cuMipmappedArrayGetLevel(
&raw mut handle,
self.as_raw(),
level
))?;
}
Ok(Array {
allocation: Arc::new(ArrayAllocation {
context: Arc::clone(self.context()),
handle,
id: self.allocation.id,
range: self.allocation.ranges[to_usize(level, "mipmap level")?].clone(),
shape: self.allocation.shape.at_level(level),
flags: self.allocation.flags,
format: T::FORMAT,
channels: T::CHANNELS,
parent: Some(Arc::clone(&self.allocation)),
}),
marker: PhantomData,
})
}
pub fn level(&self, level: u32) -> Result<ArrayLevel<'_, T, S>> {
Ok(ArrayLevel {
array: self.array_at_level(level)?,
parent: PhantomData,
})
}
pub fn level_mut(&mut self, level: u32) -> Result<ArrayLevelMut<'_, T, S>> {
Ok(ArrayLevelMut {
array: self.array_at_level(level)?,
parent: PhantomData,
})
}
pub fn into_raw(self) -> StdResult<RawMipmappedArray, Self> {
let shape = self.allocation.shape();
let flags = self.allocation.flags();
let levels = self.levels();
match Arc::try_unwrap(self.allocation) {
Ok(mut allocation) => Ok(RawMipmappedArray {
handle: mem::replace(&mut allocation.handle, ptr::null_mut()),
context: Arc::clone(&allocation.context),
shape,
flags,
levels,
}),
Err(allocation) => Err(Self {
allocation,
marker: PhantomData,
}),
}
}
}
impl<T: ArrayElement> MipmappedArray<T, Uninitialized> {
pub unsafe fn from_raw(raw: RawMipmappedArray) -> Result<Self> {
let RawMipmappedArray {
handle,
context,
shape,
flags,
levels,
} = raw;
if handle.is_null() {
return Err(Error::NullHandle);
}
let (expected, _) = descriptor::<T>(shape, flags)?;
let ranges = mip_level_ranges::<T>(shape, levels)?;
context.bind()?;
let mut level = ptr::null_mut();
unsafe {
try_ffi!(sys::cuMipmappedArrayGetLevel(&raw mut level, handle, 0))?;
}
let mut actual = MaybeUninit::<sys::CUDA_ARRAY3D_DESCRIPTOR>::uninit();
unsafe {
try_ffi!(sys::cuArray3DGetDescriptor_v2(actual.as_mut_ptr(), level))?;
}
if expected != unsafe { actual.assume_init() } {
return Err(Error::out_of_range("mipmap level descriptor"));
}
unsafe {
try_ffi!(sys::cuMipmappedArrayGetLevel(
&raw mut level,
handle,
levels - 1
))?;
}
Ok(Self {
allocation: Arc::new(MipmappedAllocation {
context,
handle,
id: AllocationId::create(),
shape,
flags,
levels,
ranges,
}),
marker: PhantomData,
})
}
}
impl<T: ArrayElement> MipmappedArray<T> {
pub fn create_uninit(
context: &Arc<Context>,
shape: ArrayShape,
flags: ArrayFlags,
levels: u32,
) -> Result<MipmappedArray<T, Uninitialized>> {
if flags.bits() & !ArrayFlags::all().bits() != 0 {
return Err(Error::out_of_range("array flags"));
}
let (desc, _) = descriptor::<T>(shape, flags)?;
let ranges = mip_level_ranges::<T>(shape, levels)?;
context.bind()?;
let mut handle = ptr::null_mut();
unsafe {
try_ffi!(sys::cuMipmappedArrayCreate(
&raw mut handle,
&raw const desc,
levels
))?;
}
if handle.is_null() {
return Err(Error::NullHandle);
}
Ok(MipmappedArray {
allocation: Arc::new(MipmappedAllocation {
context: Arc::clone(context),
handle,
id: AllocationId::create(),
shape,
flags,
levels,
ranges,
}),
marker: PhantomData,
})
}
}
impl<T: ArrayElement> MipmappedArray<T, Uninitialized> {
pub fn initialize(mut self, levels: &[&[T]]) -> Result<MipmappedArray<T>> {
let level_count = to_usize(self.levels(), "mipmap level count")?;
if levels.len() != level_count {
return Err(Error::length_mismatch(
"mipmap levels",
level_count,
levels.len(),
));
}
for (level, values) in levels.iter().enumerate() {
let mut array = self.level_mut(
u32::try_from(level).expect("mipmap level is bounded by the u32 level count"),
)?;
let region = ArrayRegion::full(array.shape())?;
array.copy_from_host(region, values)?;
}
Ok(unsafe { self.assume_init() })
}
#[must_use]
pub unsafe fn assume_init(self) -> MipmappedArray<T> {
MipmappedArray {
allocation: self.allocation,
marker: PhantomData,
}
}
}
fn mip_level_ranges<T: ArrayElement>(shape: ArrayShape, levels: u32) -> Result<Vec<Range<usize>>> {
if levels == 0 || levels > shape.maximum_levels() {
return Err(Error::out_of_range("mipmap level count"));
}
let mut end = 0usize;
(0..levels)
.map(|level| {
let bytes = volume(shape.at_level(level).extent()?)?
.checked_mul(size_of::<T>())
.ok_or_else(|| Error::out_of_range("mipmap level bytes"))?;
let start = end;
end = end
.checked_add(bytes)
.ok_or_else(|| Error::out_of_range("mipmap byte size"))?;
Ok(start..end)
})
.collect()
}
#[derive(Debug)]
pub struct ArrayLevel<'a, T: ArrayElement, S = Initialized> {
array: Array<T, S>,
parent: PhantomData<&'a MipmappedArray<T, S>>,
}
impl<T: ArrayElement, S> Deref for ArrayLevel<'_, T, S> {
type Target = Array<T, S>;
fn deref(&self) -> &Self::Target {
&self.array
}
}
#[derive(Debug)]
pub struct ArrayLevelMut<'a, T: ArrayElement, S = Initialized> {
array: Array<T, S>,
parent: PhantomData<&'a mut MipmappedArray<T, S>>,
}
impl<T: ArrayElement, S> Deref for ArrayLevelMut<'_, T, S> {
type Target = Array<T, S>;
fn deref(&self) -> &Self::Target {
&self.array
}
}
impl<T: ArrayElement, S> DerefMut for ArrayLevelMut<'_, T, S> {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.array
}
}