### Examples: Data Type Matching and Intent Validation Source: https://github.com/enet4/nifti-rs/blob/master/_autodocs/api-reference/typedef.md Examples showing how to match on a header's data type, read raw voxel values, and handle intent validation errors. ```APIDOC ## Examples ### Match on a header's data type and rescale manually ```rust use nifti::{NiftiHeader, NiftiType, Endianness}; let hdr = NiftiHeader::from_file("volume.nii.gz")?; match hdr.data_type()? { NiftiType::Float32 => println!("f32, {} bytes/voxel", NiftiType::Float32.size_of()), NiftiType::Int16 => println!("i16 voxels"), other => println!("other: {other:?}"), } // Low-level: read one raw voxel from a byte slice let bytes: &[u8] = &[0x00, 0x00, 0x80, 0x3f]; // 1.0f32 BE let v: f32 = NiftiType::Float32.read_primitive_value(bytes, Endianness::Big, 2.0, 1.0)?; assert_eq!(v, 3.0); // 1.0 * 2.0 + 1.0 ``` ### Intent and unit validation errors ```rust use nifti::{NiftiHeader}; let mut hdr = NiftiHeader::default(); hdr.intent_code = 9999; // not a valid NIFTI intent match hdr.intent() { Err(nifti::NiftiError::InvalidCode("intent", 9999)) => { eprintln!("unknown intent code"); } _ => {} } ``` ``` -------------------------------- ### Reading a volume directly and sampling voxels Source: https://github.com/enet4/nifti-rs/blob/master/_autodocs/api-reference/inmem-volume.md Example showing how to read a NIfTI volume from files and sample a voxel value, which is rescaled by the scl_slope/scl_inter parameters. ```APIDOC ## Example: Reading and sampling voxels ### Description Read a NIfTI volume from a header and image file, then get the value at the center voxel. The value is rescaled using the scl_slope/scl_inter parameters from the header. ### Code ```rust use nifti::{InMemNiftiVolume, NiftiHeader, RandomAccessNiftiVolume}; let hdr = NiftiHeader::from_file("study.hdr.gz")?; let vol = InMemNiftiVolume::from_file("study.img.gz", &hdr)?; assert_eq!(vol.dim(), &[256, 256, 120]); let center = vol.get_f32(&[128, 128, 60])?; // rescaled by scl_slope/scl_inter println!("center voxel: {center}"); ``` ``` -------------------------------- ### In-memory volume from a header and a raw buffer Source: https://github.com/enet4/nifti-rs/blob/master/_autodocs/api-reference/inmem-volume.md Example showing how to create an InMemNiftiVolume from a manually constructed NiftiHeader and raw byte buffer, and how to access voxel values with rescaling. ```APIDOC ## Example: Creating an in-memory volume ### Description Create a NIfTI header with default values, set dimensions, datatype, bitpix, and scaling factors, then build a volume from raw data and access a voxel value. ### Code ```rust use nifti::{InMemNiftiVolume, NiftiHeader, RandomAccessNiftiVolume}; let mut hdr = NiftiHeader::default(); hdr.dim = [3, 4, 4, 4, 0, 0, 0, 0]; hdr.datatype = 2; // Uint8 hdr.bitpix = 8; hdr.scl_slope = 2.0; hdr.scl_inter = -5.0; let raw: Vec = (0..64).map(|x| x * 2).collect(); let vol = InMemNiftiVolume::from_raw_data(&hdr, raw)?; assert_eq!(vol.get_f32(&[3, 1, 0])?, 9.0); // (3*2)*2 - 5 ``` ``` -------------------------------- ### from_file constructor for StreamedNiftiVolume> Source: https://github.com/enet4/nifti-rs/blob/master/_autodocs/api-reference/streamed-volume.md Constructor to read a NIFTI volume from an uncompressed file. Requires the header and expected byte order to be known in advance, and the file must start with the first voxels (not extensions). Only available for StreamedNiftiVolume>; does not handle gzip. ```rust /// Read a NIFTI volume from an uncompressed file. The header and expected /// byte order of the volume's data must be known in advance. It is also /// expected that the file starts with the first voxels of the volume, not /// with the extensions. pub fn from_file

(path: P, header: &NiftiHeader) -> Result where P: AsRef, ``` -------------------------------- ### Read a NIfTI header from a file Source: https://github.com/enet4/nifti-rs/blob/master/_autodocs/api-reference/header.md Use NiftiHeader::from_file to read .hdr, .hdr.gz, .nii, and .nii.gz files. The example shows how to access dimensions, data type, and spatial/temporal units, returning a nifti::Result. ```rust use nifti::{NiftiHeader, NiftiType}; fn read_hdr() -> nifti::Result<()> { let hdr1 = NiftiHeader::from_file("0000.hdr")?; // .hdr and .hdr.gz both work let hdr2 = NiftiHeader::from_file("4321.nii.gz")?; // .nii and .nii.gz both work let dims = hdr1.dim()?; // &[u16] without dim[0] let dtype = hdr1.data_type()?; // NiftiType let (space, time) = hdr1.xyzt_units()?; // (Unit, Unit) println!("{:?} {:?} {:?}", dims, dtype, (space, time)); Ok(()) } ``` -------------------------------- ### from_reader constructor for StreamedNiftiVolume Source: https://github.com/enet4/nifti-rs/blob/master/_autodocs/api-reference/streamed-volume.md Constructor to read a NIFTI volume from a raw voxel stream. Requires the header and expected byte order to be known in advance, and the stream must start with the first voxels (not extensions). Slice rank defaults to the volume rank minus one. ```rust /// Read a NIFTI volume from a stream of raw voxel data. The header and /// expected byte order of the volume's data must be known in advance. It /// is also expected that the following bytes represent the first voxels of /// the volume (and not part of the extensions). /// /// By default, the slice's rank is the original volume's rank minus 1. pub fn from_reader(source: R, header: &NiftiHeader) -> Result ``` -------------------------------- ### compress and compression_level - Configure gzip compression Source: https://github.com/enet4/nifti-rs/blob/master/_autodocs/api-reference/writer.md compress enables or disables gzip compression, updating the output path accordingly. compression_level sets the compression level directly using flate2::Compression. If compress(true) is called without setting a level, fast compression is used. Gzip output gets the .gz extension. ```rust /// Whether to compress the output to gz. /// /// Will update the output path accordingly. pub fn compress(mut self, compress: bool) -> Self /// Sets the compression level to use when compressing the output. pub fn compression_level(mut self, compression_level: Compression) -> Self ``` -------------------------------- ### Typed conversion with validation error handling Source: https://github.com/enet4/nifti-rs/blob/master/_autodocs/api-reference/inmem-volume.md Example showing how to convert a volume to a typed vector (e.g., Vec) and handle type conversion errors when the file's datatype does not match the requested type. ```APIDOC ## Example: Typed conversion ### Description Convert a volume to a specific Rust type using `into_nifti_typed_data`. If the file's datatype does not match the requested type, a `NiftiError::InvalidTypeConversion` is returned. ### Code ```rust use nifti::{InMemNiftiVolume, NiftiHeader, volume::element::DataElement}; let hdr = NiftiHeader::from_file("f32_data.hdr")?; let vol = InMemNiftiVolume::from_file("f32_data.img", &hdr)?; // works because the file's datatype is Float32: let voxels: Vec = vol.into_nifti_typed_data()?; // would fail with InvalidTypeConversion on a non-f32 file: let hdr2 = NiftiHeader::from_file("u16_data.hdr")?; let vol2 = InMemNiftiVolume::from_file("u16_data.img", &hdr2)?; match vol2.into_nifti_typed_data::() { Err(nifti::NiftiError::InvalidTypeConversion(from, to)) => { eprintln!("cannot convert {from:?} to {to}"); } Ok(_) => {} } ``` ``` -------------------------------- ### Iterate over slices with Iterator API Source: https://github.com/enet4/nifti-rs/blob/master/_autodocs/api-reference/streamed-volume.md Shows the usual entry point for reading a streamed volume from a file and iterating over its slices using the Iterator API. Each slice is returned as a nifti::Result; handle errors with the ? operator. The example ends with a hidden Ok::<(), nifti::NiftiError>(()) line. ```rust use nifti::{StreamedNiftiVolume, InMemNiftiVolume, NiftiHeader, ReaderStreamedOptions, NiftiObject}; // usual entry point: streamed object from file let obj = ReaderStreamedOptions::new().read_file("minimal.nii.gz")?; let volume = obj.into_volume(); for slice in volume { let slice: InMemNiftiVolume = slice?; // nifti::Result // manipulate slice here } # Ok::<(), nifti::NiftiError>(()) ``` -------------------------------- ### Buffer-recycling iteration and slice indices Source: https://github.com/enet4/nifti-rs/blob/master/_autodocs/api-reference/streamed-volume.md Demonstrates two iteration modes on a streamed volume: index-aware iteration using .indexed() to get slice positions, and buffer-reusing iteration with .next_inline() to avoid reallocations. The buffer is recovered via into_raw_data() for reuse. Requires the volume to be mutable and uses the Idx type from nifti::volume::shape. ```rust use nifti::{NiftiObject, ReaderStreamedOptions, volume::shape::Idx}; let mut obj = ReaderStreamedOptions::new().read_file("big.nii.gz")?; let mut volume = obj.into_volume(); // 1) index-aware iteration for pair in volume.by_ref().indexed() { let (idx, slice): (Idx, InMemNiftiVolume) = pair?; // idx.as_ref() gives the multi-dimensional slice position } // 2) buffer-reusing iteration let mut buffer = Vec::new(); while let Some(slice) = volume.next_inline(buffer) { let slice = slice?; // use slice, then recover the raw data vector for the next iteration buffer = slice.into_raw_data(); } # Ok::<(), nifti::NiftiError>(()) ``` -------------------------------- ### new Source: https://github.com/enet4/nifti-rs/blob/master/_autodocs/api-reference/writer.md Creates a blank new set of options ready for configuration. The output path is required and the extension is forced to .nii if none is provided. ```APIDOC ## `new` ### Description Creates a blank new set of options ready for configuration. The output path is required and the extension is forced to `.nii` if none is provided. ### Method `pub fn new

(path: P) -> WriterOptions<'a> where P: AsRef` ### Parameters - `path` (P: AsRef) - Required - Output path; extension is forced to `.nii` if none. ### Defaults Defaults derived from the path: `write_header_file = is_hdr_file(path)` (ends with `.hdr`/`.hdr.gz`), `compression = Some(Compression::fast())` if the path ends with `.gz` else `None`, `force_header_compression = write_header_file && compression.is_some()`, `header_reference = None`, `extension_sequence = None`. ### Source `src/writer.rs:68-90` ``` -------------------------------- ### from_file method Source: https://github.com/enet4/nifti-rs/blob/master/_autodocs/api-reference/inmem-volume.md Reads a NIFTI volume from an image file (.img or .img.gz). Gzip decoding is triggered when the path extension equals "gz". ```rust /// Read a NIFTI volume from an image file. NIFTI-1 volume files usually have the /// extension ".img" or ".img.gz". In the latter case, the file is automatically /// decoded as a Gzip stream. pub fn from_file>(path: P, header: &NiftiHeader) -> Result ``` -------------------------------- ### ExtensionSequence sequence API Source: https://github.com/enet4/nifti-rs/blob/master/_autodocs/api-reference/extension.md Provides methods to iterate, check emptiness, get length, compute bytes on disk, and get the extender code. bytes_on_disk sums esize over all extensions and is used by WriterOptions to compute vox_offset. ```rust /// Obtain an iterator to the extensions. pub fn iter(&self) -> ::std::slice::Iter<'_, Extension> /// Whether the sequence of extensions is empty. pub fn is_empty(&self) -> bool /// Obtain the number of extensions available. pub fn len(&self) -> usize /// Return the number of bytes the extensions take on disk pub fn bytes_on_disk(&self) -> usize /// Get the extender code from this extension sequence. pub fn extender(&self) -> Extender ``` -------------------------------- ### ExtensionSequence Sequence API Source: https://github.com/enet4/nifti-rs/blob/master/_autodocs/api-reference/extension.md Methods for iterating, checking emptiness, getting length, computing bytes on disk, and retrieving the extender code. ```APIDOC ## ExtensionSequence Sequence API ### Description Methods for iterating, checking emptiness, getting length, computing bytes on disk, and retrieving the extender code. ### Methods - `pub fn iter(&self) -> ::std::slice::Iter<'_, Extension>` - Returns an iterator over the extensions. - `pub fn is_empty(&self) -> bool` - Returns `true` if the sequence is empty. - `pub fn len(&self) -> usize` - Returns the number of extensions. - `pub fn bytes_on_disk(&self) -> usize` - Returns the total bytes the extensions take on disk (sum of `esize`). - `pub fn extender(&self) -> Extender` - Returns the extender code (by value, since `Extender` is `Copy`). ### Source `src/extension.rs:183-201` ``` -------------------------------- ### NiftiHeader::from_reader Source: https://github.com/enet4/nifti-rs/blob/master/_autodocs/api-reference/header.md Reads a NIfTI-1 header from a byte stream positioned at the start of the header. Automatically detects endianness by checking the first dimension. ```APIDOC ## NiftiHeader::from_reader ### Description Reads a NIfTI-1 header from a byte stream. The input must be positioned at the start of the NIFTI header. ### Method Rust associated function ### Signature ```rust pub fn from_reader(input: S) -> Result where S: Read, ``` ### Parameters - `input` (S: Read) - Required - Byte stream positioned at the start of the header ### Returns - `Result` - The parsed `NiftiHeader` ### Errors - `NiftiError::Io` - Including `UnexpectedEof` - `NiftiError::InvalidFormat` - If the header format is invalid ### Endianness Detection Reads native order first; if `dim[0] > 7`, re-reads with the opposite endianness. ### Source `src/header.rs:231` ``` -------------------------------- ### new - Create WriterOptions with path Source: https://github.com/enet4/nifti-rs/blob/master/_autodocs/api-reference/writer.md Creates a new WriterOptions with the given output path. The extension is forced to .nii if none is provided. Defaults are derived from the path: write_header_file is true if the path ends with .hdr or .hdr.gz, compression is set to fast if the path ends with .gz, otherwise None, and force_header_compression is true when both write_header_file and compression are set. ```rust /// Creates a blank new set of options ready for configuration. pub fn new

(path: P) -> WriterOptions<'a> where P: AsRef, ``` -------------------------------- ### Build an extension sequence for writing Source: https://github.com/enet4/nifti-rs/blob/master/_autodocs/api-reference/extension.md Constructs an ExtensionSequence with two extensions, one with raw bytes and one from a string, and computes the on-disk size for vox_offset. From examples/gen_nifti/main.rs. ```rust use nifti::{Extender, Extension, ExtensionSequence}; let extension1 = Extension::new(2, vec![0, 0, 0, 0]); let extension2 = Extension::from_str(6, "Hello World!"); // zero-padded to 16-byte multiple let extension_sequence = ExtensionSequence::new( Extender::from([1u8, 0u8, 0u8, 0u8]), vec![extension1, extension2], ); let on_disk = extension_sequence.bytes_on_disk(); // for vox_offset computation ``` -------------------------------- ### StreamedNiftiVolume::from_file Source: https://github.com/enet4/nifti-rs/blob/master/_autodocs/api-reference/streamed-volume.md Reads a NIfTI volume from an uncompressed file. The header and expected byte order must be known in advance, and the file must start with the first voxels of the volume. ```APIDOC ## from_file ### Description Read a NIFTI volume from an uncompressed file. The header and expected byte order of the volume's data must be known in advance. It is also expected that the file starts with the first voxels of the volume, not with the extensions. ### Method Constructor (associated function) ### Signature ```rust pub fn from_file

(path: P, header: &NiftiHeader) -> Result where P: AsRef, ``` ### Parameters - **path** (`P: AsRef`) - Required - Path to the uncompressed NIfTI file. - **header** (`&NiftiHeader`) - Required - Header containing dimensions, datatype, scaling, and endianness. ### Notes - Only available for `StreamedNiftiVolume>`. - Uncompressed only; for gzip sources use `ReaderStreamedOptions`. ### Errors Returns a `Result` with an error if reading fails. ``` -------------------------------- ### Full configuration with reference header and extensions Source: https://github.com/enet4/nifti-rs/blob/master/_autodocs/api-reference/writer.md Writes an i16 array with a reference header loaded from a template file and a custom extension sequence. Uses WriterOptions with .reference_header(), .with_extensions(), and .compress(true). The output path ends with .hdr.gz, so the header is compressed only when the path is .hdr.gz. ```rust use ndarray::Array3; use nifti::{ writer::WriterOptions, Extender, Extension, ExtensionSequence, NiftiHeader, NiftiType, }; let data = Array3::::from_elem((64, 64, 32), 42i16); let reference = NiftiHeader::from_file("template.hdr")?; // template metadata let ext = ExtensionSequence::new( Extender::from([1, 0, 0, 0]), vec![Extension::from_str(6, "produced by demo")], ); let opts = WriterOptions::new("result.hdr.gz") .reference_header(&reference) .with_extensions(ext) .compress(true); // .hdr.gz + .img.gz (header .gz only when path is .hdr.gz) opts.write_nifti(&data)?; ``` -------------------------------- ### Handle invalid intent code Source: https://github.com/enet4/nifti-rs/blob/master/_autodocs/api-reference/typedef.md Shows how to detect an invalid intent code by setting intent_code to 9999 and matching on the resulting error. The example prints an error message when the intent is unknown. ```rust use nifti::{NiftiHeader}; let mut hdr = NiftiHeader::default(); hdr.intent_code = 9999; // not a valid NIFTI intent match hdr.intent() { Err(nifti::NiftiError::InvalidCode("intent", 9999)) => { eprintln!("unknown intent code"); } _ => {} } ``` -------------------------------- ### StreamedNiftiVolume::from_reader Source: https://github.com/enet4/nifti-rs/blob/master/_autodocs/api-reference/streamed-volume.md Reads a NIfTI volume from a raw voxel stream. The header and expected byte order must be known in advance, and the stream must start with the first voxels of the volume. ```APIDOC ## from_reader ### Description Read a NIFTI volume from a stream of raw voxel data. The header and expected byte order of the volume's data must be known in advance. It is also expected that the following bytes represent the first voxels of the volume (and not part of the extensions). By default, the slice's rank is the original volume's rank minus 1. ### Method Constructor (associated function) ### Signature ```rust pub fn from_reader(source: R, header: &NiftiHeader) -> Result ``` ### Parameters - **source** (`R: Read`) - Required - Raw voxel stream. - **header** (`&NiftiHeader`) - Required - Header containing dimensions, datatype, scaling, and endianness. ### Notes - Available for all `R: Read`. - Slice rank defaults to `dim.rank() - 1`. ### Errors Returns a `Result` with an error if reading fails. ``` -------------------------------- ### Extension::new constructor Source: https://github.com/enet4/nifti-rs/blob/master/_autodocs/api-reference/extension.md Creates an Extension from an extension code and raw data. Sets esize = 8 + edata.len(). ```rust /// Create an extension out of its main components. pub fn new(ecode: i32, edata: Vec) -> Self ``` -------------------------------- ### StreamedNiftiVolume::from_reader_rank Source: https://github.com/enet4/nifti-rs/blob/master/_autodocs/api-reference/streamed-volume.md Reads a NIfTI volume from a stream with a custom slice rank. The header and expected byte order must be known in advance, and the stream must start with the first voxels of the volume. ```APIDOC ## from_reader_rank ### Description Read a NIFTI volume from a stream of data. The header and expected byte order of the volume's data must be known in advance. It is also expected that the following bytes represent the first voxels of the volume (and not part of the extensions). The slice rank defines how many dimensions each slice should have. ### Method Constructor (associated function) ### Signature ```rust pub fn from_reader_rank(source: R, header: &NiftiHeader, slice_rank: u16) -> Result ``` ### Parameters - **source** (`R: Read`) - Required - Raw voxel stream. - **header** (`&NiftiHeader`) - Required - Dimensions, datatype, scaling, endianness. - **slice_rank** (`u16`) - Required - Number of dimensions per slice; must be `< dim.rank()`. ### Panics - Panics (via `calculate_slice_dims` / `calculate_total_slices`) if `slice_rank >= dim.rank()` or if the volume has rank 0. ### Errors - Returns `NiftiError::InconsistentDim` or `NiftiError::InvalidCode` (datatype) on failure. ``` -------------------------------- ### Set both sform and qform consistently Source: https://github.com/enet4/nifti-rs/blob/master/_autodocs/api-reference/affine.md Creates a default header, sets a 4x4 affine using `set_affine` (which writes sform as AlignedAnat and qform as Unknown, dropping shear), and optionally sets qform to a specific code with `set_qform`. ```rust use nifti::{NiftiHeader, affine::Affine4, XForm}; use nalgebra::Matrix4; let mut hdr = NiftiHeader::default(); let affine: Affine4 = Matrix4::new( 2.0, 0.0, 0.0, 10.0, 0.0, 2.0, 0.0, 20.0, 0.0, 0.0, 2.0, 30.0, 0.0, 0.0, 0.0, 1.0, ); // writes sform (AlignedAnat) and qform (Unknown); qform drops any shear hdr.set_affine(&affine); assert_eq!(hdr.qform()?, XForm::Unknown); // or set qform to a specific code: hdr.set_qform(&affine, XForm::Talairach); ``` -------------------------------- ### reference_file - Load reference header from file Source: https://github.com/enet4/nifti-rs/blob/master/_autodocs/api-reference/writer.md Loads a reference header from a Nifti file at write time. Throws all NiftiHeader::from_file errors. ```rust /// Loads a reference header from a Nifti file. pub fn reference_file

(mut self, path: &'a P) -> Self where P: AsRef + 'a, ``` -------------------------------- ### Match on data type and read raw voxel Source: https://github.com/enet4/nifti-rs/blob/master/_autodocs/api-reference/typedef.md Shows how to match on a header's data type and read a raw voxel from a byte slice using NiftiType::read_primitive_value. The example expects a big-endian f32 value and applies scale and offset. ```rust use nifti::{NiftiHeader, NiftiType, Endianness}; let hdr = NiftiHeader::from_file("volume.nii.gz")?; match hdr.data_type()? { NiftiType::Float32 => println!("f32, {} bytes/voxel", NiftiType::Float32.size_of()), NiftiType::Int16 => println!("i16 voxels"), other => println!("other: {other:?}"), } // Low-level: read one raw voxel from a byte slice let bytes: &[u8] = &[0x00, 0x00, 0x80, 0x3f]; // 1.0f32 BE let v: f32 = NiftiType::Float32.read_primitive_value(bytes, Endianness::Big, 2.0, 1.0)?; assert_eq!(v, 3.0); // 1.0 * 2.0 + 1.0 ``` -------------------------------- ### Build a header and handle description length errors Source: https://github.com/enet4/nifti-rs/blob/master/_autodocs/api-reference/header.md Creates a default NiftiHeader, sets calibration values and datatype, and demonstrates handling the IncorrectDescriptionLength error when the description exceeds 80 bytes. ```rust use nifti::{NiftiHeader, NiftiType}; let mut hdr = NiftiHeader::default(); hdr.cal_min = 0.; hdr.cal_max = 128.; hdr.datatype = 4; // NIFTI_TYPE_INT16 assert_eq!(hdr.data_type().unwrap(), NiftiType::Int16); // Writer-oriented description handling match hdr.set_description_str("a very long description that exceeds eighty bytes...") { Err(nifti::NiftiError::IncorrectDescriptionLength(len)) => { eprintln!("description too long: {len} bytes"); } Ok(()) => {} Err(e) => panic!("unexpected: {e:?}"), } ``` -------------------------------- ### Header affine methods signatures Source: https://github.com/enet4/nifti-rs/blob/master/_autodocs/api-reference/affine.md Lists the public methods on `NiftiHeader` that become available when the `nalgebra_affine` feature is enabled. Each method returns or sets a `Matrix4` affine, with `qform_affine` panicking on bad qfac/pixdim. ```rust pub fn affine(&self) -> Matrix4 // best available: sform > qform > base pub fn sform_affine(&self) -> Matrix4 // from srow_x/y/z pub fn qform_affine(&self) -> Matrix4 // from quatern_*/pixdim; panics on bad qfac/pixdim pub fn set_affine(&mut self, affine: &Matrix4) // sets sform + qform codes pub fn set_sform(&mut self, affine: &Matrix4, code: XForm) pub fn set_qform(&mut self, affine4: &Matrix4, code: XForm) ``` -------------------------------- ### Read NIfTI file with ReaderOptions Source: https://github.com/enet4/nifti-rs/blob/master/README.md Reads a NIfTI file with default options and accesses its header, volume, and dimensions. Requires the `nifti` crate and returns a `Result`; the `?` operator propagates errors. ```rust use nifti::{NiftiObject, ReaderOptions, NiftiVolume}; let obj = ReaderOptions::new().read_file("myvolume.nii.gz")?; // use obj let header = obj.header(); let volume = obj.volume(); let dims = volume.dim(); ``` -------------------------------- ### Convert raw buffer to typed voxels with validation Source: https://github.com/enet4/nifti-rs/blob/master/_autodocs/api-reference/data-element.md Uses f32::from_raw_vec_validated to convert a raw byte buffer to Vec with runtime datatype validation. The example shows a successful conversion and a mismatch case where u16::from_raw_vec_validated returns an InvalidTypeConversion error when the NIfTI datatype is Uint8. ```rust use nifti::volume::element::DataElement; use nifti::NiftiType; use byteordered::Endianness; let raw: Vec = vec![0x00, 0x00, 0x80, 0x3f, 0x00, 0x00, 0x00, 0x40]; let vals: Vec = f32::from_raw_vec_validated(raw, Endianness::Big, NiftiType::Float32)?; assert_eq!(vals, vec![1.0, 2.0]); // mismatch between NIfTI datatype and target element type: let raw = vec![1u8, 2u8]; match u16::from_raw_vec_validated(raw, Endianness::Little, NiftiType::Uint8) { Err(nifti::NiftiError::InvalidTypeConversion(from, to)) => { eprintln!("cannot convert {from:?} to {to}"); // "Uint8" → "u16" } _ => {} } ``` -------------------------------- ### Read volume and sample voxels with InMemNiftiVolume Source: https://github.com/enet4/nifti-rs/blob/master/_autodocs/api-reference/inmem-volume.md Reads a NIfTI volume from .img/.hdr files and samples a voxel value, demonstrating the get_f32 method which applies scl_slope/scl_inter rescaling. ```rust use nifti::{InMemNiftiVolume, NiftiHeader, RandomAccessNiftiVolume}; let hdr = NiftiHeader::from_file("study.hdr.gz")?; let vol = InMemNiftiVolume::from_file("study.img.gz", &hdr)?; assert_eq!(vol.dim(), &[256, 256, 120]); let center = vol.get_f32(&[128, 128, 60])?; // rescaled by scl_slope/scl_inter println!("center voxel: {center}"); ``` -------------------------------- ### NiftiHeader::from_reader - Read header from byte stream Source: https://github.com/enet4/nifti-rs/blob/master/_autodocs/api-reference/header.md Reads a NIfTI-1 header from a byte stream positioned at the start of the header. Endianness auto-detection: reads native order first; if dim[0] > 7, re-reads with opposite endianness. Errors: NiftiError::Io (including UnexpectedEof) and NiftiError::InvalidFormat. ```rust /// Read a NIfTI-1 header, along with its byte order, from the given byte stream. /// It is assumed that the input is currently at the start of the NIFTI header. pub fn from_reader(input: S) -> Result where S: Read, ``` -------------------------------- ### Create in-memory volume from header and raw buffer Source: https://github.com/enet4/nifti-rs/blob/master/_autodocs/api-reference/inmem-volume.md Builds an InMemNiftiVolume from a NiftiHeader and raw byte buffer, demonstrating from_raw_data and get_f32 with rescaling applied. ```rust use nifti::{InMemNiftiVolume, NiftiHeader, RandomAccessNiftiVolume}; let mut hdr = NiftiHeader::default(); hdr.dim = [3, 4, 4, 4, 0, 0, 0, 0]; hdr.datatype = 2; // Uint8 hdr.bitpix = 8; hdr.scl_slope = 2.0; hdr.scl_inter = -5.0; let raw: Vec = (0..64).map(|x| x * 2).collect(); let vol = InMemNiftiVolume::from_raw_data(&hdr, raw)?; assert_eq!(vol.get_f32(&[3, 1, 0])?, 9.0); // (3*2)*2 - 5 ``` -------------------------------- ### from_reader_rank constructor for StreamedNiftiVolume Source: https://github.com/enet4/nifti-rs/blob/master/_autodocs/api-reference/streamed-volume.md Constructor to read a NIFTI volume from a stream with a custom slice rank. Requires the header and expected byte order to be known in advance, and the stream must start with the first voxels. Panics if slice_rank >= dim.rank() or if the volume has rank 0; throws NiftiError::InconsistentDim and NiftiError::InvalidCode. ```rust /// Read a NIFTI volume from a stream of data. The header and expected byte order /// of the volume's data must be known in advance. It it also expected that the /// following bytes represent the first voxels of the volume (and not part of the /// extensions). /// /// The slice rank defines how many dimensions each slice should have. pub fn from_reader_rank(source: R, header: &NiftiHeader, slice_rank: u16) -> Result ``` -------------------------------- ### reference_file Source: https://github.com/enet4/nifti-rs/blob/master/_autodocs/api-reference/writer.md Loads a reference header from a NIfTI file at write time. Throws all NiftiHeader::from_file errors. ```APIDOC ## `reference_file` ### Description Loads a reference header from a NIfTI file at write time. Throws all `NiftiHeader::from_file` errors. ### Method `pub fn reference_file

(mut self, path: &'a P) -> Self where P: AsRef + 'a` ### Parameters - `path` (&'a P) - Required - Path to the NIfTI file to load the reference header from. ### Errors Throws all `NiftiHeader::from_file` errors. ### Source `src/writer.rs:99` ``` -------------------------------- ### Write float32 volume with WriterOptions Source: https://github.com/enet4/nifti-rs/blob/master/_autodocs/api-reference/writer.md Creates a 256x256x1 float32 array and writes it as a NIfTI file using WriterOptions::new("out.nii"). The datatype is inferred as Float32 from the data element. Requires ndarray and nifti crates. ```rust use ndarray::Array3; use nifti::writer::WriterOptions; let data = Array3::::zeros((256, 256, 1)); WriterOptions::new("out.nii") .write_nifti(&data)?; // A: DataElement + Pod → datatype inferred as Float32 # Ok::<(), nifti::NiftiError>(()) ``` -------------------------------- ### from_raw_data Source: https://github.com/enet4/nifti-rs/blob/master/_autodocs/api-reference/inmem-volume.md Constructs an in-memory NIfTI volume from a header and raw data buffer. ```APIDOC ## `from_raw_data` ### Description Builds an `InMemNiftiVolume` from a header and a raw data buffer. The buffer length must match the byte count derived from the header's dimensions and datatype. ### Signature ```rust pub fn from_raw_data(header: &NiftiHeader, raw_data: Vec) -> Result ``` ### Parameters - **header** (`&NiftiHeader`) - Required - Source of `dim`, `datatype`, `scl_slope`, `scl_inter`, `endianness`. - **raw_data** (`Vec`) - Required - Raw voxel bytes, exactly `sizeof_hdr`-derived byte count. ### Errors - `NiftiError::IncompatibleLength(raw_data.len(), nbytes)` - `NiftiError::InconsistentDim` - `NiftiError::InvalidCode` (via `data_type()`) - `NiftiError::BadVolumeSize` ``` -------------------------------- ### from_file Source: https://github.com/enet4/nifti-rs/blob/master/_autodocs/api-reference/inmem-volume.md Reads a NIfTI volume from an image file, with optional Gzip decompression. ```APIDOC ## `from_file` ### Description Reads a NIfTI volume from an image file. Supports `.img` and `.img.gz` files; the latter are automatically decoded as Gzip streams. ### Signature ```rust pub fn from_file>(path: P, header: &NiftiHeader) -> Result ``` ### Parameters - **path** (`P: AsRef`) - Required - Path to the `.img` or `.img.gz` file. - **header** (`&NiftiHeader`) - Required - Corresponding header. ### Behavior Gzip decoding is triggered when the path extension equals `"gz"`. ``` -------------------------------- ### Extension::new Source: https://github.com/enet4/nifti-rs/blob/master/_autodocs/api-reference/extension.md Creates a new Extension from an extension code and raw data. The esize field is automatically computed as 8 + edata.len(). ```APIDOC ## Extension::new ### Description Creates a new Extension from an extension code and raw data. The `esize` field is automatically computed as `8 + edata.len()`. ### Method `pub fn new(ecode: i32, edata: Vec) -> Self` ### Parameters - `ecode` (i32) - Required - Extension code - `edata` (Vec) - Required - Raw extension data ### Returns - `Self` - A new `Extension` instance with `esize` set to `8 + edata.len()`. ### Source `src/extension.rs:65` ``` -------------------------------- ### ReaderOptions::new Source: https://github.com/enet4/nifti-rs/blob/master/_autodocs/api-reference/object.md Creates a blank `ReaderOptions` with all options initially set to `false`. ```rust /// Creates a blank new set of options ready for configuration. /// /// All options are initially set to `false`. pub fn new() -> Self ``` -------------------------------- ### from_reader method Source: https://github.com/enet4/nifti-rs/blob/master/_autodocs/api-reference/inmem-volume.md Reads a NIFTI volume from a stream, expecting the header and byte order to be known in advance. Reads exactly nb_bytes_for_data(header) bytes; throws NiftiError::ReserveVolume on allocation failure or NiftiError::IncompatibleLength if the stream ends early. ```rust /// Read a NIFTI volume from a stream of data. The header and expected byte order /// of the volume's data must be known in advance. It it also expected that the /// following bytes represent the first voxels of the volume (and not part of the /// extensions). pub fn from_reader(source: R, header: &NiftiHeader) -> Result ``` -------------------------------- ### Description handling methods Source: https://github.com/enet4/nifti-rs/blob/master/_autodocs/api-reference/header.md validate_description pads descrip to exactly 80 bytes, erroring with IncorrectDescriptionLength if longer. set_description replaces descrip, truncating/padding to 80 bytes, erroring if input > 80 bytes. set_description_str is a convenience wrapper taking &str/String. ```rust pub fn validate_description(&mut self) -> Result<()> pub fn set_description(&mut self, description: D) -> Result<()> where D: Into>, D: Deref, pub fn set_description_str(&mut self, description: T) -> Result<()> where T: Into, ``` -------------------------------- ### Extension::from_str constructor Source: https://github.com/enet4/nifti-rs/blob/master/_autodocs/api-reference/extension.md Creates an Extension from a string, using its UTF-8 bytes as data. The esize is padded to a multiple of 16 and the data is zero-padded to fill the padding. ```rust /// Create a new extension out of a &str pub fn from_str(ecode: i32, edata: &str) -> Self ``` -------------------------------- ### Slicing a volume with Sliceable::get_slice Source: https://github.com/enet4/nifti-rs/blob/master/_autodocs/api-reference/volume.md Demonstrates creating a 2D slice view from a volume using get_slice, verifying the reduced dimensionality, accessing a voxel through the slice, and handling an invalid axis with AxisOutOfBounds. ```rust use nifti::{NiftiObject, ReaderOptions, RandomAccessNiftiVolume, Sliceable}; let obj = ReaderOptions::new().read_file("brain.nii.gz")?; let volume = obj.volume(); // &InMemNiftiVolume // slice axis 2 (z) at index 25 → 2D view let slice = (&*volume).get_slice(2, 25)?; assert_eq!(slice.dimensionality(), volume.dimensionality() - 1); let px = slice.get_u16(&[12, 34])?; // same as volume.get_u16(&[12, 34, 25]) // invalid axis match (&*volume).get_slice(7, 0) { Err(nifti::NiftiError::AxisOutOfBounds(axis)) => eprintln!("bad axis {axis}"), _ => {} } ``` -------------------------------- ### NiftiHeader::affine Source: https://github.com/enet4/nifti-rs/blob/master/_autodocs/api-reference/affine.md Returns the best available affine matrix from the header, preferring sform, then qform, then base. ```APIDOC ## `NiftiHeader::affine` ### Description Returns the best available affine matrix: sform > qform > base. ### Signature ```rust pub fn affine(&self) -> Matrix4 ``` ### Returns `Matrix4` — the best available affine matrix. ``` -------------------------------- ### NiftiHeader::qform_affine Source: https://github.com/enet4/nifti-rs/blob/master/_autodocs/api-reference/affine.md Constructs the affine matrix from quatern_*/pixdim. Panics on bad qfac/pixdim. ```APIDOC ## `NiftiHeader::qform_affine` ### Description Constructs the affine matrix from quatern_*/pixdim. Panics on bad qfac/pixdim. ### Signature ```rust pub fn qform_affine(&self) -> Matrix4 ``` ### Returns `Matrix4` — the affine matrix from quatern_*/pixdim. ``` -------------------------------- ### ReaderStreamedOptions::new Source: https://github.com/enet4/nifti-rs/blob/master/_autodocs/api-reference/object.md Creates a new ReaderStreamedOptions instance with default settings. ```APIDOC ## `ReaderStreamedOptions::new` ### Description Creates a new `ReaderStreamedOptions` instance with default settings. ### Method `pub fn new() -> Self` ### Parameters None ### Returns - `Self` - A new `ReaderStreamedOptions` instance. ### Source `src/object.rs` ```