Skip to main content

singe_cuda/memory/device/
mod.rs

1mod copy;
2mod raw;
3
4use std::{
5    marker::PhantomData,
6    mem::{MaybeUninit, replace},
7    ptr,
8    result::Result as StdResult,
9    sync::Arc,
10};
11
12use singe_cuda_sys::runtime;
13
14use crate::{
15    context::Context,
16    error::{Error, Result},
17    ipc::IpcMemoryHandle,
18    memory::{DeviceAllocation, DeviceDeallocation, MemoryCopyKind, StreamOrderedFree, transfer},
19    stream::{AsStream, Stream, StreamBinding, StreamScope},
20    submission::{Access, AccessMode},
21    try_ffi,
22    types::DevicePtr,
23    utility::checked_bytes,
24    view::{
25        AllocationId, AnyBitPatternDeviceRepr, DeviceOutput, DeviceRange, DeviceRegion,
26        DeviceRegionProvider, DeviceRepr, NoUninitDeviceRepr, ZeroableDeviceRepr, cast_length,
27    },
28};
29
30impl<T> DeviceMemory<T> {
31    /// Takes ownership of an existing device allocation.
32    ///
33    /// # Safety
34    ///
35    /// `raw.ptr` must be null for an empty allocation or point to `raw.len` live elements of `raw.context`.
36    /// Without `raw.stream_ordered`, the allocation must be valid to free with `cudaFree`; with it, it must come from `cudaMallocAsync` or `cudaMallocFromPoolAsync` and be valid to free on its stream.
37    /// No other owner may free the pointer while the returned value is alive, and all elements must be initialized before they are read.
38    ///
39    /// # Errors
40    ///
41    /// Returns an error if the byte count overflows, a nonempty zero-sized allocation is described, or a nonempty allocation has a null pointer.
42    /// Returns `Error::StreamContextMismatch` if the freeing stream belongs to another context.
43    pub unsafe fn from_raw(raw: RawDeviceMemory<T>) -> Result<Self> {
44        let RawDeviceMemory {
45            ptr,
46            len,
47            context,
48            stream_ordered,
49        } = raw;
50        let bytes = checked_bytes::<T>(len, "byte length")?;
51        if bytes != 0 && ptr.is_null() {
52            return Err(Error::null_pointer("device memory"));
53        }
54
55        let deallocation = match stream_ordered {
56            None => DeviceDeallocation::Immediate,
57            Some(StreamOrderedFree { stream, pool }) => {
58                if stream.context() != &context {
59                    return Err(Error::StreamContextMismatch);
60                }
61
62                DeviceDeallocation::StreamOrdered { stream, pool }
63            }
64        };
65        Ok(Self {
66            allocation: DeviceAllocation::from_parts(&context, ptr.cast(), bytes, deallocation),
67            ptr,
68            length: len,
69            _phantom: PhantomData,
70        })
71    }
72
73    /// Transfers ownership to the caller when no other allocation owners remain.
74    ///
75    /// On success the caller owns the pointer and must retain the returned context until the allocation is freed.
76    ///
77    /// # Errors
78    ///
79    /// Returns the original wrapper if another owner, submission, graph, or foreign handle retains the allocation.
80    pub fn into_raw(self) -> StdResult<RawDeviceMemory<T>, Self> {
81        let Self {
82            allocation,
83            ptr,
84            length,
85            ..
86        } = self;
87        match Arc::try_unwrap(allocation) {
88            Ok(mut allocation) => {
89                let context = Arc::clone(allocation.context());
90                allocation.ptr = ptr::null_mut();
91                let stream_ordered =
92                    match replace(&mut allocation.deallocation, DeviceDeallocation::Immediate) {
93                        DeviceDeallocation::Immediate => None,
94                        DeviceDeallocation::StreamOrdered { stream, pool } => {
95                            Some(StreamOrderedFree { stream, pool })
96                        }
97                    };
98                Ok(RawDeviceMemory {
99                    ptr,
100                    len: length,
101                    context,
102                    stream_ordered,
103                })
104            }
105            Err(allocation) => Err(Self {
106                allocation,
107                ptr,
108                length,
109                _phantom: PhantomData,
110            }),
111        }
112    }
113
114    /// Erases initialization guarantees while preserving the allocation and its context.
115    #[must_use]
116    pub fn into_uninit(self) -> DeviceMemory<MaybeUninit<T>> {
117        let Self {
118            allocation,
119            ptr,
120            length,
121            ..
122        } = self;
123        DeviceMemory {
124            allocation,
125            ptr: ptr.cast(),
126            length,
127            _phantom: PhantomData,
128        }
129    }
130
131    /// Allocates uninitialized device storage while retaining its context.
132    ///
133    /// Write every element, then call [`DeviceMemory::assume_init`] to expose them as `T`.
134    ///
135    /// # Errors
136    ///
137    /// Returns an error if the byte count overflows, a nonempty zero-sized allocation is requested, context binding fails, or CUDA cannot allocate device memory.
138    pub fn create_uninit(
139        context: &Arc<Context>,
140        length: usize,
141    ) -> Result<DeviceMemory<MaybeUninit<T>>>
142    where
143        T: DeviceRepr,
144    {
145        let () = T::LAYOUT;
146        DeviceMemory::<MaybeUninit<T>>::allocate(context, length)
147    }
148
149    /// Allocates device memory and completes zero initialization before returning.
150    ///
151    /// # Errors
152    ///
153    /// Propagates allocation, byte-size, access-tracking, context-binding, CUDA fill, and default-stream synchronization errors.
154    pub fn zeroed(context: &Arc<Context>, length: usize) -> Result<Self>
155    where
156        T: ZeroableDeviceRepr,
157    {
158        let mut memory = Self::create_uninit(context, length)?;
159        memory.set_zeroes()?;
160        // SAFETY: `set_zeroes` completed a zero fill of every element, and an all-zero `T` is valid.
161        Ok(unsafe { memory.assume_init() })
162    }
163
164    /// Allocates device storage and completes its repeated byte fill before returning.
165    ///
166    /// # Errors
167    ///
168    /// Propagates allocation, byte-size, access-tracking, context-binding, CUDA fill, and default-stream synchronization errors.
169    pub fn filled(context: &Arc<Context>, length: usize, value: u8) -> Result<Self>
170    where
171        T: AnyBitPatternDeviceRepr,
172    {
173        let mut memory = Self::create_uninit(context, length)?;
174        memory.set_value(value)?;
175        // SAFETY: `set_value` completed a fill of every element, and every bit pattern is a valid `T`.
176        Ok(unsafe { memory.assume_init() })
177    }
178
179    /// Allocates device memory and completes the upload before returning.
180    ///
181    /// # Errors
182    ///
183    /// Propagates allocation, byte-size, context-binding, stream-capture, CUDA copy, and stream synchronization errors.
184    /// A nonempty synchronous transfer is rejected during stream capture.
185    pub fn from_slice(context: &Arc<Context>, v: &[T]) -> Result<Self>
186    where
187        T: DeviceRepr,
188    {
189        let () = T::LAYOUT;
190        // SAFETY: `T: DeviceRepr`, so copying the initialized host values yields valid device values.
191        unsafe { Self::from_slice_unchecked(context, v) }
192    }
193
194    /// Uploads values with an externally established device ABI.
195    ///
196    /// This supports vendor ABI descriptors whose padding or embedded device addresses are not modeled by `DeviceRepr`.
197    ///
198    /// # Safety
199    ///
200    /// `T` must match the device ABI and must not transfer Rust ownership or host references.
201    /// Embedded addresses must remain valid for every operation that consumes the uploaded descriptors.
202    ///
203    /// # Errors
204    ///
205    /// Propagates allocation, byte-size, context-binding, stream-capture, CUDA copy, and stream synchronization errors.
206    /// A nonempty synchronous transfer is rejected during stream capture.
207    pub unsafe fn from_slice_unchecked(context: &Arc<Context>, v: &[T]) -> Result<Self> {
208        let memory = DeviceMemory::<MaybeUninit<T>>::allocate(context, v.len())?;
209        if !v.is_empty() {
210            // SAFETY: `memory` holds `v.len()` fresh elements, `v` is a live host slice of that length, and the caller vouches for `T`'s device ABI.
211            unsafe {
212                transfer::copy_synchronous(
213                    memory.ptr.cast::<T>(),
214                    v.as_ptr(),
215                    v.len(),
216                    MemoryCopyKind::HostToDevice,
217                    None,
218                )?;
219            }
220        }
221        // SAFETY: the completed copy wrote every element from `v`.
222        Ok(unsafe { memory.assume_init() })
223    }
224
225    /// Allocates device memory and enqueues an upload of `v` on `stream`.
226    ///
227    /// # Safety
228    ///
229    /// The caller must ensure `v` remains valid and unmodified until `stream` has completed the transfer.
230    /// The uploaded values must match the device ABI without transferring Rust ownership or host references.
231    ///
232    /// # Errors
233    ///
234    /// Returns an error if CUDA cannot allocate device memory or enqueue the host-to-device copy.
235    pub unsafe fn from_slice_async(v: &[T], stream: &Stream) -> Result<Self> {
236        let memory = DeviceMemory::<MaybeUninit<T>>::allocate(stream.context(), v.len())?;
237        // SAFETY: the copy enqueued below initializes every element before `stream` runs any later consumer, and a failed enqueue drops the memory unread.
238        let mut mem = unsafe { memory.assume_init() };
239        // SAFETY: the caller keeps `v` live and unmodified until `stream` completes, and `mem` lives in the returned owner.
240        unsafe {
241            mem.copy_from_host_async(v, stream)?;
242        }
243        Ok(mem)
244    }
245
246    /// Returns the number of elements in the logical allocation range.
247    #[must_use]
248    pub const fn len(&self) -> usize {
249        self.length
250    }
251
252    /// Returns whether the logical allocation range contains no elements.
253    #[must_use]
254    pub const fn is_empty(&self) -> bool {
255        self.length == 0
256    }
257
258    /// Returns the size of the logical allocation range in bytes.
259    ///
260    /// # Panics
261    ///
262    /// Panics if the element count multiplied by the element size overflows `usize`.
263    /// Allocation construction validates this size, so this condition cannot occur for a valid allocation.
264    #[must_use]
265    pub fn byte_len(&self) -> usize {
266        checked_bytes::<T>(self.length, "byte length").expect("device memory byte length overflow")
267    }
268
269    /// Returns the allocation’s CUDA-accessible element pointer without synchronizing pending work.
270    #[must_use]
271    pub const fn as_ptr(&self) -> *const T {
272        self.ptr
273    }
274
275    /// Returns the allocation’s CUDA-accessible mutable element pointer.
276    ///
277    /// The pointer does not establish execution ordering or permit conflicting accesses.
278    #[must_use]
279    pub const fn as_mut_ptr(&self) -> *mut T {
280        self.ptr
281    }
282
283    /// Returns the allocation’s address as an untyped CUDA device pointer.
284    #[must_use]
285    pub const fn as_device_ptr(&self) -> DevicePtr {
286        // SAFETY: `ptr` is this live allocation's base or null, and `DevicePtr` only records the address.
287        unsafe { DevicePtr::from_raw(self.ptr.cast()) }
288    }
289
290    /// Returns the context that owns this allocation.
291    #[must_use]
292    pub fn context(&self) -> &Arc<Context> {
293        self.allocation.context()
294    }
295
296    /// Returns the shared owner retained by asynchronous submissions and interop users.
297    #[must_use]
298    pub fn allocation(&self) -> &Arc<DeviceAllocation> {
299        &self.allocation
300    }
301
302    /// Preserves allocation ownership while exposing initialized representation bytes.
303    #[must_use]
304    pub fn into_bytes(self) -> DeviceMemory<u8>
305    where
306        T: NoUninitDeviceRepr,
307    {
308        let () = T::LAYOUT;
309        let length = self.byte_len();
310        DeviceMemory {
311            allocation: self.allocation,
312            ptr: self.ptr.cast(),
313            length,
314            _phantom: PhantomData,
315        }
316    }
317
318    /// Reinterprets initialized storage without reallocating it.
319    ///
320    /// Returns the original buffer if alignment or byte length is incompatible.
321    /// The original allocation owner and deallocation metadata are preserved.
322    ///
323    /// # Errors
324    ///
325    /// Returns the original allocation if `U` is zero-sized, its size does not divide the exposed byte length, or a nonempty range is not aligned for `U`.
326    pub fn cast<U: AnyBitPatternDeviceRepr>(self) -> StdResult<DeviceMemory<U>, Self>
327    where
328        T: NoUninitDeviceRepr,
329    {
330        let () = T::LAYOUT;
331        let Ok(length) = cast_length::<U>(self.region()) else {
332            return Err(self);
333        };
334        Ok(DeviceMemory {
335            allocation: self.allocation,
336            ptr: self.ptr.cast(),
337            length,
338            _phantom: PhantomData,
339        })
340    }
341
342    fn bind(&self) -> Result<()> {
343        self.context().bind()
344    }
345
346    fn bind_stream(&self, stream: &Stream) -> Result<()> {
347        if self.context() != stream.context() {
348            return Err(Error::StreamContextMismatch);
349        }
350        self.bind()
351    }
352
353    /// Fills every element with zero bytes and waits for completion.
354    ///
355    /// # Errors
356    ///
357    /// Propagates access-tracking, context-binding, byte-size, CUDA fill, and default-stream synchronization errors.
358    pub fn set_zeroes(&mut self) -> Result<()>
359    where
360        T: ZeroableDeviceRepr,
361    {
362        let context = Arc::clone(self.context());
363        let _access = context.acquire_host_access(&[self.region()])?;
364        self.bind()?;
365        let () = T::LAYOUT;
366        if self.length == 0 {
367            return Ok(());
368        }
369
370        // SAFETY: the host access guard excludes other work on the `length` owned elements, and `T: ZeroableDeviceRepr` makes the zero fill valid.
371        unsafe {
372            Self::set(self.context(), self.ptr, 0, self.length)?;
373        }
374        StreamBinding::Default(Arc::clone(self.context())).synchronize()
375    }
376
377    /// Fills every byte of the allocation with `value` and waits for completion.
378    ///
379    /// The byte pattern repeats across each element; `value` is not converted to `T`.
380    ///
381    /// # Errors
382    ///
383    /// Propagates access-tracking, context-binding, byte-size, CUDA fill, and default-stream synchronization errors.
384    pub fn set_value(&mut self, value: u8) -> Result<()>
385    where
386        T: AnyBitPatternDeviceRepr,
387    {
388        let () = T::LAYOUT;
389        // SAFETY: `T: AnyBitPatternDeviceRepr`, so repeating `value` produces valid `T` values.
390        unsafe { self.set_value_unchecked(value) }
391    }
392
393    /// Fills storage with a byte pattern known to be valid for `T`.
394    ///
395    /// # Safety
396    ///
397    /// The repeated byte pattern must represent a valid value of `T`.
398    ///
399    /// # Errors
400    ///
401    /// Propagates access-tracking, context-binding, byte-size, CUDA fill, and default-stream synchronization errors.
402    pub unsafe fn set_value_unchecked(&mut self, value: u8) -> Result<()> {
403        let context = Arc::clone(self.context());
404        let _access = context.acquire_host_access(&[self.region()])?;
405        self.bind()?;
406        if self.length == 0 {
407            return Ok(());
408        }
409
410        // SAFETY: the host access guard excludes other work on the `length` owned elements, and the caller vouches for the byte pattern.
411        unsafe {
412            Self::set(self.context(), self.ptr, value, self.length)?;
413        }
414        StreamBinding::Default(Arc::clone(self.context())).synchronize()
415    }
416
417    /// Enqueues a repeated-byte fill of the entire allocation in a stream scope.
418    ///
419    /// The scope retains the exclusive allocation borrow until the fill completes.
420    ///
421    /// # Errors
422    ///
423    /// Returns an error if the byte count overflows or the scope’s stream belongs to another context.
424    /// Also propagates context-binding, scope submission, and CUDA fill errors.
425    pub fn set_value_scoped<'env>(
426        &'env mut self,
427        value: u8,
428        stream: &StreamScope<'_, 'env>,
429    ) -> Result<()>
430    where
431        T: AnyBitPatternDeviceRepr,
432    {
433        let () = T::LAYOUT;
434
435        checked_bytes::<T>(self.len(), "byte length")?;
436        self.bind_stream(stream.stream())?;
437        if self.is_empty() {
438            return Ok(());
439        }
440
441        let accesses = [Access::new(self.region(), AccessMode::Write)];
442        // SAFETY: the declared accesses retain both regions, and the stream orders every access to them.
443        unsafe {
444            stream.enqueue(&accesses, || {
445                Self::set_async(self.ptr, value, self.len(), stream.stream())
446            })
447        }
448    }
449
450    /// Enqueues a repeated-byte fill of this allocation on `stream`, ordered after the allocation's producer.
451    ///
452    /// # Safety
453    ///
454    /// The caller must ensure `self` remains valid until `stream` has completed the memset.
455    ///
456    /// # Errors
457    ///
458    /// Returns an error if the stream belongs to another context, producer ordering fails, or CUDA cannot enqueue the memset on `stream`.
459    pub unsafe fn set_value_async(&mut self, value: u8, stream: &Stream) -> Result<()>
460    where
461        T: AnyBitPatternDeviceRepr,
462    {
463        let () = T::LAYOUT;
464
465        self.bind_stream(stream)?;
466        if self.is_empty() {
467            return Ok(());
468        }
469
470        stream.join_regions(&[self.region()])?;
471        // SAFETY: the stream shares this allocation's context and is ordered after its producer, every byte pattern is a valid `T`, and the caller keeps the allocation valid until `stream` completes the fill.
472        unsafe { Self::set_async(self.as_mut_ptr(), value, self.len(), stream) }
473    }
474
475    /// Takes a pointer to the base of an existing device memory allocation created with [`DeviceMemory::alloc`] and exports it for use in another process.
476    /// This is a lightweight operation and may be called multiple times on an allocation without adverse effects.
477    ///
478    /// If a region of memory is freed with [`DeviceMemory::free`] and a subsequent call to [`DeviceMemory::alloc`] returns memory with the same device address, [`DeviceMemory::ipc_handle`] returns a unique handle for the new memory.
479    ///
480    /// IPC is restricted to devices with unified-addressing support on Linux and Windows.
481    /// IPC on Windows is supported for compatibility but is not recommended because of its performance cost.
482    /// Check device IPC support through the device properties exposed by this crate, for example [`DeviceProperties::ipc_event_supported`](crate::device::DeviceProperties::ipc_event_supported).
483    ///
484    /// # Errors
485    ///
486    /// Returns an error if the allocation is empty, CUDA cannot export an IPC handle for the allocation, or CUDA reports runtime initialization diagnostics.
487    pub fn ipc_handle(&self) -> Result<IpcMemoryHandle> {
488        self.bind()?;
489        if self.is_empty() {
490            // An empty allocation has no base address for CUDA to export.
491            return Err(Error::empty("device allocation"));
492        }
493
494        let mut handle = MaybeUninit::uninit();
495        // SAFETY: `handle` is a local output, the allocation is live and nonempty, and success initializes the handle.
496        unsafe {
497            try_ffi!(runtime::cudaIpcGetMemHandle(
498                handle.as_mut_ptr(),
499                self.as_ptr().cast_mut().cast(),
500            ))?;
501            Ok(IpcMemoryHandle::from_raw(handle.assume_init()))
502        }
503    }
504
505    /// Allocates independent device storage and copies all elements into it.
506    ///
507    /// Returns after the device-to-device copy completes.
508    ///
509    /// # Errors
510    ///
511    /// Propagates allocation, byte-size, context-binding, stream-capture, CUDA copy, and stream synchronization errors.
512    pub fn try_clone(&self) -> Result<Self> {
513        let new_mem = DeviceMemory::<MaybeUninit<T>>::allocate(self.context(), self.length)?;
514        if self.length == 0 || size_of::<T>() == 0 {
515            // SAFETY: an empty or zero-sized range has no bytes to initialize.
516            return Ok(unsafe { new_mem.assume_init() });
517        }
518
519        let source = self.region();
520        // Waits for tracked stream work that still writes or reads the source.
521        let _access = self.context().acquire_host_access(&[source])?;
522        self.context().bind()?;
523        // SAFETY: `new_mem` is a fresh allocation of `self.length` elements disjoint from `self`, the context is bound, and the access guard ordered the source's tracked producers before this copy.
524        unsafe {
525            transfer::copy_synchronous(
526                new_mem.as_mut_ptr().cast::<T>(),
527                self.as_ptr(),
528                self.length,
529                MemoryCopyKind::DeviceToDevice,
530                source.stream(),
531            )?;
532        }
533
534        // SAFETY: the completed copy wrote every element from `self`.
535        Ok(unsafe { new_mem.assume_init() })
536    }
537}
538
539impl<T> DeviceMemory<MaybeUninit<T>> {
540    // Allocates `length` elements whose storage stays uninitialized, which `MaybeUninit<T>` permits.
541    fn allocate(context: &Arc<Context>, length: usize) -> Result<Self> {
542        context.bind()?;
543        let bytes = checked_bytes::<T>(length, "byte length")?;
544        let device_ptr = if bytes == 0 {
545            ptr::null_mut()
546        } else {
547            // SAFETY: the allocation is owned below and freed with `cudaFree`, and its `MaybeUninit` elements need no initialization.
548            unsafe { Self::alloc(context, length)? }
549        };
550        Ok(Self {
551            allocation: Arc::new(DeviceAllocation {
552                id: AllocationId::create(),
553                context: Arc::clone(context),
554                ptr: device_ptr.cast(),
555                bytes,
556                deallocation: DeviceDeallocation::Immediate,
557            }),
558            ptr: device_ptr,
559            length,
560            _phantom: PhantomData,
561        })
562    }
563
564    /// Exposes an initialized prefix while retaining the complete allocation.
565    ///
566    /// # Safety
567    ///
568    /// The first `length` elements must contain valid initialized values of `T`.
569    /// Producing work must be ordered before every consumer and host read.
570    /// The remainder stays allocated but is no longer exposed as typed elements.
571    ///
572    /// # Errors
573    ///
574    /// Returns an error if `length` exceeds the currently exposed element count.
575    pub unsafe fn assume_init_prefix(mut self, length: usize) -> Result<DeviceMemory<T>> {
576        if length > self.length {
577            return Err(Error::buffer_too_small("allocation", length, self.length));
578        }
579
580        self.length = length;
581        // SAFETY: the caller vouches that the first `length` elements, now the whole exposed range, are valid `T` values.
582        Ok(unsafe { self.assume_init() })
583    }
584
585    /// Converts storage initialized by a device producer into initialized device memory.
586    ///
587    /// # Safety
588    ///
589    /// Every element must contain a valid, initialized `T` before any consumer reads it.
590    /// Pending initialization must be ordered before every subsequent consumer and host readback.
591    #[must_use]
592    pub unsafe fn assume_init(self) -> DeviceMemory<T> {
593        let Self {
594            allocation,
595            ptr,
596            length,
597            ..
598        } = self;
599        DeviceMemory {
600            allocation,
601            ptr: ptr.cast(),
602            length,
603            _phantom: PhantomData,
604        }
605    }
606}
607
608// SAFETY: the typed range lies inside the retained allocation, so its region is a slice of the allocation's region.
609unsafe impl<T> DeviceRegionProvider for DeviceMemory<T> {
610    fn region(&self) -> DeviceRegion<'_> {
611        let offset = self.ptr.addr() - self.allocation.ptr.addr();
612        self.allocation
613            .region()
614            .slice(offset..offset + self.byte_len())
615            .expect("device buffer exceeds its allocation")
616    }
617}
618
619/// Raw ownership of a device allocation, its context, and how it is freed.
620///
621/// Free `ptr` with `cudaFree` while `context` is alive, or with `cudaFreeAsync` on the stream in `stream_ordered`, or re-adopt the value with [`DeviceMemory::from_raw`].
622#[derive(Debug)]
623pub struct RawDeviceMemory<T> {
624    /// Base of the allocation, or null for an empty one.
625    pub ptr: *mut T,
626    /// Number of elements of `T`.
627    pub len: usize,
628    /// Context the allocation belongs to.
629    pub context: Arc<Context>,
630    /// The stream and pool of a stream-ordered allocation, or `None` for one freed with `cudaFree`.
631    pub stream_ordered: Option<StreamOrderedFree>,
632}
633
634/// Represents a region of owned CUDA device memory for elements of type `T`.
635///
636/// The last owner of the allocation frees it with `cudaFree`, or, for a stream-ordered allocation, enqueues `cudaFreeAsync` on its stream.
637#[derive(Debug)]
638pub struct DeviceMemory<T> {
639    pub(crate) allocation: Arc<DeviceAllocation>,
640    /// Raw pointer to the allocated device memory.
641    pub(crate) ptr: *mut T,
642    /// Number of elements of type `T` allocated.
643    pub(crate) length: usize,
644    /// Marker for the type `T`.
645    pub(crate) _phantom: PhantomData<T>,
646}
647
648impl<T> PartialEq for DeviceMemory<T> {
649    fn eq(&self, other: &Self) -> bool {
650        self.context() == other.context() && self.ptr == other.ptr && self.length == other.length
651    }
652}
653
654impl<T> Eq for DeviceMemory<T> {}
655
656// SAFETY: the host never dereferences `ptr`, the owner holds `T` values like a `Vec<T>`, and the shared `DeviceAllocation` is `Send`.
657unsafe impl<T: Send> Send for DeviceMemory<T> {}
658
659// SAFETY: `&DeviceMemory<T>` exposes only device pointers and metadata, and device writes need `&mut` or an unsafe raw API.
660unsafe impl<T: Sync> Sync for DeviceMemory<T> {}
661
662// SAFETY: `&mut self` is exclusive over the `length` retained elements at `ptr`.
663unsafe impl<T: DeviceRepr> DeviceOutput<T> for DeviceMemory<T> {
664    fn as_mut_ptr(&mut self) -> *mut T {
665        let () = T::LAYOUT;
666        self.ptr
667    }
668}
669
670// SAFETY: `MaybeUninit<T>` has `T`'s layout, so the retained range holds `length` slots for `T`, and no initialized reads are claimed.
671unsafe impl<T: DeviceRepr> DeviceRange<T> for DeviceMemory<MaybeUninit<T>> {
672    fn len(&self) -> usize {
673        self.length
674    }
675}
676
677// SAFETY: `&mut self` is exclusive over `length` retained slots with `T`'s layout.
678unsafe impl<T: DeviceRepr> DeviceOutput<T> for DeviceMemory<MaybeUninit<T>> {
679    fn as_mut_ptr(&mut self) -> *mut T {
680        let () = T::LAYOUT;
681        self.ptr.cast()
682    }
683}