rusty_dds 0.3.8

Memory-safe DDS texture toolkit — zero-copy container parse, decode, encode (BC1-BC7, BC6H HDR), rate-distortion optimization, GPU upload plans (Remade With Rust)
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
// The MIT License (MIT)
//
// Copyright (c) 2018 Michael Dilger
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

//! The main entry point for this library is the [`Dds`] type.
//!
//! # Features
//!
//! | Feature | Default | Provides |
//! |---------|---------|----------|
//! | `decode` | yes | [`Dds::decode_rgba8`], `bcdec_rs` BCn kernels |
//! | `encode` | yes | [`Dds::encode_from_rgba8`], [`EncodeLayout`] |
//!
//! Container parse/compose, surfaces, content classification, and GPU upload
//! plans are always available. Use `default-features = false, features = ["decode"]`
//! for loaders / WASM that never encode.

#![cfg_attr(docsrs, feature(doc_cfg))]
// The memory-safety claim is compiler-enforced, not asserted: without the
// `simd` feature the crate cannot contain a single `unsafe` block. With it,
// `unsafe` is confined to the `#[target_feature]` AVX2 kernels in
// `encode::blocks::simd`, each proven bit-exact against its scalar twin and
// reachable only behind a runtime CPU check.
#![cfg_attr(not(feature = "simd"), forbid(unsafe_code))]

#[macro_use]
extern crate bitflags;

mod error;
pub use error::*;

mod format;
pub use format::{D3DFormat, DataFormat, DxgiFormat, FourCC, PixelFormat, PixelFormatFlags};

mod header;
pub use header::{Caps, Caps2, Header, HeaderFlags};

mod header10;
pub use header10::{AlphaMode, D3D10ResourceDimension, Header10, MiscFlag};

mod surface;
pub use surface::{CubemapFace, SubresourceId, SurfaceView, SurfaceViewMut};

mod content;
pub use content::{DecodeContent, HdrDecodeContent, ImageRgba8, ImageRgbaF32};

#[cfg(feature = "decode")]
mod decode;
#[cfg(feature = "decode")]
pub use decode::reference;

#[cfg(feature = "encode")]
mod encode;
#[cfg(feature = "encode")]
pub use encode::{max_abs_diff, psnr_rgba8, EncodeLayout, EncodeQuality, Rdo};

mod upload;
pub use upload::{GpuFormat, UploadPath, UploadPlan};

use byteorder::{LittleEndian, ReadBytesExt, WriteBytesExt};
use std::fmt;
use std::io::{Read, Write};

/// This is the main DirectDraw Surface file structure, generic over how the
/// payload is stored.
///
/// Use the aliases, not this type directly: [`Dds`] owns its payload and
/// [`DdsView`] borrows one. Every query, surface, decode and upload-plan method
/// is implemented once, here, for both.
#[derive(Clone)]
pub struct DdsBase<D = Vec<u8>> {
    // magic is implicit
    pub header: Header,
    pub header10: Option<Header10>,
    pub data: D,
}

/// A DDS that owns its payload. This is what [`Dds::read`] produces, and it is
/// what `Dds` has always meant.
pub type Dds = DdsBase<Vec<u8>>;

/// A DDS that **borrows** its payload — no copy, no allocation.
///
/// A streaming engine already holds the file bytes: from `fs::read`, a memory
/// map, or an archive decompressor. [`Dds::read`] would copy them a second time,
/// and the copy is dominated by the operating system faulting in and zeroing
/// pages that are about to be overwritten — measured at ~87% of the call.
/// [`DdsView::parse`] reads the header and points at the bytes you already have.
///
/// ```
/// use rusty_dds::{DdsView, SubresourceId};
///
/// # let mut bytes = Vec::new();
/// # rusty_dds::Dds::new_dxgi(rusty_dds::NewDxgiParams {
/// #     height: 64, width: 64, depth: None,
/// #     format: rusty_dds::DxgiFormat::BC1_UNorm,
/// #     mipmap_levels: None, array_layers: None, caps2: None, is_cubemap: false,
/// #     resource_dimension: rusty_dds::D3D10ResourceDimension::Texture2D,
/// #     alpha_mode: rusty_dds::AlphaMode::Straight,
/// # })?.write(&mut bytes)?;
/// let dds = DdsView::parse(&bytes)?;
/// let plan = dds.upload_plan_compressed(SubresourceId::mip_layer(0, 0))?;
/// assert_eq!(plan.width, 64);
/// # Ok::<(), rusty_dds::Error>(())
/// ```
pub type DdsView<'a> = DdsBase<&'a [u8]>;

/// Parameters for Dds::new_d3d()
#[derive(Debug, Clone)]
pub struct NewD3dParams {
    pub height: u32,
    pub width: u32,
    pub depth: Option<u32>,
    pub format: D3DFormat,
    pub mipmap_levels: Option<u32>,
    pub caps2: Option<Caps2>,
}

/// Parameters for Dds::new_dxgi()
#[derive(Debug, Clone)]
pub struct NewDxgiParams {
    pub height: u32,
    pub width: u32,
    pub depth: Option<u32>,
    pub format: DxgiFormat,
    pub mipmap_levels: Option<u32>,
    pub array_layers: Option<u32>,
    pub caps2: Option<Caps2>,
    pub is_cubemap: bool,
    pub resource_dimension: D3D10ResourceDimension,
    pub alpha_mode: AlphaMode,
}

impl Dds {
    const MAGIC: u32 = 0x20534444; // b"DDS " in little endian

    /// Create a new DirectDraw Surface with a D3DFormat
    pub fn new_d3d(params: NewD3dParams) -> Result<Dds, Error> {
        let size = match get_texture_size(
            params.format.get_pitch(params.width),
            None,
            params.format.get_pitch_height(),
            params.height,
            params.depth,
        ) {
            Some(s) => s,
            None => return Err(Error::UnsupportedFormat),
        };

        let mml = params.mipmap_levels.unwrap_or(1);
        let min_mipmap_size = match params.format.get_minimum_mipmap_size_in_bytes() {
            Some(mms) => mms,
            None => return Err(Error::UnsupportedFormat),
        };
        let array_stride = get_array_stride(size, min_mipmap_size, mml);

        let data_size = array_stride;

        Ok(Dds {
            header: Header::new_d3d(
                params.height,
                params.width,
                params.depth,
                params.format,
                params.mipmap_levels,
                params.caps2,
            )?,
            header10: None,
            data: vec![0; data_size as usize],
        })
    }

    /// Create a new DirectDraw Surface with a DxgiFormat
    pub fn new_dxgi(params: NewDxgiParams) -> Result<Dds, Error> {
        let arraysize = params.array_layers.unwrap_or(1);

        let size = match get_texture_size(
            params.format.get_pitch(params.width),
            None,
            params.format.get_pitch_height(),
            params.height,
            params.depth,
        ) {
            Some(s) => s,
            None => return Err(Error::UnsupportedFormat),
        };

        let mml = params.mipmap_levels.unwrap_or(1);
        let min_mipmap_size = match params.format.get_minimum_mipmap_size_in_bytes() {
            Some(mms) => mms,
            None => return Err(Error::UnsupportedFormat),
        };
        let array_stride = get_array_stride(size, min_mipmap_size, mml);

        let data_size = arraysize
            .checked_mul(array_stride)
            .ok_or(Error::OutOfBounds)?;

        let arraysize = if params.is_cubemap {
            arraysize / 6
        } else {
            arraysize
        };
        let header10 = Header10::new(
            params.format,
            params.is_cubemap,
            params.resource_dimension,
            arraysize,
            params.alpha_mode,
        );

        Ok(Dds {
            header: Header::new_dxgi(
                params.height,
                params.width,
                params.depth,
                params.format,
                params.mipmap_levels,
                params.array_layers,
                params.caps2,
            )?,
            header10: Some(header10),
            data: vec![0; data_size as usize],
        })
    }

    /// Read a DDS file, accepting a payload of any length.
    ///
    /// The payload is read to end-of-stream with no cap, so the peak allocation
    /// is whatever the reader yields. That is the right behaviour for a trusted
    /// file on disk and the wrong one for bytes arriving from a network, a
    /// user upload, or a mod archive — for those, use [`Dds::read_limited`],
    /// which fails closed at a byte budget you choose.
    pub fn read<R: Read>(r: R) -> Result<Dds, Error> {
        Self::read_inner(r, None)
    }

    /// Read a DDS file, refusing a payload larger than `max_data_len` bytes.
    ///
    /// The limit covers the **payload only** — the 128-byte header (148 with a
    /// DX10 header) is read first and is not counted. Exceeding it returns
    /// [`Error::SizeLimitExceeded`] without buffering the overrun, so a hostile
    /// or corrupt stream cannot force an unbounded allocation.
    ///
    /// ```
    /// use rusty_dds::{Dds, Error};
    ///
    /// let mut bytes = Vec::new();
    /// Dds::new_dxgi(rusty_dds::NewDxgiParams {
    ///     height: 64, width: 64, depth: None,
    ///     format: rusty_dds::DxgiFormat::BC1_UNorm,
    ///     mipmap_levels: None, array_layers: None, caps2: None, is_cubemap: false,
    ///     resource_dimension: rusty_dds::D3D10ResourceDimension::Texture2D,
    ///     alpha_mode: rusty_dds::AlphaMode::Straight,
    /// })?.write(&mut bytes)?;
    ///
    /// assert!(Dds::read_limited(&bytes[..], 8 * 1024).is_ok());
    /// assert!(matches!(
    ///     Dds::read_limited(&bytes[..], 16),
    ///     Err(Error::SizeLimitExceeded { .. })
    /// ));
    /// # Ok::<(), Error>(())
    /// ```
    pub fn read_limited<R: Read>(r: R, max_data_len: usize) -> Result<Dds, Error> {
        Self::read_inner(r, Some(max_data_len))
    }

    fn read_inner<R: Read>(mut r: R, max_data_len: Option<usize>) -> Result<Dds, Error> {
        let (header, header10) = read_headers(&mut r)?;
        let mut data: Vec<u8> = Vec::new();
        read_payload(r, &mut data, max_data_len)?;
        Ok(Dds {
            header,
            header10,
            data,
        })
    }

}

impl<'a> DdsView<'a> {
    /// Parse a DDS **without copying the payload**.
    ///
    /// The returned view borrows `bytes` for its lifetime. Everything a
    /// streaming engine needs — [`DdsBase::surface`],
    /// [`DdsBase::subresource_range`], [`DdsBase::upload_plan_compressed`],
    /// decode — works on it exactly as it does on an owned [`Dds`].
    pub fn parse(bytes: &'a [u8]) -> Result<DdsView<'a>, Error> {
        let mut cursor = bytes;
        let magic = cursor.read_u32::<LittleEndian>()?;
        if magic != Dds::MAGIC {
            return Err(Error::BadMagicNumber);
        }
        let header = Header::read(&mut cursor)?;
        let header10 = if header.spf.fourcc == Some(FourCC(<FourCC>::DX10)) {
            Some(Header10::read(&mut cursor)?)
        } else {
            None
        };
        // `cursor` has been advanced past the headers by the reads above, so
        // what remains is exactly the payload — borrowed, never copied.
        Ok(DdsBase {
            header,
            header10,
            data: cursor,
        })
    }

    /// Read a DDS from any reader **into a buffer you own and recycle**.
    ///
    /// [`DdsView::parse`] is the right call when you already hold the bytes.
    /// This is for the case where you do not — an archive decompressor, a
    /// network stream — and would otherwise be forced back onto [`Dds::read`],
    /// which allocates a fresh payload buffer every time. A fresh buffer is
    /// faulted in and zeroed by the operating system before it is overwritten,
    /// which measured at ~87% of that call; reusing one buffer keeps the pages
    /// resident and the cost is the copy alone.
    ///
    /// `buf` is cleared, so its capacity survives and the second call onwards
    /// touches no new pages. Reuse one buffer per streaming worker.
    ///
    /// ```
    /// use rusty_dds::{DdsView, SubresourceId};
    ///
    /// # let mut bytes = Vec::new();
    /// # rusty_dds::Dds::new_dxgi(rusty_dds::NewDxgiParams {
    /// #     height: 64, width: 64, depth: None,
    /// #     format: rusty_dds::DxgiFormat::BC1_UNorm,
    /// #     mipmap_levels: None, array_layers: None, caps2: None, is_cubemap: false,
    /// #     resource_dimension: rusty_dds::D3D10ResourceDimension::Texture2D,
    /// #     alpha_mode: rusty_dds::AlphaMode::Straight,
    /// # })?.write(&mut bytes)?;
    /// let mut buf = Vec::new();          // hoisted out of the loop
    /// for _ in 0..2 {
    ///     let dds = DdsView::read_into(&bytes[..], &mut buf)?;
    ///     assert_eq!(dds.get_width(), 64);
    /// }
    /// # Ok::<(), rusty_dds::Error>(())
    /// ```
    pub fn read_into<R: Read>(r: R, buf: &'a mut Vec<u8>) -> Result<DdsView<'a>, Error> {
        Self::read_into_inner(r, buf, None)
    }

    /// [`DdsView::read_into`], refusing a payload larger than `max_data_len`.
    ///
    /// Same posture as [`Dds::read_limited`]: the limit covers the payload only,
    /// and an overrun fails closed without buffering the rest. Use this for
    /// bytes you did not produce — a mod archive, a download.
    pub fn read_into_limited<R: Read>(
        r: R,
        buf: &'a mut Vec<u8>,
        max_data_len: usize,
    ) -> Result<DdsView<'a>, Error> {
        Self::read_into_inner(r, buf, Some(max_data_len))
    }

    fn read_into_inner<R: Read>(
        mut r: R,
        buf: &'a mut Vec<u8>,
        max_data_len: Option<usize>,
    ) -> Result<DdsView<'a>, Error> {
        let (header, header10) = read_headers(&mut r)?;
        read_payload(r, buf, max_data_len)?;
        Ok(DdsBase {
            header,
            header10,
            data: &buf[..],
        })
    }
}

impl<D: AsRef<[u8]>> DdsBase<D> {
    /// Write to a DDS file
    pub fn write<W: Write>(&self, w: &mut W) -> Result<(), Error> {
        w.write_u32::<LittleEndian>(Dds::MAGIC)?;
        self.header.write(w)?;
        if let Some(ref header10) = self.header10 {
            header10.write(w)?;
        }
        w.write_all(self.data.as_ref())?;
        Ok(())
    }

    /// Attempt to get the format of this DDS, presuming it is a D3DFormat.
    pub fn get_d3d_format(&self) -> Option<D3DFormat> {
        // FIXME: some d3d formats are equivalent to some dxgi formats.
        //    but we dont have a try_from() between them yet.
        //    Right now we will yield None if the format is dxgi, but
        //    later on we should try to convert.

        D3DFormat::try_from_pixel_format(&self.header.spf)
    }

    /// Attempt to get the format of this DDS, presuming it is a DxgiFormat.
    pub fn get_dxgi_format(&self) -> Option<DxgiFormat> {
        // FIXME: some d3d formats are equivalent to some dxgi formats.
        //    but we dont have a try_from() between them yet.
        //    Right now we will yield None if the format is d3d, but
        //    later on we should try to convert.
        if let Some(ref h10) = self.header10 {
            Some(h10.dxgi_format)
        } else {
            DxgiFormat::try_from_pixel_format(&self.header.spf)
        }
    }

    /// The format by value, without the `Box` that [`Dds::get_format`] costs.
    ///
    /// Every internal caller uses this. `get_format` allocates, and it is called
    /// underneath every subresource offset computation.
    pub(crate) fn format_of(&self) -> Option<crate::format::FormatOf> {
        use crate::format::FormatOf;
        if let Some(dxgi) = self.get_dxgi_format() {
            return Some(FormatOf::Dxgi(dxgi));
        }
        if let Some(d3d) = self.get_d3d_format() {
            return Some(FormatOf::D3d(d3d));
        }
        None
    }

    /// Get the format of the DDS as a trait (type-erasure)
    pub fn get_format(&self) -> Option<Box<dyn DataFormat>> {
        if let Some(dxgi) = self.get_dxgi_format() {
            Some(Box::new(dxgi))
        } else if let Some(d3d) = self.get_d3d_format() {
            Some(Box::new(d3d))
        } else {
            None
        }
    }

    pub fn get_width(&self) -> u32 {
        self.header.width
    }

    pub fn get_height(&self) -> u32 {
        self.header.height
    }

    pub fn get_depth(&self) -> u32 {
        self.header.depth.unwrap_or(1)
    }

    pub fn get_bits_per_pixel(&self) -> Option<u32> {
        // Try format first
        if let Some(format) = self.format_of() {
            if let Some(bpp) = format.get_bits_per_pixel() {
                return Some(bpp as u32);
            }
        }
        // Fall back to pixel_format rgb_bit_count field
        if let Some(bpp) = self.header.spf.rgb_bit_count {
            return Some(bpp);
        }
        None
    }

    pub fn get_pitch(&self) -> Option<u32> {
        // Try format first
        if let Some(format) = self.format_of() {
            if let Some(pitch) = format.get_pitch(self.header.width) {
                return Some(pitch);
            }
        }
        // Then try header.pitch
        if let Some(pitch) = self.header.pitch {
            return Some(pitch);
        }

        // Then try to calculate it ourselves
        if let Some(bpp) = self.get_bits_per_pixel() {
            // Both operands come from the file; a header that overflows here is
            // not describing a pitch we can honour.
            return bpp
                .checked_mul(self.get_width())
                .and_then(|n| n.checked_add(7))
                .map(|n| n / 8);
        }
        None
    }

    pub fn get_pitch_height(&self) -> u32 {
        if let Some(format) = self.format_of() {
            format.get_pitch_height()
        } else {
            1
        }
    }

    pub fn get_main_texture_size(&self) -> Option<u32> {
        get_texture_size(
            self.get_pitch(),
            self.header.linear_size,
            self.get_pitch_height(),
            self.header.height,
            self.header.depth,
        )
    }

    pub fn get_array_stride(&self) -> Result<u32, Error> {
        let size = match self.get_main_texture_size() {
            Some(s) => s,
            None => return Err(Error::UnsupportedFormat),
        };
        let mml = self.get_num_mipmap_levels();
        let min_mipmap_size = self.get_min_mipmap_size_in_bytes();
        Ok(get_array_stride(size, min_mipmap_size, mml))
    }

    pub fn get_num_array_layers(&self) -> u32 {
        if let Some(ref h10) = self.header10 {
            h10.array_size
        } else if self.header.caps2.contains(Caps2::CUBEMAP) {
            6
        } else {
            1 // just the 1 layer
        }
    }

    pub fn get_num_mipmap_levels(&self) -> u32 {
        if let Some(mmc) = self.header.mip_map_count {
            mmc
        } else {
            1 // just the main image
        }
    }

    pub fn get_min_mipmap_size_in_bytes(&self) -> u32 {
        if let Some(format) = self.format_of() {
            if let Some(min) = format.get_minimum_mipmap_size_in_bytes() {
                return min;
            }
        }
        if let Some(bpp) = self.get_bits_per_pixel() {
            // `bpp` can be the raw `rgb_bit_count` header field, so it is not
            // bounded by any real format; saturate rather than overflow.
            bpp.saturating_add(7) / 8
        } else {
            1
        }
    }

    /// This gets a reference to the data at the given `array_layer` (which should be
    /// 0 for textures with just one image).
    pub fn get_data(&self, array_layer: u32) -> Result<&[u8], Error> {
        let (offset, size) = self.get_offset_and_size(array_layer)?;
        let offset = offset as usize;
        let size = size as usize;
        let end = offset.checked_add(size).ok_or(Error::OutOfBounds)?;
        self.data.as_ref().get(offset..end).ok_or(Error::OutOfBounds)
    }

    fn get_offset_and_size(&self, array_layer: u32) -> Result<(u32, u32), Error> {
        // Verify request bounds
        if array_layer >= self.get_num_array_layers() {
            return Err(Error::OutOfBounds);
        }
        let array_stride = self.get_array_stride()?;
        let offset = array_layer
            .checked_mul(array_stride)
            .ok_or(Error::OutOfBounds)?;

        Ok((offset, array_stride))
    }
}

impl<D: AsRef<[u8]> + AsMut<[u8]>> DdsBase<D> {
    /// This gets a mutable reference to the data at the given `array_layer`
    /// (which should be 0 for textures with just one image).
    ///
    /// Only available when the payload is owned or mutably borrowed — a
    /// [`DdsView`] over `&[u8]` cannot offer it.
    pub fn get_mut_data(&mut self, array_layer: u32) -> Result<&mut [u8], Error> {
        let (offset, size) = self.get_offset_and_size(array_layer)?;
        let offset = offset as usize;
        let size = size as usize;
        let end = offset.checked_add(size).ok_or(Error::OutOfBounds)?;
        self.data
            .as_mut()
            .get_mut(offset..end)
            .ok_or(Error::OutOfBounds)
    }
}

/// Magic, `DDS_HEADER`, and the DX10 extension when the pixel format asks for it.
fn read_headers<R: Read>(r: &mut R) -> Result<(Header, Option<Header10>), Error> {
    let magic = r.read_u32::<LittleEndian>()?;
    if magic != Dds::MAGIC {
        return Err(Error::BadMagicNumber);
    }
    // Reborrow: `Header::read` takes the reader by value, and `&mut R` is not
    // `Copy`, so the second read needs a fresh borrow rather than the moved one.
    let header = Header::read(&mut *r)?;
    let header10 = if header.spf.fourcc == Some(FourCC(<FourCC>::DX10)) {
        Some(Header10::read(&mut *r)?)
    } else {
        None
    };
    Ok((header, header10))
}

/// Fill `data` with the payload, honouring an optional byte budget.
///
/// `data` is cleared, not reallocated: a caller that reuses one buffer across
/// many textures keeps its pages resident, which is the entire point of
/// [`DdsView::read_into`].
fn read_payload<R: Read>(r: R, data: &mut Vec<u8>, max_data_len: Option<usize>) -> Result<(), Error> {
    data.clear();
    match max_data_len {
        None => {
            let mut r = r;
            r.read_to_end(data)?;
        }
        Some(limit) => {
            // Read one byte past the budget: if the reader still had bytes to
            // give, the payload is over the limit and we stop there rather than
            // buffering the rest.
            let mut capped = r.take(limit as u64 + 1);
            capped.read_to_end(data)?;
            if data.len() > limit {
                return Err(Error::SizeLimitExceeded {
                    limit,
                    // Only ever `limit + 1` here — the true length is unknown by
                    // construction, and that is the point.
                    at_least: data.len(),
                });
            }
        }
    }
    Ok(())
}

/// Bytes for one mip-0 surface, or `None` when the header's own fields cannot
/// describe one.
///
/// Every input here is an attacker-controlled `u32` straight out of the file,
/// so the arithmetic is checked throughout: an overflow means the header is
/// describing a texture that cannot exist, and the honest answer is `None`
/// (which callers turn into [`Error::UnsupportedFormat`]), not a wrapped size
/// that would then be used to slice the payload.
fn get_texture_size(
    pitch: Option<u32>,
    linear_size: Option<u32>,
    pitch_height: u32,
    height: u32,
    depth: Option<u32>,
) -> Option<u32> {
    let depth = depth.unwrap_or(1);

    if let Some(ls) = linear_size {
        return Some(ls);
    }
    let pitch = pitch?;
    // A zero pitch height would divide by zero; a format that reports one is
    // not describing a layout we can compute.
    if pitch_height == 0 {
        return None;
    }
    let row_height = height.checked_add(pitch_height - 1)? / pitch_height;
    pitch.checked_mul(row_height)?.checked_mul(depth)
}

/// Total bytes of one mip chain.
///
/// `mipmap_levels` comes from the file, so it can be up to `u32::MAX`. Once the
/// mip size has bottomed out at `min_mipmap_size` every remaining level
/// contributes exactly that much, so the tail is computed in closed form rather
/// than iterated — otherwise a header claiming `mip_map_count = 0xFFFF_FFFF`
/// would spin for billions of iterations on every metadata query. Accumulation
/// saturates for the same reason `get_texture_size` is checked: a wrapped
/// stride would be used to index the payload.
fn get_array_stride(texture_size: u32, min_mipmap_size: u32, mipmap_levels: u32) -> u32 {
    let mut stride: u32 = 0;
    let mut current_mipsize: u32 = texture_size;
    let mut level: u32 = 0;
    while level < mipmap_levels {
        stride = stride.saturating_add(current_mipsize);
        level += 1;
        current_mipsize /= 4;
        if current_mipsize <= min_mipmap_size {
            let remaining = mipmap_levels - level;
            return stride.saturating_add(remaining.saturating_mul(min_mipmap_size));
        }
    }
    stride
}

impl<D: AsRef<[u8]>> fmt::Debug for DdsBase<D> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        writeln!(f, "Dds:")?;
        if let Some(d3dformat) = self.get_d3d_format() {
            writeln!(f, "  Format: {:?}", d3dformat)?;
        } else if let Some(dxgiformat) = self.get_dxgi_format() {
            writeln!(f, "  Format: {:?}", dxgiformat)?;
        } else if let Some(ref fourcc) = self.header.spf.fourcc {
            writeln!(f, "  Format: FOURCC={:?} (Unknown)", fourcc)?;
        } else {
            writeln!(f, "  Format UNSPECIFIED")?;
        }
        write!(f, "{:?}", self.header)?;
        if let Some(ref h10) = self.header10 {
            write!(f, "{:?}", h10)?;
        }
        writeln!(f, "  (data elided)")?;
        Ok(())
    }
}