Skip to main content

Reader

Struct Reader 

Source
pub struct Reader { /* private fields */ }
Expand description

Consolidated MRC reader with automatic mmap/buffered backend selection. 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.

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 selects automatically for files), the default reader methods return a DataBlock whose DataView borrows directly from the mapped memory with no allocation. The same zero-copy access is available for buffered readers (created via from_bytes, from_reader, or compressed-file constructors) when the block is a native-endian contiguous full-row slab.

§Example

use mrc::Reader;

let reader = Reader::open("density.mrc")?;
for slice in reader.slices() {
    let block = slice?;
    match block.data() {
        mrc::DataView::Float32(data) => println!("f32 slice: {} voxels", data.len()),
        mrc::DataView::Int16(data)   => println!("i16 slice: {} voxels", data.len()),
        _ => {}
    }
}

Implementations§

Source§

impl Reader

Source

pub fn open<P: AsRef<Path>>(path: P) -> Result<Self, Error>

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.

§Examples
let reader = mrc::Reader::open("density.mrc")?;
println!("Dimensions: {}x{}x{}", reader.shape().nx, reader.shape().ny, reader.shape().nz);
Source

pub fn open_permissive<P: AsRef<Path>>( path: P, ) -> Result<(Self, Vec<String>), Error>

Open in permissive mode.

Non-fatal header issues are collected as warnings instead of errors.

§Examples
let (reader, warnings) = mrc::Reader::open_permissive("density.mrc")?;
for w in &warnings {
    eprintln!("Warning: {w}");
}
Source

pub fn open_plain<P: AsRef<Path>>(path: P) -> Result<Self, Error>

Open a plain (uncompressed) MRC file via buffered I/O.

§Examples
let reader = mrc::Reader::open_plain("density.mrc")?;
println!("Shape: {:?}", reader.shape());
Source

pub fn from_reader<R: Read>(reader: R) -> Result<Self, Error>

Read an MRC file from any std::io::Read source.

The entire source is read into memory, then parsed.

§Examples
use std::io::Cursor;
let reader = mrc::Reader::from_reader(Cursor::new(buf))?;
assert_eq!(reader.shape().nx, 4);
Source

pub fn from_reader_permissive<R: Read>( reader: R, ) -> Result<(Self, Vec<String>), Error>

Read from any std::io::Read source in permissive mode.

§Examples
use std::io::Cursor;
let (reader, warnings) = mrc::Reader::from_reader_permissive(Cursor::new(buf))?;
assert!(warnings.is_empty());
Source

pub fn from_bytes(data: Vec<u8>) -> Result<Self, Error>

Parse an MRC file from an in-memory byte buffer.

§Examples
let reader = mrc::Reader::from_bytes(buf)?;
assert_eq!(reader.shape().nx, 4);
Source

pub fn from_bytes_permissive( data: Vec<u8>, ) -> Result<(Self, Vec<String>), Error>

Parse an MRC file from an in-memory byte buffer in permissive mode.

§Examples
let (reader, warnings) = mrc::Reader::from_bytes_permissive(buf)?;
assert!(warnings.is_empty());
Source§

impl Reader

Source

pub fn shape(&self) -> VolumeShape

Volume dimensions.

§Examples
let s = reader.shape();
assert_eq!(s.nx, 4);
Source

pub fn mode(&self) -> Mode

Voxel data mode.

§Examples
assert_eq!(reader.mode(), mrc::Mode::Int8);
Source

pub fn header(&self) -> &Header

A reference to the parsed header.

§Examples
let header = reader.header();
assert_eq!(header.nx, 4);
Source

pub fn endian(&self) -> FileEndian

Detected file endianness.

§Examples
assert_eq!(reader.endian(), mrc::FileEndian::LittleEndian);
Source

pub fn raw_bytes(&self) -> &[u8]

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>.

§Examples
let bytes = reader.raw_bytes();
assert_eq!(bytes.len(), 64);
Source

pub fn ext_header_bytes(&self) -> &[u8]

Extended header bytes (empty slice if none).

§Examples
assert!(reader.ext_header_bytes().is_empty());
Source

pub fn is_truncated(&self) -> bool

Returns true when the file is shorter than the header’s declared data size (only possible when opened in permissive mode).

§Examples
assert!(!reader.is_truncated());
Source

pub fn is_single_image(&self) -> bool

Returns true if the file represents a single 2D image (nz == 1).

§Examples
assert!(reader.is_single_image());
Source

pub fn is_image_stack(&self) -> bool

Returns true if the file is an image stack (ispg == 0).

§Examples
assert!(reader.is_image_stack());
assert!(!reader.is_volume());
Source

pub fn is_volume(&self) -> bool

Returns true if the file represents a single 3D volume.

This is true when the file is neither an image stack nor a volume stack.

§Examples
assert!(reader.is_volume());
Source

pub fn is_volume_stack(&self) -> bool

Returns true if the file is a volume stack (ispg in 400..=630).

Volume stacks store multiple sub-volumes contiguously in Z. /// Use volumes to iterate over sub-volumes.

§Examples
assert!(reader.is_volume_stack());
Source

pub fn logical_shape(&self) -> [usize; 4]

Return the logical 4D shape [nvolumes, mz, ny, nx].

For non-stack files this is [1, nz, ny, nx]. For volume stacks it is [nz / mz, mz, ny, nx].

§Examples
assert_eq!(reader.logical_shape(), [2, 30, 64, 64]);
Source

pub fn validate_header_stats(&self) -> Result<(), Error>

Cross-check header statistics against actual data (1% tolerance).

§Examples
reader.validate_header_stats()?;
Source§

impl Reader

Source

pub fn read_block_bytes( &self, offset: [usize; 3], shape: [usize; 3], ) -> Result<Vec<u8>, Error>

Read a block of raw voxel bytes.

§Examples
let block = reader.read_block_bytes([0, 0, 0], [4, 4, 1])?;
assert_eq!(block.len(), 64);
Source

pub fn slices(&self) -> impl Iterator<Item = Result<DataBlock<'_>, Error>> + '_

Return a region iterator over Z-slices.

The returned crate::DataBlock borrows from the reader’s internal buffer (zero-copy for native-endian contiguous blocks).

Source

pub fn slabs( &self, k: usize, ) -> impl Iterator<Item = Result<DataBlock<'_>, Error>> + '_

Return a region iterator over Z-slabs of k slices.

Source

pub fn tiles( &self, tile_shape: [usize; 3], ) -> Result<impl Iterator<Item = Result<DataBlock<'_>, Error>> + '_, Error>

Return a region iterator over 3D tiles of the given shape.

Source

pub fn volumes( &self, ) -> Result<impl Iterator<Item = Result<DataBlock<'_>, Error>> + '_, Error>

Iterate over sub-volumes in a volume stack.

Each sub-volume has shape [nx, ny, mz]. Returns Error::NotAVolumeStack if the file is not a volume stack.

Source

pub fn subregion( &self, offset: [usize; 3], block_shape: [usize; 3], ) -> Result<DataBlock<'_>, Error>

Read a single 3D sub-region at offset with block_shape.

Returns a crate::DataBlock whose crate::DataView variant matches the file’s on-disk mode. The data borrows from the reader’s internal buffer when possible (zero-copy for native-endian contiguous blocks).

Source

pub fn read_volume(&self) -> Result<DataBlock<'_>, Error>

Read the entire volume as a single block.

Source

pub fn slices_u8( &self, ) -> Box<dyn Iterator<Item = Result<VoxelBlock<u8>, Error>> + '_>

Iterate over Z-slices as u8 (Uint16 narrowing or Packed4Bit unpack).

§Examples
for slice in reader.slices_u8() {
    let block = slice?;
    println!("u8 slice at z={}", block.offset[2]);
}
Source

pub fn slabs_u8( &self, k: usize, ) -> Box<dyn Iterator<Item = Result<VoxelBlock<u8>, Error>> + '_>

Iterate over Z-slabs as u8.

§Examples
for slab in reader.slabs_u8(2) {
    let block = slab?;
    println!("u8 slab depth: {}", block.shape[2]);
}
Source

pub fn slices_mode0( &self, interp: M0Interpretation, ) -> Box<dyn Iterator<Item = Result<VoxelBlock<f32>, Error>> + '_>

Iterate over Z-slices of a Mode 0 file with configurable signed/unsigned interpretation.

§Examples
for slice in reader.slices_mode0(mrc::M0Interpretation::Signed) {
    let block = slice?;
    println!("Mode 0 slice at z={}", block.offset[2]);
}
Source

pub fn slabs_mode0( &self, k: usize, interp: M0Interpretation, ) -> Box<dyn Iterator<Item = Result<VoxelBlock<f32>, Error>> + '_>

Iterate over Z-slabs of a Mode 0 file.

§Examples
for slab in reader.slabs_mode0(2, mrc::M0Interpretation::Signed) {
    let block = slab?;
    println!("Mode 0 slab depth: {}", block.shape[2]);
}
Source

pub fn convert<T>(&self) -> ConvertReader<'_, T>
where T: Voxel + ConvertFrom<f32>,

Return a wrapper that auto-converts all reads to type T.

§Examples
let converter = reader.convert::<f32>();
for slice in converter.slices() {
    let block = slice?;
    println!("Converted slice: {} voxels", block.data.len());
}
Source

pub fn read_volume_u8(&self) -> Result<VoxelBlock<u8>, Error>

Read the entire volume as u8 (Packed4Bit unpack).

§Examples
let block = reader.read_volume_u8()?;
assert_eq!(block.data.len(), 16);
Source

pub fn parse_extended_header(&self) -> ExtHeaderData

Auto-dispatch extended header parsing.

§Examples
let ext = reader.parse_extended_header();
assert_eq!(ext, mrc::ExtHeaderData::None);
Source

pub fn fei1_metadata(&self) -> Option<Vec<Fei1Metadata>>

Parse FEI1 metadata records.

§Examples
let fei1 = reader.fei1_metadata();
assert!(fei1.is_none()); // no FEI1 extended header present
Source

pub fn fei2_metadata(&self) -> Option<Vec<Fei2Metadata>>

Parse FEI2 metadata records.

§Examples
let fei2 = reader.fei2_metadata();
assert!(fei2.is_none());
Source

pub fn ccp4_records(&self) -> Option<Vec<Ccp4Record>>

Parse CCP4 symmetry records.

§Examples
let ccp4 = reader.ccp4_records();
assert!(ccp4.is_none());
Source

pub fn mrco_records(&self) -> Option<Vec<MrcoRecord>>

Parse MRCO legacy records.

§Examples
let mrco = reader.mrco_records();
assert!(mrco.is_none());
Source

pub fn seri_records(&self) -> Option<Vec<SeriRecord>>

Parse SerialEM records.

§Examples
let seri = reader.seri_records();
assert!(seri.is_none());
Source

pub fn agar_records(&self) -> Option<Vec<AgarRecord>>

Parse Agard records.

§Examples
let agar = reader.agar_records();
assert!(agar.is_none());
Source

pub fn imod_metadata(&self) -> Option<ImodMetadata>

Parse IMOD metadata.

§Examples
let imod = reader.imod_metadata();
assert!(imod.is_none());
Source§

impl Reader

Source

pub fn open_gzip<P: AsRef<Path>>(path: P) -> Result<Self, Error>

Open a gzip-compressed MRC file.

Requires the gzip feature (enabled by default). The file is decompressed into memory with a safety limit of DEFAULT_MAX_DECOMPRESSED_BYTES (256 GiB). To set a custom limit, use open_gzip_with_limit.

Source

pub fn open_gzip_with_limit<P: AsRef<Path>>( path: P, max_bytes: u64, ) -> Result<Self, Error>

Open a gzip-compressed MRC file with a custom decompression byte limit.

The decompressed stream is capped at max_bytes before the header is parsed. If the stream exceeds this limit, a decompression-bomb error is returned. Use the default open_gzip for the built-in 256 GiB safety limit.

Source

pub fn open_gzip_permissive<P: AsRef<Path>>( path: P, ) -> Result<(Self, Vec<String>), Error>

Open a gzip-compressed MRC file in permissive mode.

Trait Implementations§

Source§

impl Debug for Reader

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> Pointable for T

Source§

const ALIGN: usize

The alignment of pointer.
Source§

type Init = T

The type for initializers.
Source§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
Source§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
Source§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
Source§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
Source§

impl<T> Read<Exclusive, BecauseExclusive> for T
where T: ?Sized,

Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more