singe-cuda 0.1.0

Safe Rust wrappers for the CUDA driver and runtime APIs, including runtime compilation of CUDA C++ and NVTX annotations.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
//! Borrowed typed views over CUDA-accessible memory.

use std::{
    marker::PhantomData,
    mem::{MaybeUninit, align_of, size_of},
    num::Wrapping,
    ops::{Bound, Range, RangeBounds},
    ptr::NonNull,
    sync::{
        Arc,
        atomic::{AtomicU64, Ordering},
    },
};

#[cfg(feature = "macros")]
pub use singe_cuda_macros::{
    AnyBitPatternDeviceRepr, DeviceRepr, NoUninitDeviceRepr, ZeroableDeviceRepr,
};

use crate::{
    context::Context,
    error::{Error, Result},
    memory::{
        DeviceAllocation, DeviceMemory,
        transfer::{self, copy_device},
    },
    stream::Stream,
    types::{Complex, bf16, f4e2m1, f6e2m3, f6e3m2, f8e4m3, f8e5m2, f8ue5m3, f8ue8m0, f16},
    utility::ranges_overlap,
};

/// A Rust type that can be represented as plain CUDA device memory.
///
/// # Safety
///
/// Implementors must have a stable representation without implicit padding, Rust ownership, or host references.
/// Copying valid values must not depend on host-only pointer validity.
/// Memory APIs must evaluate [`Self::LAYOUT`] before transferring values or exposing initialized storage.
/// A generic implementation may reject unsupported layouts through that constant.
pub unsafe trait DeviceRepr: Copy + 'static {
    /// Checks that this concrete type has a transferable layout.
    ///
    /// Derives evaluate field layouts and reject implicit padding at compile time.
    /// Manual implementations must uphold the layout contract whenever this constant evaluates successfully.
    const LAYOUT: () = ();
}

/// A [`DeviceRepr`] whose all-zero byte pattern is a valid value.
///
/// # Safety
///
/// Implementors must accept an all-zero byte pattern as a valid instance.
pub unsafe trait ZeroableDeviceRepr: DeviceRepr {}

/// A device representation whose valid values contain no uninitialized bytes.
///
/// Safe byte reinterpretation requires this guarantee on the source type.
/// `MaybeUninit<T>` does not satisfy it, even when `T` does.
///
/// # Safety
///
/// Every byte of every valid value must be initialized whenever `Self::LAYOUT` evaluates successfully.
/// Consumers must evaluate that layout before reading or reinterpreting the representation's bytes.
pub unsafe trait NoUninitDeviceRepr: DeviceRepr {}

/// A [`DeviceRepr`] for which every initialized byte pattern is a valid value.
///
/// This permits safe readback from device storage without a kernel-specific validity check.
/// It does not permit reading uninitialized memory.
///
/// # Safety
///
/// Every initialized bit pattern of the representation must be valid for `Self`.
/// Types with restricted values, including `bool`, do not satisfy this contract.
pub unsafe trait AnyBitPatternDeviceRepr: ZeroableDeviceRepr {}

/// Contiguous device storage that a producer may initialize as values of `T`.
///
/// Both initialized and uninitialized buffers can provide output storage.
/// This trait does not grant permission to read existing elements or establish that a producer initializes the entire range.
///
/// # Safety
///
/// 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.
/// Mutable access must be exclusive.
/// The byte length must fit `usize`.
/// `region()` must describe that same pointer and the exact byte range of those elements.
pub unsafe trait DeviceOutput<T: DeviceRepr>: DeviceRange<T> {
    /// Returns a pointer to the writable device output range.
    ///
    /// Writing valid `T` values requires the caller to establish CUDA execution ordering.
    fn as_mut_ptr(&mut self) -> *mut T;
}

macro_rules! impl_device_repr {
    ($($ty:ty),* $(,)?) => {
        $(
            // SAFETY: the listed scalars have a fixed size, no padding, and no pointers or owned resources.
            unsafe impl DeviceRepr for $ty {}
            // SAFETY: every byte of a valid scalar of these types is initialized.
            unsafe impl NoUninitDeviceRepr for $ty {}
            // SAFETY: all-zero bytes are the zero value of each listed integer and floating-point type, and `()` has no bytes.
            unsafe impl ZeroableDeviceRepr for $ty {}
            // SAFETY: every bit pattern is a valid value of the listed integer and floating-point types.
            unsafe impl AnyBitPatternDeviceRepr for $ty {}
        )*
    };
}

impl_device_repr!(
    (),
    u8,
    u16,
    u32,
    u64,
    u128,
    usize,
    i8,
    i16,
    i32,
    i64,
    i128,
    isize,
    f32,
    f64,
    f16,
    bf16,
    f8e4m3,
    f8e5m2,
    f8ue8m0,
    f8ue5m3,
    f6e2m3,
    f6e3m2,
    f4e2m1,
);

// SAFETY: `bool` is one byte with no padding and no pointers or owned resources.
// It is not `AnyBitPatternDeviceRepr`, since device bytes other than 0 and 1 are invalid.
unsafe impl DeviceRepr for bool {}

// SAFETY: the single byte of a valid `bool` is initialized.
unsafe impl NoUninitDeviceRepr for bool {}

// SAFETY: the zero byte is `false`.
unsafe impl ZeroableDeviceRepr for bool {}

// SAFETY: array elements are laid out without padding between them, so `[T; N]` inherits `T`'s layout check.
unsafe impl<T: DeviceRepr, const N: usize> DeviceRepr for [T; N] {
    const LAYOUT: () = T::LAYOUT;
}

// SAFETY: an all-zero array is `N` all-zero elements, each valid because `T: ZeroableDeviceRepr`.
unsafe impl<T: ZeroableDeviceRepr, const N: usize> ZeroableDeviceRepr for [T; N] {}

// SAFETY: an array's bytes are exactly its elements' bytes, which `T: NoUninitDeviceRepr` keeps initialized.
unsafe impl<T: NoUninitDeviceRepr, const N: usize> NoUninitDeviceRepr for [T; N] {}

// SAFETY: every array bit pattern is `N` element patterns, each valid because `T: AnyBitPatternDeviceRepr`.
unsafe impl<T: AnyBitPatternDeviceRepr, const N: usize> AnyBitPatternDeviceRepr for [T; N] {}

// SAFETY: `Wrapping<T>` is `repr(transparent)` over `T`, so it has `T`'s layout.
unsafe impl<T: DeviceRepr> DeviceRepr for Wrapping<T> {
    const LAYOUT: () = T::LAYOUT;
}

// SAFETY: `Wrapping<T>` is `repr(transparent)`, so all-zero bytes are a valid `T` inside it.
unsafe impl<T: ZeroableDeviceRepr> ZeroableDeviceRepr for Wrapping<T> {}

// SAFETY: `Wrapping<T>` is `repr(transparent)`, so its bytes are `T`'s initialized bytes.
unsafe impl<T: NoUninitDeviceRepr> NoUninitDeviceRepr for Wrapping<T> {}

// SAFETY: `Wrapping<T>` is `repr(transparent)`, so every bit pattern valid for `T` is valid for it.
unsafe impl<T: AnyBitPatternDeviceRepr> AnyBitPatternDeviceRepr for Wrapping<T> {}

// SAFETY: `Complex<T>` is `repr(C)` with two `T` fields, so it has no padding beyond `T`'s own.
unsafe impl<T: DeviceRepr> DeviceRepr for Complex<T> {
    const LAYOUT: () = T::LAYOUT;
}

// SAFETY: all-zero bytes are two all-zero `T` fields, each valid because `T: ZeroableDeviceRepr`.
unsafe impl<T: ZeroableDeviceRepr> ZeroableDeviceRepr for Complex<T> {}

// SAFETY: the two padding-free `T` fields cover every byte, and `T: NoUninitDeviceRepr` keeps them initialized.
unsafe impl<T: NoUninitDeviceRepr> NoUninitDeviceRepr for Complex<T> {}

// SAFETY: every bit pattern is two `T` patterns, each valid because `T: AnyBitPatternDeviceRepr`.
unsafe impl<T: AnyBitPatternDeviceRepr> AnyBitPatternDeviceRepr for Complex<T> {}

// SAFETY: `MaybeUninit<T>` has `T`'s size and alignment and owns nothing, and `T: DeviceRepr` rules out host ownership.
unsafe impl<T: DeviceRepr> DeviceRepr for MaybeUninit<T> {
    const LAYOUT: () = T::LAYOUT;
}

// SAFETY: any bytes, zero included, are a valid `MaybeUninit<T>`.
unsafe impl<T: DeviceRepr> ZeroableDeviceRepr for MaybeUninit<T> {}

// SAFETY: any initialized bit pattern is a valid `MaybeUninit<T>`.
unsafe impl<T: DeviceRepr> AnyBitPatternDeviceRepr for MaybeUninit<T> {}

// SAFETY: `PhantomData` is zero-sized and owns no resource, whatever its marker type.
unsafe impl<T: ?Sized + 'static> DeviceRepr for PhantomData<T> {}

// SAFETY: `PhantomData` has no bytes, so the empty all-zero pattern is its only value.
unsafe impl<T: ?Sized + 'static> ZeroableDeviceRepr for PhantomData<T> {}

// SAFETY: `PhantomData` has no bytes that could be uninitialized.
unsafe impl<T: ?Sized + 'static> NoUninitDeviceRepr for PhantomData<T> {}

// SAFETY: `PhantomData` has no bytes, so its one empty bit pattern is valid.
unsafe impl<T: ?Sized + 'static> AnyBitPatternDeviceRepr for PhantomData<T> {}

/// Identifies one allocation across its typed handles, mappings, and subranges.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct AllocationId(u64);

impl AllocationId {
    /// Creates an identity for a new allocation or an externally owned resource.
    /// Reuse this identity for every alias of the same live allocation.
    ///
    /// # Panics
    ///
    /// Panics if the process exhausts the nonzero `u64` allocation identity space.
    pub fn create() -> Self {
        static NEXT_ID: AtomicU64 = AtomicU64::new(1);
        Self(
            NEXT_ID
                .try_update(Ordering::Relaxed, Ordering::Relaxed, |id| id.checked_add(1))
                .expect("allocation identity exhausted"),
        )
    }
}

/// A byte range in pinned or registered host storage, independent of device mappings.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct HostRegion<'a> {
    context: &'a Arc<Context>,
    allocation_id: AllocationId,
    allocation_bytes: usize,
    offset: usize,
    bytes: usize,
    portable: bool,
}

impl<'a> HostRegion<'a> {
    /// Describes a complete live host allocation or registration.
    ///
    /// # Safety
    ///
    /// The range must remain registered for `'a` in `context`.
    /// All host and device aliases must share `allocation_id` and byte offsets.
    /// `portable` must reflect CUDA's registration or allocation flags.
    #[must_use]
    pub unsafe fn from_raw_parts(
        context: &'a Arc<Context>,
        allocation_id: AllocationId,
        bytes: usize,
        portable: bool,
    ) -> Self {
        Self {
            context,
            allocation_id,
            allocation_bytes: bytes,
            offset: 0,
            bytes,
            portable,
        }
    }

    /// Returns the CUDA context associated with this allocation.
    #[must_use]
    pub fn context(self) -> &'a Arc<Context> {
        self.context
    }

    /// Returns the identity shared by all aliases of the backing allocation.
    #[must_use]
    pub const fn allocation_id(self) -> AllocationId {
        self.allocation_id
    }

    /// Returns the byte length of the complete allocation before slicing.
    #[must_use]
    pub const fn allocation_byte_len(self) -> usize {
        self.allocation_bytes
    }

    /// Returns the byte length of this region.
    #[must_use]
    pub const fn byte_len(self) -> usize {
        self.bytes
    }

    /// Returns whether CUDA recognizes this host allocation or registration in other contexts.
    #[must_use]
    pub const fn is_portable(self) -> bool {
        self.portable
    }

    /// Returns this region’s byte offsets relative to the start of the backing allocation.
    #[must_use]
    pub fn byte_range(self) -> Range<usize> {
        self.offset..self.offset + self.bytes
    }

    /// Returns metadata for a byte subrange while preserving the host registration identity.
    ///
    /// # Errors
    ///
    /// Returns an error if the byte range is reversed, exceeds this range’s bounds, or an inclusive bound cannot be converted without overflow.
    pub fn slice<R: RangeBounds<usize>>(self, range: R) -> Result<Self> {
        let (start, end) = bounds_to_range(range, self.bytes)?;
        Ok(Self {
            offset: self.offset + start,
            bytes: end - start,
            ..self
        })
    }
}

/// A borrowed byte range within one context-associated allocation.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct DeviceRegion<'a> {
    context: &'a Arc<Context>,
    stream: Option<&'a Stream>,
    allocation_id: AllocationId,
    base: *mut u8,
    allocation_bytes: usize,
    offset: usize,
    bytes: usize,
}

impl<'a> DeviceRegion<'a> {
    /// Describes an externally established allocation and its full byte range.
    ///
    /// # Safety
    ///
    /// `base` must identify `bytes` live CUDA-accessible bytes in `context` for `'a`.
    /// `allocation_id` must be shared by all aliases of this allocation and must not identify another live allocation.
    ///
    /// # Errors
    ///
    /// Returns an error if a nonempty range has a null base pointer or its ending address overflows `usize`.
    pub unsafe fn from_raw_parts(
        context: &'a Arc<Context>,
        allocation_id: AllocationId,
        base: *mut u8,
        bytes: usize,
    ) -> Result<Self> {
        if bytes != 0 && base.is_null() {
            return Err(Error::null_pointer("base"));
        }

        base.addr()
            .checked_add(bytes)
            .ok_or_else(|| Error::out_of_range("region end address"))?;
        Ok(Self {
            context,
            stream: None,
            allocation_id,
            base,
            allocation_bytes: bytes,
            offset: 0,
            bytes,
        })
    }

    /// Returns the CUDA context associated with this allocation.
    #[must_use]
    pub fn context(self) -> &'a Arc<Context> {
        self.context
    }

    /// Returns the stream that orders allocation and writes for stream-ordered storage.
    #[must_use]
    pub const fn stream(self) -> Option<&'a Stream> {
        self.stream
    }

    /// Associates this region with the stream that establishes its readiness.
    ///
    /// # Safety
    ///
    /// Allocation and pending producer writes must be ordered on this stream.
    /// Work on other streams must establish dependencies before accessing the region.
    ///
    /// # Errors
    ///
    /// Returns an error if the stream belongs to a different context.
    pub unsafe fn with_stream(self, stream: &'a Stream) -> Result<Self> {
        if stream.context() != self.context {
            return Err(Error::StreamContextMismatch);
        }
        Ok(Self {
            stream: Some(stream),
            ..self
        })
    }

    /// Orders this range's allocation and producer stream before a consumer stream.
    ///
    /// # Errors
    ///
    /// Returns an error if the consumer stream belongs to a different context or joining the readiness stream fails.
    pub fn order_on(self, stream: &Stream) -> Result<()> {
        if stream.context() != self.context {
            return Err(Error::StreamContextMismatch);
        }

        if let Some(ready) = self.stream {
            stream.join(ready)?;
        }
        Ok(())
    }

    /// Waits for an associated allocation stream before synchronous access.
    ///
    /// # Errors
    ///
    /// Propagates access-tracking and synchronization errors while waiting for pending accesses to this region.
    pub fn synchronize(self) -> Result<()> {
        let _guard = self.context.acquire_host_access(&[self])?;
        Ok(())
    }

    /// Returns the identity shared by all aliases of the backing allocation.
    #[must_use]
    pub const fn allocation_id(self) -> AllocationId {
        self.allocation_id
    }

    /// Returns the byte length of the complete allocation before slicing.
    #[must_use]
    pub const fn allocation_byte_len(self) -> usize {
        self.allocation_bytes
    }

    /// Returns the byte length of this region.
    #[must_use]
    pub const fn byte_len(self) -> usize {
        self.bytes
    }

    /// Returns this region’s byte offsets relative to the start of the backing allocation.
    #[must_use]
    pub fn byte_range(self) -> Range<usize> {
        self.offset..self.offset + self.bytes
    }

    /// Reports conflicts between byte ranges sharing one allocation identity.
    /// Empty subranges inside another range conservatively count as conflicts.
    #[must_use]
    pub fn overlaps(self, other: Self) -> bool {
        self.allocation_id == other.allocation_id
            && ranges_overlap(&self.byte_range(), &other.byte_range())
    }

    /// Returns the CUDA-accessible pointer at this region’s starting byte offset.
    ///
    /// The pointer does not grant host access or establish initialization or exclusive access.
    #[must_use]
    pub fn as_ptr(self) -> *mut u8 {
        self.base.wrapping_add(self.offset)
    }

    /// Checks that a nonempty region starts at a multiple of `alignment` bytes, which must be nonzero.
    ///
    /// # Errors
    ///
    /// Returns [`Error::Misaligned`] naming `name` if the region is nonempty and its start is not a multiple of `alignment`.
    pub fn ensure_aligned(self, alignment: usize, name: &'static str) -> Result<()> {
        if self.bytes != 0 && !self.as_ptr().addr().is_multiple_of(alignment) {
            return Err(Error::misaligned(name, alignment));
        }
        Ok(())
    }

    /// Borrows a byte subrange while preserving allocation and context identity.
    ///
    /// # Errors
    ///
    /// Returns an error if the byte range is reversed, exceeds this range’s bounds, or an inclusive bound cannot be converted without overflow.
    pub fn slice<R: RangeBounds<usize>>(self, range: R) -> Result<Self> {
        let (start, end) = bounds_to_range(range, self.bytes)?;
        Ok(Self {
            offset: self.offset + start,
            bytes: end - start,
            ..self
        })
    }
}

/// Provides the allocation identity and byte range used by CUDA operations.
///
/// # Safety
///
/// Reported metadata must describe the same live memory as the provider's pointers.
/// All aliases must preserve allocation identity and byte offsets.
/// The context must stay retained while the provider is alive.
/// Returned regions must retain their identity, bounds, and liveness for the shared borrow.
pub unsafe trait DeviceRegionProvider {
    /// Borrows the exact allocation range described by this provider’s pointers.
    fn region(&self) -> DeviceRegion<'_>;
}

/// Retains an actual CUDA allocation and a checked byte range independently of typed buffers.
///
/// This is ownership and metadata only.
/// It does not establish initialization, exclusive access, or permission to enqueue conflicting work.
#[derive(Debug)]
pub struct OwnedDeviceRegion<O: DeviceRegionProvider + 'static = DeviceAllocation> {
    owner: Arc<O>,
    range: Range<usize>,
    readiness: Option<Stream>,
}

impl<O: DeviceRegionProvider + 'static> OwnedDeviceRegion<O> {
    /// Retains a checked byte range relative to the owner's exposed region.
    ///
    /// # Errors
    ///
    /// Returns an error if the byte range is reversed or exceeds the owner’s exposed region.
    pub fn from_owner(owner: Arc<O>, range: Range<usize>) -> Result<Self> {
        owner.region().slice(range.clone())?;
        Ok(Self {
            owner,
            range,
            readiness: None,
        })
    }

    #[must_use]
    pub(crate) fn into_owner(self) -> Arc<O> {
        self.owner
    }

    /// Returns the retained allocation provider.
    #[must_use]
    pub fn owner(&self) -> &Arc<O> {
        &self.owner
    }

    /// Returns the context associated with the retained allocation.
    #[must_use]
    pub fn context(&self) -> &Arc<Context> {
        self.owner.region().context()
    }

    /// Returns the byte length of the retained subrange.
    #[must_use]
    pub fn byte_len(&self) -> usize {
        self.range.len()
    }

    /// Narrows this retained range while preserving its backing owner and readiness stream.
    ///
    /// # Errors
    ///
    /// Returns an error if the byte range is reversed, exceeds this range’s bounds, or an inclusive bound cannot be converted without overflow.
    pub fn slice<R: RangeBounds<usize>>(mut self, range: R) -> Result<Self> {
        let (start, end) = bounds_to_range(range, self.range.len())?;
        self.range = self.range.start + start..self.range.start + end;
        Ok(self)
    }

    /// Associates pending writes with a retained stream without transferring allocation ownership.
    ///
    /// # Safety
    ///
    /// Allocation and producer writes must be ordered before consumers on this stream.
    /// Other streams must establish dependencies before accessing this range.
    ///
    /// # Errors
    ///
    /// Returns an error if the stream belongs to a different context.
    pub unsafe fn with_stream(mut self, stream: &Stream) -> Result<Self> {
        if self.context() != stream.context() {
            return Err(Error::StreamContextMismatch);
        }

        self.readiness = Some(stream.clone());
        Ok(self)
    }
}

impl<O: DeviceRegionProvider + 'static> Clone for OwnedDeviceRegion<O> {
    /// Clones allocation retention and metadata without granting another access lease.
    fn clone(&self) -> Self {
        Self {
            owner: Arc::clone(&self.owner),
            range: self.range.clone(),
            readiness: self.readiness.clone(),
        }
    }
}

// SAFETY: the retained provider keeps its region live, and slicing preserves its identity and bounds.
unsafe impl<O: DeviceRegionProvider + 'static> DeviceRegionProvider for OwnedDeviceRegion<O> {
    fn region(&self) -> DeviceRegion<'_> {
        let region = self
            .owner
            .region()
            .slice(self.range.clone())
            .expect("retained range exceeds its allocation");
        self.readiness.as_ref().map_or(region, |stream| {
            // SAFETY: `readiness` is set only by `Self::with_stream`, whose caller ordered allocation and producer writes on that stream.
            unsafe { region.with_stream(stream) }
                .expect("retained readiness stream context mismatch")
        })
    }
}

impl OwnedDeviceRegion {
    /// Retains this buffer's exact logical range, including its original allocation offset.
    #[must_use]
    pub fn from_memory<T: DeviceRepr>(memory: &DeviceMemory<T>) -> Self {
        Self {
            owner: Arc::clone(memory.allocation()),
            range: memory.region().byte_range(),
            readiness: None,
        }
    }
}

pub(crate) fn cast_length<T: DeviceRepr>(region: DeviceRegion<'_>) -> Result<usize> {
    let () = T::LAYOUT;
    let size = size_of::<T>();
    if size == 0 {
        return Err(Error::not_positive("element size"));
    }

    if !region.byte_len().is_multiple_of(size) {
        return Err(Error::misaligned("region byte length", size));
    }

    if region.byte_len() != 0 && !region.as_ptr().addr().is_multiple_of(align_of::<T>()) {
        return Err(Error::misaligned("region address", align_of::<T>()));
    }

    Ok(region.byte_len() / size)
}

/// Typed input metadata for a contiguous CUDA allocation range.
///
/// The range may be initialized by an earlier operation in a captured graph.
/// This trait does not establish initialized values or grant permission to read them.
/// Raw consumers must establish validity and ordering when they execute.
///
/// # Safety
///
/// The pointer must identify live, aligned CUDA-accessible storage for `len()` elements of `T` throughout the borrow.
/// The byte length must fit `usize`.
/// `region()` must describe the exact byte range, actual context, allocation identity, and offset.
/// Nonempty ranges must have the same pointer.
pub unsafe trait DeviceRange<T: DeviceRepr>: DeviceRegionProvider {
    /// Returns the context associated with the input allocation.
    fn context(&self) -> &Arc<Context> {
        self.region().context()
    }

    /// Returns the device input pointer without asserting that its values are initialized.
    ///
    /// An empty range returns an aligned dangling pointer.
    fn as_device_ptr(&self) -> *const T {
        if self.is_empty() {
            NonNull::<T>::dangling().as_ptr()
        } else {
            self.region().as_ptr().cast()
        }
    }

    /// Returns the number of input elements.
    fn len(&self) -> usize;

    /// Returns whether the input range contains no elements.
    fn is_empty(&self) -> bool {
        self.len() == 0
    }

    /// Returns the input range length in bytes.
    ///
    /// # Errors
    ///
    /// Returns an error if the element count multiplied by `size_of::<T>()` overflows `usize`.
    fn byte_len(&self) -> Result<usize> {
        let () = T::LAYOUT;
        self.len()
            .checked_mul(size_of::<T>())
            .ok_or_else(|| Error::out_of_range("input byte length"))
    }
}

/// A typed contiguous range containing initialized device values.
///
/// # Safety
///
/// Every element must contain a valid `T` for the borrow.
/// Safe consumers may read the range using CUDA, subject to stream ordering and shared-borrow rules.
pub unsafe trait DeviceSlice<T: DeviceRepr>: DeviceRange<T> {}

/// A mutable typed contiguous range of CUDA-accessible device memory.
///
/// # Safety
///
/// The mutable pointer must identify the same range as `DeviceSlice` and grant exclusive access for its mutable borrow, including work using that borrow.
/// Its initialized input and writable output capabilities must describe the same range.
pub unsafe trait DeviceSliceMut<T: DeviceRepr>: DeviceSlice<T> + DeviceOutput<T> {}

/// A typed contiguous host-memory range that can be copied to CUDA memory.
///
/// # Safety
///
/// The pointer must identify `len()` live, aligned `T` values readable for the borrow.
/// The byte length must fit `usize`; shared access must not mutate them.
pub unsafe trait HostSlice<T: DeviceRepr> {
    /// Returns a pointer to the readable host elements.
    fn as_host_ptr(&self) -> *const T;

    /// Returns the number of host elements.
    fn len(&self) -> usize;

    /// Returns whether the host range contains no elements.
    fn is_empty(&self) -> bool {
        self.len() == 0
    }
}

/// A mutable typed contiguous host-memory range that can be copied from CUDA memory.
///
/// # Safety
///
/// The mutable pointer must identify the same range as `HostSlice`, writable exclusively for the mutable borrow.
pub unsafe trait HostSliceMut<T: DeviceRepr>: HostSlice<T> {
    /// Returns a pointer to the exclusively writable host elements.
    fn as_host_mut_ptr(&mut self) -> *mut T;
}

/// Typed CUDA input metadata without an initialization guarantee.
///
/// Construction checks the element layout and preserves the allocation's context and range.
/// Reading values requires an unsafe consumer to establish initialization and order preceding producers before each read.
#[derive(Debug, Clone, Copy)]
pub struct DeviceInputView<'a, T: DeviceRepr> {
    region: DeviceRegion<'a>,
    length: usize,
    _t: PhantomData<&'a MaybeUninit<T>>,
}

impl<'a, T: DeviceRepr> DeviceInputView<'a, T> {
    /// Describes a live allocation range as input elements of `T`.
    ///
    /// # Errors
    ///
    /// 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`.
    pub fn create(region: DeviceRegion<'a>) -> Result<Self> {
        let length = cast_length::<T>(region)?;
        Ok(Self {
            region,
            length,
            _t: PhantomData,
        })
    }

    /// Borrows typed input metadata without strengthening its validity contract.
    pub fn from_buffer<B: DeviceRange<T> + ?Sized>(buffer: &'a B) -> Self {
        let () = T::LAYOUT;
        Self {
            region: buffer.region(),
            length: buffer.len(),
            _t: PhantomData,
        }
    }

    /// Returns the CUDA-accessible element pointer.
    ///
    /// An empty view returns an aligned dangling pointer.
    /// This pointer does not grant host access.
    #[must_use]
    pub fn as_ptr(&self) -> *const T {
        if self.length == 0 {
            NonNull::<T>::dangling().as_ptr()
        } else {
            self.region.as_ptr().cast()
        }
    }

    /// Returns the number of elements in the view.
    #[must_use]
    pub const fn len(&self) -> usize {
        self.length
    }

    /// Returns whether the view contains no elements.
    #[must_use]
    pub const fn is_empty(&self) -> bool {
        self.length == 0
    }

    /// Returns the context associated with the viewed allocation.
    #[must_use]
    pub fn context(&self) -> &'a Arc<Context> {
        self.region.context()
    }

    /// Returns the view’s exact byte range and allocation identity.
    #[must_use]
    pub const fn region(&self) -> DeviceRegion<'a> {
        self.region
    }

    /// Narrows input metadata while preserving its allocation identity and offset.
    ///
    /// # Errors
    ///
    /// Returns an error if the element range is reversed, exceeds this range’s bounds, or an inclusive bound cannot be converted without overflow.
    pub fn slice<R: RangeBounds<usize>>(self, range: R) -> Result<Self> {
        let (start, end) = bounds_to_range(range, self.length)?;
        Ok(Self {
            region: self
                .region
                .slice(start * size_of::<T>()..end * size_of::<T>())?,
            length: end - start,
            _t: PhantomData,
        })
    }

    /// Reinterprets input metadata without asserting initialized destination values.
    ///
    /// # Errors
    ///
    /// 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`.
    pub fn cast<U: DeviceRepr>(self) -> Result<DeviceInputView<'a, U>> {
        DeviceInputView::create(self.region)
    }
}

// SAFETY: both constructors preserve the provider's exact live allocation range.
unsafe impl<T: DeviceRepr> DeviceRegionProvider for DeviceInputView<'_, T> {
    fn region(&self) -> DeviceRegion<'_> {
        self.region
    }
}

// SAFETY: construction checks the layout; slicing and casting preserve bounds and alignment.
unsafe impl<T: DeviceRepr> DeviceRange<T> for DeviceInputView<'_, T> {
    fn as_device_ptr(&self) -> *const T {
        self.as_ptr()
    }

    fn len(&self) -> usize {
        self.length
    }
}

/// An immutable borrow of typed CUDA storage, including its allocation identity.
#[derive(Debug, Clone, Copy)]
pub struct DeviceView<'a, T: DeviceRepr> {
    region: DeviceRegion<'a>,
    length: usize,
    _t: PhantomData<&'a T>,
}

/// An exclusive borrow of typed CUDA storage.
#[derive(Debug)]
pub struct DeviceViewMut<'a, T: DeviceRepr> {
    region: DeviceRegion<'a>,
    length: usize,
    _t: PhantomData<&'a mut T>,
}

/// An exclusive write-only range for a producer of `T` values.
///
/// The range may be uninitialized and cannot be used as a readable device slice.
/// Its element type describes produced values rather than the storage's current initialization state.
#[derive(Debug)]
pub struct DeviceOutputView<'a, T: DeviceRepr> {
    region: DeviceRegion<'a>,
    length: usize,
    _t: PhantomData<&'a mut MaybeUninit<T>>,
}

impl<'a, T: DeviceRepr> DeviceOutputView<'a, T> {
    /// Consumes the typed borrow into allocation metadata without granting access.
    #[must_use]
    pub fn into_region(self) -> DeviceRegion<'a> {
        self.region
    }

    /// Borrows an externally established writable region without claiming initialization.
    ///
    /// # Safety
    ///
    /// The region must remain live and exclusively writable for the returned lifetime, including queued CUDA accesses using this output.
    ///
    /// # Errors
    ///
    /// 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.
    pub unsafe fn from_raw_parts(region: DeviceRegion<'a>, length: usize) -> Result<Self> {
        validate_view::<T>(region, length)?;
        Ok(Self {
            region,
            length,
            _t: PhantomData,
        })
    }

    /// Borrows writable storage without exposing its existing contents as `T` values.
    pub fn from_output<B: DeviceOutput<T> + ?Sized>(output: &'a mut B) -> Self {
        let () = T::LAYOUT;
        Self {
            region: output.region(),
            length: output.len(),
            _t: PhantomData,
        }
    }

    /// Borrows this destination again for a shorter exclusive lifetime.
    pub fn reborrow(&mut self) -> DeviceOutputView<'_, T> {
        DeviceOutputView::from_output(self)
    }

    /// Returns the number of output elements.
    #[must_use]
    pub const fn len(&self) -> usize {
        self.length
    }

    /// Returns whether the output range is empty.
    #[must_use]
    pub const fn is_empty(&self) -> bool {
        self.length == 0
    }

    /// Returns the pointer a producer may write through.
    pub fn as_mut_ptr(&mut self) -> *mut T {
        self.region.as_ptr().cast()
    }

    /// Returns the output allocation's context.
    #[must_use]
    pub fn context(&self) -> &Arc<Context> {
        self.region.context()
    }

    /// Narrows this exclusive output borrow to an element range.
    ///
    /// # Errors
    ///
    /// Returns an error if the element range is reversed, exceeds this range’s bounds, or an inclusive bound cannot be converted without overflow.
    pub fn slice<R: RangeBounds<usize>>(self, range: R) -> Result<Self> {
        let (start, end) = bounds_to_range(range, self.length)?;
        Ok(Self {
            region: self
                .region
                .slice(start * size_of::<T>()..end * size_of::<T>())?,
            length: end - start,
            _t: PhantomData,
        })
    }

    /// Splits this exclusive output borrow into disjoint writable ranges.
    ///
    /// # Errors
    ///
    /// Returns an error if `mid` exceeds the view’s element count.
    pub fn split_at_mut(self, mid: usize) -> Result<(Self, Self)> {
        if mid > self.length {
            return Err(Error::buffer_too_small("view", mid, self.length));
        }

        let boundary = mid * size_of::<T>();
        let left = Self {
            region: self.region.slice(..boundary)?,
            length: mid,
            _t: PhantomData,
        };
        let right = Self {
            region: self.region.slice(boundary..)?,
            length: self.length - mid,
            _t: PhantomData,
        };
        Ok((left, right))
    }
}

// SAFETY: the region comes from a live `DeviceOutput` or a `from_raw_parts` caller, and slicing and splitting keep its identity and bounds.
unsafe impl<T: DeviceRepr> DeviceRegionProvider for DeviceOutputView<'_, T> {
    fn region(&self) -> DeviceRegion<'_> {
        self.region
    }
}

// SAFETY: construction validated `length` elements of `T` against the region's size and alignment, and no initialized reads are claimed.
unsafe impl<T: DeviceRepr> DeviceRange<T> for DeviceOutputView<'_, T> {
    fn len(&self) -> usize {
        self.length
    }
}

// SAFETY: the view holds the exclusive borrow of its writable range, and the pointer is that range's start.
unsafe impl<T: DeviceRepr> DeviceOutput<T> for DeviceOutputView<'_, T> {
    fn as_mut_ptr(&mut self) -> *mut T {
        self.region.as_ptr().cast()
    }
}

fn validate_view<T: DeviceRepr>(region: DeviceRegion<'_>, length: usize) -> Result<()> {
    let () = T::LAYOUT;
    let bytes = length
        .checked_mul(size_of::<T>())
        .ok_or_else(|| Error::out_of_range("view byte length"))?;
    if bytes != region.byte_len() {
        return Err(Error::size_mismatch(
            "view region",
            bytes,
            region.byte_len(),
        ));
    }

    if length != 0 && size_of::<T>() == 0 {
        return Err(Error::not_positive("element size"));
    }

    if length != 0 && !region.as_ptr().addr().is_multiple_of(align_of::<T>()) {
        return Err(Error::misaligned("view address", align_of::<T>()));
    }

    Ok(())
}

impl<'a, T: DeviceRepr> DeviceView<'a, T> {
    /// Consumes the typed borrow into allocation metadata without granting new access.
    #[must_use]
    pub fn into_region(self) -> DeviceRegion<'a> {
        self.region
    }

    /// Borrows a region containing `length` values of `T`.
    ///
    /// # Safety
    ///
    /// The region must contain valid `T` values for the returned lifetime.
    /// Access through other aliases must respect this shared borrow and CUDA ordering.
    ///
    /// # Errors
    ///
    /// 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.
    pub unsafe fn from_raw_parts(region: DeviceRegion<'a>, length: usize) -> Result<Self> {
        validate_view::<T>(region, length)?;
        Ok(Self {
            region,
            length,
            _t: PhantomData,
        })
    }

    /// Borrows every initialized element of a device allocation without copying data.
    #[must_use]
    pub fn from_memory(memory: &'a DeviceMemory<T>) -> Self {
        let () = T::LAYOUT;
        Self {
            region: memory.region(),
            length: memory.len(),
            _t: PhantomData,
        }
    }

    /// Borrows any typed provider that also retains allocation metadata.
    pub fn from_buffer<B: DeviceSlice<T> + ?Sized>(buffer: &'a B) -> Self {
        let () = T::LAYOUT;
        Self {
            region: buffer.region(),
            length: buffer.len(),
            _t: PhantomData,
        }
    }

    /// Returns the CUDA-accessible element pointer.
    ///
    /// An empty view returns an aligned dangling pointer.
    /// This pointer does not grant host access.
    #[must_use]
    pub fn as_ptr(&self) -> *const T {
        if self.length == 0 {
            NonNull::<T>::dangling().as_ptr()
        } else {
            self.region.as_ptr().cast()
        }
    }

    /// Returns the number of elements in the view.
    #[must_use]
    pub const fn len(&self) -> usize {
        self.length
    }

    /// Returns whether the view contains no elements.
    #[must_use]
    pub const fn is_empty(&self) -> bool {
        self.length == 0
    }

    /// Returns the context associated with the viewed allocation.
    #[must_use]
    pub fn context(&self) -> &'a Arc<Context> {
        self.region.context()
    }

    /// Returns the view’s exact byte range and allocation identity.
    #[must_use]
    pub const fn region(&self) -> DeviceRegion<'a> {
        self.region
    }

    /// Copies every viewed element into a host slice and waits for completion.
    ///
    /// # Errors
    ///
    /// Returns an error for unequal element counts or byte-size overflow.
    /// Also propagates access-tracking, readiness synchronization, context binding, stream-capture, CUDA copy, and stream synchronization errors.
    /// A nonempty synchronous transfer is rejected during stream capture.
    pub fn copy_to_host(&self, destination: &mut [T]) -> Result<()>
    where
        T: AnyBitPatternDeviceRepr,
    {
        transfer::copy_to_host(self, destination)
    }

    /// Copies every viewed element into a new host vector and waits for completion.
    ///
    /// # Errors
    ///
    /// Propagates byte-size overflow, access-tracking, readiness synchronization, context-binding, stream-capture, CUDA copy, and stream synchronization errors.
    /// A nonempty synchronous transfer is rejected during stream capture.
    pub fn copy_to_host_vec(&self) -> Result<Vec<T>>
    where
        T: AnyBitPatternDeviceRepr,
    {
        transfer::copy_to_host_vec(self)
    }

    /// Returns a view of an element subrange, preserving allocation identity and readiness.
    ///
    /// # Errors
    ///
    /// Returns an error if the element range is reversed, exceeds this range’s bounds, or an inclusive bound cannot be converted without overflow.
    pub fn slice<R: RangeBounds<usize>>(self, range: R) -> Result<Self> {
        let (start, end) = bounds_to_range(range, self.length)?;
        let region = self
            .region
            .slice(start * size_of::<T>()..end * size_of::<T>())?;
        Ok(Self {
            region,
            length: end - start,
            _t: PhantomData,
        })
    }

    /// Reinterprets initialized bytes as values accepting every bit pattern.
    ///
    /// # Errors
    ///
    /// 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`.
    pub fn cast<U: AnyBitPatternDeviceRepr>(self) -> Result<DeviceView<'a, U>>
    where
        T: NoUninitDeviceRepr,
    {
        let () = T::LAYOUT;
        // SAFETY: the source contains initialized bytes and every destination pattern is valid.
        unsafe { self.cast_unchecked() }
    }

    /// Reinterprets a region with a caller-established initialization contract.
    ///
    /// # Safety
    ///
    /// Every destination element must be initialized and valid for `U`.
    /// Alignment and byte length are checked by this method.
    ///
    /// # Errors
    ///
    /// 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`.
    pub unsafe fn cast_unchecked<U: DeviceRepr>(self) -> Result<DeviceView<'a, U>> {
        let length = cast_length::<U>(self.region)?;
        Ok(DeviceView {
            region: self.region,
            length,
            _t: PhantomData,
        })
    }
}

impl<'a, T: DeviceRepr> DeviceViewMut<'a, T> {
    /// Consumes the typed borrow into allocation metadata without granting access.
    #[must_use]
    pub fn into_region(self) -> DeviceRegion<'a> {
        self.region
    }

    /// Exclusively borrows a region containing `length` values of `T`.
    ///
    /// # Safety
    ///
    /// The region must contain valid `T` values and remain exclusively borrowed for the returned lifetime, including all GPU work using this view.
    ///
    /// # Errors
    ///
    /// 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.
    pub unsafe fn from_raw_parts(region: DeviceRegion<'a>, length: usize) -> Result<Self> {
        validate_view::<T>(region, length)?;
        Ok(Self {
            region,
            length,
            _t: PhantomData,
        })
    }

    /// Exclusively borrows every initialized element of a device allocation without copying data.
    pub fn from_memory(memory: &'a mut DeviceMemory<T>) -> Self {
        let () = T::LAYOUT;
        Self {
            region: memory.region(),
            length: memory.len(),
            _t: PhantomData,
        }
    }

    /// Exclusively borrows an initialized typed provider without copying data.
    pub fn from_buffer<B: DeviceSliceMut<T> + ?Sized>(buffer: &'a mut B) -> Self {
        let () = T::LAYOUT;
        Self {
            region: buffer.region(),
            length: buffer.len(),
            _t: PhantomData,
        }
    }

    /// Borrows this mutable view again for a shorter exclusive lifetime.
    pub fn reborrow(&mut self) -> DeviceViewMut<'_, T> {
        DeviceViewMut {
            region: self.region(),
            length: self.length,
            _t: PhantomData,
        }
    }

    /// Returns the CUDA-accessible element pointer.
    ///
    /// An empty view returns an aligned dangling pointer.
    /// This pointer does not grant host access.
    #[must_use]
    pub fn as_ptr(&self) -> *const T {
        if self.length == 0 {
            NonNull::<T>::dangling().as_ptr()
        } else {
            self.region.as_ptr().cast()
        }
    }

    /// Returns the exclusively borrowed CUDA-accessible element pointer.
    ///
    /// This pointer does not grant host access or synchronize pending work.
    pub fn as_mut_ptr(&mut self) -> *mut T {
        self.as_ptr().cast_mut()
    }

    /// Returns the number of elements in the view.
    #[must_use]
    pub const fn len(&self) -> usize {
        self.length
    }

    /// Returns whether the view contains no elements.
    #[must_use]
    pub const fn is_empty(&self) -> bool {
        self.length == 0
    }

    /// Returns the context associated with the viewed allocation.
    #[must_use]
    pub fn context(&self) -> &Arc<Context> {
        self.region.context()
    }

    /// Returns the view’s exact byte range and allocation identity.
    #[must_use]
    pub fn region(&self) -> DeviceRegion<'_> {
        self.region
    }

    /// Copies a host slice into the entire view and waits for completion.
    ///
    /// # Errors
    ///
    /// Returns an error for unequal element counts or byte-size overflow.
    /// Also propagates access-tracking, readiness synchronization, context binding, stream-capture, CUDA copy, and stream synchronization errors.
    /// A nonempty synchronous transfer is rejected during stream capture.
    pub fn copy_from_host(&mut self, source: &[T]) -> Result<()> {
        transfer::copy_from_host(self, source)
    }

    /// Copies a disjoint device range into the entire view and waits for completion.
    ///
    /// # Errors
    ///
    /// Returns an error if the ranges have different contexts or element counts, overlap in the same allocation, or their byte size overflows.
    /// Also propagates access-tracking, readiness synchronization, context binding, stream-capture, CUDA copy, and stream synchronization errors.
    /// A nonempty synchronous transfer is rejected during stream capture.
    pub fn copy_from_device<B: DeviceSlice<T> + ?Sized>(&mut self, source: &B) -> Result<()> {
        copy_device(self, source)
    }

    /// Copies every viewed element into a host slice and waits for completion.
    ///
    /// # Errors
    ///
    /// Returns an error for unequal element counts or byte-size overflow.
    /// Also propagates access-tracking, readiness synchronization, context binding, stream-capture, CUDA copy, and stream synchronization errors.
    /// A nonempty synchronous transfer is rejected during stream capture.
    pub fn copy_to_host(&self, destination: &mut [T]) -> Result<()>
    where
        T: AnyBitPatternDeviceRepr,
    {
        self.as_view().copy_to_host(destination)
    }

    /// Copies every viewed element into a new host vector and waits for completion.
    ///
    /// # Errors
    ///
    /// Propagates byte-size overflow, access-tracking, readiness synchronization, context-binding, stream-capture, CUDA copy, and stream synchronization errors.
    /// A nonempty synchronous transfer is rejected during stream capture.
    pub fn copy_to_host_vec(&self) -> Result<Vec<T>>
    where
        T: AnyBitPatternDeviceRepr,
    {
        self.as_view().copy_to_host_vec()
    }

    /// Borrows this view for reading without extending the lifetime of the mutable borrow.
    #[must_use]
    pub fn as_view(&self) -> DeviceView<'_, T> {
        DeviceView {
            region: self.region,
            length: self.length,
            _t: PhantomData,
        }
    }

    /// Borrows an initialized element subrange for reading.
    ///
    /// # Errors
    ///
    /// Returns an error if the element range is reversed, exceeds this range’s bounds, or an inclusive bound cannot be converted without overflow.
    pub fn slice<R: RangeBounds<usize>>(&self, range: R) -> Result<DeviceView<'_, T>> {
        self.as_view().slice(range)
    }

    /// Exclusively borrows an initialized element subrange.
    ///
    /// # Errors
    ///
    /// Returns an error if the element range is reversed, exceeds this range’s bounds, or an inclusive bound cannot be converted without overflow.
    pub fn slice_mut<R: RangeBounds<usize>>(&mut self, range: R) -> Result<DeviceViewMut<'_, T>> {
        let (start, end) = bounds_to_range(range, self.length)?;
        let region = self
            .region
            .slice(start * size_of::<T>()..end * size_of::<T>())?;
        Ok(DeviceViewMut {
            region,
            length: end - start,
            _t: PhantomData,
        })
    }

    /// Borrows two disjoint mutable views, split at element index `mid`.
    ///
    /// # Errors
    ///
    /// Returns an error if `mid` exceeds the view’s element count.
    pub fn split_at_mut(
        &mut self,
        mid: usize,
    ) -> Result<(DeviceViewMut<'_, T>, DeviceViewMut<'_, T>)> {
        if mid > self.length {
            return Err(Error::buffer_too_small("view", mid, self.length));
        }

        let bytes = mid * size_of::<T>();
        Ok((
            DeviceViewMut {
                region: self.region.slice(..bytes)?,
                length: mid,
                _t: PhantomData,
            },
            DeviceViewMut {
                region: self.region.slice(bytes..)?,
                length: self.length - mid,
                _t: PhantomData,
            },
        ))
    }

    /// Reinterprets a mutable borrow while preserving both element types' validity.
    ///
    /// # Errors
    ///
    /// 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`.
    pub fn cast<U: AnyBitPatternDeviceRepr + NoUninitDeviceRepr>(
        self,
    ) -> Result<DeviceViewMut<'a, U>>
    where
        T: AnyBitPatternDeviceRepr + NoUninitDeviceRepr,
    {
        let () = T::LAYOUT;
        // SAFETY: both representations accept all initialized bits and U cannot introduce uninitialized bytes.
        unsafe { self.cast_unchecked() }
    }

    /// Reinterprets a mutable borrow under a caller-established validity contract.
    ///
    /// # Safety
    ///
    /// Every destination element must be initialized and valid for `U`.
    /// Writes through the returned view must leave valid `T` values when the borrow ends.
    ///
    /// # Errors
    ///
    /// 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`.
    pub unsafe fn cast_unchecked<U: DeviceRepr>(self) -> Result<DeviceViewMut<'a, U>> {
        let length = cast_length::<U>(self.region)?;
        Ok(DeviceViewMut {
            region: self.region,
            length,
            _t: PhantomData,
        })
    }
}

// SAFETY: the region comes from a live provider or a `from_raw_parts` caller, and slicing keeps its identity and bounds.
unsafe impl<T: DeviceRepr> DeviceRegionProvider for DeviceView<'_, T> {
    fn region(&self) -> DeviceRegion<'_> {
        self.region
    }
}

// SAFETY: the region comes from a live provider or a `from_raw_parts` caller, and slicing and splitting keep its identity and bounds.
unsafe impl<T: DeviceRepr> DeviceRegionProvider for DeviceViewMut<'_, T> {
    fn region(&self) -> DeviceRegion<'_> {
        self.region
    }
}

// SAFETY: the view holds the exclusive borrow of its range, and `as_mut_ptr` returns that range's start.
unsafe impl<T: DeviceRepr> DeviceOutput<T> for DeviceViewMut<'_, T> {
    fn as_mut_ptr(&mut self) -> *mut T {
        self.as_mut_ptr()
    }
}

// SAFETY: `MaybeUninit<T>` has `T`'s size and alignment, so the validated range holds `length` slots for `T`, and no initialized reads are claimed.
unsafe impl<T: DeviceRepr> DeviceRange<T> for DeviceViewMut<'_, MaybeUninit<T>> {
    fn len(&self) -> usize {
        self.length
    }
}

// SAFETY: the view exclusively borrows `length` writable `MaybeUninit<T>` slots, which have `T`'s layout.
unsafe impl<T: DeviceRepr> DeviceOutput<T> for DeviceViewMut<'_, MaybeUninit<T>> {
    fn as_mut_ptr(&mut self) -> *mut T {
        self.as_mut_ptr().cast()
    }
}

impl<'a, T: DeviceRepr> DeviceViewMut<'a, MaybeUninit<T>> {
    /// Borrows this uninitialized range as a write-only output of `T` values.
    pub fn output(&mut self) -> DeviceOutputView<'_, T> {
        DeviceOutputView::from_output(self)
    }

    /// Exposes elements initialized by a producer through this exclusive view.
    ///
    /// # Safety
    ///
    /// Every element must contain a valid T value.
    /// Producing writes must be ordered before all consumers, and must complete before host readback.
    #[must_use]
    pub unsafe fn assume_init(self) -> DeviceViewMut<'a, T> {
        let () = T::LAYOUT;
        DeviceViewMut {
            region: self.region,
            length: self.length,
            _t: PhantomData,
        }
    }
}

impl<T: DeviceRepr> DeviceMemory<T> {
    /// Borrows all initialized elements as a shared device view.
    #[must_use]
    pub fn view(&self) -> DeviceView<'_, T> {
        DeviceView::from_memory(self)
    }

    /// Borrows all initialized elements as an exclusive device view.
    pub fn view_mut(&mut self) -> DeviceViewMut<'_, T> {
        DeviceViewMut::from_memory(self)
    }
}

impl<T: DeviceRepr> DeviceMemory<MaybeUninit<T>> {
    /// Borrows this uninitialized allocation as a write-only output of `T` values.
    pub fn output(&mut self) -> DeviceOutputView<'_, T> {
        DeviceOutputView::from_output(self)
    }
}

// SAFETY: the owner retains its allocation, whose `length` elements start at `ptr`, and `region()` slices exactly those bytes.
unsafe impl<T: DeviceRepr> DeviceRange<T> for DeviceMemory<T> {
    fn as_device_ptr(&self) -> *const T {
        self.as_ptr()
    }

    fn len(&self) -> usize {
        self.len()
    }
}

// SAFETY: `DeviceMemory<T>` is only constructed initialized; uninitialized storage is typed `DeviceMemory<MaybeUninit<T>>`.
unsafe impl<T: DeviceRepr> DeviceSlice<T> for DeviceMemory<T> {}

// SAFETY: `&mut DeviceMemory<T>` is exclusive, and its input and output pointers are both `ptr`.
unsafe impl<T: DeviceRepr> DeviceSliceMut<T> for DeviceMemory<T> {}

// SAFETY: the view's pointer and length come from the same validated region.
unsafe impl<T: DeviceRepr> DeviceRange<T> for DeviceView<'_, T> {
    fn as_device_ptr(&self) -> *const T {
        self.as_ptr()
    }

    fn len(&self) -> usize {
        self.length
    }
}

// SAFETY: a `DeviceView<T>` is built from an initialized provider or a `from_raw_parts` caller that vouches for valid values.
unsafe impl<T: DeviceRepr> DeviceSlice<T> for DeviceView<'_, T> {}

// SAFETY: the view's pointer and length come from the same validated region.
unsafe impl<T: DeviceRepr> DeviceRange<T> for DeviceViewMut<'_, T> {
    fn as_device_ptr(&self) -> *const T {
        self.as_ptr()
    }

    fn len(&self) -> usize {
        self.length
    }
}

// SAFETY: a `DeviceViewMut<T>` is built from an initialized provider or a `from_raw_parts` caller that vouches for valid values.
unsafe impl<T: DeviceRepr> DeviceSlice<T> for DeviceViewMut<'_, T> {}

// SAFETY: the view holds an exclusive borrow, and its input and output pointers describe one range.
unsafe impl<T: DeviceRepr> DeviceSliceMut<T> for DeviceViewMut<'_, T> {}

// SAFETY: a slice's pointer and length describe live, aligned `T` values readable for the borrow.
unsafe impl<T: DeviceRepr> HostSlice<T> for [T] {
    fn as_host_ptr(&self) -> *const T {
        self.as_ptr()
    }

    fn len(&self) -> usize {
        self.len()
    }
}

// SAFETY: `&mut [T]` grants exclusive write access to the same range.
unsafe impl<T: DeviceRepr> HostSliceMut<T> for [T] {
    fn as_host_mut_ptr(&mut self) -> *mut T {
        self.as_mut_ptr()
    }
}

// SAFETY: an array's pointer and `N` describe live, aligned `T` values readable for the borrow.
unsafe impl<T: DeviceRepr, const N: usize> HostSlice<T> for [T; N] {
    fn as_host_ptr(&self) -> *const T {
        self.as_ptr()
    }

    fn len(&self) -> usize {
        N
    }
}

// SAFETY: `&mut [T; N]` grants exclusive write access to the same range.
unsafe impl<T: DeviceRepr, const N: usize> HostSliceMut<T> for [T; N] {
    fn as_host_mut_ptr(&mut self) -> *mut T {
        self.as_mut_ptr()
    }
}

// SAFETY: a vector's pointer and length describe its live, aligned, initialized elements.
unsafe impl<T: DeviceRepr> HostSlice<T> for Vec<T> {
    fn as_host_ptr(&self) -> *const T {
        self.as_ptr()
    }

    fn len(&self) -> usize {
        self.len()
    }
}

// SAFETY: `&mut Vec<T>` grants exclusive write access to the same elements.
unsafe impl<T: DeviceRepr> HostSliceMut<T> for Vec<T> {
    fn as_host_mut_ptr(&mut self) -> *mut T {
        self.as_mut_ptr()
    }
}

fn bounds_to_range<R: RangeBounds<usize>>(range: R, length: usize) -> Result<(usize, usize)> {
    let start = match range.start_bound() {
        Bound::Included(&value) => value,
        Bound::Excluded(&value) => value
            .checked_add(1)
            .ok_or_else(|| Error::out_of_range("range start"))?,
        Bound::Unbounded => 0,
    };
    let end = match range.end_bound() {
        Bound::Included(&value) => value
            .checked_add(1)
            .ok_or_else(|| Error::out_of_range("range end"))?,
        Bound::Excluded(&value) => value,
        Bound::Unbounded => length,
    };

    if start > end {
        return Err(Error::out_of_range("range start"));
    }

    if end > length {
        return Err(Error::buffer_too_small("range", end, length));
    }

    Ok((start, end))
}