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
//! CUDA arrays, mipmapped arrays and borrowed mip levels.

mod sealed {
    use crate::memory::array::ArrayFormat;

    #[expect(
        unnameable_types,
        reason = "sealed supertrait that other crates must not name or implement"
    )]
    pub trait Pixel {
        const FORMAT: ArrayFormat;
        const CHANNELS: u32;
    }
}

use std::{
    ffi::c_void,
    fmt,
    marker::PhantomData,
    mem::{self, ManuallyDrop, MaybeUninit},
    ops::{Deref, DerefMut, Range},
    ptr,
    result::Result as StdResult,
    sync::Arc,
};

use bitflags::parser;
use half::f16;
use singe_core::report_cleanup_failure;
use singe_cuda_sys::driver as sys;

use crate::{
    context::Context,
    error::{Error, Result},
    stream::{AsStream, StreamBinding, StreamScope},
    submission::{Access, AccessMode},
    try_ffi,
    utility::{driver_enum, to_u64, to_usize},
    view::{AllocationId, AnyBitPatternDeviceRepr, DeviceOutput, DeviceSlice, DeviceViewMut},
};

driver_enum! {
    /// Element formats of CUDA arrays.
    pub enum ArrayFormat: sys::CUarray_format {
        /// Unsigned 8-bit integers.
        U8 = CU_AD_FORMAT_UNSIGNED_INT8,
        /// Unsigned 16-bit integers.
        U16 = CU_AD_FORMAT_UNSIGNED_INT16,
        /// Unsigned 32-bit integers.
        U32 = CU_AD_FORMAT_UNSIGNED_INT32,
        /// Signed 8-bit integers.
        I8 = CU_AD_FORMAT_SIGNED_INT8,
        /// Signed 16-bit integers.
        I16 = CU_AD_FORMAT_SIGNED_INT16,
        /// Signed 32-bit integers.
        I32 = CU_AD_FORMAT_SIGNED_INT32,
        /// 16-bit floating point.
        F16 = CU_AD_FORMAT_HALF,
        /// 32-bit floating point.
        F32 = CU_AD_FORMAT_FLOAT,
    }
}

/// Native scalar or two/four-channel pixel representation supported by CUDA arrays.
pub trait ArrayElement: AnyBitPatternDeviceRepr + Send + Sync + sealed::Pixel {}

macro_rules! pixels {
    ($($ty:ty => $format:ident),* $(,)?) => {$ (
        impl sealed::Pixel for $ty {
            const FORMAT: ArrayFormat = ArrayFormat::$format;
            const CHANNELS: u32 = 1;
        }
        impl ArrayElement for $ty {}
        impl sealed::Pixel for [$ty; 2] {
            const FORMAT: ArrayFormat = ArrayFormat::$format;
            const CHANNELS: u32 = 2;
        }
        impl ArrayElement for [$ty; 2] {}
        impl sealed::Pixel for [$ty; 4] {
            const FORMAT: ArrayFormat = ArrayFormat::$format;
            const CHANNELS: u32 = 4;
        }
        impl ArrayElement for [$ty; 4] {}
    )*};
}

pixels!(u8 => U8, u16 => U16,
    u32 => U32, i8 => I8,
    i16 => I16, i32 => I32,
    f16 => F16, f32 => F32);

/// Array initialization state in which some texels may not yet contain valid values.
#[derive(Debug)]
pub struct Uninitialized;

/// Array initialization state in which every texel contains a valid element.
#[derive(Debug)]
pub struct Initialized;

/// Shape in texels, with layers and cube faces distinguished from spatial depth.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum ArrayShape {
    /// One-dimensional array.
    D1 {
        /// Width in texels.
        width: usize,
    },
    /// Two-dimensional array.
    D2 {
        /// Width in texels.
        width: usize,
        /// Height in texels.
        height: usize,
    },
    /// Three-dimensional array.
    D3 {
        /// Width in texels.
        width: usize,
        /// Height in texels.
        height: usize,
        /// Spatial depth in texels.
        depth: usize,
    },
    /// One-dimensional arrays stored in independently addressed layers.
    Layered1D {
        /// Width in texels.
        width: usize,
        /// Number of array layers.
        layers: usize,
    },
    /// Two-dimensional arrays stored in independently addressed layers.
    Layered2D {
        /// Width in texels.
        width: usize,
        /// Height in texels.
        height: usize,
        /// Number of array layers.
        layers: usize,
    },
    /// Six square faces forming a cube map.
    Cube {
        /// Width and height of each cube face in texels.
        edge: usize,
    },
    /// Layered cube maps, with six square faces per cube.
    CubeArray {
        /// Width and height of each cube face in texels.
        edge: usize,
        /// Number of cube maps, each containing six faces.
        cubes: usize,
    },
}

bitflags::bitflags! {
    /// Usage capabilities requested when allocating an array or mipmap chain.
    ///
    /// Layered and cube-map flags are derived from [`ArrayShape`].
    /// CUDA validates the supported combinations of shape, format, and usage capabilities.
    #[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
    pub struct ArrayFlags: u32 {
        /// Allows binding the array for surface loads and stores.
        const SURFACE_LOAD_STORE = sys::CUDA_ARRAY3D_SURFACE_LDST;
        /// Allows texture gather operations on the array.
        const TEXTURE_GATHER = sys::CUDA_ARRAY3D_TEXTURE_GATHER;
        /// Marks the array as a depth texture.
        const DEPTH_TEXTURE = sys::CUDA_ARRAY3D_DEPTH_TEXTURE;
        /// Allows binding the array as a color target in an external graphics API.
        const COLOR_ATTACHMENT = sys::CUDA_ARRAY3D_COLOR_ATTACHMENT;
        /// Enables use by hardware video encoding or decoding operations.
        const VIDEO_ENCODE_DECODE = sys::CUDA_ARRAY3D_VIDEO_ENCODE_DECODE;
    }
}

impl fmt::Display for ArrayFlags {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        parser::to_writer(self, f)
    }
}

impl ArrayShape {
    fn native_dimensions(self) -> Result<([usize; 3], u32)> {
        let (dimensions, flags) = match self {
            Self::D1 { width } => ([width, 0, 0], 0),
            Self::D2 { width, height } => ([width, height, 0], 0),
            Self::D3 {
                width,
                height,
                depth,
            } => ([width, height, depth], 0),
            Self::Layered1D { width, layers } => ([width, 0, layers], sys::CUDA_ARRAY3D_LAYERED),
            Self::Layered2D {
                width,
                height,
                layers,
            } => ([width, height, layers], sys::CUDA_ARRAY3D_LAYERED),
            Self::Cube { edge } => ([edge, edge, 6], sys::CUDA_ARRAY3D_CUBEMAP),
            Self::CubeArray { edge, cubes } => (
                [
                    edge,
                    edge,
                    cubes
                        .checked_mul(6)
                        .ok_or_else(|| Error::out_of_range("cube layer count"))?,
                ],
                sys::CUDA_ARRAY3D_CUBEMAP | sys::CUDA_ARRAY3D_LAYERED,
            ),
        };
        let valid = match self {
            Self::D1 { width } => width != 0,
            Self::D2 { width, height } => width != 0 && height != 0,
            Self::D3 {
                width,
                height,
                depth,
            } => width != 0 && height != 0 && depth != 0,
            Self::Layered1D { width, layers } => width != 0 && layers != 0,
            Self::Layered2D {
                width,
                height,
                layers,
            } => width != 0 && height != 0 && layers != 0,
            Self::Cube { edge } => edge != 0,
            Self::CubeArray { edge, cubes } => edge != 0 && cubes != 0,
        };
        if !valid {
            return Err(Error::not_positive("array dimension"));
        }
        Ok((dimensions, flags))
    }

    /// Returns the three-dimensional transfer extent in texels.
    ///
    /// Unused spatial dimensions become one.
    /// The last dimension counts layers for layered arrays and faces for cube maps.
    ///
    /// # Errors
    ///
    /// Returns an error if a required dimension is zero or the number of cube faces overflows `usize`.
    pub fn extent(self) -> Result<[usize; 3]> {
        let (dimensions, _) = self.native_dimensions()?;
        Ok(dimensions.map(|dimension| dimension.max(1)))
    }

    fn at_level(self, level: u32) -> Self {
        let shrink = |value: usize| value.checked_shr(level).unwrap_or(0).max(1);
        match self {
            Self::D1 { width } => Self::D1 {
                width: shrink(width),
            },
            Self::D2 { width, height } => Self::D2 {
                width: shrink(width),
                height: shrink(height),
            },
            Self::D3 {
                width,
                height,
                depth,
            } => Self::D3 {
                width: shrink(width),
                height: shrink(height),
                depth: shrink(depth),
            },
            Self::Layered1D { width, layers } => Self::Layered1D {
                width: shrink(width),
                layers,
            },
            Self::Layered2D {
                width,
                height,
                layers,
            } => Self::Layered2D {
                width: shrink(width),
                height: shrink(height),
                layers,
            },
            Self::Cube { edge } => Self::Cube { edge: shrink(edge) },
            Self::CubeArray { edge, cubes } => Self::CubeArray {
                edge: shrink(edge),
                cubes,
            },
        }
    }

    fn maximum_levels(self) -> u32 {
        let maximum = match self {
            Self::D1 { width } | Self::Layered1D { width, .. } => width,
            Self::D2 { width, height } | Self::Layered2D { width, height, .. } => width.max(height),
            Self::D3 {
                width,
                height,
                depth,
            } => width.max(height).max(depth),
            Self::Cube { edge } | Self::CubeArray { edge, .. } => edge,
        };
        maximum.bit_width()
    }
}

/// A rectangular transfer region in texels; `[0, 0, 0]` is the first texel/layer.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ArrayRegion {
    /// Starting x, y, and z coordinates in texels; z selects layers or cube faces when present.
    pub origin: [usize; 3],
    /// Width, height, and depth of the transfer in texels, layers, or cube faces.
    pub extent: [usize; 3],
}

impl ArrayRegion {
    /// Creates a transfer region without checking it against an array shape.
    #[must_use]
    pub const fn new(origin: [usize; 3], extent: [usize; 3]) -> Self {
        Self { origin, extent }
    }

    /// Returns a region covering all texels, layers, or cube faces of `shape`.
    ///
    /// # Errors
    ///
    /// Returns an error if a required shape dimension is zero or the number of cube faces overflows `usize`.
    pub fn full(shape: ArrayShape) -> Result<Self> {
        Ok(Self::new([0; 3], shape.extent()?))
    }

    fn len(self) -> Result<usize> {
        volume(self.extent)
    }

    fn validate(self, shape: ArrayShape) -> Result<()> {
        for ((origin, extent), bound) in self
            .origin
            .into_iter()
            .zip(self.extent)
            .zip(shape.extent()?)
        {
            let end = origin
                .checked_add(extent)
                .ok_or_else(|| Error::out_of_range("array region end"))?;
            if end > bound {
                return Err(Error::buffer_too_small("array", end, bound));
            }
        }

        self.len()?;
        Ok(())
    }
}

fn volume(extent: [usize; 3]) -> Result<usize> {
    extent.into_iter().try_fold(1usize, |count, dimension| {
        count
            .checked_mul(dimension)
            .ok_or_else(|| Error::out_of_range("array element count"))
    })
}

/// Owns an array or retains the mipmapped parent owning one level.
#[derive(Debug)]
pub struct ArrayAllocation {
    context: Arc<Context>,
    handle: sys::CUarray,
    id: AllocationId,
    range: Range<usize>,
    shape: ArrayShape,
    flags: ArrayFlags,
    format: ArrayFormat,
    channels: u32,
    parent: Option<Arc<MipmappedAllocation>>,
}

// SAFETY: `handle` is a driver array handle that CUDA lets any thread use once `context` is bound, the fields never change after construction, and `Drop` destroys the handle once.
unsafe impl Send for ArrayAllocation {}

// SAFETY: `&self` methods only read immutable fields, the driver API is thread-safe for concurrent calls on one array, and texel access is ordered by the context's access tracker.
unsafe impl Sync for ArrayAllocation {}

impl ArrayAllocation {
    /// Returns the context that owns the array.
    #[must_use]
    pub fn context(&self) -> &Arc<Context> {
        &self.context
    }

    /// Borrows the native array handle; ownership remains with this allocation.
    #[must_use]
    pub fn as_raw(&self) -> sys::CUarray {
        self.handle
    }

    /// Returns the allocation identity used to track conflicting accesses.
    #[must_use]
    pub fn allocation_id(&self) -> AllocationId {
        self.id
    }

    /// Returns the logical byte range used for access tracking.
    ///
    /// Mip levels occupy distinct ranges within their parent allocation identity.
    /// This range is not a device address or a measure of physical array storage.
    #[must_use]
    pub fn byte_range(&self) -> Range<usize> {
        self.range.clone()
    }

    /// Returns the spatial dimensions and layer or cube organization.
    #[must_use]
    pub fn shape(&self) -> ArrayShape {
        self.shape
    }

    /// Returns the usage flags, excluding flags derived from the shape.
    #[must_use]
    pub fn flags(&self) -> ArrayFlags {
        self.flags
    }

    /// Returns the native format of each channel.
    #[must_use]
    pub fn format(&self) -> ArrayFormat {
        self.format
    }

    /// Returns the number of scalar channels per texel.
    #[must_use]
    pub fn channels(&self) -> u32 {
        self.channels
    }

    /// Describes an access to the whole array or mip level for dependency tracking.
    #[must_use]
    pub fn access(&self, mode: AccessMode) -> Access {
        Access::allocation(&self.context, self.id, self.range.clone(), mode)
    }
}

impl Drop for ArrayAllocation {
    fn drop(&mut self) {
        if self.handle.is_null() || self.parent.is_some() {
            return;
        }

        if let Err(error) = self.context.bind() {
            report_cleanup_failure("bind the cuda context to destroy", "cuda array", &error);
            return;
        }

        // SAFETY: `handle` is a standalone array this allocation owns, its context is bound, and no `Array` can still use it once the last `Arc` drops.
        if let Err(error) = unsafe { try_ffi!(sys::cuArrayDestroy(self.handle)) } {
            report_cleanup_failure("destroy", "cuda array", &error);
        }
    }
}

/// Raw ownership of a CUDA array, its context, and the descriptor it was created with.
///
/// Destroy `handle` while `context` is alive, or re-adopt the value with [`Array::from_raw`].
#[derive(Debug)]
pub struct RawArray {
    /// Native array handle.
    pub handle: sys::CUarray,
    /// Context the array belongs to.
    pub context: Arc<Context>,
    /// Array extent.
    pub shape: ArrayShape,
    /// Array creation flags.
    pub flags: ArrayFlags,
}

/// Typed array storage with explicit whole-array initialization state.
#[derive(Debug)]
pub struct Array<T: ArrayElement, S = Initialized> {
    allocation: Arc<ArrayAllocation>,
    marker: PhantomData<(T, S)>,
}

impl<T: ArrayElement, S> Array<T, S> {
    /// Returns the shared allocation that keeps the native array alive.
    #[must_use]
    pub fn allocation(&self) -> &Arc<ArrayAllocation> {
        &self.allocation
    }

    /// Returns the context that owns the array.
    #[must_use]
    pub fn context(&self) -> &Arc<Context> {
        self.allocation.context()
    }

    /// Borrows the native array handle without transferring destruction responsibility.
    #[must_use]
    pub fn as_raw(&self) -> sys::CUarray {
        self.allocation.as_raw()
    }

    /// Returns the spatial dimensions and layer or cube organization.
    #[must_use]
    pub fn shape(&self) -> ArrayShape {
        self.allocation.shape
    }

    /// Returns the usage flags, excluding flags derived from the shape.
    #[must_use]
    pub fn flags(&self) -> ArrayFlags {
        self.allocation.flags
    }

    /// Returns the number of `T` texels across all layers or cube faces.
    #[must_use]
    pub fn len(&self) -> usize {
        self.allocation.range.len() / size_of::<T>()
    }

    /// Returns `false`; successful array construction requires nonzero dimensions.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        false
    }

    fn endpoint(&self, region: ArrayRegion) -> Result<ArrayEndpoint> {
        region.validate(self.shape())?;
        Ok(ArrayEndpoint {
            handle: self.as_raw(),
            origin: [
                to_u64(
                    region.origin[0]
                        .checked_mul(size_of::<T>())
                        .ok_or_else(|| Error::out_of_range("array x offset"))?,
                    "array x offset",
                )?,
                to_u64(region.origin[1], "array y offset")?,
                to_u64(region.origin[2], "array z offset")?,
            ],
        })
    }

    fn run_copy(&self, raw: &sys::CUDA_MEMCPY3D, accesses: &[Access]) -> Result<()> {
        let _guard = self.context().acquire_accesses(accesses)?;
        self.context().bind()?;
        let binding = StreamBinding::Default(Arc::clone(self.context()));
        // SAFETY: `transfer` built `raw` from an array region validated against the shape and operands whose lengths match it, the guard holds the declared accesses, the context is bound, and `sync_scope` waits for the copy before the borrows end.
        binding.sync_scope(|| unsafe { try_ffi!(sys::cuMemcpy3DAsync_v2(raw, binding.as_raw())) })
    }

    /// Writes a checked rectangular region without promoting whole-array initialization.
    ///
    /// # Errors
    ///
    /// Returns an error if the region is outside the array, the element count does not match the region volume, or transfer size or offset calculations overflow.
    /// Returns an error if access tracking fails, the context cannot be bound, or CUDA cannot copy or synchronize.
    pub fn copy_from_host(&mut self, region: ArrayRegion, source: &[T]) -> Result<()> {
        let expected = region.len()?;
        if source.len() != expected {
            return Err(Error::length_mismatch(
                "host source",
                expected,
                source.len(),
            ));
        }

        let raw = transfer::<T>(
            region.extent,
            CopySource::Host(source.as_ptr().cast()),
            CopyDestination::Array(self.endpoint(region)?),
        )?;
        self.run_copy(&raw, &[self.allocation.access(AccessMode::Write)])
    }

    /// Enqueues a rectangular host-to-array copy in `scope`.
    ///
    /// The scope retains the source and array borrows until its queued work completes.
    /// A region copy does not change the whole-array initialization state.
    ///
    /// # Errors
    ///
    /// Returns an error if the scope belongs to another context, the source length does not match the region, the region is out of bounds, or size calculations overflow.
    /// Returns an error if the scope cannot order the copy or CUDA cannot enqueue it.
    pub fn copy_from_host_scoped<'env>(
        &'env mut self,
        region: ArrayRegion,
        source: &'env [T],
        scope: &StreamScope<'_, 'env>,
    ) -> Result<()> {
        if self.context() != scope.stream().context() {
            return Err(Error::MemoryContextMismatch);
        }

        let expected = region.len()?;
        if source.len() != expected {
            return Err(Error::length_mismatch(
                "host source",
                expected,
                source.len(),
            ));
        }

        let raw = transfer::<T>(
            region.extent,
            CopySource::Host(source.as_ptr().cast()),
            CopyDestination::Array(self.endpoint(region)?),
        )?;
        let accesses = [self.allocation.access(AccessMode::Write)];
        // SAFETY: `raw` describes a validated array region and a `source` of matching length, the `'env` borrows keep both live until the scope drains, the declared write orders tracked work on the array, and the contexts match.
        unsafe {
            scope.enqueue(&accesses, || {
                try_ffi!(sys::cuMemcpy3DAsync_v2(
                    &raw const raw,
                    scope.stream().as_raw()
                ))
            })
        }
    }

    /// Copies initialized contiguous device values into a checked rectangular array region.
    ///
    /// # Errors
    ///
    /// Returns an error if the source belongs to another context, its length does not match the region, the region is out of bounds, or size calculations overflow.
    /// Returns an error if access tracking fails, the context cannot be bound, or CUDA cannot copy or synchronize.
    pub fn copy_from_device<B: DeviceSlice<T> + ?Sized>(
        &mut self,
        region: ArrayRegion,
        source: &B,
    ) -> Result<()> {
        if source.context() != self.context() {
            return Err(Error::MemoryContextMismatch);
        }

        let expected = region.len()?;
        if source.len() != expected {
            return Err(Error::length_mismatch(
                "device source",
                expected,
                source.len(),
            ));
        }

        let source_address = to_u64(source.as_device_ptr().addr(), "device source address")?;
        let raw = transfer::<T>(
            region.extent,
            CopySource::Device(source_address),
            CopyDestination::Array(self.endpoint(region)?),
        )?;
        self.run_copy(
            &raw,
            &[
                self.allocation.access(AccessMode::Write),
                Access::new(source.region(), AccessMode::Read),
            ],
        )
    }

    /// Copies an initialized array region; overlapping regions in the same array are rejected.
    ///
    /// # Errors
    ///
    /// Returns an error if the arrays belong to different contexts, either region is out of bounds, the regions overlap within the same array, or size calculations overflow.
    /// Returns an error if access tracking fails, the context cannot be bound, or CUDA cannot copy or synchronize.
    pub fn copy_from_array(
        &mut self,
        destination: [usize; 3],
        source: &Array<T>,
        source_region: ArrayRegion,
    ) -> Result<()> {
        if source.context() != self.context() {
            return Err(Error::MemoryContextMismatch);
        }

        source_region.validate(source.shape())?;
        let region = ArrayRegion::new(destination, source_region.extent);
        region.validate(self.shape())?;
        if self.as_raw() == source.as_raw()
            && (0..3).all(|axis| {
                destination[axis] < source_region.origin[axis] + source_region.extent[axis]
                    && source_region.origin[axis] < destination[axis] + region.extent[axis]
            })
        {
            return Err(Error::out_of_range("overlapping array regions"));
        }

        let raw = transfer::<T>(
            region.extent,
            CopySource::Array(source.endpoint(source_region)?),
            CopyDestination::Array(self.endpoint(region)?),
        )?;
        self.run_copy(
            &raw,
            &[
                self.allocation.access(AccessMode::Write),
                source.allocation.access(AccessMode::Read),
            ],
        )
    }

    /// Transfers ownership of a standalone array handle when no retained aliases remain.
    ///
    /// # Errors
    ///
    /// Returns the array unchanged as the error if it is a borrowed mip level or another owner retains its allocation.
    pub fn into_raw(self) -> StdResult<RawArray, Self> {
        if self.allocation.parent.is_some() || Arc::strong_count(&self.allocation) != 1 {
            return Err(self);
        }

        let shape = self.shape();
        let flags = self.flags();
        match Arc::try_unwrap(self.allocation) {
            Ok(mut allocation) => Ok(RawArray {
                handle: mem::replace(&mut allocation.handle, ptr::null_mut()),
                context: Arc::clone(&allocation.context),
                shape,
                flags,
            }),
            Err(allocation) => Err(Self {
                allocation,
                marker: PhantomData,
            }),
        }
    }
}

struct ArrayEndpoint {
    handle: sys::CUarray,
    origin: [u64; 3],
}

enum CopySource {
    Host(*const c_void),
    Device(sys::CUdeviceptr),
    Array(ArrayEndpoint),
}

enum CopyDestination {
    Host(*mut c_void),
    Device(sys::CUdeviceptr),
    Array(ArrayEndpoint),
}

fn transfer<T: ArrayElement>(
    extent: [usize; 3],
    source: CopySource,
    destination: CopyDestination,
) -> Result<sys::CUDA_MEMCPY3D> {
    let row_bytes = extent[0]
        .checked_mul(size_of::<T>())
        .ok_or_else(|| Error::out_of_range("array row bytes"))?;
    volume(extent)?
        .checked_mul(size_of::<T>())
        .ok_or_else(|| Error::out_of_range("array transfer bytes"))?;
    let mut raw = MaybeUninit::<sys::CUDA_MEMCPY3D>::zeroed();
    // SAFETY: every field except the two memory-type enums is an integer or pointer that accepts zero, and both enums get valid discriminants before `assume_init`.
    let mut raw = unsafe {
        (*raw.as_mut_ptr()).srcMemoryType = sys::CUmemorytype::CU_MEMORYTYPE_HOST;
        (*raw.as_mut_ptr()).dstMemoryType = sys::CUmemorytype::CU_MEMORYTYPE_HOST;
        raw.assume_init()
    };
    raw.WidthInBytes = to_u64(row_bytes, "array row bytes")?;
    raw.Height = to_u64(extent[1], "array transfer height")?;
    raw.Depth = to_u64(extent[2], "array transfer depth")?;
    match source {
        CopySource::Host(pointer) => {
            raw.srcHost = pointer;
            raw.srcPitch = raw.WidthInBytes;
            raw.srcHeight = raw.Height;
        }
        CopySource::Device(pointer) => {
            raw.srcMemoryType = sys::CUmemorytype::CU_MEMORYTYPE_DEVICE;
            raw.srcDevice = pointer;
            raw.srcPitch = raw.WidthInBytes;
            raw.srcHeight = raw.Height;
        }
        CopySource::Array(array) => {
            raw.srcMemoryType = sys::CUmemorytype::CU_MEMORYTYPE_ARRAY;
            raw.srcArray = array.handle;
            [raw.srcXInBytes, raw.srcY, raw.srcZ] = array.origin;
        }
    }

    match destination {
        CopyDestination::Host(pointer) => {
            raw.dstHost = pointer;
            raw.dstPitch = raw.WidthInBytes;
            raw.dstHeight = raw.Height;
        }
        CopyDestination::Device(pointer) => {
            raw.dstMemoryType = sys::CUmemorytype::CU_MEMORYTYPE_DEVICE;
            raw.dstDevice = pointer;
            raw.dstPitch = raw.WidthInBytes;
            raw.dstHeight = raw.Height;
        }
        CopyDestination::Array(array) => {
            raw.dstMemoryType = sys::CUmemorytype::CU_MEMORYTYPE_ARRAY;
            raw.dstArray = array.handle;
            [raw.dstXInBytes, raw.dstY, raw.dstZ] = array.origin;
        }
    }
    Ok(raw)
}

fn descriptor<T: ArrayElement>(
    shape: ArrayShape,
    flags: ArrayFlags,
) -> Result<(sys::CUDA_ARRAY3D_DESCRIPTOR, usize)> {
    let (dimensions, shape_flags) = shape.native_dimensions()?;
    let bytes = volume(shape.extent()?)?
        .checked_mul(size_of::<T>())
        .ok_or_else(|| Error::out_of_range("array byte size"))?;
    let descriptor = sys::CUDA_ARRAY3D_DESCRIPTOR {
        Width: to_u64(dimensions[0], "array width")?,
        Height: to_u64(dimensions[1], "array height")?,
        Depth: to_u64(dimensions[2], "array depth")?,
        Format: T::FORMAT.into(),
        NumChannels: T::CHANNELS,
        Flags: flags.bits() | shape_flags,
    };
    Ok((descriptor, bytes))
}

impl<T: ArrayElement> Array<T> {
    /// Allocates an array without initializing its texels.
    ///
    /// `T` determines the scalar format and number of channels.
    /// The shape determines layered and cube-map flags in addition to the supplied usage flags.
    ///
    /// # Errors
    ///
    /// Returns an error if dimensions are zero, size calculations overflow, flags contain unknown bits, the context cannot be bound, CUDA rejects the requested format, dimensions, flags, or allocation, or CUDA returns a null handle.
    pub fn create_uninit(
        context: &Arc<Context>,
        shape: ArrayShape,
        flags: ArrayFlags,
    ) -> Result<Array<T, Uninitialized>> {
        if flags.bits() & !ArrayFlags::all().bits() != 0 {
            return Err(Error::out_of_range("array flags"));
        }

        let (descriptor, bytes) = descriptor::<T>(shape, flags)?;
        context.bind()?;
        let mut handle = ptr::null_mut();
        // SAFETY: `handle` is a writable local, `descriptor` is a local that outlives the call, and `context` is bound.
        unsafe {
            try_ffi!(sys::cuArray3DCreate_v2(
                &raw mut handle,
                &raw const descriptor
            ))?;
        }

        if handle.is_null() {
            return Err(Error::NullHandle);
        }
        Ok(Array {
            allocation: Arc::new(ArrayAllocation {
                context: Arc::clone(context),
                handle,
                id: AllocationId::create(),
                range: 0..bytes,
                shape,
                flags,
                format: T::FORMAT,
                channels: T::CHANNELS,
                parent: None,
            }),
            marker: PhantomData,
        })
    }
}

impl<T: ArrayElement> Array<T, Uninitialized> {
    /// Copies all host texels into the array and returns it as initialized.
    ///
    /// The source is contiguous in x, then y, then z, layer, or cube-face order.
    ///
    /// # Errors
    ///
    /// Returns an error if the source length differs from the full array volume or the full-array host copy fails.
    /// See [`Array::copy_from_host`].
    pub fn initialize(mut self, source: &[T]) -> Result<Array<T>> {
        self.copy_from_host(ArrayRegion::full(self.shape())?, source)?;
        // SAFETY: the synchronized full-region copy wrote a valid `T` from `source` to every texel.
        Ok(unsafe { self.assume_init() })
    }

    /// Marks the complete array initialized after external producers complete.
    ///
    /// # Safety
    ///
    /// All texels must contain valid values of `T`, with producer and subsequent consumer order established.
    #[must_use]
    pub unsafe fn assume_init(self) -> Array<T> {
        Array {
            allocation: self.allocation,
            marker: PhantomData,
        }
    }

    /// Adopts an independently owned array with an explicit format and shape contract.
    ///
    /// # Safety
    ///
    /// `raw.handle` must belong to `raw.context`, match this exact typed descriptor, and transfer destruction responsibility.
    ///
    /// # Errors
    ///
    /// Returns an error if the handle is null, the expected shape or size is invalid, the context cannot be bound, CUDA cannot report the descriptor, or it differs from the expected typed descriptor.
    pub unsafe fn from_raw(raw: RawArray) -> Result<Self> {
        let RawArray {
            handle,
            context,
            shape,
            flags,
        } = raw;
        if handle.is_null() {
            return Err(Error::NullHandle);
        }

        let (expected, bytes) = descriptor::<T>(shape, flags)?;
        context.bind()?;
        let mut actual = MaybeUninit::<sys::CUDA_ARRAY3D_DESCRIPTOR>::uninit();
        // SAFETY: `actual` is a writable local, the caller guarantees `handle` is a live array of the bound `context`, and it is non-null.
        unsafe {
            try_ffi!(sys::cuArray3DGetDescriptor_v2(actual.as_mut_ptr(), handle))?;
        }

        // SAFETY: `cuArray3DGetDescriptor_v2` succeeded, so it wrote the whole descriptor.
        let actual = unsafe { actual.assume_init() };
        if expected != actual {
            return Err(Error::out_of_range("array descriptor"));
        }
        Ok(Self {
            allocation: Arc::new(ArrayAllocation {
                context,
                handle,
                id: AllocationId::create(),
                range: 0..bytes,
                shape,
                flags,
                format: T::FORMAT,
                channels: T::CHANNELS,
                parent: None,
            }),
            marker: PhantomData,
        })
    }
}

impl<T: ArrayElement> Array<T> {
    /// Allocates an array and initializes every texel from contiguous host data.
    ///
    /// # Errors
    ///
    /// Returns an error if allocation fails or `source` does not match the full array volume.
    /// See [`Array::create_uninit`] and [`Array::initialize`].
    pub fn from_slice(
        context: &Arc<Context>,
        shape: ArrayShape,
        flags: ArrayFlags,
        source: &[T],
    ) -> Result<Self> {
        Self::create_uninit(context, shape, flags)?.initialize(source)
    }

    /// Copies an initialized array region into a contiguous host slice and waits for completion.
    ///
    /// # Errors
    ///
    /// Returns an error if the region is outside the array, the element count does not match the region volume, or transfer size or offset calculations overflow.
    /// Returns an error if access tracking fails, the context cannot be bound, or CUDA cannot copy or synchronize.
    pub fn copy_to_host(&self, region: ArrayRegion, destination: &mut [T]) -> Result<()> {
        let expected = region.len()?;
        if destination.len() != expected {
            return Err(Error::length_mismatch(
                "host destination",
                expected,
                destination.len(),
            ));
        }

        let raw = transfer::<T>(
            region.extent,
            CopySource::Array(self.endpoint(region)?),
            CopyDestination::Host(destination.as_mut_ptr().cast()),
        )?;
        self.run_copy(&raw, &[self.allocation.access(AccessMode::Read)])
    }

    /// Copies an initialized array region into a new contiguous host vector.
    ///
    /// # Errors
    ///
    /// Returns an error if the region is out of bounds or size calculations overflow.
    /// Returns an error if access tracking fails, the context cannot be bound, or CUDA cannot copy or synchronize.
    pub fn to_vec(&self, region: ArrayRegion) -> Result<Vec<T>> {
        region.validate(self.shape())?;
        let mut values = vec![MaybeUninit::<T>::uninit(); region.len()?];
        let raw = transfer::<T>(
            region.extent,
            CopySource::Array(self.endpoint(region)?),
            CopyDestination::Host(values.as_mut_ptr().cast()),
        )?;
        self.run_copy(&raw, &[self.allocation.access(AccessMode::Read)])?;
        let mut values = ManuallyDrop::new(values);
        // SAFETY: the synchronized copy wrote every element from initialized texels of `T`, and `MaybeUninit<T>` has `T`'s layout, so the length, capacity, and allocation carry over.
        Ok(unsafe {
            Vec::from_raw_parts(values.as_mut_ptr().cast(), values.len(), values.capacity())
        })
    }

    /// Copies an array region into a contiguous device destination and waits for completion.
    ///
    /// Returns an initialized mutable view covering the destination.
    ///
    /// # Errors
    ///
    /// Returns an error if the destination belongs to another context, its length does not match the region, the region is out of bounds, or size calculations overflow.
    /// Returns an error if access tracking fails, the context cannot be bound, CUDA cannot copy or synchronize, or the destination view fails validation.
    pub fn copy_to_device<'a, B: DeviceOutput<T> + ?Sized>(
        &self,
        region: ArrayRegion,
        destination: &'a mut B,
    ) -> Result<DeviceViewMut<'a, T>> {
        if destination.context() != self.context() {
            return Err(Error::MemoryContextMismatch);
        }

        let expected = region.len()?;
        if destination.len() != expected {
            return Err(Error::length_mismatch(
                "device destination",
                expected,
                destination.len(),
            ));
        }

        let destination_address = to_u64(
            destination.as_mut_ptr().addr(),
            "device destination address",
        )?;
        let raw = transfer::<T>(
            region.extent,
            CopySource::Array(self.endpoint(region)?),
            CopyDestination::Device(destination_address),
        )?;
        self.run_copy(
            &raw,
            &[
                self.allocation.access(AccessMode::Read),
                Access::new(destination.region(), AccessMode::Write),
            ],
        )?;
        // SAFETY: the synchronized copy wrote a valid `T` to each of the destination's elements, and the view lives no longer than the exclusive borrow.
        unsafe { DeviceViewMut::from_raw_parts(destination.region(), destination.len()) }
    }

    /// Enqueues a rectangular array-to-host copy in `scope`.
    ///
    /// The scope retains the array and destination borrows until its queued work completes.
    ///
    /// # Errors
    ///
    /// Returns an error if the scope belongs to another context, the destination length does not match the region, the region is out of bounds, or size calculations overflow.
    /// Returns an error if the scope cannot order the copy or CUDA cannot enqueue it.
    pub fn copy_to_host_scoped<'env>(
        &'env self,
        region: ArrayRegion,
        destination: &'env mut [T],
        scope: &StreamScope<'_, 'env>,
    ) -> Result<()> {
        if self.context() != scope.stream().context() {
            return Err(Error::MemoryContextMismatch);
        }

        let expected = region.len()?;
        if destination.len() != expected {
            return Err(Error::length_mismatch(
                "host destination",
                expected,
                destination.len(),
            ));
        }

        let raw = transfer::<T>(
            region.extent,
            CopySource::Array(self.endpoint(region)?),
            CopyDestination::Host(destination.as_mut_ptr().cast()),
        )?;
        let accesses = [self.allocation.access(AccessMode::Read)];
        // SAFETY: `raw` describes a validated array region and a `destination` of matching length, the `'env` borrows keep both live until the scope drains, the declared read orders tracked work on the array, and the contexts match.
        unsafe {
            scope.enqueue(&accesses, || {
                try_ffi!(sys::cuMemcpy3DAsync_v2(
                    &raw const raw,
                    scope.stream().as_raw()
                ))
            })
        }
    }
}

/// Owns all levels and supplies one allocation identity with distinct level ranges.
#[derive(Debug)]
pub struct MipmappedAllocation {
    context: Arc<Context>,
    handle: sys::CUmipmappedArray,
    id: AllocationId,
    shape: ArrayShape,
    flags: ArrayFlags,
    levels: u32,
    ranges: Vec<Range<usize>>,
}

// SAFETY: `handle` is a driver mipmapped-array handle that CUDA lets any thread use once `context` is bound, the fields never change after construction, and `Drop` destroys the handle once.
unsafe impl Send for MipmappedAllocation {}

// SAFETY: `&self` methods only read immutable fields, the driver API is thread-safe for concurrent calls on one mipmapped array, and texel access is ordered by the context's access tracker.
unsafe impl Sync for MipmappedAllocation {}

impl MipmappedAllocation {
    /// Returns the context that owns the mipmap chain.
    #[must_use]
    pub fn context(&self) -> &Arc<Context> {
        &self.context
    }

    /// Borrows the native mipmapped-array handle without transferring ownership.
    #[must_use]
    pub fn as_raw(&self) -> sys::CUmipmappedArray {
        self.handle
    }

    /// Returns the number of mip levels.
    #[must_use]
    pub fn levels(&self) -> u32 {
        self.levels
    }

    /// Returns the shape of mip level zero.
    #[must_use]
    pub fn shape(&self) -> ArrayShape {
        self.shape
    }

    /// Returns the usage flags, excluding flags derived from the shape.
    #[must_use]
    pub fn flags(&self) -> ArrayFlags {
        self.flags
    }

    /// Returns the allocation identity shared by all mip levels.
    #[must_use]
    pub fn allocation_id(&self) -> AllocationId {
        self.id
    }

    /// Describes an access spanning every mip level for dependency tracking.
    #[must_use]
    pub fn access(&self, mode: AccessMode) -> Access {
        Access::allocation(
            &self.context,
            self.id,
            0..self.ranges.last().map_or(0, |range| range.end),
            mode,
        )
    }
}

impl Drop for MipmappedAllocation {
    fn drop(&mut self) {
        if self.handle.is_null() {
            return;
        }

        if let Err(error) = self.context.bind() {
            report_cleanup_failure(
                "bind the cuda context to destroy",
                "cuda mipmapped array",
                &error,
            );
            return;
        }

        // SAFETY: `handle` is the mipmapped array this allocation owns, its context is bound, and every level `Array` retains this allocation, so none outlives the destroy.
        if let Err(error) = unsafe { try_ffi!(sys::cuMipmappedArrayDestroy(self.handle)) } {
            report_cleanup_failure("destroy", "cuda mipmapped array", &error);
        }
    }
}

/// Raw ownership of a mipmapped CUDA array, its context, and the descriptor it was created with.
///
/// Destroy `handle` while `context` is alive, or re-adopt the value with [`MipmappedArray::from_raw`].
#[derive(Debug)]
pub struct RawMipmappedArray {
    /// Native mipmapped array handle.
    pub handle: sys::CUmipmappedArray,
    /// Context the array belongs to.
    pub context: Arc<Context>,
    /// Extent of level zero.
    pub shape: ArrayShape,
    /// Array creation flags.
    pub flags: ArrayFlags,
    /// Number of mip levels.
    pub levels: u32,
}

/// Owns a typed mipmap chain with one initialization state covering every level.
#[derive(Debug)]
pub struct MipmappedArray<T: ArrayElement, S = Initialized> {
    allocation: Arc<MipmappedAllocation>,
    marker: PhantomData<(T, S)>,
}

impl<T: ArrayElement, S> MipmappedArray<T, S> {
    /// Returns the shared allocation that owns all mip levels.
    #[must_use]
    pub fn allocation(&self) -> &Arc<MipmappedAllocation> {
        &self.allocation
    }

    /// Borrows the native mipmapped-array handle without transferring ownership.
    #[must_use]
    pub fn as_raw(&self) -> sys::CUmipmappedArray {
        self.allocation.as_raw()
    }

    /// Returns the context that owns the mipmap chain.
    #[must_use]
    pub fn context(&self) -> &Arc<Context> {
        self.allocation.context()
    }

    /// Returns the number of mip levels.
    #[must_use]
    pub fn levels(&self) -> u32 {
        self.allocation.levels
    }

    fn array_at_level(&self, level: u32) -> Result<Array<T, S>> {
        if level >= self.levels() {
            return Err(Error::out_of_range("mipmap level"));
        }

        self.context().bind()?;
        let mut handle = ptr::null_mut();
        // SAFETY: `handle` is a writable local, the mipmapped array is live for `&self`, its context is bound, and `level` is below the level count.
        unsafe {
            try_ffi!(sys::cuMipmappedArrayGetLevel(
                &raw mut handle,
                self.as_raw(),
                level
            ))?;
        }
        Ok(Array {
            allocation: Arc::new(ArrayAllocation {
                context: Arc::clone(self.context()),
                handle,
                id: self.allocation.id,
                range: self.allocation.ranges[to_usize(level, "mipmap level")?].clone(),
                shape: self.allocation.shape.at_level(level),
                flags: self.allocation.flags,
                format: T::FORMAT,
                channels: T::CHANNELS,
                parent: Some(Arc::clone(&self.allocation)),
            }),
            marker: PhantomData,
        })
    }

    /// Borrows a mip level for reading while retaining its parent allocation.
    ///
    /// # Errors
    ///
    /// Returns an error if `level` is outside `0..self.levels()`, context binding fails, or CUDA cannot retrieve the level handle.
    pub fn level(&self, level: u32) -> Result<ArrayLevel<'_, T, S>> {
        Ok(ArrayLevel {
            array: self.array_at_level(level)?,
            parent: PhantomData,
        })
    }

    /// Borrows a mip level exclusively while retaining its parent allocation.
    ///
    /// # Errors
    ///
    /// Returns an error if `level` is outside `0..self.levels()`, context binding fails, or CUDA cannot retrieve the level handle.
    pub fn level_mut(&mut self, level: u32) -> Result<ArrayLevelMut<'_, T, S>> {
        Ok(ArrayLevelMut {
            array: self.array_at_level(level)?,
            parent: PhantomData,
        })
    }

    /// Transfers ownership of the complete native mipmap chain and its context.
    ///
    /// # Errors
    ///
    /// Returns the mipmapped array unchanged as the error if another owner retains the allocation, including a retained mip level.
    pub fn into_raw(self) -> StdResult<RawMipmappedArray, Self> {
        let shape = self.allocation.shape();
        let flags = self.allocation.flags();
        let levels = self.levels();
        match Arc::try_unwrap(self.allocation) {
            Ok(mut allocation) => Ok(RawMipmappedArray {
                handle: mem::replace(&mut allocation.handle, ptr::null_mut()),
                context: Arc::clone(&allocation.context),
                shape,
                flags,
                levels,
            }),
            Err(allocation) => Err(Self {
                allocation,
                marker: PhantomData,
            }),
        }
    }
}

impl<T: ArrayElement> MipmappedArray<T, Uninitialized> {
    /// Adopts a complete mip chain with independently owned destruction responsibility.
    ///
    /// # Safety
    ///
    /// `raw.handle` must belong to `raw.context`, match the exact descriptor and level count, and have dense mapped storage before any transfer or sampling operation.
    ///
    /// # Errors
    ///
    /// Returns an error if the handle is null, the shape or byte ranges are invalid, the requested level count is zero or exceeds the shape maximum, or level zero has a different typed descriptor.
    /// Returns an error if the context cannot be bound or CUDA cannot report a level or its descriptor.
    pub unsafe fn from_raw(raw: RawMipmappedArray) -> Result<Self> {
        let RawMipmappedArray {
            handle,
            context,
            shape,
            flags,
            levels,
        } = raw;
        if handle.is_null() {
            return Err(Error::NullHandle);
        }

        let (expected, _) = descriptor::<T>(shape, flags)?;
        let ranges = mip_level_ranges::<T>(shape, levels)?;
        context.bind()?;
        let mut level = ptr::null_mut();
        // SAFETY: `level` is a writable local, the caller guarantees `handle` is a live mipmapped array of the bound `context`, and level 0 always exists.
        unsafe {
            try_ffi!(sys::cuMipmappedArrayGetLevel(&raw mut level, handle, 0))?;
        }

        let mut actual = MaybeUninit::<sys::CUDA_ARRAY3D_DESCRIPTOR>::uninit();
        // SAFETY: `actual` is a writable local, and `level` is the live level-zero array CUDA just returned.
        unsafe {
            try_ffi!(sys::cuArray3DGetDescriptor_v2(actual.as_mut_ptr(), level))?;
        }

        // SAFETY: `cuArray3DGetDescriptor_v2` succeeded, so it wrote the whole descriptor.
        if expected != unsafe { actual.assume_init() } {
            return Err(Error::out_of_range("mipmap level descriptor"));
        }

        // SAFETY: `level` is a writable local, `handle` is the live mipmapped array, and `levels` is nonzero, as `mip_level_ranges` checked; CUDA rejects a last level the chain lacks.
        unsafe {
            try_ffi!(sys::cuMipmappedArrayGetLevel(
                &raw mut level,
                handle,
                levels - 1
            ))?;
        }
        Ok(Self {
            allocation: Arc::new(MipmappedAllocation {
                context,
                handle,
                id: AllocationId::create(),
                shape,
                flags,
                levels,
                ranges,
            }),
            marker: PhantomData,
        })
    }
}

impl<T: ArrayElement> MipmappedArray<T> {
    /// Allocates a mipmap chain without initializing its texels.
    ///
    /// Each level halves spatial dimensions, rounded down to a minimum of one; layer and cube counts remain constant.
    ///
    /// # Errors
    ///
    /// Returns an error if dimensions are zero, size calculations overflow, flags contain unknown bits, `levels` is zero or exceeds the shape maximum, the context cannot be bound, CUDA cannot allocate the chain, or CUDA returns a null handle.
    pub fn create_uninit(
        context: &Arc<Context>,
        shape: ArrayShape,
        flags: ArrayFlags,
        levels: u32,
    ) -> Result<MipmappedArray<T, Uninitialized>> {
        if flags.bits() & !ArrayFlags::all().bits() != 0 {
            return Err(Error::out_of_range("array flags"));
        }

        let (desc, _) = descriptor::<T>(shape, flags)?;
        let ranges = mip_level_ranges::<T>(shape, levels)?;
        context.bind()?;
        let mut handle = ptr::null_mut();
        // SAFETY: `handle` is a writable local, `desc` is a local that outlives the call, and `context` is bound.
        unsafe {
            try_ffi!(sys::cuMipmappedArrayCreate(
                &raw mut handle,
                &raw const desc,
                levels
            ))?;
        }

        if handle.is_null() {
            return Err(Error::NullHandle);
        }
        Ok(MipmappedArray {
            allocation: Arc::new(MipmappedAllocation {
                context: Arc::clone(context),
                handle,
                id: AllocationId::create(),
                shape,
                flags,
                levels,
                ranges,
            }),
            marker: PhantomData,
        })
    }
}

impl<T: ArrayElement> MipmappedArray<T, Uninitialized> {
    /// Initializes every mip level from one contiguous host slice per level.
    ///
    /// `levels[0]` supplies the largest level.
    /// Each slice must contain all texels of that level, including its layers or cube faces.
    ///
    /// # Errors
    ///
    /// Returns an error if the slice count differs from the mip level count, any slice has the wrong length, or retrieving or copying a level fails.
    ///
    /// # Panics
    ///
    /// Panics if a level index cannot fit in `u32`.
    /// Construction bounds the level count by `u32`, so this condition cannot occur for a valid mipmapped array.
    pub fn initialize(mut self, levels: &[&[T]]) -> Result<MipmappedArray<T>> {
        let level_count = to_usize(self.levels(), "mipmap level count")?;
        if levels.len() != level_count {
            return Err(Error::length_mismatch(
                "mipmap levels",
                level_count,
                levels.len(),
            ));
        }

        for (level, values) in levels.iter().enumerate() {
            let mut array = self.level_mut(
                u32::try_from(level).expect("mipmap level is bounded by the u32 level count"),
            )?;
            let region = ArrayRegion::full(array.shape())?;
            array.copy_from_host(region, values)?;
        }
        // SAFETY: the loop ran one synchronized full-region copy per level, so every texel of every level holds a valid `T`.
        Ok(unsafe { self.assume_init() })
    }

    /// Marks every mip level initialized after external producers complete.
    ///
    /// # Safety
    ///
    /// Every texel in every level must be initialized and all producers must be ordered before readers.
    #[must_use]
    pub unsafe fn assume_init(self) -> MipmappedArray<T> {
        MipmappedArray {
            allocation: self.allocation,
            marker: PhantomData,
        }
    }
}

fn mip_level_ranges<T: ArrayElement>(shape: ArrayShape, levels: u32) -> Result<Vec<Range<usize>>> {
    if levels == 0 || levels > shape.maximum_levels() {
        return Err(Error::out_of_range("mipmap level count"));
    }

    let mut end = 0usize;
    (0..levels)
        .map(|level| {
            let bytes = volume(shape.at_level(level).extent()?)?
                .checked_mul(size_of::<T>())
                .ok_or_else(|| Error::out_of_range("mipmap level bytes"))?;
            let start = end;
            end = end
                .checked_add(bytes)
                .ok_or_else(|| Error::out_of_range("mipmap byte size"))?;
            Ok(start..end)
        })
        .collect()
}

/// Shared borrowed mip level retaining the actual parent allocation.
#[derive(Debug)]
pub struct ArrayLevel<'a, T: ArrayElement, S = Initialized> {
    array: Array<T, S>,
    parent: PhantomData<&'a MipmappedArray<T, S>>,
}

impl<T: ArrayElement, S> Deref for ArrayLevel<'_, T, S> {
    type Target = Array<T, S>;

    fn deref(&self) -> &Self::Target {
        &self.array
    }
}

/// Exclusive borrowed mip level; writes cannot overlap another safe parent borrow.
#[derive(Debug)]
pub struct ArrayLevelMut<'a, T: ArrayElement, S = Initialized> {
    array: Array<T, S>,
    parent: PhantomData<&'a mut MipmappedArray<T, S>>,
}

impl<T: ArrayElement, S> Deref for ArrayLevelMut<'_, T, S> {
    type Target = Array<T, S>;

    fn deref(&self) -> &Self::Target {
        &self.array
    }
}

impl<T: ArrayElement, S> DerefMut for ArrayLevelMut<'_, T, S> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.array
    }
}