mrc 0.5.0

MRC-2014 file format reader/writer for cryo-EM — SIMD-accelerated, mmap-enabled
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
//! Consolidated MRC file reader with automatic backend selection.
//!
//! Provides [`Reader`], which auto-selects between memory-mapped (zero-copy)
//! and buffered I/O based on the file and platform capabilities. Use
//! [`Reader::open`] for files or [`Reader::from_reader`] for custom sources.
//!
//! Also provides compression detection helpers used by the reader constructors.

use crate::VoxelBlock;
use crate::engine::block::VolumeShape;
use crate::engine::endian::FileEndian;
use crate::mode::Voxel;
use crate::{Error, Header, Mode};

use std::borrow::Cow;
use std::path::Path;
use std::vec::Vec;

// ============================================================================
// Compression detection (used internally by Reader::open)
// ============================================================================

/// Detected compression format of an MRC file.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum CompressionType {
    /// Uncompressed MRC file.
    Plain,
    /// Gzip-compressed MRC file.
    #[cfg(feature = "gzip")]
    Gzip,
    /// Bzip2-compressed MRC file.
    #[cfg(feature = "bzip2")]
    Bzip2,
}

/// Peek at a byte slice to determine its compression format.
#[doc(hidden)]
pub fn detect_compression_from_bytes(bytes: &[u8]) -> CompressionType {
    if bytes.len() < 2 {
        return CompressionType::Plain;
    }
    let magic = [bytes[0], bytes[1]];
    #[cfg(feature = "gzip")]
    if magic == [0x1f, 0x8b] {
        return CompressionType::Gzip;
    }
    #[cfg(feature = "bzip2")]
    if magic == [b'B', b'Z'] {
        return CompressionType::Bzip2;
    }
    CompressionType::Plain
}

/// Peek at the first bytes of a file to determine its compression format.
pub fn detect_compression<P: AsRef<Path>>(path: P) -> Result<CompressionType, Error> {
    use std::fs::File;
    use std::io::Read;
    let mut file = File::open(path)?;
    let mut buf = [0u8; 2];
    let n = file.read(&mut buf)?;
    Ok(detect_compression_from_bytes(&buf[..n]))
}

// ============================================================================
// ============================================================================
// Data source and Reader type
// ============================================================================

/// How the reader accesses voxel data.
#[derive(Debug)]
enum DataSource {
    /// Loaded entirely into memory.
    Buffered {
        data: Vec<u8>,
        truncated: bool,
    },
    /// Memory-mapped file (zero-copy).
    #[cfg(feature = "mmap")]
    Mmap {
        map: memmap2::Mmap,
        data_offset: usize,
        truncated: bool,
    },
}

/// MRC file reader with automatic backend selection.
///
/// Opens files via memory mapping (zero-copy for large files) or buffered
/// I/O (in-memory for smaller files). Accepts custom [`std::io::Read`] sources
/// via [`from_reader`](Self::from_reader).
///
/// All iteration methods (`slices`, `slabs`, `tiles`, `subregion`, etc.)
/// are **inherent methods** — no trait imports needed.
///
/// # Zero-copy access
///
/// When backed by a memory map (which [`open`](Self::open) selects
/// automatically for files), [`slab_as`](Self::slab_as) returns `&[T]`
/// directly into the mapped memory with no allocation. Requires native
/// endianness and matching voxel type.
///
/// # Example
/// ```no_run
/// use mrc::Reader;
///
/// let reader = Reader::open("density.mrc")?;
/// for slice in reader.slices::<f32>() {
///     let block = slice?;
/// }
/// # Ok::<_, mrc::Error>(())
/// ```
#[derive(Debug)]
pub struct Reader {
    pub(crate) header: Header,
    pub(crate) ext_header: Vec<u8>,
    pub(crate) endian: FileEndian,
    pub(crate) mode: Mode,
    pub(crate) shape: VolumeShape,
    source: DataSource,
}

// ============================================================================
// Constructors
// ============================================================================

impl Reader {
    /// Open an MRC file, auto-detecting gzip/bzip2 compression.
    ///
    /// For plain files, selects memory-mapped I/O when available (the `mmap`
    /// feature) and falls back to buffered I/O otherwise.
    pub fn open<P: AsRef<std::path::Path>>(path: P) -> Result<Self, Error> {
        Self::_open_detect(path.as_ref(), false).map(|(r, _)| r)
    }

    /// Open in **permissive** mode.
    ///
    /// Non-fatal header issues are collected as warnings instead of errors.
    pub fn open_permissive<P: AsRef<std::path::Path>>(
        path: P,
    ) -> Result<(Self, Vec<String>), Error> {
        Self::_open_detect(path.as_ref(), true)
    }

    /// Open a plain (uncompressed) MRC file via buffered I/O.
    pub fn open_plain<P: AsRef<std::path::Path>>(path: P) -> Result<Self, Error> {
        Self::_open_plain(path, false).map(|(r, _)| r)
    }

    /// Read an MRC file from any [`std::io::Read`] source.
    ///
    /// The entire source is read into memory, then parsed.
    pub fn from_reader<R: std::io::Read>(mut reader: R) -> Result<Self, Error> {
        let mut buf = Vec::new();
        reader.read_to_end(&mut buf)?;
        Self::_read_from_buf(buf, false).map(|(r, _)| r)
    }

    /// Read from any [`std::io::Read`] source in permissive mode.
    pub fn from_reader_permissive<R: std::io::Read>(
        mut reader: R,
    ) -> Result<(Self, Vec<String>), Error> {
        let mut buf = Vec::new();
        reader.read_to_end(&mut buf)?;
        Self::_read_from_buf(buf, true)
    }

    /// Parse an MRC file from an in-memory byte buffer.
    pub fn from_bytes(data: Vec<u8>) -> Result<Self, Error> {
        Self::_read_from_buf(data, false).map(|(r, _)| r)
    }

    /// Parse an MRC file from an in-memory byte buffer in permissive mode.
    pub fn from_bytes_permissive(data: Vec<u8>) -> Result<(Self, Vec<String>), Error> {
        Self::_read_from_buf(data, true)
    }

    // ── Internal open helpers ──────────────────────────────────────────

    /// Detect compression and open. Tries mmap first for plain files.
    fn _open_detect(
        path: &std::path::Path,
        permissive: bool,
    ) -> Result<(Self, Vec<String>), Error> {
        use std::io::{Read, Seek};

        let mut file = std::fs::File::open(path)?;
        let mut magic = [0u8; 2];
        let n = file.read(&mut magic)?;

        if n >= 2 {
            match magic {
                #[cfg(feature = "gzip")]
                [0x1f, 0x8b] => {
                    // Seek back to start before handing to the gzip decoder.
                    // An error here is benign — the decoder will fail on its own.
                    let _ = file.seek(std::io::SeekFrom::Start(0));
                    return Self::_open_gzip_file(
                        file,
                        permissive,
                        crate::io::reader_common::DEFAULT_MAX_DECOMPRESSED_BYTES,
                    );
                }
                #[cfg(feature = "bzip2")]
                [b'B', b'Z'] => {
                    // Seek back to start before handing to the bzip2 decoder.
                    // An error here is benign — the decoder will fail on its own.
                    let _ = file.seek(std::io::SeekFrom::Start(0));
                    return Self::_open_bzip2_file(
                        file,
                        permissive,
                        crate::io::reader_common::DEFAULT_MAX_DECOMPRESSED_BYTES,
                    );
                }
                _ => {}
            }
        }

        // Plain file — try mmap first; fall back to buffered on any error.
        #[cfg(feature = "mmap")]
        {
            drop(file);
            if let Ok(result) = Self::_open_mmap_path(path, permissive) {
                return Ok(result);
            }
            // mmap failed — re-open for buffered fallback.
            let file = std::fs::File::open(path)?;
            Self::_open_plain_file(file, permissive)
        }

        #[cfg(not(feature = "mmap"))]
        {
            // Seek back to start (file is at offset 2 after reading magic bytes).
            // An error here is benign — the plain-file reader will fail with
            // its own I/O error if the file is genuinely unreadable.
            let _ = file.seek(std::io::SeekFrom::Start(0));
            Self::_open_plain_file(file, permissive)
        }
    }

    fn _open_plain<P: AsRef<std::path::Path>>(
        path: P,
        permissive: bool,
    ) -> Result<(Self, Vec<String>), Error> {
        Self::_open_plain_file(std::fs::File::open(path)?, permissive)
    }

    fn _open_plain_file(
        mut file: std::fs::File,
        permissive: bool,
    ) -> Result<(Self, Vec<String>), Error> {
        use std::io::Read;

        let mut header_bytes = [0u8; 1024];
        file.read_exact(&mut header_bytes)?;

        let (header, warnings, _endian, data_size) =
            crate::io::reader_common::parse_header(&header_bytes, permissive)?;

        let ext_size = header.nsymbt as usize;
        let mut ext_header = vec![0u8; ext_size];
        if ext_size > 0 {
            file.read_exact(&mut ext_header)?;
        }

        let mut data = vec![0u8; data_size];
        file.read_exact(&mut data)?;

        if !permissive {
            let file_len = file.metadata()?.len() as usize;
            let expected_len = header.data_offset() + data_size;
            if file_len != expected_len {
                return Err(Error::FileSizeMismatch {
                    expected: expected_len,
                    actual: file_len,
                });
            }
        }

        Self::_build(
            header,
            ext_header,
            DataSource::Buffered {
                data,
                truncated: false,
            },
            warnings,
        )
    }

    fn _read_from_buf(data: Vec<u8>, permissive: bool) -> Result<(Self, Vec<String>), Error> {
        if data.len() < 1024 {
            return Err(Error::InvalidHeader);
        }
        let mut header_bytes = [0u8; 1024];
        header_bytes.copy_from_slice(&data[..1024]);
        let (header, mut warnings, _endian, data_size) =
            crate::io::reader_common::parse_header(&header_bytes, permissive)?;

        let ext_size = header.nsymbt as usize;
        let ext_end = (1024 + ext_size).min(data.len());
        let ext_header = if ext_size > 0 && ext_end > 1024 {
            if ext_end < 1024 + ext_size {
                warnings.push(format!(
                    "Extended header truncated: expected {} bytes, got {}",
                    ext_size,
                    ext_end - 1024
                ));
            }
            data[1024..ext_end].to_vec()
        } else {
            Vec::new()
        };

        let data_offset = header.data_offset();
        let voxel_data = if data_offset < data.len() {
            let available = data.len() - data_offset;
            let expected = data_size.min(available);
            data[data_offset..data_offset + expected].to_vec()
        } else {
            Vec::new()
        };

        if !permissive && voxel_data.len() != data_size {
            return Err(Error::FileSizeMismatch {
                expected: header.data_offset() + data_size,
                actual: data.len(),
            });
        }

        let truncated = voxel_data.len() != data_size;
        Self::_build(
            header,
            ext_header,
            DataSource::Buffered {
                data: voxel_data,
                truncated,
            },
            warnings,
        )
    }

    #[cfg(feature = "mmap")]
    fn _open_mmap_path(
        path: &std::path::Path,
        permissive: bool,
    ) -> Result<(Self, Vec<String>), Error> {
        use std::fs::File;

        let file = File::open(path)?;
        let mmap = unsafe {
            memmap2::MmapOptions::new()
                .map(&file)
                .map_err(|_| Error::Mmap)?
        };
        // File is closed here; mmap keeps the mapping alive.

        // Read header from mmap (file is already mapped)
        if mmap.len() < 1024 {
            return Err(Error::InvalidHeader);
        }
        let mut header_bytes = [0u8; 1024];
        header_bytes.copy_from_slice(&mmap[..1024]);

        let (header, warnings, _endian, data_size) =
            crate::io::reader_common::parse_header(&header_bytes, permissive)?;

        let expected_size = header
            .data_offset()
            .checked_add(data_size)
            .ok_or(Error::InvalidHeader)?;
        let truncated = if !permissive {
            if mmap.len() != expected_size {
                return Err(Error::FileSizeMismatch {
                    expected: expected_size,
                    actual: mmap.len(),
                });
            }
            false
        } else if mmap.len() < header.data_offset() {
            return Err(Error::FileSizeMismatch {
                expected: header.data_offset(),
                actual: mmap.len(),
            });
        } else {
            mmap.len() < expected_size
        };

        // IMOD detection is done in _build; warnings passed through
        Self::_build(
            header,
            Vec::new(), // ext_header read from mmap on demand
            DataSource::Mmap {
                map: mmap,
                data_offset: header.data_offset(),
                truncated,
            },
            warnings,
        )
    }

    /// Common path: build a Reader from parsed header + data source.
    fn _build(
        header: Header,
        ext_header: Vec<u8>,
        source: DataSource,
        warnings: Vec<String>,
    ) -> Result<(Self, Vec<String>), Error> {
        let shape = VolumeShape::new(header.nx as usize, header.ny as usize, header.nz as usize);
        let mode = Mode::from_i32(header.mode).ok_or(Error::UnsupportedMode)?;
        let endian = header.detect_endian();

        let mut warnings = warnings;
        if mode == Mode::Int8 {
            if let Some(imod) = header.detect_imod() {
                if !imod.bytes_are_signed {
                    warnings.push(
                        "IMOD file with unsigned Mode 0 detected: use slices_mode0() \
                         or convert::<f32>() for correct values"
                            .into(),
                    );
                }
            }
        }

        Ok((
            Self {
                header,
                ext_header,
                endian,
                mode,
                shape,
                source,
            },
            warnings,
        ))
    }

    /// Construct a Reader from a decompressed MRC (used by gzip/bzip2 readers).
    pub(crate) fn _from_decompressed(
        d: crate::io::reader_common::DecompressedMrc,
    ) -> Result<(Self, Vec<String>), Error> {
        Self::_build(
            d.header,
            d.ext_header,
            DataSource::Buffered {
                data: d.data,
                truncated: false,
            },
            d.warnings,
        )
    }
}

// ============================================================================
// Public accessors
// ============================================================================

impl Reader {
    /// Volume dimensions.
    pub fn shape(&self) -> VolumeShape {
        self.shape
    }

    /// Voxel data mode.
    pub fn mode(&self) -> Mode {
        self.mode
    }

    /// A reference to the parsed header.
    pub fn header(&self) -> &Header {
        &self.header
    }

    /// Detected file endianness.
    pub fn endian(&self) -> FileEndian {
        self.endian
    }

    /// Raw voxel data bytes.
    ///
    /// For memory-mapped readers this returns a zero-copy `&[u8]` view.
    /// For buffered readers this borrows from the internal `Vec<u8>`.
    pub fn data_bytes(&self) -> &[u8] {
        match &self.source {
            DataSource::Buffered { data, .. } => data,
            #[cfg(feature = "mmap")]
            DataSource::Mmap {
                map, data_offset, ..
            } => {
                let data_size = self.header.data_size().unwrap_or(0);
                let end = data_offset + data_size;
                if end > map.len() {
                    &map[*data_offset..]
                } else {
                    &map[*data_offset..end]
                }
            }
        }
    }

    /// Extended header bytes (empty slice if none).
    pub fn ext_header_bytes(&self) -> &[u8] {
        if !self.ext_header.is_empty() {
            return &self.ext_header;
        }
        // For mmap readers, ext_header is empty because ext bytes are in the map.
        // We parse them from the map on demand.
        let ext_size = self.header.nsymbt.max(0) as usize;
        if ext_size == 0 {
            return &[];
        }
        match &self.source {
            #[cfg(feature = "mmap")]
            DataSource::Mmap { map, .. } => {
                if 1024 + ext_size <= map.len() {
                    &map[1024..1024 + ext_size]
                } else {
                    &[]
                }
            }
            _ => &[],
        }
    }

    /// Returns `true` when the file is shorter than the header's declared data
    /// size (only possible when opened in permissive mode).
    pub fn is_truncated(&self) -> bool {
        match &self.source {
            DataSource::Buffered { truncated, .. } => *truncated,
            #[cfg(feature = "mmap")]
            DataSource::Mmap { truncated, .. } => *truncated,
        }
    }

    /// Cross-check header statistics against actual data (1% tolerance).
    pub fn validate_header_stats(&self) -> Result<(), Error> {
        crate::engine::stats::validate_header_stats(&self.header, self.data_bytes())
    }
}

// ============================================================================
// Read block methods
// ============================================================================

impl Reader {
    /// Read a block of raw voxel bytes.
    pub fn read_block_bytes(
        &self,
        offset: [usize; 3],
        shape: [usize; 3],
    ) -> Result<Vec<u8>, Error> {
        let data = self._source_data();
        let data_len = data.len();
        crate::io::reader_common::validate_block_bounds(
            self.shape,
            self.mode(),
            data_len,
            offset,
            shape,
        )?;
        Ok(crate::io::reader_common::gather_block_bytes(
            data,
            self.shape,
            self.mode(),
            offset,
            shape,
        ))
    }

    /// Zero-copy read of a contiguous Z-slab as `&[T]`.
    ///
    /// Only available for memory-mapped readers with native endianness
    /// and matching voxel type. Returns [`Error::TypeMismatch`] for
    /// buffered readers — use [`subregion`](Self::subregion) instead.
    pub fn slab_as<T: Voxel>(&self, z: usize, k: usize) -> Result<&[T], Error> {
        #[cfg(feature = "mmap")]
        if let DataSource::Mmap {
            map, data_offset, ..
        } = &self.source
        {
            return self._slab_as_mmap::<T>(map, *data_offset, z, k);
        }
        Err(Error::TypeMismatch {
            expected: 0,
            actual: 0,
        })
    }

    #[cfg(feature = "mmap")]
    fn _slab_as_mmap<'a, T: Voxel>(
        &self,
        map: &'a memmap2::Mmap,
        data_offset: usize,
        z: usize,
        k: usize,
    ) -> Result<&'a [T], Error> {
        if T::MODE != self.mode() {
            return Err(Error::ModeMismatch {
                file_mode: self.mode(),
                requested_mode: T::MODE,
                offset: None,
            });
        }
        if !self.endian.is_native() {
            return Err(Error::TypeMismatch {
                expected: T::BYTE_SIZE,
                actual: 0,
            });
        }

        let b = T::BYTE_SIZE;
        let [nx, ny, nz] = [self.shape.nx, self.shape.ny, self.shape.nz];

        if k == 0 || z + k > nz {
            return Err(Error::bounds_err());
        }

        let linear_start = z * nx * ny;
        let byte_start = data_offset + linear_start * b;
        let count = nx * ny * k;
        let byte_end = byte_start + count * b;

        if byte_end > map.len() {
            return Err(Error::bounds_err());
        }

        if byte_start % core::mem::align_of::<T>() != 0 {
            return Err(Error::TypeMismatch {
                expected: core::mem::align_of::<T>(),
                actual: byte_start % core::mem::align_of::<T>(),
            });
        }

        unsafe {
            let ptr = map.as_ptr().add(byte_start) as *const T;
            Ok(core::slice::from_raw_parts(ptr, count))
        }
    }

    pub(crate) fn read_block_bytes_cow<'a>(
        &'a self,
        offset: [usize; 3],
        shape: [usize; 3],
    ) -> Result<Cow<'a, [u8]>, Error> {
        match &self.source {
            DataSource::Buffered { data, .. } => {
                let data_len = data.len();
                crate::io::reader_common::validate_block_bounds(
                    self.shape,
                    self.mode(),
                    data_len,
                    offset,
                    shape,
                )?;
                Ok(Cow::Owned(crate::io::reader_common::gather_block_bytes(
                    data,
                    self.shape,
                    self.mode(),
                    offset,
                    shape,
                )))
            }
            #[cfg(feature = "mmap")]
            DataSource::Mmap {
                map, data_offset, ..
            } => {
                let [nx, ny, ..] = [self.shape.nx, self.shape.ny, self.shape.nz];
                let [ox, oy, oz] = offset;
                let [sx, sy, sz] = shape;
                let data_len = map.len().saturating_sub(*data_offset);
                crate::io::reader_common::validate_block_bounds(
                    self.shape,
                    self.mode(),
                    data_len,
                    offset,
                    shape,
                )?;

                if ox == 0 && sx == nx && oy == 0 && sy == ny {
                    let (start_offset, byte_len) = if self.mode == Mode::Packed4Bit {
                        let row_bytes = nx.div_ceil(2);
                        (data_offset + oz * ny * row_bytes, row_bytes * ny * sz)
                    } else {
                        let linear = oz * nx * ny;
                        let b = self.mode.byte_size();
                        (data_offset + linear * b, sx * sy * sz * b)
                    };
                    return Ok(Cow::Borrowed(&map[start_offset..start_offset + byte_len]));
                }

                Ok(Cow::Owned(crate::io::reader_common::gather_block_bytes(
                    &map[*data_offset..],
                    self.shape,
                    self.mode(),
                    offset,
                    shape,
                )))
            }
        }
    }

    pub(crate) fn decode_block<T: Voxel>(&self, bytes: &[u8]) -> Result<Vec<T>, Error> {
        crate::io::reader_common::decode_block(bytes, self.mode(), self.endian)
    }

    /// Internal: return a `&[u8]` to the full data region regardless of backend.
    fn _source_data(&self) -> &[u8] {
        match &self.source {
            DataSource::Buffered { data, .. } => data,
            #[cfg(feature = "mmap")]
            DataSource::Mmap {
                map, data_offset, ..
            } => &map[*data_offset..],
        }
    }

    // ── Iteration methods ─────────────────────────────────────────────

    /// Iterate over Z-slices.
    pub fn slices<T: Voxel>(&self) -> crate::iter::RegionIter<'_, T, crate::iter::SliceStepper> {
        crate::iter::RegionIter::with_stepper(
            self,
            self.shape(),
            crate::iter::SliceStepper::default(),
        )
    }

    /// Iterate over Z-slabs.
    pub fn slabs<T: Voxel>(
        &self,
        k: usize,
    ) -> crate::iter::RegionIter<'_, T, crate::iter::SlabStepper> {
        crate::iter::RegionIter::with_stepper(self, self.shape(), crate::iter::SlabStepper::new(k))
    }

    /// Iterate over 3D tiles.
    pub fn tiles<T: Voxel>(
        &self,
        tile_shape: [usize; 3],
    ) -> Result<crate::iter::RegionIter<'_, T, crate::iter::TileStepper>, Error> {
        Ok(crate::iter::RegionIter::with_stepper(
            self,
            self.shape(),
            crate::iter::TileStepper::new(tile_shape)?,
        ))
    }

    /// Iterate over sub-volumes (volume stacks only).
    pub fn volumes<T: Voxel>(
        &self,
    ) -> Result<crate::iter::RegionIter<'_, T, crate::iter::SlabStepper>, Error> {
        let mz = self.header().mz.max(0) as usize;
        if !self.header().is_volume_stack() || mz == 0 {
            return Err(Error::NotAVolumeStack {
                ispg: self.header().ispg,
                mz: self.header().mz,
            });
        }
        Ok(self.slabs(mz))
    }

    /// Read a single sub-region.
    pub fn subregion<T: Voxel>(
        &self,
        offset: [usize; 3],
        shape: [usize; 3],
    ) -> Result<VoxelBlock<T>, Error> {
        let bytes = self.read_block_bytes_cow(offset, shape)?;
        let data = self.decode_block::<T>(&bytes)?;
        Ok(VoxelBlock {
            offset,
            shape,
            data,
        })
    }

    /// Read the entire volume.
    pub fn read_volume<T: Voxel>(&self) -> Result<VoxelBlock<T>, Error> {
        self.subregion([0, 0, 0], [self.shape.nx, self.shape.ny, self.shape.nz])
    }

    /// Iterate over Z-slices as u8 (Uint16 narrowing or Packed4Bit unpack).
    pub fn slices_u8(&self) -> crate::io::reader_common::VoxelIter<'_, u8> {
        if self.mode() == Mode::Packed4Bit {
            let shape = self.shape();
            let nx = shape.nx;
            let ny = shape.ny;
            let nz = shape.nz;
            return Box::new((0..nz).map(move |z| {
                let bytes = self.read_block_bytes_cow([0, 0, z], [nx, ny, 1])?;
                let data = crate::engine::convert::unpack_u4_bytes_to_u8(&bytes, nx, ny);
                Ok(VoxelBlock {
                    offset: [0, 0, z],
                    shape: [nx, ny, 1],
                    data,
                })
            }));
        }
        if self.mode() != Mode::Uint16 {
            return Box::new(std::iter::once(Err(Error::ModeMismatch {
                file_mode: self.mode(),
                requested_mode: Mode::Uint16,
                offset: None,
            })));
        }
        Box::new(self.slices::<u16>().map(|b| {
            let b = b?;
            Ok(VoxelBlock {
                offset: b.offset,
                shape: b.shape,
                data: crate::engine::convert::convert_u16_slice_to_u8(&b.data)?,
            })
        }))
    }

    /// Iterate over Z-slabs as u8.
    pub fn slabs_u8(&self, k: usize) -> crate::io::reader_common::VoxelIter<'_, u8> {
        if self.mode() == Mode::Packed4Bit {
            let volume_shape = self.shape();
            let nx = volume_shape.nx;
            let ny = volume_shape.ny;
            let k = k.max(1);
            let mut z = 0usize;
            return Box::new(std::iter::from_fn(move || {
                if z >= volume_shape.nz {
                    return None;
                }
                let start = z;
                let sz = k.min(volume_shape.nz - z);
                z += sz;
                let bytes = match self.read_block_bytes_cow([0, 0, start], [nx, ny, sz]) {
                    Ok(b) => b,
                    Err(e) => return Some(Err(e)),
                };
                let data = crate::engine::convert::unpack_u4_bytes_to_u8(&bytes, nx, ny * sz);
                Some(Ok(VoxelBlock {
                    offset: [0, 0, start],
                    shape: [nx, ny, sz],
                    data,
                }))
            }));
        }
        if self.mode() != Mode::Uint16 {
            return Box::new(std::iter::once(Err(Error::ModeMismatch {
                file_mode: self.mode(),
                requested_mode: Mode::Uint16,
                offset: None,
            })));
        }
        let k = k.max(1);
        Box::new(self.slabs::<u16>(k).map(|b| {
            let b = b?;
            Ok(VoxelBlock {
                offset: b.offset,
                shape: b.shape,
                data: crate::engine::convert::convert_u16_slice_to_u8(&b.data)?,
            })
        }))
    }

    /// Iterate over Z-slices of a Mode 0 file with configurable signed/unsigned interpretation.
    pub fn slices_mode0(
        &self,
        interp: crate::M0Interpretation,
    ) -> crate::io::reader_common::VoxelIter<'_, f32> {
        if self.mode() != Mode::Int8 {
            return Box::new(std::iter::once(Err(Error::ModeMismatch {
                file_mode: self.mode(),
                requested_mode: Mode::Int8,
                offset: None,
            })));
        }
        let volume_shape = self.shape();
        Box::new((0..volume_shape.nz).map(move |z| {
            let bytes =
                self.read_block_bytes_cow([0, 0, z], [volume_shape.nx, volume_shape.ny, 1])?;
            let data = crate::engine::convert::reinterpret_m0(&bytes, interp);
            Ok(VoxelBlock {
                offset: [0, 0, z],
                shape: [volume_shape.nx, volume_shape.ny, 1],
                data,
            })
        }))
    }

    /// Iterate over Z-slabs of a Mode 0 file.
    pub fn slabs_mode0(
        &self,
        k: usize,
        interp: crate::M0Interpretation,
    ) -> crate::io::reader_common::VoxelIter<'_, f32> {
        if self.mode() != Mode::Int8 {
            return Box::new(std::iter::once(Err(Error::ModeMismatch {
                file_mode: self.mode(),
                requested_mode: Mode::Int8,
                offset: None,
            })));
        }
        let volume_shape = self.shape();
        let k = k.max(1);
        let mut z = 0usize;
        Box::new(std::iter::from_fn(move || {
            if z >= volume_shape.nz {
                return None;
            }
            let start = z;
            let sz = k.min(volume_shape.nz - z);
            z += sz;
            let bytes = match self
                .read_block_bytes_cow([0, 0, start], [volume_shape.nx, volume_shape.ny, sz])
            {
                Ok(b) => b,
                Err(e) => return Some(Err(e)),
            };
            let data = crate::engine::convert::reinterpret_m0(&bytes, interp);
            Some(Ok(VoxelBlock {
                offset: [0, 0, start],
                shape: [volume_shape.nx, volume_shape.ny, sz],
                data,
            }))
        }))
    }

    /// Return a wrapper that auto-converts all reads to type `T`.
    pub fn convert<T>(&self) -> crate::io::reader_common::ConvertReader<'_, T>
    where
        T: Voxel + crate::engine::convert::ConvertFrom<f32>,
    {
        let m0_interp = if self.mode() == Mode::Int8 {
            if let Some(imod) = self.header().detect_imod() {
                if !imod.bytes_are_signed {
                    crate::M0Interpretation::Unsigned
                } else {
                    crate::M0Interpretation::Signed
                }
            } else {
                crate::M0Interpretation::Signed
            }
        } else {
            crate::M0Interpretation::Signed
        };

        crate::io::reader_common::ConvertReader {
            reader: self,
            complex_strategy: crate::ComplexToRealStrategy::Magnitude,
            m0_interp,
            _target: std::marker::PhantomData,
        }
    }

    /// Read the entire volume as an ndarray (requires `ndarray` feature).
    #[cfg(feature = "ndarray")]
    pub fn to_ndarray<T: Voxel>(&self) -> Result<ndarray::Array3<T>, Error> {
        let block = self.read_volume::<T>()?;
        ndarray::Array3::from_shape_vec([self.shape.nz, self.shape.ny, self.shape.nx], block.data)
            .map_err(|_| Error::bounds_err())
    }

    /// Read the entire volume as u8 (Packed4Bit unpack).
    pub fn read_volume_u8(&self) -> Result<VoxelBlock<u8>, Error> {
        if self.mode() != Mode::Packed4Bit {
            return Err(Error::ModeMismatch {
                file_mode: self.mode(),
                requested_mode: Mode::Packed4Bit,
                offset: None,
            });
        }
        let shape = self.shape();
        let block_shape = [shape.nx, shape.ny, shape.nz];
        let bytes = self.read_block_bytes_cow([0, 0, 0], block_shape)?;
        let data =
            crate::engine::convert::unpack_u4_bytes_to_u8(&bytes, shape.nx, shape.ny * shape.nz);
        Ok(VoxelBlock {
            offset: [0, 0, 0],
            shape: block_shape,
            data,
        })
    }

    // ── Extended header convenience methods ──────────────────────────

    /// Auto-dispatch extended header parsing.
    pub fn parse_extended_header(&self) -> crate::ExtHeaderData {
        crate::ExtHeaderData::from_header(&self.header, self.ext_header_bytes())
    }

    /// Parse FEI1 metadata records.
    pub fn fei1_metadata(&self) -> Option<Vec<crate::Fei1Metadata>> {
        crate::parse_fei1_records(self.ext_header_bytes())
    }

    /// Parse FEI2 metadata records.
    pub fn fei2_metadata(&self) -> Option<Vec<crate::Fei2Metadata>> {
        crate::parse_fei2_records(self.ext_header_bytes())
    }

    /// Parse CCP4 symmetry records.
    pub fn ccp4_records(&self) -> Option<Vec<crate::Ccp4Record>> {
        crate::parse_ccp4_records(self.ext_header_bytes())
    }

    /// Parse MRCO legacy records.
    pub fn mrco_records(&self) -> Option<Vec<crate::MrcoRecord>> {
        crate::parse_mrco_records(self.ext_header_bytes())
    }

    /// Parse SerialEM records.
    pub fn seri_records(&self) -> Option<Vec<crate::SeriRecord>> {
        crate::parse_seri_records(self.ext_header_bytes())
    }

    /// Parse Agard records.
    pub fn agar_records(&self) -> Option<Vec<crate::AgarRecord>> {
        crate::parse_agar_records(self.ext_header_bytes())
    }

    /// Parse IMOD metadata.
    pub fn imod_metadata(&self) -> Option<crate::ImodMetadata> {
        crate::parse_imod_metadata(&self.header)
    }
}