singe_cuda/view.rs
1//! Borrowed typed views over CUDA-accessible memory.
2
3use std::{
4 marker::PhantomData,
5 mem::{MaybeUninit, align_of, size_of},
6 num::Wrapping,
7 ops::{Bound, Range, RangeBounds},
8 ptr::NonNull,
9 sync::{
10 Arc,
11 atomic::{AtomicU64, Ordering},
12 },
13};
14
15#[cfg(feature = "macros")]
16pub use singe_cuda_macros::{
17 AnyBitPatternDeviceRepr, DeviceRepr, NoUninitDeviceRepr, ZeroableDeviceRepr,
18};
19
20use crate::{
21 context::Context,
22 error::{Error, Result},
23 memory::{
24 DeviceAllocation, DeviceMemory,
25 transfer::{self, copy_device},
26 },
27 stream::Stream,
28 types::{Complex, bf16, f4e2m1, f6e2m3, f6e3m2, f8e4m3, f8e5m2, f8ue5m3, f8ue8m0, f16},
29 utility::ranges_overlap,
30};
31
32/// A Rust type that can be represented as plain CUDA device memory.
33///
34/// # Safety
35///
36/// Implementors must have a stable representation without implicit padding, Rust ownership, or host references.
37/// Copying valid values must not depend on host-only pointer validity.
38/// Memory APIs must evaluate [`Self::LAYOUT`] before transferring values or exposing initialized storage.
39/// A generic implementation may reject unsupported layouts through that constant.
40pub unsafe trait DeviceRepr: Copy + 'static {
41 /// Checks that this concrete type has a transferable layout.
42 ///
43 /// Derives evaluate field layouts and reject implicit padding at compile time.
44 /// Manual implementations must uphold the layout contract whenever this constant evaluates successfully.
45 const LAYOUT: () = ();
46}
47
48/// A [`DeviceRepr`] whose all-zero byte pattern is a valid value.
49///
50/// # Safety
51///
52/// Implementors must accept an all-zero byte pattern as a valid instance.
53pub unsafe trait ZeroableDeviceRepr: DeviceRepr {}
54
55/// A device representation whose valid values contain no uninitialized bytes.
56///
57/// Safe byte reinterpretation requires this guarantee on the source type.
58/// `MaybeUninit<T>` does not satisfy it, even when `T` does.
59///
60/// # Safety
61///
62/// Every byte of every valid value must be initialized whenever `Self::LAYOUT` evaluates successfully.
63/// Consumers must evaluate that layout before reading or reinterpreting the representation's bytes.
64pub unsafe trait NoUninitDeviceRepr: DeviceRepr {}
65
66/// A [`DeviceRepr`] for which every initialized byte pattern is a valid value.
67///
68/// This permits safe readback from device storage without a kernel-specific validity check.
69/// It does not permit reading uninitialized memory.
70///
71/// # Safety
72///
73/// Every initialized bit pattern of the representation must be valid for `Self`.
74/// Types with restricted values, including `bool`, do not satisfy this contract.
75pub unsafe trait AnyBitPatternDeviceRepr: ZeroableDeviceRepr {}
76
77/// Contiguous device storage that a producer may initialize as values of `T`.
78///
79/// Both initialized and uninitialized buffers can provide output storage.
80/// This trait does not grant permission to read existing elements or establish that a producer initializes the entire range.
81///
82/// # Safety
83///
84/// The pointer must identify writable storage for `len()` elements with the device ABI and alignment of `T`, owned by `context()` and live for the borrow.
85/// Mutable access must be exclusive.
86/// The byte length must fit `usize`.
87/// `region()` must describe that same pointer and the exact byte range of those elements.
88pub unsafe trait DeviceOutput<T: DeviceRepr>: DeviceRange<T> {
89 /// Returns a pointer to the writable device output range.
90 ///
91 /// Writing valid `T` values requires the caller to establish CUDA execution ordering.
92 fn as_mut_ptr(&mut self) -> *mut T;
93}
94
95macro_rules! impl_device_repr {
96 ($($ty:ty),* $(,)?) => {
97 $(
98 // SAFETY: the listed scalars have a fixed size, no padding, and no pointers or owned resources.
99 unsafe impl DeviceRepr for $ty {}
100 // SAFETY: every byte of a valid scalar of these types is initialized.
101 unsafe impl NoUninitDeviceRepr for $ty {}
102 // SAFETY: all-zero bytes are the zero value of each listed integer and floating-point type, and `()` has no bytes.
103 unsafe impl ZeroableDeviceRepr for $ty {}
104 // SAFETY: every bit pattern is a valid value of the listed integer and floating-point types.
105 unsafe impl AnyBitPatternDeviceRepr for $ty {}
106 )*
107 };
108}
109
110impl_device_repr!(
111 (),
112 u8,
113 u16,
114 u32,
115 u64,
116 u128,
117 usize,
118 i8,
119 i16,
120 i32,
121 i64,
122 i128,
123 isize,
124 f32,
125 f64,
126 f16,
127 bf16,
128 f8e4m3,
129 f8e5m2,
130 f8ue8m0,
131 f8ue5m3,
132 f6e2m3,
133 f6e3m2,
134 f4e2m1,
135);
136
137// SAFETY: `bool` is one byte with no padding and no pointers or owned resources.
138// It is not `AnyBitPatternDeviceRepr`, since device bytes other than 0 and 1 are invalid.
139unsafe impl DeviceRepr for bool {}
140
141// SAFETY: the single byte of a valid `bool` is initialized.
142unsafe impl NoUninitDeviceRepr for bool {}
143
144// SAFETY: the zero byte is `false`.
145unsafe impl ZeroableDeviceRepr for bool {}
146
147// SAFETY: array elements are laid out without padding between them, so `[T; N]` inherits `T`'s layout check.
148unsafe impl<T: DeviceRepr, const N: usize> DeviceRepr for [T; N] {
149 const LAYOUT: () = T::LAYOUT;
150}
151
152// SAFETY: an all-zero array is `N` all-zero elements, each valid because `T: ZeroableDeviceRepr`.
153unsafe impl<T: ZeroableDeviceRepr, const N: usize> ZeroableDeviceRepr for [T; N] {}
154
155// SAFETY: an array's bytes are exactly its elements' bytes, which `T: NoUninitDeviceRepr` keeps initialized.
156unsafe impl<T: NoUninitDeviceRepr, const N: usize> NoUninitDeviceRepr for [T; N] {}
157
158// SAFETY: every array bit pattern is `N` element patterns, each valid because `T: AnyBitPatternDeviceRepr`.
159unsafe impl<T: AnyBitPatternDeviceRepr, const N: usize> AnyBitPatternDeviceRepr for [T; N] {}
160
161// SAFETY: `Wrapping<T>` is `repr(transparent)` over `T`, so it has `T`'s layout.
162unsafe impl<T: DeviceRepr> DeviceRepr for Wrapping<T> {
163 const LAYOUT: () = T::LAYOUT;
164}
165
166// SAFETY: `Wrapping<T>` is `repr(transparent)`, so all-zero bytes are a valid `T` inside it.
167unsafe impl<T: ZeroableDeviceRepr> ZeroableDeviceRepr for Wrapping<T> {}
168
169// SAFETY: `Wrapping<T>` is `repr(transparent)`, so its bytes are `T`'s initialized bytes.
170unsafe impl<T: NoUninitDeviceRepr> NoUninitDeviceRepr for Wrapping<T> {}
171
172// SAFETY: `Wrapping<T>` is `repr(transparent)`, so every bit pattern valid for `T` is valid for it.
173unsafe impl<T: AnyBitPatternDeviceRepr> AnyBitPatternDeviceRepr for Wrapping<T> {}
174
175// SAFETY: `Complex<T>` is `repr(C)` with two `T` fields, so it has no padding beyond `T`'s own.
176unsafe impl<T: DeviceRepr> DeviceRepr for Complex<T> {
177 const LAYOUT: () = T::LAYOUT;
178}
179
180// SAFETY: all-zero bytes are two all-zero `T` fields, each valid because `T: ZeroableDeviceRepr`.
181unsafe impl<T: ZeroableDeviceRepr> ZeroableDeviceRepr for Complex<T> {}
182
183// SAFETY: the two padding-free `T` fields cover every byte, and `T: NoUninitDeviceRepr` keeps them initialized.
184unsafe impl<T: NoUninitDeviceRepr> NoUninitDeviceRepr for Complex<T> {}
185
186// SAFETY: every bit pattern is two `T` patterns, each valid because `T: AnyBitPatternDeviceRepr`.
187unsafe impl<T: AnyBitPatternDeviceRepr> AnyBitPatternDeviceRepr for Complex<T> {}
188
189// SAFETY: `MaybeUninit<T>` has `T`'s size and alignment and owns nothing, and `T: DeviceRepr` rules out host ownership.
190unsafe impl<T: DeviceRepr> DeviceRepr for MaybeUninit<T> {
191 const LAYOUT: () = T::LAYOUT;
192}
193
194// SAFETY: any bytes, zero included, are a valid `MaybeUninit<T>`.
195unsafe impl<T: DeviceRepr> ZeroableDeviceRepr for MaybeUninit<T> {}
196
197// SAFETY: any initialized bit pattern is a valid `MaybeUninit<T>`.
198unsafe impl<T: DeviceRepr> AnyBitPatternDeviceRepr for MaybeUninit<T> {}
199
200// SAFETY: `PhantomData` is zero-sized and owns no resource, whatever its marker type.
201unsafe impl<T: ?Sized + 'static> DeviceRepr for PhantomData<T> {}
202
203// SAFETY: `PhantomData` has no bytes, so the empty all-zero pattern is its only value.
204unsafe impl<T: ?Sized + 'static> ZeroableDeviceRepr for PhantomData<T> {}
205
206// SAFETY: `PhantomData` has no bytes that could be uninitialized.
207unsafe impl<T: ?Sized + 'static> NoUninitDeviceRepr for PhantomData<T> {}
208
209// SAFETY: `PhantomData` has no bytes, so its one empty bit pattern is valid.
210unsafe impl<T: ?Sized + 'static> AnyBitPatternDeviceRepr for PhantomData<T> {}
211
212/// Identifies one allocation across its typed handles, mappings, and subranges.
213#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
214pub struct AllocationId(u64);
215
216impl AllocationId {
217 /// Creates an identity for a new allocation or an externally owned resource.
218 /// Reuse this identity for every alias of the same live allocation.
219 ///
220 /// # Panics
221 ///
222 /// Panics if the process exhausts the nonzero `u64` allocation identity space.
223 pub fn create() -> Self {
224 static NEXT_ID: AtomicU64 = AtomicU64::new(1);
225 Self(
226 NEXT_ID
227 .try_update(Ordering::Relaxed, Ordering::Relaxed, |id| id.checked_add(1))
228 .expect("allocation identity exhausted"),
229 )
230 }
231}
232
233/// A byte range in pinned or registered host storage, independent of device mappings.
234#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
235pub struct HostRegion<'a> {
236 context: &'a Arc<Context>,
237 allocation_id: AllocationId,
238 allocation_bytes: usize,
239 offset: usize,
240 bytes: usize,
241 portable: bool,
242}
243
244impl<'a> HostRegion<'a> {
245 /// Describes a complete live host allocation or registration.
246 ///
247 /// # Safety
248 ///
249 /// The range must remain registered for `'a` in `context`.
250 /// All host and device aliases must share `allocation_id` and byte offsets.
251 /// `portable` must reflect CUDA's registration or allocation flags.
252 #[must_use]
253 pub unsafe fn from_raw_parts(
254 context: &'a Arc<Context>,
255 allocation_id: AllocationId,
256 bytes: usize,
257 portable: bool,
258 ) -> Self {
259 Self {
260 context,
261 allocation_id,
262 allocation_bytes: bytes,
263 offset: 0,
264 bytes,
265 portable,
266 }
267 }
268
269 /// Returns the CUDA context associated with this allocation.
270 #[must_use]
271 pub fn context(self) -> &'a Arc<Context> {
272 self.context
273 }
274
275 /// Returns the identity shared by all aliases of the backing allocation.
276 #[must_use]
277 pub const fn allocation_id(self) -> AllocationId {
278 self.allocation_id
279 }
280
281 /// Returns the byte length of the complete allocation before slicing.
282 #[must_use]
283 pub const fn allocation_byte_len(self) -> usize {
284 self.allocation_bytes
285 }
286
287 /// Returns the byte length of this region.
288 #[must_use]
289 pub const fn byte_len(self) -> usize {
290 self.bytes
291 }
292
293 /// Returns whether CUDA recognizes this host allocation or registration in other contexts.
294 #[must_use]
295 pub const fn is_portable(self) -> bool {
296 self.portable
297 }
298
299 /// Returns this region’s byte offsets relative to the start of the backing allocation.
300 #[must_use]
301 pub fn byte_range(self) -> Range<usize> {
302 self.offset..self.offset + self.bytes
303 }
304
305 /// Returns metadata for a byte subrange while preserving the host registration identity.
306 ///
307 /// # Errors
308 ///
309 /// Returns an error if the byte range is reversed, exceeds this range’s bounds, or an inclusive bound cannot be converted without overflow.
310 pub fn slice<R: RangeBounds<usize>>(self, range: R) -> Result<Self> {
311 let (start, end) = bounds_to_range(range, self.bytes)?;
312 Ok(Self {
313 offset: self.offset + start,
314 bytes: end - start,
315 ..self
316 })
317 }
318}
319
320/// A borrowed byte range within one context-associated allocation.
321#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
322pub struct DeviceRegion<'a> {
323 context: &'a Arc<Context>,
324 stream: Option<&'a Stream>,
325 allocation_id: AllocationId,
326 base: *mut u8,
327 allocation_bytes: usize,
328 offset: usize,
329 bytes: usize,
330}
331
332impl<'a> DeviceRegion<'a> {
333 /// Describes an externally established allocation and its full byte range.
334 ///
335 /// # Safety
336 ///
337 /// `base` must identify `bytes` live CUDA-accessible bytes in `context` for `'a`.
338 /// `allocation_id` must be shared by all aliases of this allocation and must not identify another live allocation.
339 ///
340 /// # Errors
341 ///
342 /// Returns an error if a nonempty range has a null base pointer or its ending address overflows `usize`.
343 pub unsafe fn from_raw_parts(
344 context: &'a Arc<Context>,
345 allocation_id: AllocationId,
346 base: *mut u8,
347 bytes: usize,
348 ) -> Result<Self> {
349 if bytes != 0 && base.is_null() {
350 return Err(Error::null_pointer("base"));
351 }
352
353 base.addr()
354 .checked_add(bytes)
355 .ok_or_else(|| Error::out_of_range("region end address"))?;
356 Ok(Self {
357 context,
358 stream: None,
359 allocation_id,
360 base,
361 allocation_bytes: bytes,
362 offset: 0,
363 bytes,
364 })
365 }
366
367 /// Returns the CUDA context associated with this allocation.
368 #[must_use]
369 pub fn context(self) -> &'a Arc<Context> {
370 self.context
371 }
372
373 /// Returns the stream that orders allocation and writes for stream-ordered storage.
374 #[must_use]
375 pub const fn stream(self) -> Option<&'a Stream> {
376 self.stream
377 }
378
379 /// Associates this region with the stream that establishes its readiness.
380 ///
381 /// # Safety
382 ///
383 /// Allocation and pending producer writes must be ordered on this stream.
384 /// Work on other streams must establish dependencies before accessing the region.
385 ///
386 /// # Errors
387 ///
388 /// Returns an error if the stream belongs to a different context.
389 pub unsafe fn with_stream(self, stream: &'a Stream) -> Result<Self> {
390 if stream.context() != self.context {
391 return Err(Error::StreamContextMismatch);
392 }
393 Ok(Self {
394 stream: Some(stream),
395 ..self
396 })
397 }
398
399 /// Orders this range's allocation and producer stream before a consumer stream.
400 ///
401 /// # Errors
402 ///
403 /// Returns an error if the consumer stream belongs to a different context or joining the readiness stream fails.
404 pub fn order_on(self, stream: &Stream) -> Result<()> {
405 if stream.context() != self.context {
406 return Err(Error::StreamContextMismatch);
407 }
408
409 if let Some(ready) = self.stream {
410 stream.join(ready)?;
411 }
412 Ok(())
413 }
414
415 /// Waits for an associated allocation stream before synchronous access.
416 ///
417 /// # Errors
418 ///
419 /// Propagates access-tracking and synchronization errors while waiting for pending accesses to this region.
420 pub fn synchronize(self) -> Result<()> {
421 let _guard = self.context.acquire_host_access(&[self])?;
422 Ok(())
423 }
424
425 /// Returns the identity shared by all aliases of the backing allocation.
426 #[must_use]
427 pub const fn allocation_id(self) -> AllocationId {
428 self.allocation_id
429 }
430
431 /// Returns the byte length of the complete allocation before slicing.
432 #[must_use]
433 pub const fn allocation_byte_len(self) -> usize {
434 self.allocation_bytes
435 }
436
437 /// Returns the byte length of this region.
438 #[must_use]
439 pub const fn byte_len(self) -> usize {
440 self.bytes
441 }
442
443 /// Returns this region’s byte offsets relative to the start of the backing allocation.
444 #[must_use]
445 pub fn byte_range(self) -> Range<usize> {
446 self.offset..self.offset + self.bytes
447 }
448
449 /// Reports conflicts between byte ranges sharing one allocation identity.
450 /// Empty subranges inside another range conservatively count as conflicts.
451 #[must_use]
452 pub fn overlaps(self, other: Self) -> bool {
453 self.allocation_id == other.allocation_id
454 && ranges_overlap(&self.byte_range(), &other.byte_range())
455 }
456
457 /// Returns the CUDA-accessible pointer at this region’s starting byte offset.
458 ///
459 /// The pointer does not grant host access or establish initialization or exclusive access.
460 #[must_use]
461 pub fn as_ptr(self) -> *mut u8 {
462 self.base.wrapping_add(self.offset)
463 }
464
465 /// Checks that a nonempty region starts at a multiple of `alignment` bytes, which must be nonzero.
466 ///
467 /// # Errors
468 ///
469 /// Returns [`Error::Misaligned`] naming `name` if the region is nonempty and its start is not a multiple of `alignment`.
470 pub fn ensure_aligned(self, alignment: usize, name: &'static str) -> Result<()> {
471 if self.bytes != 0 && !self.as_ptr().addr().is_multiple_of(alignment) {
472 return Err(Error::misaligned(name, alignment));
473 }
474 Ok(())
475 }
476
477 /// Borrows a byte subrange while preserving allocation and context identity.
478 ///
479 /// # Errors
480 ///
481 /// Returns an error if the byte range is reversed, exceeds this range’s bounds, or an inclusive bound cannot be converted without overflow.
482 pub fn slice<R: RangeBounds<usize>>(self, range: R) -> Result<Self> {
483 let (start, end) = bounds_to_range(range, self.bytes)?;
484 Ok(Self {
485 offset: self.offset + start,
486 bytes: end - start,
487 ..self
488 })
489 }
490}
491
492/// Provides the allocation identity and byte range used by CUDA operations.
493///
494/// # Safety
495///
496/// Reported metadata must describe the same live memory as the provider's pointers.
497/// All aliases must preserve allocation identity and byte offsets.
498/// The context must stay retained while the provider is alive.
499/// Returned regions must retain their identity, bounds, and liveness for the shared borrow.
500pub unsafe trait DeviceRegionProvider {
501 /// Borrows the exact allocation range described by this provider’s pointers.
502 fn region(&self) -> DeviceRegion<'_>;
503}
504
505/// Retains an actual CUDA allocation and a checked byte range independently of typed buffers.
506///
507/// This is ownership and metadata only.
508/// It does not establish initialization, exclusive access, or permission to enqueue conflicting work.
509#[derive(Debug)]
510pub struct OwnedDeviceRegion<O: DeviceRegionProvider + 'static = DeviceAllocation> {
511 owner: Arc<O>,
512 range: Range<usize>,
513 readiness: Option<Stream>,
514}
515
516impl<O: DeviceRegionProvider + 'static> OwnedDeviceRegion<O> {
517 /// Retains a checked byte range relative to the owner's exposed region.
518 ///
519 /// # Errors
520 ///
521 /// Returns an error if the byte range is reversed or exceeds the owner’s exposed region.
522 pub fn from_owner(owner: Arc<O>, range: Range<usize>) -> Result<Self> {
523 owner.region().slice(range.clone())?;
524 Ok(Self {
525 owner,
526 range,
527 readiness: None,
528 })
529 }
530
531 #[must_use]
532 pub(crate) fn into_owner(self) -> Arc<O> {
533 self.owner
534 }
535
536 /// Returns the retained allocation provider.
537 #[must_use]
538 pub fn owner(&self) -> &Arc<O> {
539 &self.owner
540 }
541
542 /// Returns the context associated with the retained allocation.
543 #[must_use]
544 pub fn context(&self) -> &Arc<Context> {
545 self.owner.region().context()
546 }
547
548 /// Returns the byte length of the retained subrange.
549 #[must_use]
550 pub fn byte_len(&self) -> usize {
551 self.range.len()
552 }
553
554 /// Narrows this retained range while preserving its backing owner and readiness stream.
555 ///
556 /// # Errors
557 ///
558 /// Returns an error if the byte range is reversed, exceeds this range’s bounds, or an inclusive bound cannot be converted without overflow.
559 pub fn slice<R: RangeBounds<usize>>(mut self, range: R) -> Result<Self> {
560 let (start, end) = bounds_to_range(range, self.range.len())?;
561 self.range = self.range.start + start..self.range.start + end;
562 Ok(self)
563 }
564
565 /// Associates pending writes with a retained stream without transferring allocation ownership.
566 ///
567 /// # Safety
568 ///
569 /// Allocation and producer writes must be ordered before consumers on this stream.
570 /// Other streams must establish dependencies before accessing this range.
571 ///
572 /// # Errors
573 ///
574 /// Returns an error if the stream belongs to a different context.
575 pub unsafe fn with_stream(mut self, stream: &Stream) -> Result<Self> {
576 if self.context() != stream.context() {
577 return Err(Error::StreamContextMismatch);
578 }
579
580 self.readiness = Some(stream.clone());
581 Ok(self)
582 }
583}
584
585impl<O: DeviceRegionProvider + 'static> Clone for OwnedDeviceRegion<O> {
586 /// Clones allocation retention and metadata without granting another access lease.
587 fn clone(&self) -> Self {
588 Self {
589 owner: Arc::clone(&self.owner),
590 range: self.range.clone(),
591 readiness: self.readiness.clone(),
592 }
593 }
594}
595
596// SAFETY: the retained provider keeps its region live, and slicing preserves its identity and bounds.
597unsafe impl<O: DeviceRegionProvider + 'static> DeviceRegionProvider for OwnedDeviceRegion<O> {
598 fn region(&self) -> DeviceRegion<'_> {
599 let region = self
600 .owner
601 .region()
602 .slice(self.range.clone())
603 .expect("retained range exceeds its allocation");
604 self.readiness.as_ref().map_or(region, |stream| {
605 // SAFETY: `readiness` is set only by `Self::with_stream`, whose caller ordered allocation and producer writes on that stream.
606 unsafe { region.with_stream(stream) }
607 .expect("retained readiness stream context mismatch")
608 })
609 }
610}
611
612impl OwnedDeviceRegion {
613 /// Retains this buffer's exact logical range, including its original allocation offset.
614 #[must_use]
615 pub fn from_memory<T: DeviceRepr>(memory: &DeviceMemory<T>) -> Self {
616 Self {
617 owner: Arc::clone(memory.allocation()),
618 range: memory.region().byte_range(),
619 readiness: None,
620 }
621 }
622}
623
624pub(crate) fn cast_length<T: DeviceRepr>(region: DeviceRegion<'_>) -> Result<usize> {
625 let () = T::LAYOUT;
626 let size = size_of::<T>();
627 if size == 0 {
628 return Err(Error::not_positive("element size"));
629 }
630
631 if !region.byte_len().is_multiple_of(size) {
632 return Err(Error::misaligned("region byte length", size));
633 }
634
635 if region.byte_len() != 0 && !region.as_ptr().addr().is_multiple_of(align_of::<T>()) {
636 return Err(Error::misaligned("region address", align_of::<T>()));
637 }
638
639 Ok(region.byte_len() / size)
640}
641
642/// Typed input metadata for a contiguous CUDA allocation range.
643///
644/// The range may be initialized by an earlier operation in a captured graph.
645/// This trait does not establish initialized values or grant permission to read them.
646/// Raw consumers must establish validity and ordering when they execute.
647///
648/// # Safety
649///
650/// The pointer must identify live, aligned CUDA-accessible storage for `len()` elements of `T` throughout the borrow.
651/// The byte length must fit `usize`.
652/// `region()` must describe the exact byte range, actual context, allocation identity, and offset.
653/// Nonempty ranges must have the same pointer.
654pub unsafe trait DeviceRange<T: DeviceRepr>: DeviceRegionProvider {
655 /// Returns the context associated with the input allocation.
656 fn context(&self) -> &Arc<Context> {
657 self.region().context()
658 }
659
660 /// Returns the device input pointer without asserting that its values are initialized.
661 ///
662 /// An empty range returns an aligned dangling pointer.
663 fn as_device_ptr(&self) -> *const T {
664 if self.is_empty() {
665 NonNull::<T>::dangling().as_ptr()
666 } else {
667 self.region().as_ptr().cast()
668 }
669 }
670
671 /// Returns the number of input elements.
672 fn len(&self) -> usize;
673
674 /// Returns whether the input range contains no elements.
675 fn is_empty(&self) -> bool {
676 self.len() == 0
677 }
678
679 /// Returns the input range length in bytes.
680 ///
681 /// # Errors
682 ///
683 /// Returns an error if the element count multiplied by `size_of::<T>()` overflows `usize`.
684 fn byte_len(&self) -> Result<usize> {
685 let () = T::LAYOUT;
686 self.len()
687 .checked_mul(size_of::<T>())
688 .ok_or_else(|| Error::out_of_range("input byte length"))
689 }
690}
691
692/// A typed contiguous range containing initialized device values.
693///
694/// # Safety
695///
696/// Every element must contain a valid `T` for the borrow.
697/// Safe consumers may read the range using CUDA, subject to stream ordering and shared-borrow rules.
698pub unsafe trait DeviceSlice<T: DeviceRepr>: DeviceRange<T> {}
699
700/// A mutable typed contiguous range of CUDA-accessible device memory.
701///
702/// # Safety
703///
704/// The mutable pointer must identify the same range as `DeviceSlice` and grant exclusive access for its mutable borrow, including work using that borrow.
705/// Its initialized input and writable output capabilities must describe the same range.
706pub unsafe trait DeviceSliceMut<T: DeviceRepr>: DeviceSlice<T> + DeviceOutput<T> {}
707
708/// A typed contiguous host-memory range that can be copied to CUDA memory.
709///
710/// # Safety
711///
712/// The pointer must identify `len()` live, aligned `T` values readable for the borrow.
713/// The byte length must fit `usize`; shared access must not mutate them.
714pub unsafe trait HostSlice<T: DeviceRepr> {
715 /// Returns a pointer to the readable host elements.
716 fn as_host_ptr(&self) -> *const T;
717
718 /// Returns the number of host elements.
719 fn len(&self) -> usize;
720
721 /// Returns whether the host range contains no elements.
722 fn is_empty(&self) -> bool {
723 self.len() == 0
724 }
725}
726
727/// A mutable typed contiguous host-memory range that can be copied from CUDA memory.
728///
729/// # Safety
730///
731/// The mutable pointer must identify the same range as `HostSlice`, writable exclusively for the mutable borrow.
732pub unsafe trait HostSliceMut<T: DeviceRepr>: HostSlice<T> {
733 /// Returns a pointer to the exclusively writable host elements.
734 fn as_host_mut_ptr(&mut self) -> *mut T;
735}
736
737/// Typed CUDA input metadata without an initialization guarantee.
738///
739/// Construction checks the element layout and preserves the allocation's context and range.
740/// Reading values requires an unsafe consumer to establish initialization and order preceding producers before each read.
741#[derive(Debug, Clone, Copy)]
742pub struct DeviceInputView<'a, T: DeviceRepr> {
743 region: DeviceRegion<'a>,
744 length: usize,
745 _t: PhantomData<&'a MaybeUninit<T>>,
746}
747
748impl<'a, T: DeviceRepr> DeviceInputView<'a, T> {
749 /// Describes a live allocation range as input elements of `T`.
750 ///
751 /// # Errors
752 ///
753 /// Returns an error if `T` is zero-sized, the region’s byte length is not divisible by `size_of::<T>()`, or a nonempty region is not aligned for `T`.
754 pub fn create(region: DeviceRegion<'a>) -> Result<Self> {
755 let length = cast_length::<T>(region)?;
756 Ok(Self {
757 region,
758 length,
759 _t: PhantomData,
760 })
761 }
762
763 /// Borrows typed input metadata without strengthening its validity contract.
764 pub fn from_buffer<B: DeviceRange<T> + ?Sized>(buffer: &'a B) -> Self {
765 let () = T::LAYOUT;
766 Self {
767 region: buffer.region(),
768 length: buffer.len(),
769 _t: PhantomData,
770 }
771 }
772
773 /// Returns the CUDA-accessible element pointer.
774 ///
775 /// An empty view returns an aligned dangling pointer.
776 /// This pointer does not grant host access.
777 #[must_use]
778 pub fn as_ptr(&self) -> *const T {
779 if self.length == 0 {
780 NonNull::<T>::dangling().as_ptr()
781 } else {
782 self.region.as_ptr().cast()
783 }
784 }
785
786 /// Returns the number of elements in the view.
787 #[must_use]
788 pub const fn len(&self) -> usize {
789 self.length
790 }
791
792 /// Returns whether the view contains no elements.
793 #[must_use]
794 pub const fn is_empty(&self) -> bool {
795 self.length == 0
796 }
797
798 /// Returns the context associated with the viewed allocation.
799 #[must_use]
800 pub fn context(&self) -> &'a Arc<Context> {
801 self.region.context()
802 }
803
804 /// Returns the view’s exact byte range and allocation identity.
805 #[must_use]
806 pub const fn region(&self) -> DeviceRegion<'a> {
807 self.region
808 }
809
810 /// Narrows input metadata while preserving its allocation identity and offset.
811 ///
812 /// # Errors
813 ///
814 /// Returns an error if the element range is reversed, exceeds this range’s bounds, or an inclusive bound cannot be converted without overflow.
815 pub fn slice<R: RangeBounds<usize>>(self, range: R) -> Result<Self> {
816 let (start, end) = bounds_to_range(range, self.length)?;
817 Ok(Self {
818 region: self
819 .region
820 .slice(start * size_of::<T>()..end * size_of::<T>())?,
821 length: end - start,
822 _t: PhantomData,
823 })
824 }
825
826 /// Reinterprets input metadata without asserting initialized destination values.
827 ///
828 /// # Errors
829 ///
830 /// Returns an error if `U` is zero-sized, the region’s byte length is not divisible by `size_of::<U>()`, or a nonempty region is not aligned for `U`.
831 pub fn cast<U: DeviceRepr>(self) -> Result<DeviceInputView<'a, U>> {
832 DeviceInputView::create(self.region)
833 }
834}
835
836// SAFETY: both constructors preserve the provider's exact live allocation range.
837unsafe impl<T: DeviceRepr> DeviceRegionProvider for DeviceInputView<'_, T> {
838 fn region(&self) -> DeviceRegion<'_> {
839 self.region
840 }
841}
842
843// SAFETY: construction checks the layout; slicing and casting preserve bounds and alignment.
844unsafe impl<T: DeviceRepr> DeviceRange<T> for DeviceInputView<'_, T> {
845 fn as_device_ptr(&self) -> *const T {
846 self.as_ptr()
847 }
848
849 fn len(&self) -> usize {
850 self.length
851 }
852}
853
854/// An immutable borrow of typed CUDA storage, including its allocation identity.
855#[derive(Debug, Clone, Copy)]
856pub struct DeviceView<'a, T: DeviceRepr> {
857 region: DeviceRegion<'a>,
858 length: usize,
859 _t: PhantomData<&'a T>,
860}
861
862/// An exclusive borrow of typed CUDA storage.
863#[derive(Debug)]
864pub struct DeviceViewMut<'a, T: DeviceRepr> {
865 region: DeviceRegion<'a>,
866 length: usize,
867 _t: PhantomData<&'a mut T>,
868}
869
870/// An exclusive write-only range for a producer of `T` values.
871///
872/// The range may be uninitialized and cannot be used as a readable device slice.
873/// Its element type describes produced values rather than the storage's current initialization state.
874#[derive(Debug)]
875pub struct DeviceOutputView<'a, T: DeviceRepr> {
876 region: DeviceRegion<'a>,
877 length: usize,
878 _t: PhantomData<&'a mut MaybeUninit<T>>,
879}
880
881impl<'a, T: DeviceRepr> DeviceOutputView<'a, T> {
882 /// Consumes the typed borrow into allocation metadata without granting access.
883 #[must_use]
884 pub fn into_region(self) -> DeviceRegion<'a> {
885 self.region
886 }
887
888 /// Borrows an externally established writable region without claiming initialization.
889 ///
890 /// # Safety
891 ///
892 /// The region must remain live and exclusively writable for the returned lifetime, including queued CUDA accesses using this output.
893 ///
894 /// # Errors
895 ///
896 /// Returns an error if `length * size_of::<T>()` overflows or differs from the region’s byte length, or a nonempty region has a zero-sized element type or insufficient alignment.
897 pub unsafe fn from_raw_parts(region: DeviceRegion<'a>, length: usize) -> Result<Self> {
898 validate_view::<T>(region, length)?;
899 Ok(Self {
900 region,
901 length,
902 _t: PhantomData,
903 })
904 }
905
906 /// Borrows writable storage without exposing its existing contents as `T` values.
907 pub fn from_output<B: DeviceOutput<T> + ?Sized>(output: &'a mut B) -> Self {
908 let () = T::LAYOUT;
909 Self {
910 region: output.region(),
911 length: output.len(),
912 _t: PhantomData,
913 }
914 }
915
916 /// Borrows this destination again for a shorter exclusive lifetime.
917 pub fn reborrow(&mut self) -> DeviceOutputView<'_, T> {
918 DeviceOutputView::from_output(self)
919 }
920
921 /// Returns the number of output elements.
922 #[must_use]
923 pub const fn len(&self) -> usize {
924 self.length
925 }
926
927 /// Returns whether the output range is empty.
928 #[must_use]
929 pub const fn is_empty(&self) -> bool {
930 self.length == 0
931 }
932
933 /// Returns the pointer a producer may write through.
934 pub fn as_mut_ptr(&mut self) -> *mut T {
935 self.region.as_ptr().cast()
936 }
937
938 /// Returns the output allocation's context.
939 #[must_use]
940 pub fn context(&self) -> &Arc<Context> {
941 self.region.context()
942 }
943
944 /// Narrows this exclusive output borrow to an element range.
945 ///
946 /// # Errors
947 ///
948 /// Returns an error if the element range is reversed, exceeds this range’s bounds, or an inclusive bound cannot be converted without overflow.
949 pub fn slice<R: RangeBounds<usize>>(self, range: R) -> Result<Self> {
950 let (start, end) = bounds_to_range(range, self.length)?;
951 Ok(Self {
952 region: self
953 .region
954 .slice(start * size_of::<T>()..end * size_of::<T>())?,
955 length: end - start,
956 _t: PhantomData,
957 })
958 }
959
960 /// Splits this exclusive output borrow into disjoint writable ranges.
961 ///
962 /// # Errors
963 ///
964 /// Returns an error if `mid` exceeds the view’s element count.
965 pub fn split_at_mut(self, mid: usize) -> Result<(Self, Self)> {
966 if mid > self.length {
967 return Err(Error::buffer_too_small("view", mid, self.length));
968 }
969
970 let boundary = mid * size_of::<T>();
971 let left = Self {
972 region: self.region.slice(..boundary)?,
973 length: mid,
974 _t: PhantomData,
975 };
976 let right = Self {
977 region: self.region.slice(boundary..)?,
978 length: self.length - mid,
979 _t: PhantomData,
980 };
981 Ok((left, right))
982 }
983}
984
985// SAFETY: the region comes from a live `DeviceOutput` or a `from_raw_parts` caller, and slicing and splitting keep its identity and bounds.
986unsafe impl<T: DeviceRepr> DeviceRegionProvider for DeviceOutputView<'_, T> {
987 fn region(&self) -> DeviceRegion<'_> {
988 self.region
989 }
990}
991
992// SAFETY: construction validated `length` elements of `T` against the region's size and alignment, and no initialized reads are claimed.
993unsafe impl<T: DeviceRepr> DeviceRange<T> for DeviceOutputView<'_, T> {
994 fn len(&self) -> usize {
995 self.length
996 }
997}
998
999// SAFETY: the view holds the exclusive borrow of its writable range, and the pointer is that range's start.
1000unsafe impl<T: DeviceRepr> DeviceOutput<T> for DeviceOutputView<'_, T> {
1001 fn as_mut_ptr(&mut self) -> *mut T {
1002 self.region.as_ptr().cast()
1003 }
1004}
1005
1006fn validate_view<T: DeviceRepr>(region: DeviceRegion<'_>, length: usize) -> Result<()> {
1007 let () = T::LAYOUT;
1008 let bytes = length
1009 .checked_mul(size_of::<T>())
1010 .ok_or_else(|| Error::out_of_range("view byte length"))?;
1011 if bytes != region.byte_len() {
1012 return Err(Error::size_mismatch(
1013 "view region",
1014 bytes,
1015 region.byte_len(),
1016 ));
1017 }
1018
1019 if length != 0 && size_of::<T>() == 0 {
1020 return Err(Error::not_positive("element size"));
1021 }
1022
1023 if length != 0 && !region.as_ptr().addr().is_multiple_of(align_of::<T>()) {
1024 return Err(Error::misaligned("view address", align_of::<T>()));
1025 }
1026
1027 Ok(())
1028}
1029
1030impl<'a, T: DeviceRepr> DeviceView<'a, T> {
1031 /// Consumes the typed borrow into allocation metadata without granting new access.
1032 #[must_use]
1033 pub fn into_region(self) -> DeviceRegion<'a> {
1034 self.region
1035 }
1036
1037 /// Borrows a region containing `length` values of `T`.
1038 ///
1039 /// # Safety
1040 ///
1041 /// The region must contain valid `T` values for the returned lifetime.
1042 /// Access through other aliases must respect this shared borrow and CUDA ordering.
1043 ///
1044 /// # Errors
1045 ///
1046 /// Returns an error if `length * size_of::<T>()` overflows or differs from the region’s byte length, or a nonempty region has a zero-sized element type or insufficient alignment.
1047 pub unsafe fn from_raw_parts(region: DeviceRegion<'a>, length: usize) -> Result<Self> {
1048 validate_view::<T>(region, length)?;
1049 Ok(Self {
1050 region,
1051 length,
1052 _t: PhantomData,
1053 })
1054 }
1055
1056 /// Borrows every initialized element of a device allocation without copying data.
1057 #[must_use]
1058 pub fn from_memory(memory: &'a DeviceMemory<T>) -> Self {
1059 let () = T::LAYOUT;
1060 Self {
1061 region: memory.region(),
1062 length: memory.len(),
1063 _t: PhantomData,
1064 }
1065 }
1066
1067 /// Borrows any typed provider that also retains allocation metadata.
1068 pub fn from_buffer<B: DeviceSlice<T> + ?Sized>(buffer: &'a B) -> Self {
1069 let () = T::LAYOUT;
1070 Self {
1071 region: buffer.region(),
1072 length: buffer.len(),
1073 _t: PhantomData,
1074 }
1075 }
1076
1077 /// Returns the CUDA-accessible element pointer.
1078 ///
1079 /// An empty view returns an aligned dangling pointer.
1080 /// This pointer does not grant host access.
1081 #[must_use]
1082 pub fn as_ptr(&self) -> *const T {
1083 if self.length == 0 {
1084 NonNull::<T>::dangling().as_ptr()
1085 } else {
1086 self.region.as_ptr().cast()
1087 }
1088 }
1089
1090 /// Returns the number of elements in the view.
1091 #[must_use]
1092 pub const fn len(&self) -> usize {
1093 self.length
1094 }
1095
1096 /// Returns whether the view contains no elements.
1097 #[must_use]
1098 pub const fn is_empty(&self) -> bool {
1099 self.length == 0
1100 }
1101
1102 /// Returns the context associated with the viewed allocation.
1103 #[must_use]
1104 pub fn context(&self) -> &'a Arc<Context> {
1105 self.region.context()
1106 }
1107
1108 /// Returns the view’s exact byte range and allocation identity.
1109 #[must_use]
1110 pub const fn region(&self) -> DeviceRegion<'a> {
1111 self.region
1112 }
1113
1114 /// Copies every viewed element into a host slice and waits for completion.
1115 ///
1116 /// # Errors
1117 ///
1118 /// Returns an error for unequal element counts or byte-size overflow.
1119 /// Also propagates access-tracking, readiness synchronization, context binding, stream-capture, CUDA copy, and stream synchronization errors.
1120 /// A nonempty synchronous transfer is rejected during stream capture.
1121 pub fn copy_to_host(&self, destination: &mut [T]) -> Result<()>
1122 where
1123 T: AnyBitPatternDeviceRepr,
1124 {
1125 transfer::copy_to_host(self, destination)
1126 }
1127
1128 /// Copies every viewed element into a new host vector and waits for completion.
1129 ///
1130 /// # Errors
1131 ///
1132 /// Propagates byte-size overflow, access-tracking, readiness synchronization, context-binding, stream-capture, CUDA copy, and stream synchronization errors.
1133 /// A nonempty synchronous transfer is rejected during stream capture.
1134 pub fn copy_to_host_vec(&self) -> Result<Vec<T>>
1135 where
1136 T: AnyBitPatternDeviceRepr,
1137 {
1138 transfer::copy_to_host_vec(self)
1139 }
1140
1141 /// Returns a view of an element subrange, preserving allocation identity and readiness.
1142 ///
1143 /// # Errors
1144 ///
1145 /// Returns an error if the element range is reversed, exceeds this range’s bounds, or an inclusive bound cannot be converted without overflow.
1146 pub fn slice<R: RangeBounds<usize>>(self, range: R) -> Result<Self> {
1147 let (start, end) = bounds_to_range(range, self.length)?;
1148 let region = self
1149 .region
1150 .slice(start * size_of::<T>()..end * size_of::<T>())?;
1151 Ok(Self {
1152 region,
1153 length: end - start,
1154 _t: PhantomData,
1155 })
1156 }
1157
1158 /// Reinterprets initialized bytes as values accepting every bit pattern.
1159 ///
1160 /// # Errors
1161 ///
1162 /// Returns an error if `U` is zero-sized, the region’s byte length is not divisible by `size_of::<U>()`, or a nonempty region is not aligned for `U`.
1163 pub fn cast<U: AnyBitPatternDeviceRepr>(self) -> Result<DeviceView<'a, U>>
1164 where
1165 T: NoUninitDeviceRepr,
1166 {
1167 let () = T::LAYOUT;
1168 // SAFETY: the source contains initialized bytes and every destination pattern is valid.
1169 unsafe { self.cast_unchecked() }
1170 }
1171
1172 /// Reinterprets a region with a caller-established initialization contract.
1173 ///
1174 /// # Safety
1175 ///
1176 /// Every destination element must be initialized and valid for `U`.
1177 /// Alignment and byte length are checked by this method.
1178 ///
1179 /// # Errors
1180 ///
1181 /// Returns an error if `U` is zero-sized, the region’s byte length is not divisible by `size_of::<U>()`, or a nonempty region is not aligned for `U`.
1182 pub unsafe fn cast_unchecked<U: DeviceRepr>(self) -> Result<DeviceView<'a, U>> {
1183 let length = cast_length::<U>(self.region)?;
1184 Ok(DeviceView {
1185 region: self.region,
1186 length,
1187 _t: PhantomData,
1188 })
1189 }
1190}
1191
1192impl<'a, T: DeviceRepr> DeviceViewMut<'a, T> {
1193 /// Consumes the typed borrow into allocation metadata without granting access.
1194 #[must_use]
1195 pub fn into_region(self) -> DeviceRegion<'a> {
1196 self.region
1197 }
1198
1199 /// Exclusively borrows a region containing `length` values of `T`.
1200 ///
1201 /// # Safety
1202 ///
1203 /// The region must contain valid `T` values and remain exclusively borrowed for the returned lifetime, including all GPU work using this view.
1204 ///
1205 /// # Errors
1206 ///
1207 /// Returns an error if `length * size_of::<T>()` overflows or differs from the region’s byte length, or a nonempty region has a zero-sized element type or insufficient alignment.
1208 pub unsafe fn from_raw_parts(region: DeviceRegion<'a>, length: usize) -> Result<Self> {
1209 validate_view::<T>(region, length)?;
1210 Ok(Self {
1211 region,
1212 length,
1213 _t: PhantomData,
1214 })
1215 }
1216
1217 /// Exclusively borrows every initialized element of a device allocation without copying data.
1218 pub fn from_memory(memory: &'a mut DeviceMemory<T>) -> Self {
1219 let () = T::LAYOUT;
1220 Self {
1221 region: memory.region(),
1222 length: memory.len(),
1223 _t: PhantomData,
1224 }
1225 }
1226
1227 /// Exclusively borrows an initialized typed provider without copying data.
1228 pub fn from_buffer<B: DeviceSliceMut<T> + ?Sized>(buffer: &'a mut B) -> Self {
1229 let () = T::LAYOUT;
1230 Self {
1231 region: buffer.region(),
1232 length: buffer.len(),
1233 _t: PhantomData,
1234 }
1235 }
1236
1237 /// Borrows this mutable view again for a shorter exclusive lifetime.
1238 pub fn reborrow(&mut self) -> DeviceViewMut<'_, T> {
1239 DeviceViewMut {
1240 region: self.region(),
1241 length: self.length,
1242 _t: PhantomData,
1243 }
1244 }
1245
1246 /// Returns the CUDA-accessible element pointer.
1247 ///
1248 /// An empty view returns an aligned dangling pointer.
1249 /// This pointer does not grant host access.
1250 #[must_use]
1251 pub fn as_ptr(&self) -> *const T {
1252 if self.length == 0 {
1253 NonNull::<T>::dangling().as_ptr()
1254 } else {
1255 self.region.as_ptr().cast()
1256 }
1257 }
1258
1259 /// Returns the exclusively borrowed CUDA-accessible element pointer.
1260 ///
1261 /// This pointer does not grant host access or synchronize pending work.
1262 pub fn as_mut_ptr(&mut self) -> *mut T {
1263 self.as_ptr().cast_mut()
1264 }
1265
1266 /// Returns the number of elements in the view.
1267 #[must_use]
1268 pub const fn len(&self) -> usize {
1269 self.length
1270 }
1271
1272 /// Returns whether the view contains no elements.
1273 #[must_use]
1274 pub const fn is_empty(&self) -> bool {
1275 self.length == 0
1276 }
1277
1278 /// Returns the context associated with the viewed allocation.
1279 #[must_use]
1280 pub fn context(&self) -> &Arc<Context> {
1281 self.region.context()
1282 }
1283
1284 /// Returns the view’s exact byte range and allocation identity.
1285 #[must_use]
1286 pub fn region(&self) -> DeviceRegion<'_> {
1287 self.region
1288 }
1289
1290 /// Copies a host slice into the entire view and waits for completion.
1291 ///
1292 /// # Errors
1293 ///
1294 /// Returns an error for unequal element counts or byte-size overflow.
1295 /// Also propagates access-tracking, readiness synchronization, context binding, stream-capture, CUDA copy, and stream synchronization errors.
1296 /// A nonempty synchronous transfer is rejected during stream capture.
1297 pub fn copy_from_host(&mut self, source: &[T]) -> Result<()> {
1298 transfer::copy_from_host(self, source)
1299 }
1300
1301 /// Copies a disjoint device range into the entire view and waits for completion.
1302 ///
1303 /// # Errors
1304 ///
1305 /// Returns an error if the ranges have different contexts or element counts, overlap in the same allocation, or their byte size overflows.
1306 /// Also propagates access-tracking, readiness synchronization, context binding, stream-capture, CUDA copy, and stream synchronization errors.
1307 /// A nonempty synchronous transfer is rejected during stream capture.
1308 pub fn copy_from_device<B: DeviceSlice<T> + ?Sized>(&mut self, source: &B) -> Result<()> {
1309 copy_device(self, source)
1310 }
1311
1312 /// Copies every viewed element into a host slice and waits for completion.
1313 ///
1314 /// # Errors
1315 ///
1316 /// Returns an error for unequal element counts or byte-size overflow.
1317 /// Also propagates access-tracking, readiness synchronization, context binding, stream-capture, CUDA copy, and stream synchronization errors.
1318 /// A nonempty synchronous transfer is rejected during stream capture.
1319 pub fn copy_to_host(&self, destination: &mut [T]) -> Result<()>
1320 where
1321 T: AnyBitPatternDeviceRepr,
1322 {
1323 self.as_view().copy_to_host(destination)
1324 }
1325
1326 /// Copies every viewed element into a new host vector and waits for completion.
1327 ///
1328 /// # Errors
1329 ///
1330 /// Propagates byte-size overflow, access-tracking, readiness synchronization, context-binding, stream-capture, CUDA copy, and stream synchronization errors.
1331 /// A nonempty synchronous transfer is rejected during stream capture.
1332 pub fn copy_to_host_vec(&self) -> Result<Vec<T>>
1333 where
1334 T: AnyBitPatternDeviceRepr,
1335 {
1336 self.as_view().copy_to_host_vec()
1337 }
1338
1339 /// Borrows this view for reading without extending the lifetime of the mutable borrow.
1340 #[must_use]
1341 pub fn as_view(&self) -> DeviceView<'_, T> {
1342 DeviceView {
1343 region: self.region,
1344 length: self.length,
1345 _t: PhantomData,
1346 }
1347 }
1348
1349 /// Borrows an initialized element subrange for reading.
1350 ///
1351 /// # Errors
1352 ///
1353 /// Returns an error if the element range is reversed, exceeds this range’s bounds, or an inclusive bound cannot be converted without overflow.
1354 pub fn slice<R: RangeBounds<usize>>(&self, range: R) -> Result<DeviceView<'_, T>> {
1355 self.as_view().slice(range)
1356 }
1357
1358 /// Exclusively borrows an initialized element subrange.
1359 ///
1360 /// # Errors
1361 ///
1362 /// Returns an error if the element range is reversed, exceeds this range’s bounds, or an inclusive bound cannot be converted without overflow.
1363 pub fn slice_mut<R: RangeBounds<usize>>(&mut self, range: R) -> Result<DeviceViewMut<'_, T>> {
1364 let (start, end) = bounds_to_range(range, self.length)?;
1365 let region = self
1366 .region
1367 .slice(start * size_of::<T>()..end * size_of::<T>())?;
1368 Ok(DeviceViewMut {
1369 region,
1370 length: end - start,
1371 _t: PhantomData,
1372 })
1373 }
1374
1375 /// Borrows two disjoint mutable views, split at element index `mid`.
1376 ///
1377 /// # Errors
1378 ///
1379 /// Returns an error if `mid` exceeds the view’s element count.
1380 pub fn split_at_mut(
1381 &mut self,
1382 mid: usize,
1383 ) -> Result<(DeviceViewMut<'_, T>, DeviceViewMut<'_, T>)> {
1384 if mid > self.length {
1385 return Err(Error::buffer_too_small("view", mid, self.length));
1386 }
1387
1388 let bytes = mid * size_of::<T>();
1389 Ok((
1390 DeviceViewMut {
1391 region: self.region.slice(..bytes)?,
1392 length: mid,
1393 _t: PhantomData,
1394 },
1395 DeviceViewMut {
1396 region: self.region.slice(bytes..)?,
1397 length: self.length - mid,
1398 _t: PhantomData,
1399 },
1400 ))
1401 }
1402
1403 /// Reinterprets a mutable borrow while preserving both element types' validity.
1404 ///
1405 /// # Errors
1406 ///
1407 /// Returns an error if `U` is zero-sized, the region’s byte length is not divisible by `size_of::<U>()`, or a nonempty region is not aligned for `U`.
1408 pub fn cast<U: AnyBitPatternDeviceRepr + NoUninitDeviceRepr>(
1409 self,
1410 ) -> Result<DeviceViewMut<'a, U>>
1411 where
1412 T: AnyBitPatternDeviceRepr + NoUninitDeviceRepr,
1413 {
1414 let () = T::LAYOUT;
1415 // SAFETY: both representations accept all initialized bits and U cannot introduce uninitialized bytes.
1416 unsafe { self.cast_unchecked() }
1417 }
1418
1419 /// Reinterprets a mutable borrow under a caller-established validity contract.
1420 ///
1421 /// # Safety
1422 ///
1423 /// Every destination element must be initialized and valid for `U`.
1424 /// Writes through the returned view must leave valid `T` values when the borrow ends.
1425 ///
1426 /// # Errors
1427 ///
1428 /// Returns an error if `U` is zero-sized, the region’s byte length is not divisible by `size_of::<U>()`, or a nonempty region is not aligned for `U`.
1429 pub unsafe fn cast_unchecked<U: DeviceRepr>(self) -> Result<DeviceViewMut<'a, U>> {
1430 let length = cast_length::<U>(self.region)?;
1431 Ok(DeviceViewMut {
1432 region: self.region,
1433 length,
1434 _t: PhantomData,
1435 })
1436 }
1437}
1438
1439// SAFETY: the region comes from a live provider or a `from_raw_parts` caller, and slicing keeps its identity and bounds.
1440unsafe impl<T: DeviceRepr> DeviceRegionProvider for DeviceView<'_, T> {
1441 fn region(&self) -> DeviceRegion<'_> {
1442 self.region
1443 }
1444}
1445
1446// SAFETY: the region comes from a live provider or a `from_raw_parts` caller, and slicing and splitting keep its identity and bounds.
1447unsafe impl<T: DeviceRepr> DeviceRegionProvider for DeviceViewMut<'_, T> {
1448 fn region(&self) -> DeviceRegion<'_> {
1449 self.region
1450 }
1451}
1452
1453// SAFETY: the view holds the exclusive borrow of its range, and `as_mut_ptr` returns that range's start.
1454unsafe impl<T: DeviceRepr> DeviceOutput<T> for DeviceViewMut<'_, T> {
1455 fn as_mut_ptr(&mut self) -> *mut T {
1456 self.as_mut_ptr()
1457 }
1458}
1459
1460// SAFETY: `MaybeUninit<T>` has `T`'s size and alignment, so the validated range holds `length` slots for `T`, and no initialized reads are claimed.
1461unsafe impl<T: DeviceRepr> DeviceRange<T> for DeviceViewMut<'_, MaybeUninit<T>> {
1462 fn len(&self) -> usize {
1463 self.length
1464 }
1465}
1466
1467// SAFETY: the view exclusively borrows `length` writable `MaybeUninit<T>` slots, which have `T`'s layout.
1468unsafe impl<T: DeviceRepr> DeviceOutput<T> for DeviceViewMut<'_, MaybeUninit<T>> {
1469 fn as_mut_ptr(&mut self) -> *mut T {
1470 self.as_mut_ptr().cast()
1471 }
1472}
1473
1474impl<'a, T: DeviceRepr> DeviceViewMut<'a, MaybeUninit<T>> {
1475 /// Borrows this uninitialized range as a write-only output of `T` values.
1476 pub fn output(&mut self) -> DeviceOutputView<'_, T> {
1477 DeviceOutputView::from_output(self)
1478 }
1479
1480 /// Exposes elements initialized by a producer through this exclusive view.
1481 ///
1482 /// # Safety
1483 ///
1484 /// Every element must contain a valid T value.
1485 /// Producing writes must be ordered before all consumers, and must complete before host readback.
1486 #[must_use]
1487 pub unsafe fn assume_init(self) -> DeviceViewMut<'a, T> {
1488 let () = T::LAYOUT;
1489 DeviceViewMut {
1490 region: self.region,
1491 length: self.length,
1492 _t: PhantomData,
1493 }
1494 }
1495}
1496
1497impl<T: DeviceRepr> DeviceMemory<T> {
1498 /// Borrows all initialized elements as a shared device view.
1499 #[must_use]
1500 pub fn view(&self) -> DeviceView<'_, T> {
1501 DeviceView::from_memory(self)
1502 }
1503
1504 /// Borrows all initialized elements as an exclusive device view.
1505 pub fn view_mut(&mut self) -> DeviceViewMut<'_, T> {
1506 DeviceViewMut::from_memory(self)
1507 }
1508}
1509
1510impl<T: DeviceRepr> DeviceMemory<MaybeUninit<T>> {
1511 /// Borrows this uninitialized allocation as a write-only output of `T` values.
1512 pub fn output(&mut self) -> DeviceOutputView<'_, T> {
1513 DeviceOutputView::from_output(self)
1514 }
1515}
1516
1517// SAFETY: the owner retains its allocation, whose `length` elements start at `ptr`, and `region()` slices exactly those bytes.
1518unsafe impl<T: DeviceRepr> DeviceRange<T> for DeviceMemory<T> {
1519 fn as_device_ptr(&self) -> *const T {
1520 self.as_ptr()
1521 }
1522
1523 fn len(&self) -> usize {
1524 self.len()
1525 }
1526}
1527
1528// SAFETY: `DeviceMemory<T>` is only constructed initialized; uninitialized storage is typed `DeviceMemory<MaybeUninit<T>>`.
1529unsafe impl<T: DeviceRepr> DeviceSlice<T> for DeviceMemory<T> {}
1530
1531// SAFETY: `&mut DeviceMemory<T>` is exclusive, and its input and output pointers are both `ptr`.
1532unsafe impl<T: DeviceRepr> DeviceSliceMut<T> for DeviceMemory<T> {}
1533
1534// SAFETY: the view's pointer and length come from the same validated region.
1535unsafe impl<T: DeviceRepr> DeviceRange<T> for DeviceView<'_, T> {
1536 fn as_device_ptr(&self) -> *const T {
1537 self.as_ptr()
1538 }
1539
1540 fn len(&self) -> usize {
1541 self.length
1542 }
1543}
1544
1545// SAFETY: a `DeviceView<T>` is built from an initialized provider or a `from_raw_parts` caller that vouches for valid values.
1546unsafe impl<T: DeviceRepr> DeviceSlice<T> for DeviceView<'_, T> {}
1547
1548// SAFETY: the view's pointer and length come from the same validated region.
1549unsafe impl<T: DeviceRepr> DeviceRange<T> for DeviceViewMut<'_, T> {
1550 fn as_device_ptr(&self) -> *const T {
1551 self.as_ptr()
1552 }
1553
1554 fn len(&self) -> usize {
1555 self.length
1556 }
1557}
1558
1559// SAFETY: a `DeviceViewMut<T>` is built from an initialized provider or a `from_raw_parts` caller that vouches for valid values.
1560unsafe impl<T: DeviceRepr> DeviceSlice<T> for DeviceViewMut<'_, T> {}
1561
1562// SAFETY: the view holds an exclusive borrow, and its input and output pointers describe one range.
1563unsafe impl<T: DeviceRepr> DeviceSliceMut<T> for DeviceViewMut<'_, T> {}
1564
1565// SAFETY: a slice's pointer and length describe live, aligned `T` values readable for the borrow.
1566unsafe impl<T: DeviceRepr> HostSlice<T> for [T] {
1567 fn as_host_ptr(&self) -> *const T {
1568 self.as_ptr()
1569 }
1570
1571 fn len(&self) -> usize {
1572 self.len()
1573 }
1574}
1575
1576// SAFETY: `&mut [T]` grants exclusive write access to the same range.
1577unsafe impl<T: DeviceRepr> HostSliceMut<T> for [T] {
1578 fn as_host_mut_ptr(&mut self) -> *mut T {
1579 self.as_mut_ptr()
1580 }
1581}
1582
1583// SAFETY: an array's pointer and `N` describe live, aligned `T` values readable for the borrow.
1584unsafe impl<T: DeviceRepr, const N: usize> HostSlice<T> for [T; N] {
1585 fn as_host_ptr(&self) -> *const T {
1586 self.as_ptr()
1587 }
1588
1589 fn len(&self) -> usize {
1590 N
1591 }
1592}
1593
1594// SAFETY: `&mut [T; N]` grants exclusive write access to the same range.
1595unsafe impl<T: DeviceRepr, const N: usize> HostSliceMut<T> for [T; N] {
1596 fn as_host_mut_ptr(&mut self) -> *mut T {
1597 self.as_mut_ptr()
1598 }
1599}
1600
1601// SAFETY: a vector's pointer and length describe its live, aligned, initialized elements.
1602unsafe impl<T: DeviceRepr> HostSlice<T> for Vec<T> {
1603 fn as_host_ptr(&self) -> *const T {
1604 self.as_ptr()
1605 }
1606
1607 fn len(&self) -> usize {
1608 self.len()
1609 }
1610}
1611
1612// SAFETY: `&mut Vec<T>` grants exclusive write access to the same elements.
1613unsafe impl<T: DeviceRepr> HostSliceMut<T> for Vec<T> {
1614 fn as_host_mut_ptr(&mut self) -> *mut T {
1615 self.as_mut_ptr()
1616 }
1617}
1618
1619fn bounds_to_range<R: RangeBounds<usize>>(range: R, length: usize) -> Result<(usize, usize)> {
1620 let start = match range.start_bound() {
1621 Bound::Included(&value) => value,
1622 Bound::Excluded(&value) => value
1623 .checked_add(1)
1624 .ok_or_else(|| Error::out_of_range("range start"))?,
1625 Bound::Unbounded => 0,
1626 };
1627 let end = match range.end_bound() {
1628 Bound::Included(&value) => value
1629 .checked_add(1)
1630 .ok_or_else(|| Error::out_of_range("range end"))?,
1631 Bound::Excluded(&value) => value,
1632 Bound::Unbounded => length,
1633 };
1634
1635 if start > end {
1636 return Err(Error::out_of_range("range start"));
1637 }
1638
1639 if end > length {
1640 return Err(Error::buffer_too_small("range", end, length));
1641 }
1642
1643 Ok((start, end))
1644}