Skip to main content

singe_cuda/memory/
pitched.rs

1use std::{marker::PhantomData, mem::MaybeUninit, ptr, result::Result as StdResult, sync::Arc};
2
3use singe_cuda_sys::runtime;
4
5use crate::{
6    context::Context,
7    error::{Error, Result},
8    memory::{DeviceAllocation, DeviceDeallocation, DeviceMemory, MemoryCopyKind},
9    stream::{AsStream, StreamBinding, StreamScope},
10    submission::{Access, AccessMode},
11    types::DevicePtr,
12    utility::{checked_bytes, checked_element_count, to_usize},
13    view::{
14        AllocationId, AnyBitPatternDeviceRepr, DeviceRegion, DeviceRegionProvider, DeviceRepr,
15        DeviceView, DeviceViewMut, NoUninitDeviceRepr, ZeroableDeviceRepr,
16    },
17};
18
19fn checked_pitched_bytes<T>(
20    ptr: *mut T,
21    width: usize,
22    height: usize,
23    depth: usize,
24    pitch: usize,
25) -> Result<usize> {
26    let row_bytes = checked_bytes::<T>(width, "row bytes")?;
27    checked_element_count(&[row_bytes, height, depth], "logical bytes")?;
28    if width == 0 || height == 0 || depth == 0 {
29        return Ok(0);
30    }
31
32    let bytes = checked_element_count(&[pitch, height, depth], "pitched bytes")?;
33    if ptr.is_null() {
34        return Err(Error::null_pointer("pitched pointer"));
35    }
36
37    if pitch < row_bytes {
38        return Err(Error::buffer_too_small("pitch", row_bytes, pitch));
39    }
40
41    if !ptr.addr().is_multiple_of(align_of::<T>()) {
42        return Err(Error::misaligned("pitched pointer", align_of::<T>()));
43    }
44
45    if !pitch.is_multiple_of(align_of::<T>()) {
46        return Err(Error::misaligned("pitch", align_of::<T>()));
47    }
48
49    if ptr.addr().checked_add(bytes).is_none() {
50        return Err(Error::out_of_range("pitched allocation end"));
51    }
52
53    Ok(bytes)
54}
55
56// Adopt a newly allocated pointer before checking CUDA's returned pitch, so a rejected layout still frees the allocation in its owning context.
57fn own_pitched_allocation<T>(
58    context: &Arc<Context>,
59    ptr: *mut T,
60    width: usize,
61    height: usize,
62    depth: usize,
63    pitch: usize,
64) -> Result<Arc<DeviceAllocation>> {
65    let mut allocation = DeviceAllocation {
66        id: AllocationId::create(),
67        context: Arc::clone(context),
68        ptr: ptr.cast(),
69        bytes: 0,
70        deallocation: DeviceDeallocation::Immediate,
71    };
72    allocation.bytes = checked_pitched_bytes(ptr, width, height, depth, pitch)?;
73    Ok(Arc::new(allocation))
74}
75
76impl<T: DeviceRepr> PitchedDeviceMemory<T> {
77    fn allocate(context: &Arc<Context>, width: usize, height: usize) -> Result<Self> {
78        let () = T::LAYOUT;
79        context.bind()?;
80        // SAFETY: the context is bound above, and `own_pitched_allocation` adopts the returned pointer before anything can fail, so it is freed in this context.
81        let (ptr, pitch) = unsafe { DeviceMemory::<T>::alloc_pitched(context, width, height)? };
82        let allocation = own_pitched_allocation(context, ptr, width, height, 1, pitch)?;
83        Ok(Self {
84            allocation,
85            ptr,
86            width,
87            height,
88            pitch,
89            _phantom: PhantomData,
90        })
91    }
92
93    /// Allocates pitched storage whose logical elements are uninitialized.
94    ///
95    /// # Errors
96    ///
97    /// Returns an error if size calculations overflow, a nonempty zero-sized element range is requested, the context cannot be bound, or CUDA cannot allocate pitched storage.
98    /// Returns an error if CUDA returns a pointer or pitch that violates the requested row size, alignment, or address-range bounds.
99    pub fn create_uninit(
100        context: &Arc<Context>,
101        width: usize,
102        height: usize,
103    ) -> Result<PitchedDeviceMemory<MaybeUninit<T>>> {
104        PitchedDeviceMemory::<MaybeUninit<T>>::allocate(context, width, height)
105    }
106
107    /// Allocates pitched storage and completes zero initialization of its logical elements.
108    ///
109    /// # Errors
110    ///
111    /// Returns an error if allocation fails for the reasons `create_uninit` gives, access tracking fails, or CUDA cannot fill or synchronize.
112    pub fn zeroed(context: &Arc<Context>, width: usize, height: usize) -> Result<Self>
113    where
114        T: ZeroableDeviceRepr,
115    {
116        let mut memory = Self::create_uninit(context, width, height)?;
117        memory.set_zeroes()?;
118        // SAFETY: `set_zeroes` completed a zero fill of every logical element, and an all-zero `T` is valid.
119        Ok(unsafe { memory.assume_init() })
120    }
121
122    /// Allocates pitched storage and completes a repeated byte fill of its logical elements.
123    ///
124    /// # Errors
125    ///
126    /// Returns an error if allocation fails for the reasons `create_uninit` gives, access tracking fails, or CUDA cannot fill or synchronize.
127    pub fn filled(context: &Arc<Context>, width: usize, height: usize, value: u8) -> Result<Self>
128    where
129        T: AnyBitPatternDeviceRepr,
130    {
131        let mut memory = Self::create_uninit(context, width, height)?;
132        memory.set_value(value)?;
133        // SAFETY: `set_value` completed a fill of every logical element, and every bit pattern is a valid `T`.
134        Ok(unsafe { memory.assume_init() })
135    }
136
137    /// Allocates pitched storage and completes a copy of contiguous row-major host values.
138    ///
139    /// # Errors
140    ///
141    /// Returns an error if the source length differs from the logical element count, allocation fails for the reasons `create_uninit` gives, or CUDA cannot copy or synchronize.
142    pub fn from_slice(
143        context: &Arc<Context>,
144        width: usize,
145        height: usize,
146        values: &[T],
147    ) -> Result<Self> {
148        Self::create_uninit(context, width, height)?.initialize_from_host(values)
149    }
150
151    /// Takes ownership of a pitched allocation in `raw.context`.
152    ///
153    /// # Safety
154    ///
155    /// `raw.ptr` must be the base of a live CUDA allocation compatible with `cudaFree`, with no other destruction owner.
156    /// It must contain initialized, valid `T` values at every logical element.
157    /// The pitch and dimensions must describe its storage, and previous accesses must be ordered before future consumers.
158    /// A null pointer is accepted for an empty shape.
159    ///
160    /// # Errors
161    ///
162    /// Returns an error if row or volume size calculations overflow or a nonempty zero-sized element range is requested.
163    /// Returns an error if nonempty storage has a null or misaligned pointer, a pitch smaller than the row width or not aligned for `T`, or an overflowing ending address.
164    pub unsafe fn from_raw(raw: RawPitchedDeviceMemory<T>) -> Result<Self> {
165        let RawPitchedDeviceMemory {
166            ptr,
167            width,
168            height,
169            pitch,
170            context,
171        } = raw;
172        let () = T::LAYOUT;
173        let bytes = checked_pitched_bytes(ptr, width, height, 1, pitch)?;
174        Ok(Self {
175            allocation: DeviceAllocation::from_parts(
176                &context,
177                ptr.cast(),
178                bytes,
179                DeviceDeallocation::Immediate,
180            ),
181            ptr,
182            width,
183            height,
184            pitch,
185            _phantom: PhantomData,
186        })
187    }
188
189    /// Transfers raw ownership, or returns this buffer unchanged if another owner retains it.
190    ///
191    /// The returned pointer must eventually be freed in the returned context.
192    ///
193    /// # Errors
194    ///
195    /// Returns the wrapper unchanged as the error if another owner, submission, graph, or foreign handle retains the allocation.
196    pub fn into_raw(self) -> StdResult<RawPitchedDeviceMemory<T>, Self> {
197        let Self {
198            allocation,
199            ptr,
200            width,
201            height,
202            pitch,
203            _phantom: PhantomData,
204        } = self;
205        match Arc::try_unwrap(allocation) {
206            Ok(mut allocation) => {
207                let context = Arc::clone(allocation.context());
208                allocation.ptr = ptr::null_mut();
209                Ok(RawPitchedDeviceMemory {
210                    ptr,
211                    width,
212                    height,
213                    pitch,
214                    context,
215                })
216            }
217            Err(allocation) => Err(Self {
218                allocation,
219                ptr,
220                width,
221                height,
222                pitch,
223                _phantom: PhantomData,
224            }),
225        }
226    }
227
228    /// Returns the allocation's retained CUDA context.
229    #[must_use]
230    pub fn context(&self) -> &Arc<Context> {
231        self.allocation.context()
232    }
233
234    /// Returns the shared owner of the physical allocation, including row padding.
235    #[must_use]
236    pub fn allocation(&self) -> &Arc<DeviceAllocation> {
237        &self.allocation
238    }
239
240    /// Reinterprets logical row bytes while preserving pitch, capacity, and allocation identity.
241    ///
242    /// Row padding is excluded from the initialized representation.
243    ///
244    /// # Errors
245    ///
246    /// Returns the allocation unchanged as the error if `U` is zero-sized, its size does not divide the logical row byte width, or nonempty storage has a base pointer or pitch not aligned for `U`.
247    ///
248    /// # Panics
249    ///
250    /// Panics if the logical row byte width overflows `usize`.
251    /// Construction validates this width, so this cannot occur for a valid pitched allocation.
252    pub fn cast<U: AnyBitPatternDeviceRepr>(self) -> StdResult<PitchedDeviceMemory<U>, Self>
253    where
254        T: NoUninitDeviceRepr,
255    {
256        let () = T::LAYOUT;
257        let () = U::LAYOUT;
258        let size = size_of::<U>();
259        let row_bytes = self
260            .row_byte_width()
261            .expect("pitched row byte length overflow");
262        if size == 0
263            || !row_bytes.is_multiple_of(size)
264            || (!self.is_empty()
265                && (!self.ptr.addr().is_multiple_of(align_of::<U>())
266                    || !self.pitch.is_multiple_of(align_of::<U>())))
267        {
268            return Err(self);
269        }
270        Ok(PitchedDeviceMemory {
271            allocation: self.allocation,
272            ptr: self.ptr.cast(),
273            width: row_bytes / size,
274            height: self.height,
275            pitch: self.pitch,
276            _phantom: PhantomData,
277        })
278    }
279
280    /// Erases logical element initialization without changing allocation ownership.
281    #[must_use]
282    pub fn into_uninit(self) -> PitchedDeviceMemory<MaybeUninit<T>> {
283        PitchedDeviceMemory {
284            allocation: self.allocation,
285            ptr: self.ptr.cast(),
286            width: self.width,
287            height: self.height,
288            pitch: self.pitch,
289            _phantom: PhantomData,
290        }
291    }
292
293    /// Returns the logical row width in elements.
294    #[must_use]
295    pub const fn width(&self) -> usize {
296        self.width
297    }
298
299    /// Returns the logical number of rows.
300    #[must_use]
301    pub const fn height(&self) -> usize {
302        self.height
303    }
304
305    /// Returns the row stride in bytes.
306    #[must_use]
307    pub const fn pitch(&self) -> usize {
308        self.pitch
309    }
310
311    /// Returns the base device pointer.
312    #[must_use]
313    pub const fn as_ptr(&self) -> *const T {
314        self.ptr
315    }
316
317    /// Returns the mutable base device pointer.
318    pub const fn as_mut_ptr(&mut self) -> *mut T {
319        self.ptr
320    }
321
322    /// Returns the base pointer as a CUDA device pointer wrapper.
323    #[must_use]
324    pub const fn as_device_ptr(&self) -> DevicePtr {
325        // SAFETY: `self.ptr` is the base of the pitched allocation that `allocation` keeps live, and `DevicePtr` only carries the address.
326        unsafe { DevicePtr::from_raw(self.ptr.cast()) }
327    }
328
329    /// Returns the logical element count.
330    ///
331    /// # Errors
332    ///
333    /// Returns an error if `width * height` overflows.
334    pub fn len(&self) -> Result<usize> {
335        checked_element_count(&[self.width, self.height], "element count")
336    }
337
338    /// Returns the logical row width in bytes.
339    ///
340    /// # Errors
341    ///
342    /// Returns an error if `width * size_of::<T>()` overflows or `T` is a non-empty zero-sized element type.
343    pub fn row_byte_width(&self) -> Result<usize> {
344        checked_bytes::<T>(self.width, "row bytes")
345    }
346
347    /// Returns the physical allocation span described by `pitch * height`.
348    ///
349    /// # Errors
350    ///
351    /// Returns an error if `pitch * height` overflows.
352    pub fn byte_len(&self) -> Result<usize> {
353        Ok(self.allocation.byte_len())
354    }
355
356    /// Returns whether any dimension is zero.
357    #[must_use]
358    pub fn is_empty(&self) -> bool {
359        self.width == 0 || self.height == 0
360    }
361
362    /// Copies a contiguous host slice into this pitched device allocation.
363    ///
364    /// `src` must contain exactly `width * height` elements in row-major order.
365    ///
366    /// # Errors
367    ///
368    /// Returns an error if `src` has the wrong length, byte-size arithmetic overflows, or CUDA rejects the 2D copy.
369    pub fn copy_from_host(&mut self, src: &[T]) -> Result<()> {
370        let context = Arc::clone(self.context());
371        let _access = context.acquire_host_access(&[self.region()])?;
372        self.context().bind()?;
373        let len = self.len()?;
374        if src.len() != len {
375            return Err(Error::length_mismatch("host source", len, src.len()));
376        }
377
378        let row_bytes = self.row_byte_width()?;
379        // SAFETY: `src` holds exactly `width * height` values at a `row_bytes` pitch, construction validated this allocation's pitch and rows, the host access excludes tracked GPU work, and the context is bound.
380        unsafe {
381            DeviceMemory::<T>::copy_2d(
382                self.context(),
383                self.ptr,
384                self.pitch,
385                src.as_ptr(),
386                row_bytes,
387                self.width,
388                self.height,
389                MemoryCopyKind::HostToDevice,
390            )
391        }?;
392        StreamBinding::Default(Arc::clone(self.context())).synchronize()
393    }
394
395    /// Copies this pitched device allocation into a contiguous host slice.
396    ///
397    /// `dst` must contain exactly `width * height` elements and is filled in row-major order.
398    ///
399    /// # Errors
400    ///
401    /// Returns an error if `dst` has the wrong length, byte-size arithmetic overflows, or CUDA rejects the 2D copy.
402    pub fn copy_to_host(&self, dst: &mut [T]) -> Result<()>
403    where
404        T: AnyBitPatternDeviceRepr,
405    {
406        let () = T::LAYOUT;
407        // SAFETY: `T: AnyBitPatternDeviceRepr`, so any device bytes are valid `T` values.
408        unsafe { self.copy_to_host_unchecked(dst) }
409    }
410
411    /// Copies device values whose validity is established by the producing kernel.
412    ///
413    /// # Safety
414    ///
415    /// Every copied element must be initialized and valid for `T`.
416    ///
417    /// # Errors
418    ///
419    /// Returns an error if the destination length differs from the logical element count, transfer size calculations overflow, access tracking fails, the context cannot be bound, or CUDA cannot copy or synchronize.
420    pub unsafe fn copy_to_host_unchecked(&self, dst: &mut [T]) -> Result<()> {
421        let context = Arc::clone(self.context());
422        let _access = context.acquire_host_access(&[self.region()])?;
423        self.context().bind()?;
424        let len = self.len()?;
425        if dst.len() != len {
426            return Err(Error::length_mismatch("host destination", len, dst.len()));
427        }
428
429        let row_bytes = self.row_byte_width()?;
430        // SAFETY: `dst` holds exactly `width * height` writable values at a `row_bytes` pitch, the host access waited for tracked GPU work, and the caller guarantees the copied elements are valid `T` values.
431        unsafe {
432            DeviceMemory::<T>::copy_2d(
433                self.context(),
434                dst.as_mut_ptr(),
435                row_bytes,
436                self.ptr,
437                self.pitch,
438                self.width,
439                self.height,
440                MemoryCopyKind::DeviceToHost,
441            )
442        }?;
443        StreamBinding::Default(Arc::clone(self.context())).synchronize()
444    }
445
446    /// Copies another pitched device allocation with the same shape into this one.
447    ///
448    /// # Errors
449    ///
450    /// Returns an error if the shapes differ, byte-size arithmetic overflows, or CUDA rejects the device-to-device 2D copy.
451    pub fn copy_from_pitched(&mut self, src: &Self) -> Result<()> {
452        self.context().bind()?;
453        if self.context() != src.context() {
454            return Err(Error::MemoryContextMismatch);
455        }
456
457        if self.width != src.width {
458            return Err(Error::length_mismatch(
459                "source width",
460                self.width,
461                src.width,
462            ));
463        }
464
465        if self.height != src.height {
466            return Err(Error::length_mismatch(
467                "source height",
468                self.height,
469                src.height,
470            ));
471        }
472
473        // SAFETY: both allocations are in this bound context and have the same validated width and height, so each row copy stays inside both, and `&mut self` excludes aliasing with `src`.
474        unsafe {
475            DeviceMemory::<T>::copy_2d(
476                self.context(),
477                self.ptr,
478                self.pitch,
479                src.ptr,
480                src.pitch,
481                self.width,
482                self.height,
483                MemoryCopyKind::DeviceToDevice,
484            )
485        }?;
486        StreamBinding::Default(Arc::clone(self.context())).synchronize()
487    }
488
489    /// Enqueues a host-to-device 2D copy from a contiguous host slice.
490    ///
491    /// `src` must remain valid until `stream` reaches the copy.
492    /// The [`StreamScope`] lifetime enforces that requirement for safe callers.
493    ///
494    /// # Errors
495    ///
496    /// Returns an error if `src` has the wrong length, byte-size arithmetic overflows, or CUDA cannot enqueue the copy.
497    pub fn copy_from_host_scoped<'env>(
498        &'env mut self,
499        src: &'env [T],
500        stream: &StreamScope<'_, 'env>,
501    ) -> Result<()> {
502        let accesses = [Access::new(self.region(), AccessMode::Write)];
503        if self.context() != stream.stream().context() {
504            return Err(Error::StreamContextMismatch);
505        }
506
507        self.context().bind()?;
508        let len = self.len()?;
509        if src.len() != len {
510            return Err(Error::length_mismatch("host source", len, src.len()));
511        }
512
513        let row_bytes = self.row_byte_width()?;
514        // SAFETY: `src` holds exactly the logical element count, the `'env` borrows keep it and this allocation live until the scope drains, the declared write orders tracked work, and the contexts match.
515        unsafe {
516            stream.enqueue(&accesses, || {
517                DeviceMemory::<T>::copy_2d_async(
518                    self.ptr,
519                    self.pitch,
520                    src.as_ptr(),
521                    row_bytes,
522                    self.width,
523                    self.height,
524                    MemoryCopyKind::HostToDevice,
525                    stream.stream(),
526                )
527            })
528        }
529    }
530
531    /// Enqueues a device-to-host 2D copy into a contiguous host slice.
532    ///
533    /// `dst` must remain valid until `stream` reaches the copy.
534    /// The [`StreamScope`] lifetime enforces that requirement for safe callers.
535    ///
536    /// # Errors
537    ///
538    /// Returns an error if `dst` has the wrong length, byte-size arithmetic overflows, or CUDA cannot enqueue the copy.
539    pub fn copy_to_host_scoped<'env>(
540        &'env self,
541        dst: &'env mut [T],
542        stream: &StreamScope<'_, 'env>,
543    ) -> Result<()>
544    where
545        T: AnyBitPatternDeviceRepr,
546    {
547        let accesses = [Access::new(self.region(), AccessMode::Read)];
548        if self.context() != stream.stream().context() {
549            return Err(Error::StreamContextMismatch);
550        }
551
552        self.context().bind()?;
553        let () = T::LAYOUT;
554        let len = self.len()?;
555        if dst.len() != len {
556            return Err(Error::length_mismatch("host destination", len, dst.len()));
557        }
558
559        let row_bytes = self.row_byte_width()?;
560        // SAFETY: `dst` holds exactly the logical element count, the `'env` borrows keep it and this allocation live until the scope drains, the declared read orders tracked work, and `T: AnyBitPatternDeviceRepr` makes any copied bytes valid.
561        unsafe {
562            stream.enqueue(&accesses, || {
563                DeviceMemory::<T>::copy_2d_async(
564                    dst.as_mut_ptr(),
565                    row_bytes,
566                    self.ptr,
567                    self.pitch,
568                    self.width,
569                    self.height,
570                    MemoryCopyKind::DeviceToHost,
571                    stream.stream(),
572                )
573            })
574        }
575    }
576
577    /// Fills this pitched allocation with zero bytes.
578    ///
579    /// # Errors
580    ///
581    /// Returns an error if CUDA rejects the 2D memset.
582    pub fn set_zeroes(&mut self) -> Result<()>
583    where
584        T: ZeroableDeviceRepr,
585    {
586        // SAFETY: `T: ZeroableDeviceRepr`, so all-zero bytes are a valid `T`.
587        unsafe { self.set_value_unchecked(0) }
588    }
589
590    /// Fills this pitched allocation with `value` bytes.
591    ///
592    /// # Errors
593    ///
594    /// Returns an error if CUDA rejects the 2D memset.
595    pub fn set_value(&mut self, value: u8) -> Result<()>
596    where
597        T: AnyBitPatternDeviceRepr,
598    {
599        let () = T::LAYOUT;
600        // SAFETY: `T: AnyBitPatternDeviceRepr`, so repeating `value` produces valid `T` values.
601        unsafe { self.set_value_unchecked(value) }
602    }
603
604    /// Fills storage with a byte pattern known to be valid for `T`.
605    ///
606    /// # Safety
607    ///
608    /// The repeated byte pattern must represent a valid value of `T`.
609    ///
610    /// # Errors
611    ///
612    /// Returns an error if access tracking fails, the context cannot be bound, the transfer size overflows, or CUDA cannot fill the memory or synchronize the default stream.
613    pub unsafe fn set_value_unchecked(&mut self, value: u8) -> Result<()> {
614        let context = Arc::clone(self.context());
615        let _access = context.acquire_host_access(&[self.region()])?;
616        self.context().bind()?;
617        // SAFETY: the validated pitch and shape keep the fill inside the allocation, the host access excludes tracked GPU work, and the caller guarantees the repeated byte is a valid `T` pattern.
618        unsafe {
619            DeviceMemory::<T>::set_2d(
620                self.context(),
621                self.ptr,
622                self.pitch,
623                value,
624                self.width,
625                self.height,
626            )?;
627        }
628        StreamBinding::Default(Arc::clone(self.context())).synchronize()
629    }
630
631    /// Enqueues a byte fill of this pitched allocation on `stream`.
632    ///
633    /// # Errors
634    ///
635    /// Returns an error if CUDA cannot enqueue the 2D memset.
636    pub fn set_value_scoped<'env>(
637        &'env mut self,
638        value: u8,
639        stream: &StreamScope<'_, 'env>,
640    ) -> Result<()>
641    where
642        T: AnyBitPatternDeviceRepr,
643    {
644        let accesses = [Access::new(self.region(), AccessMode::Write)];
645        if self.context() != stream.stream().context() {
646            return Err(Error::StreamContextMismatch);
647        }
648
649        self.context().bind()?;
650        let () = T::LAYOUT;
651        checked_element_count(&[self.row_byte_width()?, self.height], "logical bytes")?;
652        // SAFETY: the `'env` borrow keeps this allocation live until the scope drains, the declared write orders tracked work, the contexts match, and `T: AnyBitPatternDeviceRepr` makes any repeated byte valid.
653        unsafe {
654            stream.enqueue(&accesses, || {
655                DeviceMemory::<T>::set_2d_async(
656                    self.ptr,
657                    self.pitch,
658                    value,
659                    self.width,
660                    self.height,
661                    stream.stream(),
662                )
663            })
664        }
665    }
666
667    fn row_region(&self, row: usize) -> Result<DeviceRegion<'_>> {
668        if row >= self.height {
669            return Err(Error::out_of_range("row"));
670        }
671
672        if self.width == 0 {
673            return self.region().slice(0..0);
674        }
675
676        let start = row
677            .checked_mul(self.pitch)
678            .ok_or_else(|| Error::out_of_range("row offset"))?;
679        let end = start
680            .checked_add(self.row_byte_width()?)
681            .ok_or_else(|| Error::out_of_range("row end"))?;
682        self.region().slice(start..end)
683    }
684
685    /// Borrows one initialized logical row, excluding CUDA's row padding.
686    ///
687    /// # Errors
688    ///
689    /// Returns an error if the row index is out of bounds, row offset calculations overflow, or the resulting range fails byte-length or alignment validation.
690    pub fn row(&self, row: usize) -> Result<DeviceView<'_, T>> {
691        // SAFETY: a `T`-typed pitched owner only exists once every logical element is initialized, and the row region excludes the padding.
692        unsafe { DeviceView::from_raw_parts(self.row_region(row)?, self.width) }
693    }
694
695    /// Exclusively borrows one logical row, excluding CUDA's row padding.
696    ///
697    /// # Errors
698    ///
699    /// Returns an error if the row index is out of bounds, row offset calculations overflow, or the resulting range fails byte-length or alignment validation.
700    pub fn row_mut(&mut self, row: usize) -> Result<DeviceViewMut<'_, T>> {
701        // SAFETY: the row region excludes the padding and holds initialized `T` values, and `&mut self` makes the view the only access to them.
702        unsafe { DeviceViewMut::from_raw_parts(self.row_region(row)?, self.width) }
703    }
704}
705
706impl<T: DeviceRepr> PitchedDeviceMemory<MaybeUninit<T>> {
707    /// Copies every logical element from host values and completes before promotion.
708    ///
709    /// # Errors
710    ///
711    /// Returns an error if the source length differs from the logical element count, transfer size calculations overflow, the context cannot be bound, or CUDA cannot copy or synchronize.
712    pub fn initialize_from_host(self, values: &[T]) -> Result<PitchedDeviceMemory<T>> {
713        let len = self.len()?;
714        if values.len() != len {
715            return Err(Error::length_mismatch("host values", len, values.len()));
716        }
717
718        self.context().bind()?;
719        // SAFETY: `values` holds exactly `width * height` values, the validated pitch and rows make the allocation writable for the whole rectangle, `self` is owned so nothing else accesses it, and the context is bound.
720        unsafe {
721            DeviceMemory::<T>::copy_2d(
722                self.context(),
723                self.ptr.cast(),
724                self.pitch,
725                values.as_ptr(),
726                self.row_byte_width()?,
727                self.width,
728                self.height,
729                MemoryCopyKind::HostToDevice,
730            )?;
731        }
732
733        StreamBinding::Default(Arc::clone(self.context())).synchronize()?;
734        // SAFETY: the synchronized copy wrote every logical element from initialized host values of `T`.
735        Ok(unsafe { self.assume_init() })
736    }
737
738    /// Marks all logical elements initialized without changing the owner or pitch.
739    ///
740    /// # Safety
741    ///
742    /// Every logical element must contain an initialized valid `T` value.
743    /// Producers must be ordered before subsequent consumers and complete before host readback.
744    /// Row padding remains uninitialized.
745    #[must_use]
746    pub unsafe fn assume_init(self) -> PitchedDeviceMemory<T> {
747        let () = T::LAYOUT;
748        PitchedDeviceMemory {
749            allocation: self.allocation,
750            ptr: self.ptr.cast(),
751            width: self.width,
752            height: self.height,
753            pitch: self.pitch,
754            _phantom: PhantomData,
755        }
756    }
757}
758
759// SAFETY: the region is the whole pitched allocation, padding included, which `allocation` retains with its context for as long as `self` lives.
760unsafe impl<T: DeviceRepr> DeviceRegionProvider for PitchedDeviceMemory<T> {
761    fn region(&self) -> DeviceRegion<'_> {
762        self.allocation.region()
763    }
764}
765
766// SAFETY: `ptr` is a device address that the host never dereferences, the allocation behind it is owned through the `Send` `Arc<DeviceAllocation>`, and CUDA driver calls on it are thread-safe once the retained context is bound.
767unsafe impl<T: DeviceRepr + Send> Send for PitchedDeviceMemory<T> {}
768
769// SAFETY: `&self` methods only read the address and shape and enqueue CUDA work under the context's access tracker, and the driver API is thread-safe, so shared use from several threads performs no unsynchronized host access.
770unsafe impl<T: DeviceRepr + Sync> Sync for PitchedDeviceMemory<T> {}
771
772impl<T: DeviceRepr> PitchedDeviceVolume<T> {
773    fn allocate(context: &Arc<Context>, width: usize, height: usize, depth: usize) -> Result<Self> {
774        let () = T::LAYOUT;
775        context.bind()?;
776        // SAFETY: the context is bound above, and `own_pitched_allocation` adopts the returned pointer, so it is freed in this context.
777        let pitched =
778            unsafe { DeviceMemory::<T>::alloc_pitched_3d(context, width, height, depth)? };
779        let ptr = pitched.ptr.cast();
780        let pitch = to_usize(pitched.pitch, "allocation pitch")?;
781        let allocation = own_pitched_allocation(context, ptr, width, height, depth, pitch)?;
782        Ok(Self {
783            allocation,
784            ptr,
785            width,
786            height,
787            depth,
788            pitch,
789            _phantom: PhantomData,
790        })
791    }
792
793    /// Allocates pitched storage whose logical elements are uninitialized.
794    ///
795    /// # Errors
796    ///
797    /// Returns an error if size calculations overflow, a nonempty zero-sized element range is requested, the context cannot be bound, or CUDA cannot allocate pitched storage.
798    /// Returns an error if CUDA returns a pointer or pitch that violates the requested row size, alignment, or address-range bounds.
799    pub fn create_uninit(
800        context: &Arc<Context>,
801        width: usize,
802        height: usize,
803        depth: usize,
804    ) -> Result<PitchedDeviceVolume<MaybeUninit<T>>> {
805        PitchedDeviceVolume::<MaybeUninit<T>>::allocate(context, width, height, depth)
806    }
807
808    /// Allocates pitched storage and completes zero initialization of its logical elements.
809    ///
810    /// # Errors
811    ///
812    /// Returns an error if allocation fails for the reasons `create_uninit` gives, access tracking fails, or CUDA cannot fill or synchronize.
813    pub fn zeroed(context: &Arc<Context>, width: usize, height: usize, depth: usize) -> Result<Self>
814    where
815        T: ZeroableDeviceRepr,
816    {
817        let mut memory = Self::create_uninit(context, width, height, depth)?;
818        memory.set_zeroes()?;
819        // SAFETY: `set_zeroes` completed a zero fill of every logical element, and an all-zero `T` is valid.
820        Ok(unsafe { memory.assume_init() })
821    }
822
823    /// Allocates pitched storage and completes a repeated byte fill of its logical elements.
824    ///
825    /// # Errors
826    ///
827    /// Returns an error if allocation fails for the reasons `create_uninit` gives, access tracking fails, or CUDA cannot fill or synchronize.
828    pub fn filled(
829        context: &Arc<Context>,
830        width: usize,
831        height: usize,
832        depth: usize,
833        value: u8,
834    ) -> Result<Self>
835    where
836        T: AnyBitPatternDeviceRepr,
837    {
838        let mut memory = Self::create_uninit(context, width, height, depth)?;
839        memory.set_value(value)?;
840        // SAFETY: `set_value` completed a fill of every logical element, and every bit pattern is a valid `T`.
841        Ok(unsafe { memory.assume_init() })
842    }
843
844    /// Allocates pitched storage and completes a copy of contiguous row-major host values.
845    ///
846    /// # Errors
847    ///
848    /// Returns an error if the source length differs from the logical element count, allocation fails for the reasons `create_uninit` gives, or CUDA cannot copy or synchronize.
849    pub fn from_slice(
850        context: &Arc<Context>,
851        width: usize,
852        height: usize,
853        depth: usize,
854        values: &[T],
855    ) -> Result<Self> {
856        Self::create_uninit(context, width, height, depth)?.initialize_from_host(values)
857    }
858
859    /// Takes ownership of a pitched allocation in `raw.context`.
860    ///
861    /// # Safety
862    ///
863    /// `raw.ptr` must be the base of a live CUDA allocation compatible with `cudaFree`, with no other destruction owner.
864    /// It must contain initialized, valid `T` values at every logical element.
865    /// The pitch and dimensions must describe its storage, and previous accesses must be ordered before future consumers.
866    /// A null pointer is accepted for an empty shape.
867    ///
868    /// # Errors
869    ///
870    /// Returns an error if row or volume size calculations overflow or a nonempty zero-sized element range is requested.
871    /// Returns an error if nonempty storage has a null or misaligned pointer, a pitch smaller than the row width or not aligned for `T`, or an overflowing ending address.
872    pub unsafe fn from_raw(raw: RawPitchedDeviceVolume<T>) -> Result<Self> {
873        let RawPitchedDeviceVolume {
874            ptr,
875            width,
876            height,
877            depth,
878            pitch,
879            context,
880        } = raw;
881        let () = T::LAYOUT;
882        let bytes = checked_pitched_bytes(ptr, width, height, depth, pitch)?;
883        Ok(Self {
884            allocation: DeviceAllocation::from_parts(
885                &context,
886                ptr.cast(),
887                bytes,
888                DeviceDeallocation::Immediate,
889            ),
890            ptr,
891            width,
892            height,
893            depth,
894            pitch,
895            _phantom: PhantomData,
896        })
897    }
898
899    /// Transfers raw ownership, or returns this buffer unchanged if another owner retains it.
900    ///
901    /// The returned pointer must eventually be freed in the returned context.
902    ///
903    /// # Errors
904    ///
905    /// Returns the wrapper unchanged as the error if another owner, submission, graph, or foreign handle retains the allocation.
906    pub fn into_raw(self) -> StdResult<RawPitchedDeviceVolume<T>, Self> {
907        let Self {
908            allocation,
909            ptr,
910            width,
911            height,
912            depth,
913            pitch,
914            _phantom: PhantomData,
915        } = self;
916        match Arc::try_unwrap(allocation) {
917            Ok(mut allocation) => {
918                let context = Arc::clone(allocation.context());
919                allocation.ptr = ptr::null_mut();
920                Ok(RawPitchedDeviceVolume {
921                    ptr,
922                    width,
923                    height,
924                    depth,
925                    pitch,
926                    context,
927                })
928            }
929            Err(allocation) => Err(Self {
930                allocation,
931                ptr,
932                width,
933                height,
934                depth,
935                pitch,
936                _phantom: PhantomData,
937            }),
938        }
939    }
940
941    /// Returns the allocation's retained CUDA context.
942    #[must_use]
943    pub fn context(&self) -> &Arc<Context> {
944        self.allocation.context()
945    }
946
947    /// Returns the shared owner of the physical allocation, including row padding.
948    #[must_use]
949    pub fn allocation(&self) -> &Arc<DeviceAllocation> {
950        &self.allocation
951    }
952
953    /// Reinterprets logical row bytes while preserving pitch, capacity, and allocation identity.
954    ///
955    /// Row padding is excluded from the initialized representation.
956    ///
957    /// # Errors
958    ///
959    /// Returns the allocation unchanged as the error if `U` is zero-sized, its size does not divide the logical row byte width, or nonempty storage has a base pointer or pitch not aligned for `U`.
960    ///
961    /// # Panics
962    ///
963    /// Panics if the logical row byte width overflows `usize`.
964    /// Construction validates this width, so this cannot occur for a valid pitched allocation.
965    pub fn cast<U: AnyBitPatternDeviceRepr>(self) -> StdResult<PitchedDeviceVolume<U>, Self>
966    where
967        T: NoUninitDeviceRepr,
968    {
969        let () = T::LAYOUT;
970        let () = U::LAYOUT;
971        let size = size_of::<U>();
972        let row_bytes = self
973            .row_byte_width()
974            .expect("pitched row byte length overflow");
975        if size == 0
976            || !row_bytes.is_multiple_of(size)
977            || (!self.is_empty()
978                && (!self.ptr.addr().is_multiple_of(align_of::<U>())
979                    || !self.pitch.is_multiple_of(align_of::<U>())))
980        {
981            return Err(self);
982        }
983        Ok(PitchedDeviceVolume {
984            allocation: self.allocation,
985            ptr: self.ptr.cast(),
986            width: row_bytes / size,
987            height: self.height,
988            depth: self.depth,
989            pitch: self.pitch,
990            _phantom: PhantomData,
991        })
992    }
993
994    /// Erases logical element initialization without changing allocation ownership.
995    #[must_use]
996    pub fn into_uninit(self) -> PitchedDeviceVolume<MaybeUninit<T>> {
997        PitchedDeviceVolume {
998            allocation: self.allocation,
999            ptr: self.ptr.cast(),
1000            width: self.width,
1001            height: self.height,
1002            depth: self.depth,
1003            pitch: self.pitch,
1004            _phantom: PhantomData,
1005        }
1006    }
1007
1008    /// Returns the logical row width in elements.
1009    #[must_use]
1010    pub const fn width(&self) -> usize {
1011        self.width
1012    }
1013
1014    /// Returns the logical number of rows per slice.
1015    #[must_use]
1016    pub const fn height(&self) -> usize {
1017        self.height
1018    }
1019
1020    /// Returns the logical number of slices.
1021    #[must_use]
1022    pub const fn depth(&self) -> usize {
1023        self.depth
1024    }
1025
1026    /// Returns the row stride in bytes.
1027    #[must_use]
1028    pub const fn pitch(&self) -> usize {
1029        self.pitch
1030    }
1031
1032    /// Returns the base device pointer.
1033    #[must_use]
1034    pub const fn as_ptr(&self) -> *const T {
1035        self.ptr
1036    }
1037
1038    /// Returns the mutable base device pointer.
1039    pub const fn as_mut_ptr(&mut self) -> *mut T {
1040        self.ptr
1041    }
1042
1043    /// Returns the base pointer as a CUDA device pointer wrapper.
1044    #[must_use]
1045    pub const fn as_device_ptr(&self) -> DevicePtr {
1046        // SAFETY: `self.ptr` is the base of the pitched allocation that `allocation` keeps live, and `DevicePtr` only carries the address.
1047        unsafe { DevicePtr::from_raw(self.ptr.cast()) }
1048    }
1049
1050    /// Returns the logical element count.
1051    ///
1052    /// # Errors
1053    ///
1054    /// Returns an error if `width * height * depth` overflows.
1055    pub fn len(&self) -> Result<usize> {
1056        checked_element_count(&[self.width, self.height, self.depth], "element count")
1057    }
1058
1059    /// Returns the logical row width in bytes.
1060    ///
1061    /// # Errors
1062    ///
1063    /// Returns an error if `width * size_of::<T>()` overflows or `T` is a non-empty zero-sized element type.
1064    pub fn row_byte_width(&self) -> Result<usize> {
1065        checked_bytes::<T>(self.width, "row bytes")
1066    }
1067
1068    /// Returns the physical allocation span described by `pitch * height * depth`.
1069    ///
1070    /// # Errors
1071    ///
1072    /// Returns an error if the byte-volume calculation overflows.
1073    pub fn byte_len(&self) -> Result<usize> {
1074        Ok(self.allocation.byte_len())
1075    }
1076
1077    /// Returns whether any dimension is zero.
1078    #[must_use]
1079    pub fn is_empty(&self) -> bool {
1080        self.width == 0 || self.height == 0 || self.depth == 0
1081    }
1082
1083    /// Returns a CUDA pitched pointer descriptor for this volume.
1084    ///
1085    /// The descriptor suits CUDA's 3D copies and fills.
1086    /// CUDA expects the `xsize` field in bytes for linear memory, so this method reports the typed row width converted to bytes.
1087    #[must_use]
1088    pub fn pitched_ptr(&self) -> runtime::cudaPitchedPtr {
1089        runtime::cudaPitchedPtr {
1090            ptr: self.ptr.cast(),
1091            pitch: self.pitch as _,
1092            xsize: self.row_byte_width().unwrap_or(0) as _,
1093            ysize: self.height as _,
1094        }
1095    }
1096
1097    fn linear_host_ptr(
1098        ptr: *mut T,
1099        width: usize,
1100        height: usize,
1101    ) -> Result<runtime::cudaPitchedPtr> {
1102        let row_bytes = checked_bytes::<T>(width, "row bytes")?;
1103        Ok(runtime::cudaPitchedPtr {
1104            ptr: ptr.cast(),
1105            pitch: row_bytes as _,
1106            xsize: row_bytes as _,
1107            ysize: height as _,
1108        })
1109    }
1110
1111    /// Copies a contiguous host slice into this 3D pitched allocation.
1112    ///
1113    /// `src` must contain exactly `width * height * depth` elements in row-major slice order.
1114    ///
1115    /// # Errors
1116    ///
1117    /// Returns an error if `src` has the wrong length, byte-size arithmetic overflows, or CUDA rejects the 3D copy.
1118    pub fn copy_from_host(&mut self, src: &[T]) -> Result<()> {
1119        let context = Arc::clone(self.context());
1120        let _access = context.acquire_host_access(&[self.region()])?;
1121        self.context().bind()?;
1122        let len = self.len()?;
1123        if src.len() != len {
1124            return Err(Error::length_mismatch("host source", len, src.len()));
1125        }
1126
1127        // SAFETY: `src` holds exactly `width * height * depth` values in a linear layout, construction validated this allocation's pitch and shape, the host access excludes tracked GPU work, and the context is bound.
1128        unsafe {
1129            DeviceMemory::<T>::copy_3d(
1130                self.context(),
1131                self.pitched_ptr(),
1132                Self::linear_host_ptr(src.as_ptr().cast_mut(), self.width, self.height)?,
1133                self.width,
1134                self.height,
1135                self.depth,
1136                MemoryCopyKind::HostToDevice,
1137            )
1138        }?;
1139        StreamBinding::Default(Arc::clone(self.context())).synchronize()
1140    }
1141
1142    /// Copies this 3D pitched allocation into a contiguous host slice.
1143    ///
1144    /// `dst` must contain exactly `width * height * depth` elements and is filled in row-major slice order.
1145    ///
1146    /// # Errors
1147    ///
1148    /// Returns an error if `dst` has the wrong length, byte-size arithmetic overflows, or CUDA rejects the 3D copy.
1149    pub fn copy_to_host(&self, dst: &mut [T]) -> Result<()>
1150    where
1151        T: AnyBitPatternDeviceRepr,
1152    {
1153        let () = T::LAYOUT;
1154        // SAFETY: `T: AnyBitPatternDeviceRepr`, so any device bytes are valid `T` values.
1155        unsafe { self.copy_to_host_unchecked(dst) }
1156    }
1157
1158    /// Copies device values whose validity is established by the producing kernel.
1159    ///
1160    /// # Safety
1161    ///
1162    /// Every copied element must be initialized and valid for `T`.
1163    ///
1164    /// # Errors
1165    ///
1166    /// Returns an error if the destination length differs from the logical element count, transfer size calculations overflow, access tracking fails, the context cannot be bound, or CUDA cannot copy or synchronize.
1167    pub unsafe fn copy_to_host_unchecked(&self, dst: &mut [T]) -> Result<()> {
1168        let context = Arc::clone(self.context());
1169        let _access = context.acquire_host_access(&[self.region()])?;
1170        self.context().bind()?;
1171        let len = self.len()?;
1172        if dst.len() != len {
1173            return Err(Error::length_mismatch("host destination", len, dst.len()));
1174        }
1175
1176        // SAFETY: `dst` holds exactly `width * height * depth` writable values in a linear layout, the host access waited for tracked GPU work, and the caller guarantees the copied elements are valid `T` values.
1177        unsafe {
1178            DeviceMemory::<T>::copy_3d(
1179                self.context(),
1180                Self::linear_host_ptr(dst.as_mut_ptr(), self.width, self.height)?,
1181                self.pitched_ptr(),
1182                self.width,
1183                self.height,
1184                self.depth,
1185                MemoryCopyKind::DeviceToHost,
1186            )
1187        }?;
1188        StreamBinding::Default(Arc::clone(self.context())).synchronize()
1189    }
1190
1191    /// Copies another 3D pitched allocation with the same shape into this one.
1192    ///
1193    /// # Errors
1194    ///
1195    /// Returns an error if the shapes differ, byte-size arithmetic overflows, or CUDA rejects the device-to-device 3D copy.
1196    pub fn copy_from_volume(&mut self, src: &Self) -> Result<()> {
1197        self.context().bind()?;
1198        if self.context() != src.context() {
1199            return Err(Error::MemoryContextMismatch);
1200        }
1201
1202        if self.width != src.width {
1203            return Err(Error::length_mismatch(
1204                "source width",
1205                self.width,
1206                src.width,
1207            ));
1208        }
1209
1210        if self.height != src.height {
1211            return Err(Error::length_mismatch(
1212                "source height",
1213                self.height,
1214                src.height,
1215            ));
1216        }
1217
1218        if self.depth != src.depth {
1219            return Err(Error::length_mismatch(
1220                "source depth",
1221                self.depth,
1222                src.depth,
1223            ));
1224        }
1225
1226        // SAFETY: both volumes are in this bound context and have the same validated width, height, and depth, so the copy stays inside both, and `&mut self` excludes aliasing with `src`.
1227        unsafe {
1228            DeviceMemory::<T>::copy_3d(
1229                self.context(),
1230                self.pitched_ptr(),
1231                src.pitched_ptr(),
1232                self.width,
1233                self.height,
1234                self.depth,
1235                MemoryCopyKind::DeviceToDevice,
1236            )
1237        }?;
1238        StreamBinding::Default(Arc::clone(self.context())).synchronize()
1239    }
1240
1241    /// Enqueues a host-to-device 3D copy from a contiguous host slice.
1242    ///
1243    /// `src` must remain valid until `stream` reaches the copy.
1244    /// The [`StreamScope`] lifetime enforces that requirement for safe callers.
1245    ///
1246    /// # Errors
1247    ///
1248    /// Returns an error if `src` has the wrong length, byte-size arithmetic overflows, or CUDA cannot enqueue the copy.
1249    pub fn copy_from_host_scoped<'env>(
1250        &'env mut self,
1251        src: &'env [T],
1252        stream: &StreamScope<'_, 'env>,
1253    ) -> Result<()> {
1254        let accesses = [Access::new(self.region(), AccessMode::Write)];
1255        if self.context() != stream.stream().context() {
1256            return Err(Error::StreamContextMismatch);
1257        }
1258
1259        self.context().bind()?;
1260        let len = self.len()?;
1261        if src.len() != len {
1262            return Err(Error::length_mismatch("host source", len, src.len()));
1263        }
1264
1265        let host = Self::linear_host_ptr(src.as_ptr().cast_mut(), self.width, self.height)?;
1266        checked_element_count(
1267            &[self.row_byte_width()?, self.height, self.depth],
1268            "logical bytes",
1269        )?;
1270        // SAFETY: `src` holds exactly the logical element count, the `'env` borrows keep it and this volume live until the scope drains, the declared write orders tracked work, and the contexts match.
1271        unsafe {
1272            stream.enqueue(&accesses, || {
1273                DeviceMemory::<T>::copy_3d_async(
1274                    self.pitched_ptr(),
1275                    host,
1276                    self.width,
1277                    self.height,
1278                    self.depth,
1279                    MemoryCopyKind::HostToDevice,
1280                    stream.stream(),
1281                )
1282            })
1283        }
1284    }
1285
1286    /// Enqueues a device-to-host 3D copy into a contiguous host slice.
1287    ///
1288    /// `dst` must remain valid until `stream` reaches the copy.
1289    /// The [`StreamScope`] lifetime enforces that requirement for safe callers.
1290    ///
1291    /// # Errors
1292    ///
1293    /// Returns an error if `dst` has the wrong length, byte-size arithmetic overflows, or CUDA cannot enqueue the copy.
1294    pub fn copy_to_host_scoped<'env>(
1295        &'env self,
1296        dst: &'env mut [T],
1297        stream: &StreamScope<'_, 'env>,
1298    ) -> Result<()>
1299    where
1300        T: AnyBitPatternDeviceRepr,
1301    {
1302        let accesses = [Access::new(self.region(), AccessMode::Read)];
1303        if self.context() != stream.stream().context() {
1304            return Err(Error::StreamContextMismatch);
1305        }
1306
1307        self.context().bind()?;
1308        let () = T::LAYOUT;
1309        let len = self.len()?;
1310        if dst.len() != len {
1311            return Err(Error::length_mismatch("host destination", len, dst.len()));
1312        }
1313
1314        let host = Self::linear_host_ptr(dst.as_mut_ptr(), self.width, self.height)?;
1315        checked_element_count(
1316            &[self.row_byte_width()?, self.height, self.depth],
1317            "logical bytes",
1318        )?;
1319        // SAFETY: `dst` holds exactly the logical element count, the `'env` borrows keep it and this volume live until the scope drains, the declared read orders tracked work, and `T: AnyBitPatternDeviceRepr` makes any copied bytes valid.
1320        unsafe {
1321            stream.enqueue(&accesses, || {
1322                DeviceMemory::<T>::copy_3d_async(
1323                    host,
1324                    self.pitched_ptr(),
1325                    self.width,
1326                    self.height,
1327                    self.depth,
1328                    MemoryCopyKind::DeviceToHost,
1329                    stream.stream(),
1330                )
1331            })
1332        }
1333    }
1334
1335    /// Fills this 3D pitched allocation with zero bytes.
1336    ///
1337    /// # Errors
1338    ///
1339    /// Returns an error if CUDA rejects the 3D memset.
1340    pub fn set_zeroes(&mut self) -> Result<()>
1341    where
1342        T: ZeroableDeviceRepr,
1343    {
1344        // SAFETY: `T: ZeroableDeviceRepr`, so all-zero bytes are a valid `T`.
1345        unsafe { self.set_value_unchecked(0) }
1346    }
1347
1348    /// Fills this 3D pitched allocation with `value` bytes.
1349    ///
1350    /// # Errors
1351    ///
1352    /// Returns an error if CUDA rejects the 3D memset.
1353    pub fn set_value(&mut self, value: u8) -> Result<()>
1354    where
1355        T: AnyBitPatternDeviceRepr,
1356    {
1357        let () = T::LAYOUT;
1358        // SAFETY: `T: AnyBitPatternDeviceRepr`, so repeating `value` produces valid `T` values.
1359        unsafe { self.set_value_unchecked(value) }
1360    }
1361
1362    /// Fills storage with a byte pattern known to be valid for `T`.
1363    ///
1364    /// # Safety
1365    ///
1366    /// The repeated byte pattern must represent a valid value of `T`.
1367    ///
1368    /// # Errors
1369    ///
1370    /// Returns an error if access tracking fails, the context cannot be bound, the transfer size overflows, or CUDA cannot fill the memory or synchronize the default stream.
1371    pub unsafe fn set_value_unchecked(&mut self, value: u8) -> Result<()> {
1372        let context = Arc::clone(self.context());
1373        let _access = context.acquire_host_access(&[self.region()])?;
1374        self.context().bind()?;
1375        // SAFETY: the validated pitch and shape keep the fill inside the volume, the host access excludes tracked GPU work, and the caller guarantees the repeated byte is a valid `T` pattern.
1376        unsafe {
1377            DeviceMemory::<T>::set_3d(
1378                self.context(),
1379                self.pitched_ptr(),
1380                value,
1381                self.width,
1382                self.height,
1383                self.depth,
1384            )
1385        }?;
1386        StreamBinding::Default(Arc::clone(self.context())).synchronize()
1387    }
1388
1389    /// Enqueues a byte fill of this 3D pitched allocation on `stream`.
1390    ///
1391    /// # Errors
1392    ///
1393    /// Returns an error if CUDA cannot enqueue the 3D memset.
1394    pub fn set_value_scoped<'env>(
1395        &'env mut self,
1396        value: u8,
1397        stream: &StreamScope<'_, 'env>,
1398    ) -> Result<()>
1399    where
1400        T: AnyBitPatternDeviceRepr,
1401    {
1402        let accesses = [Access::new(self.region(), AccessMode::Write)];
1403        if self.context() != stream.stream().context() {
1404            return Err(Error::StreamContextMismatch);
1405        }
1406
1407        self.context().bind()?;
1408        let () = T::LAYOUT;
1409        checked_element_count(
1410            &[self.row_byte_width()?, self.height, self.depth],
1411            "logical bytes",
1412        )?;
1413        // SAFETY: the `'env` borrow keeps this volume live until the scope drains, the declared write orders tracked work, the contexts match, and `T: AnyBitPatternDeviceRepr` makes any repeated byte valid.
1414        unsafe {
1415            stream.enqueue(&accesses, || {
1416                DeviceMemory::<T>::set_3d_async(
1417                    self.pitched_ptr(),
1418                    value,
1419                    self.width,
1420                    self.height,
1421                    self.depth,
1422                    stream.stream(),
1423                )
1424            })
1425        }
1426    }
1427
1428    fn row_region(&self, slice: usize, row: usize) -> Result<DeviceRegion<'_>> {
1429        if slice >= self.depth {
1430            return Err(Error::out_of_range("slice"));
1431        }
1432
1433        if row >= self.height {
1434            return Err(Error::out_of_range("row"));
1435        }
1436
1437        if self.width == 0 {
1438            return self.region().slice(0..0);
1439        }
1440
1441        let start = slice
1442            .checked_mul(self.height)
1443            .and_then(|offset| offset.checked_add(row))
1444            .and_then(|offset| offset.checked_mul(self.pitch))
1445            .ok_or_else(|| Error::out_of_range("row offset"))?;
1446        let end = start
1447            .checked_add(self.row_byte_width()?)
1448            .ok_or_else(|| Error::out_of_range("row end"))?;
1449        self.region().slice(start..end)
1450    }
1451
1452    /// Borrows one initialized logical row, excluding CUDA's row padding.
1453    ///
1454    /// # Errors
1455    ///
1456    /// Returns an error if the slice or row index is out of bounds, row offset calculations overflow, or the resulting range fails byte-length or alignment validation.
1457    pub fn row(&self, slice: usize, row: usize) -> Result<DeviceView<'_, T>> {
1458        // SAFETY: a `T`-typed pitched owner only exists once every logical element is initialized, and the row region excludes the padding.
1459        unsafe { DeviceView::from_raw_parts(self.row_region(slice, row)?, self.width) }
1460    }
1461
1462    /// Exclusively borrows one logical row, excluding CUDA's row padding.
1463    ///
1464    /// # Errors
1465    ///
1466    /// Returns an error if the slice or row index is out of bounds, row offset calculations overflow, or the resulting range fails byte-length or alignment validation.
1467    pub fn row_mut(&mut self, slice: usize, row: usize) -> Result<DeviceViewMut<'_, T>> {
1468        // SAFETY: the row region excludes the padding and holds initialized `T` values, and `&mut self` makes the view the only access to them.
1469        unsafe { DeviceViewMut::from_raw_parts(self.row_region(slice, row)?, self.width) }
1470    }
1471}
1472
1473impl<T: DeviceRepr> PitchedDeviceVolume<MaybeUninit<T>> {
1474    /// Copies every logical element from host values and completes before promotion.
1475    ///
1476    /// # Errors
1477    ///
1478    /// Returns an error if the source length differs from the logical element count, transfer size calculations overflow, the context cannot be bound, or CUDA cannot copy or synchronize.
1479    pub fn initialize_from_host(self, values: &[T]) -> Result<PitchedDeviceVolume<T>> {
1480        let len = self.len()?;
1481        if values.len() != len {
1482            return Err(Error::length_mismatch("host values", len, values.len()));
1483        }
1484
1485        self.context().bind()?;
1486        let row_bytes = self.row_byte_width()?;
1487        let source = runtime::cudaPitchedPtr {
1488            ptr: values.as_ptr().cast_mut().cast(),
1489            pitch: row_bytes as _,
1490            xsize: row_bytes as _,
1491            ysize: self.height as _,
1492        };
1493        // SAFETY: `values` holds exactly `width * height * depth` values in a linear layout, the validated pitch and shape make the volume writable throughout, `self` is owned so nothing else accesses it, and the context is bound.
1494        unsafe {
1495            DeviceMemory::<T>::copy_3d(
1496                self.context(),
1497                self.pitched_ptr(),
1498                source,
1499                self.width,
1500                self.height,
1501                self.depth,
1502                MemoryCopyKind::HostToDevice,
1503            )?;
1504        }
1505
1506        StreamBinding::Default(Arc::clone(self.context())).synchronize()?;
1507        // SAFETY: the synchronized copy wrote every logical element from initialized host values of `T`.
1508        Ok(unsafe { self.assume_init() })
1509    }
1510
1511    /// Marks all logical elements initialized without changing the owner or pitch.
1512    ///
1513    /// # Safety
1514    ///
1515    /// Every logical element must contain an initialized valid `T` value.
1516    /// Producers must be ordered before subsequent consumers and complete before host readback.
1517    /// Row padding remains uninitialized.
1518    #[must_use]
1519    pub unsafe fn assume_init(self) -> PitchedDeviceVolume<T> {
1520        let () = T::LAYOUT;
1521        PitchedDeviceVolume {
1522            allocation: self.allocation,
1523            ptr: self.ptr.cast(),
1524            width: self.width,
1525            height: self.height,
1526            depth: self.depth,
1527            pitch: self.pitch,
1528            _phantom: PhantomData,
1529        }
1530    }
1531}
1532
1533/// Raw ownership of a pitched two-dimensional allocation and its context.
1534///
1535/// Free `ptr` while `context` is alive, or re-adopt the value with [`PitchedDeviceMemory::from_raw`].
1536#[derive(Debug)]
1537pub struct RawPitchedDeviceMemory<T> {
1538    /// Base of the allocation, or null for an empty shape.
1539    pub ptr: *mut T,
1540    /// Row width in elements.
1541    pub width: usize,
1542    /// Number of rows.
1543    pub height: usize,
1544    /// Byte stride between rows.
1545    pub pitch: usize,
1546    /// Context the allocation belongs to.
1547    pub context: Arc<Context>,
1548}
1549
1550/// Raw ownership of a pitched three-dimensional allocation and its context.
1551///
1552/// Free `ptr` while `context` is alive, or re-adopt the value with [`PitchedDeviceVolume::from_raw`].
1553#[derive(Debug)]
1554pub struct RawPitchedDeviceVolume<T> {
1555    /// Base of the allocation, or null for an empty shape.
1556    pub ptr: *mut T,
1557    /// Row width in elements.
1558    pub width: usize,
1559    /// Number of rows per slice.
1560    pub height: usize,
1561    /// Number of slices.
1562    pub depth: usize,
1563    /// Byte stride between rows.
1564    pub pitch: usize,
1565    /// Context the allocation belongs to.
1566    pub context: Arc<Context>,
1567}
1568
1569/// Owned 2D pitched CUDA device memory.
1570///
1571/// The logical dimensions are expressed in elements of `T`; the CUDA pitch is stored as a byte stride between rows.
1572#[derive(Debug)]
1573pub struct PitchedDeviceMemory<T: DeviceRepr> {
1574    allocation: Arc<DeviceAllocation>,
1575    ptr: *mut T,
1576    width: usize,
1577    height: usize,
1578    pitch: usize,
1579    _phantom: PhantomData<T>,
1580}
1581
1582/// Owned 3D pitched CUDA device memory.
1583///
1584/// The logical dimensions are expressed in elements of `T`; the CUDA pitch is stored as a byte stride between rows inside each slice.
1585#[derive(Debug)]
1586pub struct PitchedDeviceVolume<T: DeviceRepr> {
1587    allocation: Arc<DeviceAllocation>,
1588    ptr: *mut T,
1589    width: usize,
1590    height: usize,
1591    depth: usize,
1592    pitch: usize,
1593    _phantom: PhantomData<T>,
1594}
1595
1596// SAFETY: the volume owns its whole retained allocation, so the allocation's region describes its pointers.
1597unsafe impl<T: DeviceRepr> DeviceRegionProvider for PitchedDeviceVolume<T> {
1598    fn region(&self) -> DeviceRegion<'_> {
1599        self.allocation.region()
1600    }
1601}
1602
1603// SAFETY: the host never dereferences `ptr`, the owner holds `T` values like a `Vec<T>`, and every operation binds the retained context.
1604unsafe impl<T: DeviceRepr + Send> Send for PitchedDeviceVolume<T> {}
1605
1606// SAFETY: `&PitchedDeviceVolume<T>` exposes only device pointers and metadata, and device writes need `&mut` or an unsafe raw API.
1607unsafe impl<T: DeviceRepr + Sync> Sync for PitchedDeviceVolume<T> {}