edgefirst-tensor 0.35.0

Zero-copy tensor memory management with DMA, shared memory, and heap backends
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
// SPDX-FileCopyrightText: Copyright 2026 Au-Zone Technologies
// SPDX-License-Identifier: Apache-2.0
//! `Tensor::image(.., TensorMemory::DmaBuf, ..)` on Windows: the public
//! surface wired onto the D3D11 texture storage.
#![cfg(all(target_os = "windows", feature = "static"))]

use edgefirst_tensor::blob::TransportMode;
use edgefirst_tensor::{
    CpuAccess, DType, Error, PixelFormat, Tensor, TensorDyn, TensorMapTrait, TensorMemory,
    TensorTrait,
};
use std::os::windows::io::AsRawHandle;

#[path = "support/cuda_require.rs"]
mod cuda_require;

/// The WARP exclusion for the three CUDA interop tests, reporting
/// `SKIPPED: {what}: ...` through `report_skip` and returning `true` when the
/// caller must return early.
///
/// `cudaD3D11GetDevice` has no ordinal for the WARP adapter, so no amount of
/// working CUDA runtime can give a WARP device a CUDA import: the skip is a
/// property of the adapter, not a missing precondition, and it is deliberately
/// checked *before* `cuda_require::cuda_available_or_skip`. Ordered the other
/// way, a WARP run with `HAL_TEST_REQUIRE_CUDA=1` (which
/// `scripts/test-windows.ps1` can arm from host detection alone) would panic
/// on the absent runtime before reaching this skip, contradicting the
/// documented promise that the WARP path is unaffected by the gate.
///
/// A failure to create the device at all is not treated as WARP: that host has
/// no D3D11 at all, and the CUDA gate below is the one that should speak.
fn warp_has_no_cuda_device(what: &str) -> bool {
    let warp = edgefirst_tensor::d3d11::device().is_ok_and(|d| d.is_warp());
    if warp {
        report_skip(&format!("{what}: WARP adapter has no CUDA device"));
    }
    warp
}

/// Reports a test skip with `reason`, writing `SKIPPED: {reason}` directly
/// to stderr (not via `eprintln!`) so libtest's output capture cannot hide
/// it -- see `edgefirst_tensor`'s (crate-internal) `test_support` module
/// for the same mechanism in the library's own `#[cfg(test)]` code; this
/// integration test binary is a separate compilation unit and cannot reach
/// that `pub(crate)` helper, so it carries a local copy.
fn report_skip(reason: &str) {
    use std::io::Write;
    let _ = writeln!(&mut std::io::stderr(), "SKIPPED: {reason}");
}

#[test]
fn image_with_dmabuf_on_windows_is_a_texture_tensor() {
    if !edgefirst_tensor::is_gpu_buffer_available() {
        report_skip("no D3D11 device on this box");
        return;
    }
    let t = Tensor::<u8>::image(
        640,
        480,
        PixelFormat::Rgba,
        Some(TensorMemory::DmaBuf),
        CpuAccess::ReadWrite,
    )
    .unwrap();
    assert_eq!(t.memory(), TensorMemory::DmaBuf);
    assert!(t.d3d11_texture().is_some());
    assert_eq!(t.d3d11_layout().unwrap().texture_width, 640);
    assert_eq!(t.d3d11_layout().unwrap().texture_height, 480);
    let stride = t.row_stride().unwrap_or(640 * 4);
    assert!(stride >= 640 * 4);
    {
        let mut m = t.map().unwrap();
        m.as_mut_slice()[..4].copy_from_slice(&[1, 2, 3, 4]);
    }
    assert_eq!(&t.map().unwrap().as_slice()[..4], &[1, 2, 3, 4]);
}

#[test]
fn nv12_odd_height_allocates_the_combined_plane() {
    let t = Tensor::<u8>::image(
        640,
        481,
        PixelFormat::Nv12,
        Some(TensorMemory::DmaBuf),
        CpuAccess::Read,
    )
    .unwrap();
    assert_eq!(
        t.d3d11_layout().unwrap().texture_height,
        PixelFormat::Nv12.allocation_shape(640, 481).unwrap()[0]
    );
}

#[test]
fn unsupported_format_is_a_loud_error_not_a_silent_downgrade() {
    let err = Tensor::<u8>::image(
        64,
        64,
        PixelFormat::Vyuy,
        Some(TensorMemory::DmaBuf),
        CpuAccess::None,
    )
    .unwrap_err();
    assert!(
        err.to_string()
            .contains("no zero-copy D3D11 texture layout"),
        "unexpected error: {err}"
    );
}

#[test]
fn try_map_returns_would_block_or_succeeds_and_other_backings_alias_map() {
    let t = Tensor::<u8>::image(
        1920,
        1080,
        PixelFormat::Rgba,
        Some(TensorMemory::DmaBuf),
        CpuAccess::ReadWrite,
    )
    .unwrap();
    match t.try_map() {
        Ok(_) => {}
        Err(Error::IoError(e)) => assert_eq!(e.kind(), std::io::ErrorKind::WouldBlock),
        Err(e) => panic!("unexpected {e}"),
    }
    match t.try_map_with(CpuAccess::Read) {
        Ok(_) => {}
        Err(Error::IoError(e)) => assert_eq!(e.kind(), std::io::ErrorKind::WouldBlock),
        Err(e) => panic!("unexpected {e}"),
    }
    let m = Tensor::<u8>::new(&[16], None, None).unwrap();
    assert!(m.try_map().is_ok());
}

/// A texture tensor's non-blocking map makes progress: retried, it hands back
/// the bytes a preceding CPU write put there.
#[test]
fn try_map_makes_progress_and_sees_the_written_bytes() {
    let t = Tensor::<u8>::image(
        64,
        64,
        PixelFormat::Rgba,
        Some(TensorMemory::DmaBuf),
        CpuAccess::ReadWrite,
    )
    .unwrap();
    {
        let mut m = t.map_write().unwrap();
        m.as_mut_slice()[..4].copy_from_slice(&[9, 8, 7, 6]);
    }
    let deadline = std::time::Instant::now() + std::time::Duration::from_secs(2);
    let mapped = loop {
        match t.try_map_with(CpuAccess::Read) {
            Ok(v) => break v,
            Err(Error::IoError(e)) if e.kind() == std::io::ErrorKind::WouldBlock => {}
            Err(e) => panic!("unexpected {e}"),
        }
        assert!(
            std::time::Instant::now() < deadline,
            "try_map_with never succeeded"
        );
        // On WARP the threads that finish the staging copy are CPU threads
        // competing with this one for the same cores, so a tight retry starves
        // the very copy it waits for.
        std::thread::yield_now();
    };
    assert_eq!(&mapped.as_slice()[..4], &[9, 8, 7, 6]);
}

#[test]
fn tensordyn_exposes_the_same_surface() {
    let t = TensorDyn::image(
        64,
        32,
        PixelFormat::Bgra,
        DType::U8,
        Some(TensorMemory::DmaBuf),
        CpuAccess::None,
    )
    .unwrap();
    assert!(t.d3d11_texture().is_some());
    assert!(t.gpu_completion().unwrap().is_none());
    let h = t.d3d11_shared_handle().unwrap();
    // SAFETY: `h` is a shared NT handle this process owns and keeps alive for
    // the rest of the test; the constructor duplicates what it keeps.
    let again = unsafe {
        TensorDyn::from_d3d11_shared_handle(
            h.as_raw_handle() as _,
            64,
            32,
            PixelFormat::Bgra,
            DType::U8,
            CpuAccess::None,
            None,
            None,
        )
    }
    .unwrap();
    assert_eq!(again.memory(), TensorMemory::DmaBuf);
    assert!(again.d3d11_texture().is_some());
}

/// The pointer constructor adopts a texture the HAL allocated, and a recorded
/// fence value surfaces through `gpu_completion`.
#[test]
fn from_d3d11_texture_wraps_and_gpu_write_is_recorded() {
    let t = Tensor::<u8>::image(
        32,
        16,
        PixelFormat::Rgba,
        Some(TensorMemory::DmaBuf),
        CpuAccess::Read,
    )
    .unwrap();
    let ptr = t.d3d11_texture().unwrap();
    // SAFETY: `ptr` borrows `t`'s live texture, which the HAL device created
    // and `t` keeps alive across this call.
    let wrapped = unsafe {
        Tensor::<u8>::from_d3d11_texture(ptr, 32, 16, PixelFormat::Rgba, CpuAccess::Read, None)
    }
    .unwrap();
    assert_eq!(wrapped.memory(), TensorMemory::DmaBuf);
    assert_eq!(wrapped.d3d11_texture(), Some(ptr));
    // A wrapped texture keys on the texture pointer, so it aliases the
    // original; the same texture reopened from its NT handle would not.
    assert_eq!(
        wrapped.buffer_identity().id(),
        t.buffer_identity().id(),
        "a pointer-wrapped texture shares the original's identity"
    );
    // The exact key, not just "the two agree": this is the formula
    // `dynamic_primitives.rs`'s
    // `a_texture_handles_identity_names_its_texture_not_its_recyclable_handle_address`
    // pins for the dynamic backend, and `edgefirst-image`'s `texture_of`
    // recomputes before it will import. Asserting it on both sides is what
    // stops the backends drifting apart -- when they did, the image crate's
    // EGLImage cache served dropped textures.
    assert_eq!(
        t.buffer_identity().kind(),
        edgefirst_tensor::IdentityKind::D3d11Texture,
        "a texture tensor is identified by its texture"
    );
    assert_eq!(
        t.buffer_identity().id(),
        ((edgefirst_tensor::IdentityKind::D3d11Texture as u64) << 56) ^ (ptr as usize as u64),
        "the static backend's key is the ID3D11Texture2D pointer, the same value \
         the dynamic backend reads back through ef_tensor_d3d11_texture"
    );
    assert!(wrapped.gpu_completion().unwrap().is_none());
    wrapped.set_gpu_write(7).unwrap();
    let completion = wrapped.gpu_completion().unwrap().expect("a recorded write");
    assert_eq!(completion.value, 7);
}

/// Two handle imports of *different* textures with the same geometry get
/// different identities even when the caller's handle values are recycled: the
/// tensor keys on the `ID3D11Texture2D` its own open produced, and a live COM
/// object's address cannot be handed to another object.
///
/// The first import's source handle is closed before the second is opened,
/// which is what makes Windows free to hand the same numeric value back.
#[test]
fn handle_imports_of_different_textures_do_not_share_an_identity() {
    let open = |t: &TensorDyn| {
        let h = t.d3d11_shared_handle().unwrap();
        // SAFETY: `h` is a shared NT handle this process owns for the length
        // of this closure; the constructor duplicates what it keeps.
        let imported = unsafe {
            TensorDyn::from_d3d11_shared_handle(
                h.as_raw_handle() as _,
                32,
                16,
                PixelFormat::Rgba,
                DType::U8,
                CpuAccess::None,
                None,
                None,
            )
        }
        .unwrap();
        drop(h);
        imported
    };
    let make = || {
        TensorDyn::image(
            32,
            16,
            PixelFormat::Rgba,
            DType::U8,
            Some(TensorMemory::DmaBuf),
            CpuAccess::None,
        )
        .unwrap()
    };
    let (a, b) = (make(), make());
    let (ia, ib) = (open(&a), open(&b));
    assert_ne!(
        ia.buffer_identity().id(),
        ib.buffer_identity().id(),
        "two imports of different textures must not collide on a recycled handle value"
    );
}

/// A write-only map has to publish the whole texture, so a window shorter than
/// the backing is refused rather than silently overwriting the rows outside
/// it. `ReadWrite` is the same window with the refresh, and it is accepted.
#[test]
fn write_only_map_of_a_narrowed_window_is_refused_and_names_readwrite() {
    let mut t = Tensor::<u8>::image(
        64,
        16,
        PixelFormat::Rgba,
        Some(TensorMemory::DmaBuf),
        CpuAccess::ReadWrite,
    )
    .unwrap();
    assert!(t.map_write().is_ok(), "the whole tensor is writable");
    t.set_logical_shape(&[4, 64, 4]).unwrap();
    let err = t.map_write().unwrap_err();
    assert!(
        matches!(&err, Error::PartialWriteRequiresReadWrite(m) if m.contains("CpuAccess::ReadWrite")),
        "unexpected error: {err}"
    );
    assert!(t.map_mut().is_ok(), "the read-write window is accepted");
}

/// `gpu_write_value` is the recorded value alone, with no duplicated fence
/// handle: 0 before any write, then the number `gpu_completion` carries, on
/// the typed tensor and on `TensorDyn` alike. A host tensor answers 0 rather
/// than an error.
#[test]
fn d3d11_gpu_write_value_matches_the_completion_value() {
    let t = Tensor::<u8>::image(
        32,
        16,
        PixelFormat::Rgba,
        Some(TensorMemory::DmaBuf),
        CpuAccess::None,
    )
    .unwrap();
    assert_eq!(t.gpu_write_value(), 0);
    t.set_gpu_write(11).unwrap();
    let completion = t.gpu_completion().unwrap().expect("a recorded write");
    assert_eq!(t.gpu_write_value(), completion.value);

    let t = TensorDyn::from(t);
    assert_eq!(t.gpu_write_value(), 11);
    t.set_gpu_write(12).unwrap();
    let completion = t.gpu_completion().unwrap().expect("a recorded write");
    assert_eq!(t.gpu_write_value(), completion.value);

    let host = Tensor::<u8>::new(&[16], None, None).unwrap();
    assert_eq!(host.gpu_write_value(), 0);
    assert_eq!(TensorDyn::from(host).gpu_write_value(), 0);
}

/// The Windows accessors are `None`/`NotImplemented` for a tensor that is not
/// a texture, rather than panicking or lying.
#[test]
fn non_texture_tensors_report_no_d3d11_backing() {
    let m = Tensor::<u8>::new(&[16], None, None).unwrap();
    assert!(m.d3d11_texture().is_none());
    assert!(m.d3d11_layout().is_none());
    assert!(matches!(
        m.d3d11_shared_handle(),
        Err(Error::NotImplemented(_))
    ));
    assert!(matches!(m.gpu_completion(), Err(Error::NotImplemented(_))));
}

/// `Tensor::new` with an explicit `DmaBuf` request says why a texture tensor
/// cannot serve it instead of silently allocating host memory.
#[test]
fn plain_new_with_dmabuf_names_the_image_constructor() {
    let err = Tensor::<u8>::new(&[16], Some(TensorMemory::DmaBuf), None).unwrap_err();
    assert!(
        err.to_string().contains("Tensor::image"),
        "unexpected error: {err}"
    );
}

/// A texture tensor's descriptor names the texture's own NT handle, the
/// device fence and the value of the last recorded write, and importing it
/// rebuilds a tensor over the same texture.
#[test]
fn descriptor_round_trips_a_texture_with_its_completion() {
    let t = TensorDyn::image(
        32,
        16,
        PixelFormat::Rgba,
        DType::U8,
        Some(TensorMemory::DmaBuf),
        CpuAccess::ReadWrite,
    )
    .unwrap();
    {
        let mut m = t.map_bytes(CpuAccess::ReadWrite).unwrap();
        m.as_mut_slice()[..4].copy_from_slice(&[9, 8, 7, 6]);
    }
    let v = edgefirst_tensor::d3d11::device()
        .unwrap()
        .signal()
        .expect("fence");
    t.set_gpu_write(v).unwrap();
    let desc = t.descriptor_pinned(None);
    assert_eq!(desc.kind, edgefirst_tensor::protocol::kind::D3D11_TEXTURE);
    assert!(desc.flags & edgefirst_tensor::protocol::flags::SYNC_PRESENT != 0);
    assert_eq!(desc.sync, v);
    let imported = TensorDyn::import_descriptor(&desc).unwrap();
    assert_eq!(imported.memory(), TensorMemory::DmaBuf);
    assert_eq!(
        &imported.map_bytes(CpuAccess::Read).unwrap().as_slice()[..4],
        &[9, 8, 7, 6]
    );

    // A pinned capsule (Python's `access="read"`) pins a texture tensor too.
    // `ptr` is the fence under this kind, so the pin's host address must not
    // displace it -- a consumer would open that address as a fence.
    let pin = t.pin_host(CpuAccess::Read).unwrap();
    assert!(!pin.as_mut_ptr().is_null(), "a texture tensor does pin");
    let pinned = t.descriptor_pinned(Some(&pin));
    assert_eq!(pinned.ptr.0, desc.ptr.0);
    assert_ne!(pinned.ptr.0, pin.as_mut_ptr());
    assert!(TensorDyn::import_descriptor(&pinned).is_ok());
}

/// A semi-planar texture is as wide as its padded row pitch, so the import's
/// image width can only come from the descriptor's shape. Both spellings of
/// that shape are accepted and the producer's own is what the consumer sees.
#[test]
fn descriptor_round_trips_a_semi_planar_texture() {
    let mut t = TensorDyn::image(
        640,
        481,
        PixelFormat::Nv12,
        DType::U8,
        Some(TensorMemory::DmaBuf),
        CpuAccess::ReadWrite,
    )
    .unwrap();
    let imported = TensorDyn::import_descriptor(&t.descriptor_pinned(None)).unwrap();
    assert_eq!(imported.width(), Some(640));
    assert_eq!(imported.height(), Some(481));
    assert_eq!(imported.width(), t.width());
    assert_eq!(imported.height(), t.height());
    assert_eq!(imported.shape(), t.shape());
    assert_eq!(imported.row_stride(), t.row_stride());

    // The addressing spelling of the same image: the producer's logical shape
    // is restored onto the import, not the allocation shape it opens at.
    t.set_logical_shape(&[481, 640]).unwrap();
    let imported = TensorDyn::import_descriptor(&t.descriptor_pinned(None)).unwrap();
    assert_eq!(imported.shape(), &[481, 640]);
    assert_eq!(imported.row_stride(), t.row_stride());
}

/// Copies `src`'s tight rows into a destination whose rows are `dst_stride`
/// bytes apart, so a texture tensor whose backing pitch exceeds its image row
/// is written row by row rather than as one flat block.
fn copy_rows(dst: &mut [u8], src: &[u8], row_bytes: usize, dst_stride: usize) {
    for (i, row) in src.chunks(row_bytes).enumerate() {
        dst[i * dst_stride..i * dst_stride + row.len()].copy_from_slice(row);
    }
}

/// CUDA reads a texture tensor's pixels through the external-memory import
/// attached at allocation, and a writable CUDA map publishes its buffer back
/// into the texture when the guard drops.
#[test]
fn cuda_map_matches_the_cpu_map_and_map_mut_writes_back() {
    if warp_has_no_cuda_device("cuda_map_matches_the_cpu_map_and_map_mut_writes_back") {
        return;
    }
    if !cuda_require::cuda_available_or_skip("cuda_map_matches_the_cpu_map_and_map_mut_writes_back")
    {
        return;
    }
    let device = edgefirst_tensor::d3d11::device().unwrap();
    let t = Tensor::<u8>::image(
        256,
        128,
        PixelFormat::Rgba,
        Some(TensorMemory::DmaBuf),
        CpuAccess::ReadWrite,
    )
    .unwrap();
    let pattern: Vec<u8> = (0..256 * 128 * 4).map(|i| (i * 7 + 13) as u8).collect();
    {
        let mut m = t.map().unwrap();
        copy_rows(
            m.as_mut_slice(),
            &pattern,
            256 * 4,
            t.row_stride().unwrap_or(256 * 4),
        );
    }
    let v = device.signal().unwrap();
    // A CPU write needs no fence, but the map must tolerate a recorded value.
    t.set_gpu_write(v).unwrap();
    let cm = t.cuda_map().expect("CUDA handle attached at allocation");
    assert_eq!(cm.len(), 256 * 128 * 4);
    let mut host = vec![0u8; cm.len()];
    // SAFETY: `host` holds `cm.len()` writable bytes and `cm.device_ptr()` is
    // the live CUDA buffer of exactly that size for as long as `cm` lives.
    assert!(unsafe {
        edgefirst_tensor::memcpy_device_to_host(
            host.as_mut_ptr().cast(),
            cm.device_ptr(),
            host.len(),
        )
    });
    assert_eq!(host, pattern);
    drop(cm);
    {
        let cm = t.cuda_map_mut().unwrap();
        let ones = vec![1u8; cm.len()];
        // SAFETY: mirror of the read above -- `ones` holds `cm.len()` readable
        // bytes and the device pointer is live for the guard's lifetime.
        assert!(unsafe {
            edgefirst_tensor::memcpy_host_to_device(
                cm.device_ptr(),
                ones.as_ptr().cast(),
                ones.len(),
            )
        });
    }
    // Every row, not just the first: a release that copies the wrong row count
    // or the wrong row length leaves the tail of the image untouched.
    let m = t.map_read().unwrap();
    let stride = t.row_stride().unwrap_or(256 * 4);
    for row in 0..128 {
        let at = row * stride;
        assert!(
            m.as_slice()[at..at + 256 * 4].iter().all(|&b| b == 1),
            "row {row} was not written back"
        );
    }
}

/// A geometry whose D3D11 allocation the driver pads still imports: the
/// declared external-memory size has to cover that padding, and 640x480 is one
/// of the shapes whose padding-free byte count the driver rejects (the brief's
/// 256x128 is one it accepts, so only this test covers the fallback).
#[test]
fn cuda_map_covers_a_texture_whose_allocation_the_driver_padded() {
    if warp_has_no_cuda_device("cuda_map_covers_a_texture_whose_allocation_the_driver_padded") {
        return;
    }
    if !cuda_require::cuda_available_or_skip(
        "cuda_map_covers_a_texture_whose_allocation_the_driver_padded",
    ) {
        return;
    }
    let (w, h) = (640usize, 480usize);
    let t = Tensor::<u8>::image(
        w,
        h,
        PixelFormat::Rgba,
        Some(TensorMemory::DmaBuf),
        CpuAccess::ReadWrite,
    )
    .unwrap();
    let pattern: Vec<u8> = (0..w * h * 4).map(|i| (i % 251) as u8).collect();
    {
        let mut m = t.map().unwrap();
        copy_rows(
            m.as_mut_slice(),
            &pattern,
            w * 4,
            t.row_stride().unwrap_or(w * 4),
        );
    }
    let cm = t.cuda_map().expect("the padded declaration imports");
    assert_eq!(cm.len(), w * h * 4);
    let mut host = vec![0u8; cm.len()];
    // SAFETY: `host` holds `cm.len()` writable bytes and `cm.device_ptr()` is
    // the live CUDA buffer of exactly that size while `cm` lives.
    assert!(unsafe {
        edgefirst_tensor::memcpy_device_to_host(
            host.as_mut_ptr().cast(),
            cm.device_ptr(),
            host.len(),
        )
    });
    assert_eq!(host, pattern);
}

/// The semi-planar arm: NV12 is one R8 texture of the combined plane, whose
/// texture width *is* the row stride, so the CUDA mapping and the CPU map are
/// laid out identically and the whole plane round-trips byte for byte.
#[test]
fn cuda_map_reads_the_nv12_combined_plane() {
    if warp_has_no_cuda_device("cuda_map_reads_the_nv12_combined_plane") {
        return;
    }
    if !cuda_require::cuda_available_or_skip("cuda_map_reads_the_nv12_combined_plane") {
        return;
    }
    let (w, h) = (640usize, 480usize);
    let t = Tensor::<u8>::image(
        w,
        h,
        PixelFormat::Nv12,
        Some(TensorMemory::DmaBuf),
        CpuAccess::ReadWrite,
    )
    .unwrap();
    // The texture's own row, which for a semi-planar backing is also the row
    // a CPU map sees -- the allocator widens the texture to the driver's pitch
    // precisely so the two are one number, and `row_stride()` is only recorded
    // when it exceeds the natural stride.
    let layout = t.d3d11_layout().unwrap();
    let stride = layout.tight_row_bytes();
    assert_eq!(t.row_stride().unwrap_or(stride), stride);
    let rows = layout.texture_height;
    assert_eq!(rows, PixelFormat::Nv12.allocation_shape(w, h).unwrap()[0]);
    let pattern: Vec<u8> = (0..stride * rows).map(|i| (i % 253) as u8).collect();
    {
        let mut m = t.map().unwrap();
        copy_rows(m.as_mut_slice(), &pattern, stride, stride);
    }
    let cm = t.cuda_map().expect("the combined plane imports");
    assert_eq!(
        cm.len(),
        stride * rows,
        "the mapping is the whole combined plane at the texture's own row"
    );
    let mut host = vec![0u8; cm.len()];
    // SAFETY: `host` holds `cm.len()` writable bytes and `cm.device_ptr()` is
    // the live CUDA buffer of exactly that size while `cm` lives.
    assert!(unsafe {
        edgefirst_tensor::memcpy_device_to_host(
            host.as_mut_ptr().cast(),
            cm.device_ptr(),
            host.len(),
        )
    });
    assert_eq!(host, pattern);
}

/// Reference-mode blob transport of a texture, in one process: there is no fd
/// table to carry an NT handle, so the handle values ride in the plane record
/// and the header's pid says whose handle table they belong to.
#[test]
fn blob_export_import_shares_a_texture_in_process() {
    let t = TensorDyn::image(
        32,
        16,
        PixelFormat::Rgba,
        DType::U8,
        Some(TensorMemory::DmaBuf),
        CpuAccess::ReadWrite,
    )
    .unwrap();
    {
        let mut m = t.map_bytes(CpuAccess::ReadWrite).unwrap();
        m.as_mut_slice()[..2].copy_from_slice(&[3, 4]);
    }
    let (blob, fds) = edgefirst_tensor::blob::export(&t, TransportMode::Reference).unwrap();
    assert!(
        fds.is_empty(),
        "an NT handle does not travel in an fd table"
    );

    let view = edgefirst_tensor::blob::BlobView::parse(&blob).unwrap();
    assert_eq!(view.header().pid, std::process::id());
    let planes = view.planes().unwrap();
    assert!(planes
        .iter()
        .all(|p| p.handle_bytes.len() == edgefirst_tensor::blob::D3D11_HANDLE_BYTES));

    let back = edgefirst_tensor::blob::import(&blob, &[]).unwrap();
    assert_eq!(back.memory(), TensorMemory::DmaBuf);
    assert_eq!(back.format(), Some(PixelFormat::Rgba));
    assert_eq!(back.shape(), t.shape());
    assert_eq!(
        &back.map_bytes(CpuAccess::Read).unwrap().as_slice()[..2],
        &[3, 4]
    );
}

/// A texture import keeps the pitch its own device reports, not the producer's
/// that the blob happens to carry: the two are facts about different drivers,
/// and `from_d3d11_shared_handle` has already recorded the local one. The
/// descriptor path makes the same exclusion (`restore_imported_row_stride`
/// skips `D3D11_TEXTURE`), so a blob stride saying otherwise must not move it.
#[test]
fn blob_import_keeps_the_local_pitch_not_the_blobs_stride() {
    let (w, h) = (37usize, 16usize);
    let t = TensorDyn::image(
        w,
        h,
        PixelFormat::Rgba,
        DType::U8,
        Some(TensorMemory::DmaBuf),
        CpuAccess::ReadWrite,
    )
    .unwrap();
    let (blob, _) = edgefirst_tensor::blob::export(&t, TransportMode::Reference).unwrap();

    // What a fresh open of this very texture records for itself -- the answer
    // the import has to match, whatever the blob says.
    let handle = t.d3d11_shared_handle().unwrap();
    // SAFETY: `handle` is a live shared NT handle of this process's texture
    // and `t` holds the texture alive across the call.
    let direct = unsafe {
        TensorDyn::from_d3d11_shared_handle(
            handle.as_raw_handle(),
            w,
            h,
            PixelFormat::Rgba,
            DType::U8,
            CpuAccess::ReadWrite,
            None,
            None,
        )
    }
    .unwrap();

    // A plausible but wrong pitch in the blob's plane 0 record, whose `stride`
    // is the third of its six scalars.
    let view = edgefirst_tensor::blob::BlobView::parse(&blob).unwrap();
    let regions = edgefirst_tensor::blob::region_offsets(&view.header()).unwrap();
    let carried = view.planes().unwrap()[0].stride;
    let bogus = carried + 64;
    let at = regions.planes + 16;
    let mut tampered = blob.clone();
    tampered[at..at + 8].copy_from_slice(&bogus.to_le_bytes());

    let back = edgefirst_tensor::blob::import(&tampered, &[]).unwrap();
    assert_eq!(
        back.row_stride(),
        direct.row_stride(),
        "the import keeps the pitch this device reports for the texture"
    );
    // Through `effective_row_stride`, which is a real number on every adapter:
    // WARP pads nothing at this width, so `row_stride()` is `None` there and
    // comparing it alone would prove nothing.
    assert_eq!(
        back.effective_row_stride(),
        direct.effective_row_stride(),
        "and reports the same row as a fresh open of the same texture"
    );
    assert_ne!(
        back.effective_row_stride(),
        Some(bogus as usize),
        "the blob's stride field must not reach the imported tensor"
    );
}

/// Removes the blob file on every path out of the parent, panic included.
struct TempBlob(std::path::PathBuf);

impl Drop for TempBlob {
    fn drop(&mut self) {
        let _ = std::fs::remove_file(&self.0);
    }
}

/// The cross-process half: the child re-runs this test binary with
/// `EF_D3D11_CHILD` naming the blob file. Its D3D11 device is its own, so the
/// import can only work by duplicating both NT handles out of the exporting
/// process the header names and opening the texture on the child's device.
///
/// The parent records a GPU write before exporting, so the child's import
/// opens the *fence* out of the parent too and waits on it -- which is only
/// reachable because `signal()` submits the context it signalled on. The
/// child then re-signals its own fence behind that wait, so what it reports
/// is a value on its own timeline rather than the parent's.
#[test]
fn blob_import_from_another_process_duplicates_the_handles() {
    if let Ok(path) = std::env::var("EF_D3D11_CHILD") {
        return child_imports_the_exported_blob(&path);
    }
    let t = TensorDyn::image(
        32,
        16,
        PixelFormat::Rgba,
        DType::U8,
        Some(TensorMemory::DmaBuf),
        CpuAccess::ReadWrite,
    )
    .unwrap();
    {
        let mut m = t.map_bytes(CpuAccess::ReadWrite).unwrap();
        m.as_mut_slice()[..2].copy_from_slice(&[5, 6]);
    }
    let value = edgefirst_tensor::d3d11::device()
        .unwrap()
        .signal()
        .expect("fence");
    t.set_gpu_write(value).unwrap();

    let (blob, _) = edgefirst_tensor::blob::export(&t, TransportMode::Reference).unwrap();
    let file =
        TempBlob(std::env::temp_dir().join(format!("ef-d3d11-blob-{}.bin", std::process::id())));
    std::fs::write(&file.0, &blob).unwrap();
    let status = std::process::Command::new(std::env::current_exe().unwrap())
        .args([
            "blob_import_from_another_process_duplicates_the_handles",
            "--exact",
            "--nocapture",
        ])
        .env("EF_D3D11_CHILD", &file.0)
        .status()
        .unwrap();
    // Export borrows: the handle values in the blob are this process's, so
    // the exporting tensor has to outlive the child that reads them.
    drop(t);
    assert!(
        status.success(),
        "child could not import the exported texture"
    );
}

fn child_imports_the_exported_blob(path: &str) {
    let blob = std::fs::read(path).expect("the parent wrote the blob");
    let t = edgefirst_tensor::blob::import(&blob, &[]).expect("import in the child");
    assert_eq!(t.memory(), TensorMemory::DmaBuf);

    // The parent's fence handle was duplicated out of it and reopened here, so
    // the import could wait on the parent's value -- and then record a value
    // of its *own* device's timeline, which is the only one the fence this
    // completion names ever reaches. The two numbers are unrelated: asserting
    // equality would pin the cross-process hang the local re-signal removes.
    let completion = t
        .gpu_completion()
        .expect("gpu_completion")
        .expect("the blob carried a completion, so the import recorded a local one");
    assert_ne!(
        completion.value, 0,
        "the import recorded a value on this process's fence"
    );

    // Reachable on the fence it came back with, which is the pairing every
    // consumer relies on: the parent's value on the child's fence would never
    // arrive.
    let d = edgefirst_tensor::d3d11::device().unwrap();
    let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5);
    while d.completed_value() < completion.value {
        assert!(
            std::time::Instant::now() < deadline,
            "the recorded value {} never completed on this process's fence (at {})",
            completion.value,
            d.completed_value()
        );
        std::thread::yield_now();
    }

    assert_eq!(
        &t.map_bytes(CpuAccess::Read).unwrap().as_slice()[..2],
        &[5, 6]
    );

    // With CUDA present the same ordering has to hold for the device path: a
    // completion on a foreign timeline made this wait forever.
    if edgefirst_tensor::is_cuda_available() {
        match t.cuda_map() {
            Some(m) => assert!(
                !m.device_ptr().is_null(),
                "the CUDA map has a device pointer"
            ),
            None => report_skip("no CUDA registration on the imported texture"),
        }
    }
}

// ---------------------------------------------------------------------------
// Plane offset on a reconstructed tensor -- issue #161, the Windows half.
//
// `TensorDesc` has no field for the plane offset, so a consumer rebuilding a
// `view()` from a descriptor opens the whole texture and puts the offset back
// with `Tensor::set_plane_offset`. That was a silent no-op on this backing:
// the `Dma` arm was `cfg(target_os = "linux")` and `TensorStorage::Dma` is a
// cfg-multiplexed *name* rather than one type, so Windows fell through to the
// catch-all. And it could not even be reached: the import refused a window
// shape outright. Each test below pins one piece of the fix and was seen to
// fail without it.
// ---------------------------------------------------------------------------

/// A ramp so byte `i` holds `i & 0xff`: a window that lands at the wrong
/// origin cannot coincidentally match the expected bytes.
fn ramped_rgba(w: usize, h: usize) -> TensorDyn {
    let t = TensorDyn::image(
        w,
        h,
        PixelFormat::Rgba,
        DType::U8,
        Some(TensorMemory::DmaBuf),
        CpuAccess::ReadWrite,
    )
    .expect("texture alloc");
    assert_eq!(t.memory(), TensorMemory::DmaBuf);
    let mut m = t.map_bytes(CpuAccess::Write).expect("map parent");
    for (i, b) in m.as_mut_slice().iter_mut().enumerate() {
        *b = (i & 0xff) as u8;
    }
    drop(m);
    t
}

/// A view's descriptor imports at the window's shape, over the whole
/// texture, keeping the texture's pitch as its row stride. Before the fix
/// this import failed with "neither the allocation shape nor the addressing
/// shape", which is the *loud* half of the Windows bug.
#[test]
fn d3d11_view_descriptor_imports_at_the_window_with_the_textures_pitch() {
    let parent = ramped_rgba(64, 64);
    let pitch = parent.effective_row_stride().expect("parent pitch");
    let view = parent
        .view(edgefirst_tensor::Region::new(8, 8, 16, 16))
        .expect("view");
    let desc = view.descriptor_pinned(None);
    assert_eq!(desc.kind, edgefirst_tensor::protocol::kind::D3D11_TEXTURE);
    assert_eq!(desc.shape(), &[16, 16, 4]);

    let rebuilt = TensorDyn::import_descriptor(&desc).expect("a window is a valid shape");
    assert_eq!(rebuilt.shape(), &[16, 16, 4], "narrowed to the window");
    assert_eq!(
        rebuilt.effective_row_stride(),
        Some(pitch),
        "rows are still the texture's rows"
    );
    assert_eq!(
        rebuilt.plane_offset(),
        None,
        "the descriptor cannot carry the offset; the capsule restores it"
    );
    // Before the offset is put back, the window sits at the texture's
    // origin -- the state `apply_plane_offset` corrects.
    let m = rebuilt.map_bytes(CpuAccess::Read).expect("map rebuilt");
    assert_eq!(m.as_slice()[0], 0);
}

/// A window is the only third spelling: a semi-planar sub-rectangle is not
/// one (`Tensor::view` makes packed views only), nor a window with a
/// different channel count, nor an empty one. Untrusted descriptor input
/// keeps failing loudly.
#[test]
fn d3d11_window_descriptor_is_packed_and_non_empty_only() {
    let nv12 = TensorDyn::image(
        64,
        64,
        PixelFormat::Nv12,
        DType::U8,
        Some(TensorMemory::DmaBuf),
        CpuAccess::ReadWrite,
    )
    .expect("nv12 alloc");
    let mut desc = nv12.descriptor_pinned(None);
    desc.ndim = 2;
    desc.shape[0] = 32;
    desc.shape[1] = 32;
    let err = TensorDyn::import_descriptor(&desc).expect_err("semi-planar window");
    assert!(matches!(err, Error::InvalidArgument(_)), "{err}");

    let rgba = ramped_rgba(64, 64);
    for (label, shape) in [
        ("wrong channels", [16usize, 16, 3]),
        ("empty rows", [0, 16, 4]),
        ("taller than the texture", [65, 16, 4]),
    ] {
        let mut desc = rgba.descriptor_pinned(None);
        desc.shape[0] = shape[0] as u64;
        desc.shape[1] = shape[1] as u64;
        desc.shape[2] = shape[2] as u64;
        let err = TensorDyn::import_descriptor(&desc).expect_err(label);
        assert!(matches!(err, Error::InvalidArgument(_)), "{label}: {err}");
    }
}

/// Restoring a plane offset onto a reconstructed texture tensor must move
/// where `map()` starts. The Windows twin of
/// `set_plane_offset_moves_the_iosurface_map_window`.
#[test]
fn set_plane_offset_moves_the_d3d11_map_window() {
    let parent = ramped_rgba(64, 64);
    let view = parent
        .view(edgefirst_tensor::Region::new(8, 8, 16, 16))
        .expect("view");
    let offset = view.plane_offset().expect("a view carries its offset");
    let mut rebuilt =
        TensorDyn::import_descriptor(&view.descriptor_pinned(None)).expect("reconstruct");

    // The restore under test: what `interop::apply_plane_offset` does.
    rebuilt.set_plane_offset(offset);
    assert_eq!(rebuilt.plane_offset(), Some(offset));

    let m = rebuilt
        .map_bytes(CpuAccess::Read)
        .expect("map after the offset");
    let s = m.as_slice();
    assert_ne!(
        s[0], 0,
        "map() still starts at the texture's origin -- set_plane_offset was a \
         no-op on D3D11 storage (issue #161)"
    );
    let pitch = rebuilt.effective_row_stride().expect("pitch");
    for row in 0..16 {
        for x in 0..16 * 4 {
            let at = row * pitch + x;
            assert_eq!(
                s[at],
                ((offset + at) & 0xff) as u8,
                "window byte {at} must be parent[{}]",
                offset + at
            );
        }
    }
}

/// A nested `subview` must not compound its offset now that
/// `set_plane_offset` writes through to the texture storage: `Tensor::subview`
/// sets the offset twice by two routes (`D3d11TextureTensor::view` computes
/// `view_offset + offset_bytes`, then `subview` writes `plane_offset +
/// offset_bytes` back), which agree only while the wrapper and storage fields
/// stay in sync. Two levels, because one level cannot tell an idempotent
/// write from one that compounds from zero.
#[test]
fn nested_d3d11_subviews_do_not_compound_their_plane_offset() {
    let parent = ramped_rgba(64, 64);
    let pitch = parent.effective_row_stride().expect("pitch");
    let outer = parent
        .view(edgefirst_tensor::Region::new(8, 8, 32, 32))
        .expect("outer view");
    assert_eq!(outer.plane_offset(), Some(8 * pitch + 8 * 4));
    let inner = outer
        .view(edgefirst_tensor::Region::new(4, 4, 16, 16))
        .expect("inner view");
    let expected = 12 * pitch + 12 * 4;
    assert_eq!(
        inner.plane_offset(),
        Some(expected),
        "offsets add once, not twice"
    );
    let m = inner.map_bytes(CpuAccess::Read).expect("map nested view");
    assert_eq!(
        m.as_slice()[0],
        (expected & 0xff) as u8,
        "nested window byte 0 must be parent[{expected}], not a compounded offset"
    );
}

/// `set_format` must clear the texture storage offset, not just the wrapper
/// field, or `plane_offset()` reports `None` while `map()` still starts at
/// the old offset -- a stale window instead of a lost one.
#[test]
fn set_format_clears_the_d3d11_map_window() {
    let parent = ramped_rgba(64, 64);
    let view = parent
        .view(edgefirst_tensor::Region::new(8, 8, 16, 16))
        .expect("view");
    let mut t = TensorDyn::import_descriptor(&view.descriptor_pinned(None)).expect("reconstruct");
    t.set_plane_offset(view.plane_offset().expect("offset"));
    assert_ne!(
        t.map_bytes(CpuAccess::Read).expect("map before").as_slice()[0],
        0,
        "precondition: the offset is live before the format change"
    );

    // A different packed format of the same channel count keeps the shape
    // valid; changing it drops the offset it cannot vouch for.
    t.set_format(PixelFormat::Bgra).expect("new format");
    assert_eq!(t.plane_offset(), None, "the wrapper field is cleared");
    assert_eq!(
        t.map_bytes(CpuAccess::Read).expect("map after").as_slice()[0],
        0,
        "map() still starts at the old offset -- set_format cleared the wrapper \
         field but not the D3D11 storage (issue #161)"
    );
}

/// `reshape` is the other clear site, and unlike `IoSurfaceTensor::reshape`
/// the D3D11 storage's own `reshape` leaves `view_offset` alone, so the
/// wrapper's arm is what clears it.
#[test]
fn reshape_clears_the_d3d11_map_window() {
    let parent = ramped_rgba(64, 64);
    let view = parent
        .view(edgefirst_tensor::Region::new(8, 8, 16, 16))
        .expect("view");
    let mut t = TensorDyn::import_descriptor(&view.descriptor_pinned(None)).expect("reconstruct");
    t.set_plane_offset(view.plane_offset().expect("offset"));
    assert_ne!(
        t.map_bytes(CpuAccess::Read).expect("map before").as_slice()[0],
        0
    );

    t.reshape(&[16 * 16 * 4]).expect("same element count");
    assert_eq!(t.plane_offset(), None);
    assert_eq!(
        t.map_bytes(CpuAccess::Read).expect("map after").as_slice()[0],
        0,
        "map() still starts at the old offset after reshape (issue #161)"
    );
}

/// `set_plane_offset` takes any value -- a descriptor's restored offset is
/// untrusted -- so the pins bound it rather than offsetting a base pointer
/// past the backing.
///
/// The bound is the whole image, not just its first byte. A pin's length is
/// the backing less the offset, so an offset near the end leaves a map
/// shorter than the image while the tensor still reports its full width and
/// height, and a consumer reading `width x height` through the map's pointer
/// runs past the allocation -- which the GL upload path does, since GL takes
/// a raw pointer and cannot see a slice's length.
#[test]
fn d3d11_map_refuses_a_plane_offset_past_the_backing() {
    let parent = ramped_rgba(64, 64);
    let mut t = TensorDyn::import_descriptor(&parent.descriptor_pinned(None)).expect("reconstruct");
    let backing = t.effective_row_stride().expect("pitch") * 64;
    t.set_plane_offset(backing + 1);
    let err = t
        .map_bytes(CpuAccess::Read)
        .expect_err("a window past the backing");
    assert!(matches!(err, Error::InsufficientCapacity { .. }), "{err}");

    // Exactly the backing is a legal one-past-the-end pointer, but it is an
    // empty window for a tensor that still calls itself 64x64 -- the shape
    // that fed a short map to `TexImage2D`. Refused, not handed back empty.
    t.set_plane_offset(backing);
    let err = t
        .map_bytes(CpuAccess::Read)
        .expect_err("an empty window for a non-empty tensor");
    assert!(matches!(err, Error::InsufficientCapacity { .. }), "{err}");

    // One byte short of the whole image is refused for the same reason: the
    // map would be a byte shy of what width x height reads.
    t.set_plane_offset(1);
    let err = t
        .map_bytes(CpuAccess::Read)
        .expect_err("a window one byte short of the image");
    assert!(matches!(err, Error::InsufficientCapacity { .. }), "{err}");

    // The whole image at its own origin still maps.
    t.set_plane_offset(0);
    assert!(!t.map_bytes(CpuAccess::Read).expect("origin").is_empty());
}

/// A single-row view records a tight row stride (`Tensor::view`) while its
/// offset is measured in the texture's pitch. The descriptor round trip
/// keeps the two apart: the window imports at one row with the same tight
/// stride, and the offset put back is the producer's own, so the rebuilt
/// window maps the same texels -- including in the texture's last row,
/// where one pitched row would run past the backing. Dividing the offset by
/// the descriptor's stride, as a pitch translation once did, named row 32
/// for a view of row 8.
#[test]
fn one_row_d3d11_view_descriptor_maps_the_producers_texels() {
    let parent = ramped_rgba(64, 64);
    let pitch = parent.effective_row_stride().expect("parent pitch");
    for (x, y) in [(8usize, 8usize), (48, 63)] {
        let view = parent
            .view(edgefirst_tensor::Region::new(x, y, 16, 1))
            .expect("one-row view");
        assert_eq!(
            view.effective_row_stride(),
            Some(16 * 4),
            "a one-row view is tight"
        );
        let offset = view.plane_offset().expect("a view carries its offset");
        assert_eq!(offset, y * pitch + x * 4, "the offset is in the pitch");

        let desc = view.descriptor_pinned(None);
        let mut rebuilt = TensorDyn::import_descriptor(&desc).expect("a one-row window");
        assert_eq!(rebuilt.shape(), &[1, 16, 4]);
        assert_eq!(
            rebuilt.effective_row_stride(),
            Some(16 * 4),
            "a narrowed one-row window keeps view()'s tight stride"
        );
        rebuilt.set_plane_offset(offset);

        let expect: Vec<u8> = (offset..offset + 16 * 4)
            .map(|i| (i & 0xff) as u8)
            .collect();
        let m = rebuilt
            .map_bytes(CpuAccess::Read)
            .expect("the window maps, last row included");
        assert_eq!(
            m.as_slice(),
            expect.as_slice(),
            "rebuilt window at ({x}, {y})"
        );
        let v = view.map_bytes(CpuAccess::Read).expect("map the view");
        assert_eq!(v.as_slice(), expect.as_slice(), "fresh view at ({x}, {y})");
    }
}